π₯ Make videos programmatically with React
refactor(core): extract media-sync decision logic into a pure function (#8936)
iliya-vidrushbe7b60a1f06a
diff --git a/packages/core/src/get-media-sync-action.ts b/packages/core/src/get-media-sync-action.tsnew file mode 100644index 0000000000..bcece86768--- /dev/null+++ b/packages/core/src/get-media-sync-action.ts@@ -0,0 +1,166 @@+// Pure decision logic for `useMediaPlayback`.+//+// Every frame, the media element's clock has to be reconciled with the+// timeline clock. This function takes a snapshot of the relevant state and+// decides *what* should happen (seek / play / buffer / nothing). The effect in+// `use-media-playback.ts` is responsible for actually executing the returned+// action. Keeping the decision separate makes the branch ordering testable+// without a DOM or a real media element.++export type MediaSyncAction =+ | {+ type: 'seek-due-to-shift';+ shouldBeTime: number;+ why: string;+ bufferUntilFirstFrame: boolean;+ playReason: string | null;+ warnAboutNonSeekable: boolean;+ }+ | {+ type: 'seek-if-not-playing';+ shouldBeTime: number;+ why: string | null;+ }+ | {+ type: 'play-and-seek';+ shouldBeTime: number;+ why: string | null;+ playReason: string;+ bufferUntilFirstFrame: boolean;+ }+ | {+ type: 'none';+ };++export type GetMediaSyncActionInput = {+ duration: number;+ currentTime: number;+ paused: boolean;+ ended: boolean;+ desiredUnclampedTime: number;+ mediaTagTime: number;+ mediaTagLastUpdate: number;+ rvcTime: number | null;+ rvcLastUpdate: number | null;+ isVariableFpsVideo: boolean;+ acceptableTimeShift: number;+ lastSeekDueToShift: number | null;+ playing: boolean;+ playbackRate: number;+ mediaTagBufferingOrStalled: boolean;+ playerBuffering: boolean;+ absoluteFrame: number;+ onlyWarnForMediaSeekingError: boolean;+ // Only used to build the log message for parity with the previous behavior.+ isPremounting: boolean;+ isPostmounting: boolean;+ pauseWhenBuffering: boolean;+};++export const getMediaSyncAction = (+ input: GetMediaSyncActionInput,+): MediaSyncAction => {+ const {+ duration,+ currentTime,+ paused,+ ended,+ desiredUnclampedTime,+ mediaTagTime,+ mediaTagLastUpdate,+ rvcTime,+ rvcLastUpdate,+ isVariableFpsVideo,+ acceptableTimeShift,+ lastSeekDueToShift,+ playing,+ playbackRate,+ mediaTagBufferingOrStalled,+ playerBuffering,+ absoluteFrame,+ onlyWarnForMediaSeekingError,+ isPremounting,+ isPostmounting,+ pauseWhenBuffering,+ } = input;++ const shouldBeTime =+ !Number.isNaN(duration) && Number.isFinite(duration)+ ? Math.min(duration, desiredUnclampedTime)+ : desiredUnclampedTime;++ const timeShiftMediaTag = Math.abs(shouldBeTime - mediaTagTime);+ const timeShiftRvcTag = rvcTime ? Math.abs(shouldBeTime - rvcTime) : null;++ const mostRecentTimeshift =+ rvcLastUpdate && (rvcTime as number) > mediaTagLastUpdate+ ? (timeShiftRvcTag as number)+ : timeShiftMediaTag;++ const timeShift =+ timeShiftRvcTag && !isVariableFpsVideo+ ? mostRecentTimeshift+ : timeShiftMediaTag;++ if (timeShift > acceptableTimeShift && lastSeekDueToShift !== shouldBeTime) {+ // If scrubbing around, adjust timing+ // or if time shift is bigger than 0.45sec+ return {+ type: 'seek-due-to-shift',+ shouldBeTime,+ why: `because time shift is too big. shouldBeTime = ${shouldBeTime}, isTime = ${mediaTagTime}, requestVideoCallbackTime = ${rvcTime}, timeShift = ${timeShift}${isVariableFpsVideo ? ', isVariableFpsVideo = true' : ''}, isPremounting = ${isPremounting}, isPostmounting = ${isPostmounting}, pauseWhenBuffering = ${pauseWhenBuffering}`,+ bufferUntilFirstFrame: playing && playbackRate > 0,+ playReason:+ playing && paused+ ? 'player is playing but media tag is paused, and just seeked'+ : null,+ warnAboutNonSeekable: !onlyWarnForMediaSeekingError,+ };+ }++ const seekThreshold = playing ? 0.15 : 0.01;++ // Only perform a seek if the time is not already the same.+ // Chrome rounds to 6 digits, so 0.033333333 -> 0.033333,+ // therefore a threshold is allowed.+ // Refer to the https://github.com/remotion-dev/video-buffering-example+ // which is fixed by only seeking conditionally.+ const makesSenseToSeek = Math.abs(currentTime - shouldBeTime) > seekThreshold;++ const isSomethingElseBuffering =+ playerBuffering && !mediaTagBufferingOrStalled;++ if (!playing || isSomethingElseBuffering) {+ return {+ type: 'seek-if-not-playing',+ shouldBeTime,+ why: makesSenseToSeek+ ? `not playing or something else is buffering. time offset is over seek threshold (${seekThreshold})`+ : null,+ };+ }++ if (!playing || playerBuffering) {+ return {type: 'none'};+ }++ // We now assured we are in playing state and not buffering+ const pausedCondition = paused && !ended;+ const firstFrameCondition = absoluteFrame === 0;+ if (pausedCondition || firstFrameCondition) {+ const reason = pausedCondition+ ? 'media tag is paused'+ : 'absolute frame is 0';+ return {+ type: 'play-and-seek',+ shouldBeTime,+ why: makesSenseToSeek+ ? `is over timeshift threshold (threshold = ${seekThreshold}) and ${reason}`+ : null,+ playReason: `player is playing and ${reason}`,+ bufferUntilFirstFrame: !isVariableFpsVideo && playbackRate > 0,+ };+ }++ return {type: 'none'};+};diff --git a/packages/core/src/test/get-media-sync-action.test.ts b/packages/core/src/test/get-media-sync-action.test.tsnew file mode 100644index 0000000000..803d1133a1--- /dev/null+++ b/packages/core/src/test/get-media-sync-action.test.ts@@ -0,0 +1,314 @@+import {describe, expect, test} from 'bun:test';+import type {GetMediaSyncActionInput} from '../get-media-sync-action.js';+import {getMediaSyncAction} from '../get-media-sync-action.js';++const makeInput = (+ overrides: Partial<GetMediaSyncActionInput> = {},+): GetMediaSyncActionInput => ({+ duration: Number.POSITIVE_INFINITY,+ currentTime: 0,+ paused: false,+ ended: false,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ mediaTagLastUpdate: 0,+ rvcTime: null,+ rvcLastUpdate: null,+ isVariableFpsVideo: false,+ acceptableTimeShift: 0.45,+ lastSeekDueToShift: null,+ playing: true,+ playbackRate: 1,+ mediaTagBufferingOrStalled: false,+ playerBuffering: false,+ absoluteFrame: 30,+ onlyWarnForMediaSeekingError: false,+ isPremounting: false,+ isPostmounting: false,+ pauseWhenBuffering: true,+ ...overrides,+});++describe('shouldBeTime clamping', () => {+ test('clamps to duration when finite', () => {+ const action = getMediaSyncAction(+ makeInput({duration: 3, desiredUnclampedTime: 5, playing: false}),+ );+ // big shift is triggered first here, but shouldBeTime is exposed on it+ expect(action.type).toBe('seek-due-to-shift');+ if (action.type === 'seek-due-to-shift') {+ expect(action.shouldBeTime).toBe(3);+ }+ });++ test('uses desired time when duration is NaN', () => {+ const action = getMediaSyncAction(+ makeInput({+ duration: Number.NaN,+ desiredUnclampedTime: 5,+ mediaTagTime: 0,+ playing: false,+ }),+ );+ expect(action.type).toBe('seek-due-to-shift');+ if (action.type === 'seek-due-to-shift') {+ expect(action.shouldBeTime).toBe(5);+ }+ });++ test('uses desired time when duration is Infinity', () => {+ const action = getMediaSyncAction(+ makeInput({+ duration: Number.POSITIVE_INFINITY,+ desiredUnclampedTime: 5,+ mediaTagTime: 0,+ playing: false,+ }),+ );+ expect(action.type).toBe('seek-due-to-shift');+ if (action.type === 'seek-due-to-shift') {+ expect(action.shouldBeTime).toBe(5);+ }+ });+});++describe('seek-due-to-shift (big time shift)', () => {+ test('triggers when time shift exceeds the acceptable shift', () => {+ const action = getMediaSyncAction(+ makeInput({mediaTagTime: 0, desiredUnclampedTime: 5, paused: true}),+ );+ expect(action.type).toBe('seek-due-to-shift');+ if (action.type === 'seek-due-to-shift') {+ expect(action.shouldBeTime).toBe(5);+ // playing && playbackRate > 0+ expect(action.bufferUntilFirstFrame).toBe(true);+ // playing && paused+ expect(action.playReason).toBe(+ 'player is playing but media tag is paused, and just seeked',+ );+ expect(action.warnAboutNonSeekable).toBe(true);+ }+ });++ test('does not set playReason when the media tag is not paused', () => {+ const action = getMediaSyncAction(+ makeInput({mediaTagTime: 0, paused: false}),+ );+ expect(action.type).toBe('seek-due-to-shift');+ if (action.type === 'seek-due-to-shift') {+ expect(action.playReason).toBe(null);+ }+ });++ test('does not buffer when not playing', () => {+ const action = getMediaSyncAction(+ makeInput({mediaTagTime: 0, playing: false}),+ );+ expect(action.type).toBe('seek-due-to-shift');+ if (action.type === 'seek-due-to-shift') {+ expect(action.bufferUntilFirstFrame).toBe(false);+ expect(action.playReason).toBe(null);+ }+ });++ test('does not warn when onlyWarnForMediaSeekingError is true', () => {+ const action = getMediaSyncAction(+ makeInput({mediaTagTime: 0, onlyWarnForMediaSeekingError: true}),+ );+ expect(action.type).toBe('seek-due-to-shift');+ if (action.type === 'seek-due-to-shift') {+ expect(action.warnAboutNonSeekable).toBe(false);+ }+ });++ test('is skipped when the last shift-seek already targeted this time', () => {+ const action = getMediaSyncAction(+ makeInput({+ mediaTagTime: 0,+ desiredUnclampedTime: 5,+ lastSeekDueToShift: 5,+ }),+ );+ expect(action.type).not.toBe('seek-due-to-shift');+ });+});++describe('rvc vs media tag time shift', () => {+ // The "most recent" comparison uses `rvcTime > mediaTagLastUpdate`, which is+ // the (odd) behavior of the original implementation. These inputs are chosen+ // so that branch is taken: rvcLastUpdate is truthy and rvcTime (0.5) is+ // greater than mediaTagLastUpdate (0).+ test('uses rvc time shift when it is more recent', () => {+ // media tag is on time, but rvc reports a big shift β should still trigger+ const action = getMediaSyncAction(+ makeInput({+ desiredUnclampedTime: 10,+ mediaTagTime: 10,+ mediaTagLastUpdate: 0,+ rvcTime: 0.5,+ rvcLastUpdate: 1,+ }),+ );+ expect(action.type).toBe('seek-due-to-shift');+ });++ test('ignores rvc time shift for variable fps videos', () => {+ const action = getMediaSyncAction(+ makeInput({+ desiredUnclampedTime: 10,+ mediaTagTime: 10,+ mediaTagLastUpdate: 0,+ rvcTime: 0.5,+ rvcLastUpdate: 1,+ isVariableFpsVideo: true,+ // media tag says on time, rvc ignored β no big shift+ currentTime: 10,+ }),+ );+ expect(action.type).not.toBe('seek-due-to-shift');+ });+});++describe('seek-if-not-playing', () => {+ test('when not playing and above the seek threshold', () => {+ const action = getMediaSyncAction(+ makeInput({playing: false, currentTime: 0, mediaTagTime: 5}),+ );+ expect(action.type).toBe('seek-if-not-playing');+ if (action.type === 'seek-if-not-playing') {+ expect(action.why).not.toBe(null);+ expect(action.shouldBeTime).toBe(5);+ }+ });++ test('does not seek when within the (paused) threshold', () => {+ const action = getMediaSyncAction(+ makeInput({+ playing: false,+ currentTime: 5,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ }),+ );+ expect(action.type).toBe('seek-if-not-playing');+ if (action.type === 'seek-if-not-playing') {+ expect(action.why).toBe(null);+ }+ });++ test('when playing but something else is buffering', () => {+ const action = getMediaSyncAction(+ makeInput({+ playing: true,+ playerBuffering: true,+ mediaTagBufferingOrStalled: false,+ currentTime: 0,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ }),+ );+ expect(action.type).toBe('seek-if-not-playing');+ });+});++describe('none', () => {+ test('playing, on time, not paused, not first frame', () => {+ const action = getMediaSyncAction(+ makeInput({currentTime: 5, desiredUnclampedTime: 5, mediaTagTime: 5}),+ );+ expect(action.type).toBe('none');+ });++ test('playing and player buffering while media tag is also buffering', () => {+ const action = getMediaSyncAction(+ makeInput({+ playing: true,+ playerBuffering: true,+ mediaTagBufferingOrStalled: true,+ currentTime: 5,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ }),+ );+ expect(action.type).toBe('none');+ });+});++describe('play-and-seek', () => {+ test('playing but media tag is paused', () => {+ const action = getMediaSyncAction(+ makeInput({+ playing: true,+ paused: true,+ ended: false,+ currentTime: 5,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ }),+ );+ expect(action.type).toBe('play-and-seek');+ if (action.type === 'play-and-seek') {+ expect(action.playReason).toBe(+ 'player is playing and media tag is paused',+ );+ // within threshold β no seek+ expect(action.why).toBe(null);+ expect(action.bufferUntilFirstFrame).toBe(true);+ }+ });++ test('playing on the first absolute frame', () => {+ const action = getMediaSyncAction(+ makeInput({+ playing: true,+ paused: false,+ absoluteFrame: 0,+ currentTime: 5,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ }),+ );+ expect(action.type).toBe('play-and-seek');+ if (action.type === 'play-and-seek') {+ expect(action.playReason).toBe(+ 'player is playing and absolute frame is 0',+ );+ }+ });++ test('seeks and does not buffer for variable fps videos', () => {+ const action = getMediaSyncAction(+ makeInput({+ playing: true,+ paused: true,+ absoluteFrame: 30,+ isVariableFpsVideo: true,+ currentTime: 0,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ }),+ );+ expect(action.type).toBe('play-and-seek');+ if (action.type === 'play-and-seek') {+ expect(action.why).not.toBe(null);+ expect(action.bufferUntilFirstFrame).toBe(false);+ }+ });++ test('does not buffer when playback rate is 0', () => {+ const action = getMediaSyncAction(+ makeInput({+ playing: true,+ paused: true,+ playbackRate: 0,+ currentTime: 5,+ desiredUnclampedTime: 5,+ mediaTagTime: 5,+ }),+ );+ expect(action.type).toBe('play-and-seek');+ if (action.type === 'play-and-seek') {+ expect(action.bufferUntilFirstFrame).toBe(false);+ }+ });+});diff --git a/packages/core/src/use-media-playback.ts b/packages/core/src/use-media-playback.tsindex 9cfffeac34..2c80e83cc8 100644--- a/packages/core/src/use-media-playback.ts+++ b/packages/core/src/use-media-playback.ts@@ -9,6 +9,7 @@ import {import {useMediaStartsAt} from './audio/use-audio-frame.js';import {useBufferUntilFirstFrame} from './buffer-until-first-frame.js';import {BufferingContextReact, useIsPlayerBuffering} from './buffering.js';+import {getMediaSyncAction} from './get-media-sync-action.js';import {useLogLevel, useMountTime} from './log-level-context.js';import {Log} from './log.js';import {useCurrentTimeOfMediaTagWithUpdateTimeStamp} from './media-tag-current-time-timestamp.js';@@ -223,136 +224,105 @@ export const useMediaPlayback = ({);}- const {duration} = mediaRef.current;- const shouldBeTime =- !Number.isNaN(duration) && Number.isFinite(duration)- ? Math.min(duration, desiredUnclampedTime)- : desiredUnclampedTime;-- const mediaTagTime = mediaTagCurrentTime.current.time;- const rvcTime = rvcCurrentTime.current?.time ?? null;-- const isVariableFpsVideo = isVariableFpsVideoMap.current[src];-- const timeShiftMediaTag = Math.abs(shouldBeTime - mediaTagTime);- const timeShiftRvcTag = rvcTime ? Math.abs(shouldBeTime - rvcTime) : null;-- const mostRecentTimeshift =- rvcCurrentTime.current?.lastUpdate &&- rvcCurrentTime.current.time > mediaTagCurrentTime.current.lastUpdate- ? (timeShiftRvcTag as number)- : timeShiftMediaTag;-- const timeShift =- timeShiftRvcTag && !isVariableFpsVideo- ? mostRecentTimeshift- : timeShiftMediaTag;-- if (- timeShift > acceptableTimeShiftButLessThanDuration &&- lastSeekDueToShift.current !== shouldBeTime- ) {- // If scrubbing around, adjust timing- // or if time shift is bigger than 0.45sec+ const {current} = mediaRef;++ const action = getMediaSyncAction({+ duration: current.duration,+ currentTime: current.currentTime,+ paused: current.paused,+ ended: current.ended,+ desiredUnclampedTime,+ mediaTagTime: mediaTagCurrentTime.current.time,+ mediaTagLastUpdate: mediaTagCurrentTime.current.lastUpdate,+ rvcTime: rvcCurrentTime.current?.time ?? null,+ rvcLastUpdate: rvcCurrentTime.current?.lastUpdate ?? null,+ isVariableFpsVideo: Boolean(isVariableFpsVideoMap.current[src]),+ acceptableTimeShift: acceptableTimeShiftButLessThanDuration,+ lastSeekDueToShift: lastSeekDueToShift.current,+ playing,+ playbackRate,+ mediaTagBufferingOrStalled: isMediaTagBuffering || isBuffering(),+ playerBuffering: buffering.buffering.current,+ absoluteFrame,+ onlyWarnForMediaSeekingError,+ isPremounting,+ isPostmounting,+ pauseWhenBuffering,+ });++ if (action.type === 'none') {+ return;+ }+ if (action.type === 'seek-due-to-shift') {lastSeek.current = seek({- mediaRef: mediaRef.current,- time: shouldBeTime,+ mediaRef: current,+ time: action.shouldBeTime,logLevel,- why: `because time shift is too big. shouldBeTime = ${shouldBeTime}, isTime = ${mediaTagTime}, requestVideoCallbackTime = ${rvcTime}, timeShift = ${timeShift}${isVariableFpsVideo ? ', isVariableFpsVideo = true' : ''}, isPremounting = ${isPremounting}, isPostmounting = ${isPostmounting}, pauseWhenBuffering = ${pauseWhenBuffering}`,+ why: action.why,mountTime,});lastSeekDueToShift.current = lastSeek.current;- if (playing) {- if (playbackRate > 0) {- bufferUntilFirstFrame(shouldBeTime);- }-- if (mediaRef.current.paused) {- playAndHandleNotAllowedError({- mediaRef,- mediaType,- onAutoPlayError,- logLevel,- mountTime,- reason:- 'player is playing but media tag is paused, and just seeked',- isPlayer: env.isPlayer,- });- }- }- if (!onlyWarnForMediaSeekingError) {- warnAboutNonSeekableMedia(- mediaRef.current,- onlyWarnForMediaSeekingError ? 'console-warning' : 'console-error',- );+ if (action.bufferUntilFirstFrame) {+ bufferUntilFirstFrame(action.shouldBeTime);}- return;- }-- const seekThreshold = playing ? 0.15 : 0.01;-- // Only perform a seek if the time is not already the same.- // Chrome rounds to 6 digits, so 0.033333333 -> 0.033333,- // therefore a threshold is allowed.- // Refer to the https://github.com/remotion-dev/video-buffering-example- // which is fixed by only seeking conditionally.- const makesSenseToSeek =- Math.abs(mediaRef.current.currentTime - shouldBeTime) > seekThreshold;-- const isMediaTagBufferingOrStalled = isMediaTagBuffering || isBuffering();- const isSomethingElseBuffering =- buffering.buffering.current && !isMediaTagBufferingOrStalled;-- if (!playing || isSomethingElseBuffering) {- if (makesSenseToSeek) {- lastSeek.current = seek({- mediaRef: mediaRef.current,- time: shouldBeTime,+ if (action.playReason !== null) {+ playAndHandleNotAllowedError({+ mediaRef,+ mediaType,+ onAutoPlayError,logLevel,- why: `not playing or something else is buffering. time offset is over seek threshold (${seekThreshold})`,mountTime,+ reason: action.playReason,+ isPlayer: env.isPlayer,});}- return;- }+ if (action.warnAboutNonSeekable) {+ warnAboutNonSeekableMedia(current, 'console-error');+ }- if (!playing || buffering.buffering.current) {return;}- // We now assured we are in playing state and not buffering- const pausedCondition = mediaRef.current.paused && !mediaRef.current.ended;- const firstFrameCondition = absoluteFrame === 0;- if (pausedCondition || firstFrameCondition) {- const reason = pausedCondition- ? 'media tag is paused'- : 'absolute frame is 0';- if (makesSenseToSeek) {+ if (action.type === 'seek-if-not-playing') {+ if (action.why !== null) {lastSeek.current = seek({- mediaRef: mediaRef.current,- time: shouldBeTime,+ mediaRef: current,+ time: action.shouldBeTime,logLevel,- why: `is over timeshift threshold (threshold = ${seekThreshold}) and ${reason}`,+ why: action.why,mountTime,});}- playAndHandleNotAllowedError({- mediaRef,- mediaType,- onAutoPlayError,+ return;+ }++ // action.type === 'play-and-seek'+ if (action.why !== null) {+ lastSeek.current = seek({+ mediaRef: current,+ time: action.shouldBeTime,logLevel,+ why: action.why,mountTime,- reason: `player is playing and ${reason}`,- isPlayer: env.isPlayer,});- if (!isVariableFpsVideo && playbackRate > 0) {- bufferUntilFirstFrame(shouldBeTime);- }+ }++ playAndHandleNotAllowedError({+ mediaRef,+ mediaType,+ onAutoPlayError,+ logLevel,+ mountTime,+ reason: action.playReason,+ isPlayer: env.isPlayer,+ });+ if (action.bufferUntilFirstFrame) {+ bufferUntilFirstFrame(action.shouldBeTime);}}, [absoluteFrame,