Skip to content

🎥 Make videos programmatically with React

work on seek request

Jonny Burgerc2971cac1e90
diff --git a/packages/media-parser/src/containers/iso-base-media/get-seeking-from-mp4.ts b/packages/media-parser/src/containers/iso-base-media/get-seeking-from-mp4.ts
index 0471fec035..39f6c2947e 100644
--- a/packages/media-parser/src/containers/iso-base-media/get-seeking-from-mp4.ts
+++ b/packages/media-parser/src/containers/iso-base-media/get-seeking-from-mp4.ts
@@ -2,6 +2,11 @@ import {getTracksFromMoovBox} from '../../get-tracks';
import type {LogLevel} from '../../log';
import {Log} from '../../log';
import type {IsoBaseMediaSeekingInfo} from '../../seeking-info';
+import {
+ getCurrentVideoSection,
+ isByteInVideoSection,
+} from '../../state/video-section';
+import type {SeekResolution} from '../../work-on-seek-request';
import {collectSamplePositionsFromMoofBoxes} from './collect-sample-positions-from-moof-boxes';
import {findKeyframeBeforeTime} from './find-keyframe-before-time';
import {getSamplePositionBounds} from './get-sample-position-bounds';
@@ -13,11 +18,13 @@ export const getSeekingByteFromIsoBaseMedia = ({
info,
time,
logLevel,
+ currentPosition,
}: {
info: IsoBaseMediaSeekingInfo;
time: number;
logLevel: LogLevel;
-}) => {
+ currentPosition: number;
+}): SeekResolution => {
const tracks = getTracksFromMoovBox(info.moovBox);
const allTracks = [
...tracks.videoTracks,
@@ -57,22 +64,53 @@ export const getSeekingByteFromIsoBaseMedia = ({
logLevel,
`Fragmented MP4 - Found that we have seeking info for this time range: ${min} <= ${time} <= ${max}`,
);
- return findKeyframeBeforeTime({
+ const kf = findKeyframeBeforeTime({
samplePositions: positions,
time,
timescale,
logLevel,
videoSections: info.videoSections,
});
+ if (kf) {
+ return {
+ type: 'do-seek',
+ byte: kf,
+ };
+ }
}
}
Log.trace(
logLevel,
- 'Fragmented MP4 - No seeking info found for this time range. Not returning a byte',
+ 'Fragmented MP4 - No seeking info found for this time range.',
);
+ if (
+ isByteInVideoSection({
+ position: currentPosition,
+ videoSections: info.videoSections,
+ }) === 'in-section'
+ ) {
+ Log.trace(
+ logLevel,
+ 'Fragmented MP4 - Inside the wrong video section, skipping to the end of the section',
+ );
+ const videoSection = getCurrentVideoSection({
+ offset: currentPosition,
+ videoSections: info.videoSections,
+ });
+ if (!videoSection) {
+ throw new Error('No video section defined');
+ }
+
+ return {
+ type: 'intermediary-seek',
+ byte: videoSection.start + videoSection.size,
+ };
+ }
- return null;
+ return {
+ type: 'valid-but-must-wait',
+ };
}
const {samplePositions, isComplete} = getSamplePositionsFromTrack({
@@ -85,11 +123,22 @@ export const getSeekingByteFromIsoBaseMedia = ({
throw new Error('Incomplete sample positions');
}
- return findKeyframeBeforeTime({
+ const keyframe = findKeyframeBeforeTime({
samplePositions,
time,
timescale,
logLevel,
videoSections: info.videoSections,
});
+
+ if (keyframe) {
+ return {
+ type: 'do-seek',
+ byte: keyframe,
+ };
+ }
+
+ return {
+ type: 'invalid',
+ };
};
diff --git a/packages/media-parser/src/containers/iso-base-media/mdat/mdat.ts b/packages/media-parser/src/containers/iso-base-media/mdat/mdat.ts
index a8531a8c1a..4d2c1a4a19 100644
--- a/packages/media-parser/src/containers/iso-base-media/mdat/mdat.ts
+++ b/packages/media-parser/src/containers/iso-base-media/mdat/mdat.ts
@@ -7,14 +7,16 @@ import type {FlatSample} from '../../../state/iso-base-media/cached-sample-posit
import {calculateFlatSamples} from '../../../state/iso-base-media/cached-sample-positions';
import {maySkipVideoData} from '../../../state/may-skip-video-data';
import type {ParserState} from '../../../state/parser-state';
+import {getCurrentVideoSection} from '../../../state/video-section';
import {getMoovAtom} from '../get-moov-atom';
export const parseMdatSection = async (
state: ParserState,
): Promise<Skip | null> => {
- const videoSection = state.videoSection.getCurrentVideoSection(
- state.iterator.counter.getOffset(),
- );
+ const videoSection = getCurrentVideoSection({
+ offset: state.iterator.counter.getOffset(),
+ videoSections: state.videoSection.getVideoSections(),
+ });
if (!videoSection) {
throw new Error('No video section defined');
}
diff --git a/packages/media-parser/src/containers/riff/parse-riff-body.ts b/packages/media-parser/src/containers/riff/parse-riff-body.ts
index 6a870494d5..eaaef56763 100644
--- a/packages/media-parser/src/containers/riff/parse-riff-body.ts
+++ b/packages/media-parser/src/containers/riff/parse-riff-body.ts
@@ -2,6 +2,7 @@ import type {ParseResult} from '../../parse-result';
import {makeSkip} from '../../skip';
import {maySkipVideoData} from '../../state/may-skip-video-data';
import type {ParserState} from '../../state/parser-state';
+import {getCurrentVideoSection} from '../../state/video-section';
import {expectRiffBox} from './expect-riff-box';
import {parseVideoSection} from './parse-video-section';
@@ -18,9 +19,10 @@ export const parseRiffBody = async (
}) &&
state.riff.getAvcProfile()
) {
- const videoSection = state.videoSection.getCurrentVideoSection(
- state.iterator.counter.getOffset(),
- );
+ const videoSection = getCurrentVideoSection({
+ offset: state.iterator.counter.getOffset(),
+ videoSections: state.videoSection.getVideoSections(),
+ });
if (!videoSection) {
throw new Error('No video section defined');
}
diff --git a/packages/media-parser/src/containers/wav/parse-video-section.ts b/packages/media-parser/src/containers/wav/parse-video-section.ts
index 5951ac305d..9bd3b817a3 100644
--- a/packages/media-parser/src/containers/wav/parse-video-section.ts
+++ b/packages/media-parser/src/containers/wav/parse-video-section.ts
@@ -2,6 +2,7 @@ import {convertAudioOrVideoSampleToWebCodecsTimestamps} from '../../convert-audi
import {emitAudioSample} from '../../emit-audio-sample';
import type {ParseResult} from '../../parse-result';
import type {ParserState} from '../../state/parser-state';
+import {getCurrentVideoSection} from '../../state/video-section';
import type {WavFmt} from './types';
export const parseVideoSection = async ({
@@ -12,9 +13,10 @@ export const parseVideoSection = async ({
const {iterator} = state;
const structure = state.getWavStructure();
- const videoSection = state.videoSection.getCurrentVideoSection(
- iterator.counter.getOffset(),
- );
+ const videoSection = getCurrentVideoSection({
+ offset: iterator.counter.getOffset(),
+ videoSections: state.videoSection.getVideoSections(),
+ });
if (!videoSection) {
throw new Error('No video section defined');
}
diff --git a/packages/media-parser/src/controller/media-parser-controller.ts b/packages/media-parser/src/controller/media-parser-controller.ts
index c0781b033d..423e149b28 100644
--- a/packages/media-parser/src/controller/media-parser-controller.ts
+++ b/packages/media-parser/src/controller/media-parser-controller.ts
@@ -2,6 +2,8 @@ import {MediaParserAbortError} from '../errors';
import {MediaParserEmitter} from './emitter';
import type {PauseSignal} from './pause-signal';
import {makePauseSignal} from './pause-signal';
+import type {PerformedSeeksSignal} from './performed-seeks-stats';
+import {performedSeeksStats} from './performed-seeks-stats';
import type {SeekSignal} from './seek-signal';
import {makeSeekSignal} from './seek-signal';
@@ -21,6 +23,7 @@ export type MediaParserController = {
checkForAbortAndPause: () => Promise<void>;
seekSignal: SeekSignal;
markAsReadyToEmitEvents: () => void;
+ performedSeeksSignal: PerformedSeeksSignal;
};
};
@@ -29,6 +32,7 @@ export const mediaParserController = (): MediaParserController => {
const emitter = new MediaParserEmitter();
const pauseSignal = makePauseSignal(emitter);
const seekSignal = makeSeekSignal(emitter);
+ const performedSeeksSignal = performedSeeksStats();
const checkForAbortAndPause = async () => {
if (abortController.signal.aborted) {
@@ -54,6 +58,7 @@ export const mediaParserController = (): MediaParserController => {
checkForAbortAndPause,
seekSignal,
markAsReadyToEmitEvents: emitter.markAsReady,
+ performedSeeksSignal,
},
};
};
diff --git a/packages/media-parser/src/controller/performed-seeks-stats.ts b/packages/media-parser/src/controller/performed-seeks-stats.ts
new file mode 100644
index 0000000000..0e2e0a94ad
--- /dev/null
+++ b/packages/media-parser/src/controller/performed-seeks-stats.ts
@@ -0,0 +1,20 @@
+export type PerformedSeek = {
+ from: number;
+ to: number;
+ type: 'user-initiated' | 'internal';
+};
+
+export const performedSeeksStats = () => {
+ const performedSeeks: PerformedSeek[] = [];
+
+ return {
+ recordSeek: (seek: PerformedSeek) => {
+ performedSeeks.push(seek);
+ },
+ getPerformedSeeks: () => {
+ return performedSeeks;
+ },
+ };
+};
+
+export type PerformedSeeksSignal = ReturnType<typeof performedSeeksStats>;
diff --git a/packages/media-parser/src/controller/seek-signal.ts b/packages/media-parser/src/controller/seek-signal.ts
index 1d3279039c..01608883fb 100644
--- a/packages/media-parser/src/controller/seek-signal.ts
+++ b/packages/media-parser/src/controller/seek-signal.ts
@@ -10,6 +10,7 @@ type SeekToTime = {
type: 'keyframe-before-time-in-seconds';
time: number;
};
+
type SeekToByte = {
type: 'byte';
byte: number;
diff --git a/packages/media-parser/src/get-seeking-info.ts b/packages/media-parser/src/get-seeking-info.ts
index 51354ee3c6..c02f138c2c 100644
--- a/packages/media-parser/src/get-seeking-info.ts
+++ b/packages/media-parser/src/get-seeking-info.ts
@@ -3,6 +3,7 @@ import {getSeekingInfoFromMp4} from './containers/iso-base-media/get-seeking-inf
import type {LogLevel} from './log';
import type {SeekingInfo} from './seeking-info';
import type {ParserState} from './state/parser-state';
+import type {SeekResolution} from './work-on-seek-request';
export const getSeekingInfo = (state: ParserState): SeekingInfo | null => {
const structure = state.getStructureOrNull();
@@ -22,13 +23,20 @@ export const getSeekingByte = ({
info,
time,
logLevel,
+ currentPosition,
}: {
info: SeekingInfo;
time: number;
logLevel: LogLevel;
-}): number | null => {
+ currentPosition: number;
+}): SeekResolution => {
if (info.type === 'iso-base-media-seeking-info') {
- return getSeekingByteFromIsoBaseMedia({info, time, logLevel});
+ return getSeekingByteFromIsoBaseMedia({
+ info,
+ time,
+ logLevel,
+ currentPosition,
+ });
}
throw new Error(`Unknown seeking info type: ${info.type as never}`);
diff --git a/packages/media-parser/src/perform-seek.ts b/packages/media-parser/src/perform-seek.ts
index a1923cbb60..1da27a51b9 100644
--- a/packages/media-parser/src/perform-seek.ts
+++ b/packages/media-parser/src/perform-seek.ts
@@ -2,6 +2,7 @@ import {Log} from './log';
import {seekBackwards} from './seek-backwards';
import {seekForward} from './seek-forwards';
import type {ParserState} from './state/parser-state';
+import {isByteInVideoSection} from './state/video-section';
export const performSeek = async ({
seekTo,
@@ -19,9 +20,13 @@ export const performSeek = async ({
contentLength,
seekInfiniteLoop,
videoSection,
+ controller,
} = state;
- const byteInVideoSection = videoSection.isByteInVideoSection(seekTo);
+ const byteInVideoSection = isByteInVideoSection({
+ position: seekTo,
+ videoSections: videoSection.getVideoSections(),
+ });
if (byteInVideoSection !== 'in-section' && userInitiated) {
const sections = videoSection.getVideoSections();
const sectionStrings = sections.map((section) => {
@@ -57,7 +62,7 @@ export const performSeek = async ({
return;
}
- await state.controller?._internals.checkForAbortAndPause();
+ await controller._internals.checkForAbortAndPause();
const alreadyAtByte = iterator.counter.getOffset() === seekTo;
if (alreadyAtByte) {
@@ -66,6 +71,11 @@ export const performSeek = async ({
}
const skippingForward = seekTo > iterator.counter.getOffset();
+ controller._internals.performedSeeksSignal.recordSeek({
+ from: iterator.counter.getOffset(),
+ to: seekTo,
+ type: userInitiated ? 'user-initiated' : 'internal',
+ });
if (skippingForward) {
await seekForward({state, seekTo, userInitiated});
} else {
diff --git a/packages/media-parser/src/state/video-section.ts b/packages/media-parser/src/state/video-section.ts
index d18f491f24..b4ab4ffa6b 100644
--- a/packages/media-parser/src/state/video-section.ts
+++ b/packages/media-parser/src/state/video-section.ts
@@ -11,6 +11,42 @@ export type VideoSection = {
size: number;
};
+export const isByteInVideoSection = ({
+ position,
+ videoSections,
+}: {
+ position: number;
+ videoSections: VideoSection[];
+}): 'no-section-defined' | 'in-section' | 'outside-section' => {
+ if (videoSections.length === 0) {
+ return 'no-section-defined';
+ }
+
+ for (const section of videoSections) {
+ if (position >= section.start && position < section.start + section.size) {
+ return 'in-section';
+ }
+ }
+
+ return 'outside-section';
+};
+
+export const getCurrentVideoSection = ({
+ offset,
+ videoSections,
+}: {
+ offset: number;
+ videoSections: VideoSection[];
+}): VideoSection | null => {
+ for (const section of videoSections) {
+ if (offset >= section.start && offset < section.start + section.size) {
+ return section;
+ }
+ }
+
+ return null;
+};
+
export const videoSectionState = () => {
const videoSections: VideoSection[] = [];
@@ -31,37 +67,11 @@ export const videoSectionState = () => {
return videoSections;
};
- const isByteInVideoSection = (
- byte: number,
- ): 'no-section-defined' | 'in-section' | 'outside-section' => {
- if (videoSections.length === 0) {
- return 'no-section-defined';
- }
-
- for (const section of videoSections) {
- if (byte >= section.start && byte < section.start + section.size) {
- return 'in-section';
- }
- }
-
- return 'outside-section';
- };
-
const isCurrentByteInVideoSection = (
iterator: BufferIterator,
): 'no-section-defined' | 'in-section' | 'outside-section' => {
const offset = iterator.counter.getOffset();
- return isByteInVideoSection(offset);
- };
-
- const getCurrentVideoSection = (offset: number): VideoSection | null => {
- for (const section of videoSections) {
- if (offset >= section.start && offset < section.start + section.size) {
- return section;
- }
- }
-
- return null;
+ return isByteInVideoSection({position: offset, videoSections});
};
const getVideoSectionAssertOnlyOne = (): VideoSection => {
diff --git a/packages/media-parser/src/test/seeking/seek-moof.test.ts b/packages/media-parser/src/test/seeking/seek-moof.test.ts
index 2d2b7c2adf..dfb3648d48 100644
--- a/packages/media-parser/src/test/seeking/seek-moof.test.ts
+++ b/packages/media-parser/src/test/seeking/seek-moof.test.ts
@@ -40,5 +40,119 @@ test('seek moof', async () => {
throw new Error('should not reach here');
} catch (err) {
expect(hasBeenAborted(err)).toBe(true);
+ expect(
+ controller._internals.performedSeeksSignal.getPerformedSeeks(),
+ ).toEqual([
+ {
+ from: 2052,
+ to: 12482,
+ type: 'internal',
+ },
+ {
+ from: 12758,
+ to: 25532,
+ type: 'internal',
+ },
+ {
+ from: 25976,
+ to: 94095,
+ type: 'internal',
+ },
+ {
+ from: 94539,
+ to: 241735,
+ type: 'internal',
+ },
+ {
+ from: 242179,
+ to: 355739,
+ type: 'internal',
+ },
+ {
+ from: 356183,
+ to: 490611,
+ type: 'internal',
+ },
+ {
+ from: 491227,
+ to: 586370,
+ type: 'internal',
+ },
+ {
+ from: 586814,
+ to: 674532,
+ type: 'internal',
+ },
+ {
+ from: 674976,
+ to: 713330,
+ type: 'internal',
+ },
+ {
+ from: 713774,
+ to: 771926,
+ type: 'internal',
+ },
+ {
+ from: 772226,
+ to: 802392,
+ type: 'internal',
+ },
+ {
+ from: 802836,
+ to: 832655,
+ type: 'internal',
+ },
+ {
+ from: 833099,
+ to: 880227,
+ type: 'internal',
+ },
+ {
+ from: 880843,
+ to: 914385,
+ type: 'internal',
+ },
+ {
+ from: 914805,
+ to: 943825,
+ type: 'internal',
+ },
+ {
+ from: 944269,
+ to: 974849,
+ type: 'internal',
+ },
+ {
+ from: 975293,
+ to: 1020488,
+ type: 'internal',
+ },
+ {
+ from: 1020932,
+ to: 1064325,
+ type: 'internal',
+ },
+ {
+ from: 1064649,
+ to: 1094851,
+ type: 'internal',
+ },
+ {
+ from: 1095467,
+ to: 1133409,
+ type: 'internal',
+ },
+ {
+ from: 1133701,
+ to: 1162569,
+ type: 'internal',
+ },
+ {
+ from: 1163013,
+ to: 1214780,
+ type: 'internal',
+ },
+ ]);
}
});
diff --git a/packages/media-parser/src/test/seeking/seek-on-worker.test.ts b/packages/media-parser/src/test/seeking/seek-on-worker.test.ts
index a6d0b0cd2e..feaa34141c 100644
--- a/packages/media-parser/src/test/seeking/seek-on-worker.test.ts
+++ b/packages/media-parser/src/test/seeking/seek-on-worker.test.ts
@@ -1,7 +1,7 @@
import {exampleVideos} from '@remotion/example-videos';
import {expect, test} from 'bun:test';
+import {mediaParserController} from '../../controller/media-parser-controller';
import {hasBeenAborted} from '../../errors';
-import {mediaParserController} from '../../media-parser-controller';
import type {AudioOrVideoSample} from '../../webcodec-sample-types';
import {parseMediaOnServerWorker} from '../../worker.module';
diff --git a/packages/media-parser/src/test/worker.test.ts b/packages/media-parser/src/test/worker.test.ts
index 659c3f60f6..4d5a9f5a2e 100644
--- a/packages/media-parser/src/test/worker.test.ts
+++ b/packages/media-parser/src/test/worker.test.ts
@@ -1,7 +1,7 @@
import {exampleVideos} from '@remotion/example-videos';
import {expect, test} from 'bun:test';
+import {mediaParserController} from '../controller/media-parser-controller';
import {hasBeenAborted, IsAnImageError} from '../errors';
-import {mediaParserController} from '../media-parser-controller';
import {
parseMediaOnServerWorker,
parseMediaOnWebWorker,
diff --git a/packages/media-parser/src/work-on-seek-request.ts b/packages/media-parser/src/work-on-seek-request.ts
index 54fe5a9892..b0835c4e06 100644
--- a/packages/media-parser/src/work-on-seek-request.ts
+++ b/packages/media-parser/src/work-on-seek-request.ts
@@ -32,22 +32,10 @@ const turnSeekIntoByte = ({
info: seekingInfo,
time: seek.time,
logLevel: state.logLevel,
+ currentPosition: state.iterator.counter.getOffset(),
});
- if (!seekingByte) {
- Log.trace(
- state.logLevel,
- 'Could not calculate seeking byte, cannot seek yet',
- );
- return {
- type: 'valid-but-must-wait',
- };
- }
-
- return {
- type: 'do-seek',
- byte: seekingByte,
- };
+ return seekingByte;
}
if (seek.type === 'byte') {
@@ -72,6 +60,15 @@ export const workOnSeekRequest = async (state: ParserState) => {
const resolution = turnSeekIntoByte({seek, state});
Log.trace(state.logLevel, `Seek action: ${JSON.stringify(resolution)}`);
+ if (resolution.type === 'intermediary-seek') {
+ await performSeek({
+ state,
+ seekTo: resolution.byte,
+ userInitiated: false,
+ });
+ return;
+ }
+
if (resolution.type === 'do-seek') {
await performSeek({state, seekTo: resolution.byte, userInitiated: true});
const {hasChanged} =
@@ -101,13 +98,17 @@ export const workOnSeekRequest = async (state: ParserState) => {
}
};
-type SeekResolution =
+export type SeekResolution =
| {
type: 'valid-but-must-wait';
}
| {
type: 'invalid';
}
+ | {
+ type: 'intermediary-seek';
+ byte: number;
+ }
| {
type: 'do-seek';
byte: number;