Skip to content

🎥 Make videos programmatically with React

more efficient fetching of when a lot of more data is required

Jonny Burger49d30ba8cbd8
diff --git a/packages/media-parser/src/containers/iso-base-media/base-media-box.ts b/packages/media-parser/src/containers/iso-base-media/base-media-box.ts
index fd051514a8..44ef49c2b1 100644
--- a/packages/media-parser/src/containers/iso-base-media/base-media-box.ts
+++ b/packages/media-parser/src/containers/iso-base-media/base-media-box.ts
@@ -36,8 +36,6 @@ export interface RegularBox extends BaseBox {
type: 'regular-box';
}
-export type BoxAndNext = IsoBaseMediaBox | null;
-
export type IsoBaseMediaBox =
| RegularBox
| FtypBox
diff --git a/packages/media-parser/src/containers/iso-base-media/get-children.ts b/packages/media-parser/src/containers/iso-base-media/get-children.ts
index 1831dca6b1..b9503f697c 100644
--- a/packages/media-parser/src/containers/iso-base-media/get-children.ts
+++ b/packages/media-parser/src/containers/iso-base-media/get-children.ts
@@ -28,11 +28,11 @@ export const getIsoBaseMediaChildren = async ({
onlyIfMdatAtomExpected: null,
contentLength,
});
- if (!parsed) {
+ if (parsed.type !== 'box') {
throw new Error('Expected box');
}
- boxes.push(parsed);
+ boxes.push(parsed.box);
}
if (iterator.counter.getOffset() > size + initial) {
diff --git a/packages/media-parser/src/containers/iso-base-media/get-moov-atom.ts b/packages/media-parser/src/containers/iso-base-media/get-moov-atom.ts
index 1125462840..475f39c2a8 100644
--- a/packages/media-parser/src/containers/iso-base-media/get-moov-atom.ts
+++ b/packages/media-parser/src/containers/iso-base-media/get-moov-atom.ts
@@ -111,8 +111,8 @@ export const getMoovAtom = async ({
onlyIfMdatAtomExpected: null,
contentLength: state.contentLength - endOfMdat,
});
- if (box) {
- boxes.push(box);
+ if (box.type === 'box') {
+ boxes.push(box.box);
}
if (iterator.counter.getOffset() + endOfMdat > state.contentLength) {
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 2e6d734734..d87bce2ddd 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
@@ -1,7 +1,7 @@
import {convertAudioOrVideoSampleToWebCodecsTimestamps} from '../../../convert-audio-or-video-sample';
import {getHasTracks} from '../../../get-tracks';
-import type {Skip} from '../../../skip';
-import {makeSkip} from '../../../skip';
+import type {FetchMoreData, Skip} from '../../../skip';
+import {makeFetchMoreData, makeSkip} from '../../../skip';
import type {FlatSample} from '../../../state/iso-base-media/cached-sample-positions';
import {calculateFlatSamples} from '../../../state/iso-base-media/cached-sample-positions';
import {maySkipVideoData} from '../../../state/may-skip-video-data';
@@ -13,7 +13,7 @@ import {postprocessBytes} from './postprocess-bytes';
export const parseMdatSection = async (
state: ParserState,
-): Promise<Skip | null> => {
+): Promise<Skip | FetchMoreData | null> => {
const mediaSection = getCurrentMediaSection({
offset: state.iterator.counter.getOffset(),
mediaSections: state.mediaSection.getMediaSections(),
@@ -97,7 +97,9 @@ export const parseMdatSection = async (
// Need to fetch more data
if (iterator.bytesRemaining() < samplesWithIndex.samplePosition.size) {
- return null;
+ return makeFetchMoreData(
+ samplesWithIndex.samplePosition.size - iterator.bytesRemaining(),
+ );
}
const {cts, dts, duration, isKeyframe, offset, bigEndian, chunkSize} =
diff --git a/packages/media-parser/src/containers/iso-base-media/parse-boxes.ts b/packages/media-parser/src/containers/iso-base-media/parse-boxes.ts
index e93294dfe5..a6e563931e 100644
--- a/packages/media-parser/src/containers/iso-base-media/parse-boxes.ts
+++ b/packages/media-parser/src/containers/iso-base-media/parse-boxes.ts
@@ -32,8 +32,12 @@ export const parseIsoBaseMedia = async (
},
contentLength: state.contentLength,
});
- if (result) {
- state.structure.getIsoStructure().boxes.push(result);
+ if (result.type === 'fetch-more-data') {
+ return result.bytesNeeded;
+ }
+
+ if (result.type === 'box') {
+ state.structure.getIsoStructure().boxes.push(result.box);
}
return null;
diff --git a/packages/media-parser/src/containers/iso-base-media/process-box.ts b/packages/media-parser/src/containers/iso-base-media/process-box.ts
index 1b4ace9069..d974f5a315 100644
--- a/packages/media-parser/src/containers/iso-base-media/process-box.ts
+++ b/packages/media-parser/src/containers/iso-base-media/process-box.ts
@@ -2,12 +2,14 @@ import type {BufferIterator} from '../../iterator/buffer-iterator';
import type {LogLevel} from '../../log';
import {Log} from '../../log';
import {registerAudioTrack, registerVideoTrack} from '../../register-track';
+import type {FetchMoreData} from '../../skip';
+import {makeFetchMoreData} from '../../skip';
import type {TracksState} from '../../state/has-tracks-section';
import type {IsoBaseMediaState} from '../../state/iso-base-media/iso-state';
import type {CallbacksState} from '../../state/sample-callbacks';
import type {MediaSectionState} from '../../state/video-section';
import type {OnAudioTrack, OnVideoTrack} from '../../webcodec-sample-types';
-import type {BoxAndNext} from './base-media-box';
+import type {IsoBaseMediaBox} from './base-media-box';
import {parseEsds} from './esds/esds';
import {parseFtyp} from './ftyp';
import {getIsoBaseMediaChildren} from './get-children';
@@ -51,6 +53,19 @@ export type OnlyIfMdatAtomExpected = {
mediaSectionState: MediaSectionState;
};
+type ProcessBoxResult =
+ | {
+ type: 'box';
+ box: IsoBaseMediaBox;
+ }
+ | {
+ type: 'nothing';
+ }
+ | {
+ type: 'fetch-more-data';
+ bytesNeeded: FetchMoreData;
+ };
+
export const processBox = async ({
iterator,
logLevel,
@@ -63,7 +78,7 @@ export const processBox = async ({
onlyIfMoovAtomExpected: OnlyIfMoovAtomExpected | null;
onlyIfMdatAtomExpected: OnlyIfMdatAtomExpected | null;
contentLength: number;
-}): Promise<BoxAndNext> => {
+}): Promise<ProcessBoxResult> => {
const fileOffset = iterator.counter.getOffset();
const {returnToCheckpoint} = iterator.startCheckpoint();
const bytesRemaining = iterator.bytesRemaining();
@@ -73,8 +88,11 @@ export const processBox = async ({
if (boxSizeRaw === 0) {
return {
- type: 'void-box',
- boxSize: 0,
+ type: 'box',
+ box: {
+ type: 'void-box',
+ boxSize: 0,
+ },
};
}
@@ -98,7 +116,7 @@ export const processBox = async ({
if (boxType === 'mdat') {
if (!onlyIfMdatAtomExpected) {
- return null;
+ return {type: 'nothing'};
}
const {mediaSectionState} = onlyIfMdatAtomExpected;
@@ -107,132 +125,189 @@ export const processBox = async ({
start: iterator.counter.getOffset(),
});
- return null;
+ return {type: 'nothing'};
}
if (bytesRemaining < boxSize) {
returnToCheckpoint();
- return null;
+ return {
+ type: 'fetch-more-data',
+ bytesNeeded: makeFetchMoreData(boxSize - bytesRemaining),
+ };
}
if (boxType === 'ftyp') {
- return parseFtyp({iterator, size: boxSize, offset: fileOffset});
+ return {
+ type: 'box',
+ box: await parseFtyp({iterator, size: boxSize, offset: fileOffset}),
+ };
}
if (boxType === 'colr') {
- return parseColorParameterBox({
- iterator,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseColorParameterBox({
+ iterator,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'mvhd') {
- return parseMvhd({iterator, offset: fileOffset, size: boxSize});
+ return {
+ type: 'box',
+ box: await parseMvhd({iterator, offset: fileOffset, size: boxSize}),
+ };
}
if (boxType === 'tkhd') {
- return parseTkhd({iterator, offset: fileOffset, size: boxSize});
+ return {
+ type: 'box',
+ box: await parseTkhd({iterator, offset: fileOffset, size: boxSize}),
+ };
}
if (boxType === 'trun') {
- return parseTrun({iterator, offset: fileOffset, size: boxSize});
+ return {
+ type: 'box',
+ box: await parseTrun({iterator, offset: fileOffset, size: boxSize}),
+ };
}
if (boxType === 'tfdt') {
- return parseTfdt({iterator, size: boxSize, offset: fileOffset});
+ return {
+ type: 'box',
+ box: await parseTfdt({iterator, size: boxSize, offset: fileOffset}),
+ };
}
if (boxType === 'stsd') {
- return parseStsd({
- offset: fileOffset,
- size: boxSize,
- iterator,
- logLevel,
- contentLength,
- });
+ return {
+ type: 'box',
+ box: await parseStsd({
+ offset: fileOffset,
+ size: boxSize,
+ iterator,
+ logLevel,
+ contentLength,
+ }),
+ };
}
if (boxType === 'stsz') {
- return parseStsz({
- iterator,
- offset: fileOffset,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseStsz({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'stco' || boxType === 'co64') {
- return parseStco({
- iterator,
- offset: fileOffset,
- size: boxSize,
- mode64Bit: boxType === 'co64',
- });
+ return {
+ type: 'box',
+ box: await parseStco({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ mode64Bit: boxType === 'co64',
+ }),
+ };
}
if (boxType === 'pasp') {
- return parsePasp({
- iterator,
- offset: fileOffset,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parsePasp({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'stss') {
- return parseStss({
- iterator,
- offset: fileOffset,
- boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseStss({
+ iterator,
+ offset: fileOffset,
+ boxSize,
+ }),
+ };
}
if (boxType === 'ctts') {
- return parseCtts({
- iterator,
- offset: fileOffset,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseCtts({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'stsc') {
- return parseStsc({
- iterator,
- offset: fileOffset,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseStsc({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'mebx') {
- return parseMebx({
- offset: fileOffset,
- size: boxSize,
- iterator,
- logLevel,
- contentLength,
- });
+ return {
+ type: 'box',
+ box: await parseMebx({
+ offset: fileOffset,
+ size: boxSize,
+ iterator,
+ logLevel,
+ contentLength,
+ }),
+ };
}
if (boxType === 'hdlr') {
- return parseHdlr({iterator, size: boxSize, offset: fileOffset});
+ return {
+ type: 'box',
+ box: await parseHdlr({iterator, size: boxSize, offset: fileOffset}),
+ };
}
if (boxType === 'keys') {
- return parseKeys({iterator, size: boxSize, offset: fileOffset});
+ return {
+ type: 'box',
+ box: await parseKeys({iterator, size: boxSize, offset: fileOffset}),
+ };
}
if (boxType === 'ilst') {
- return parseIlstBox({
- iterator,
- offset: fileOffset,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseIlstBox({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'tfra') {
- return parseTfraBox({
- iterator,
- offset: fileOffset,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseTfraBox({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'moov') {
@@ -243,7 +318,7 @@ export const processBox = async ({
const {tracks, isoState} = onlyIfMoovAtomExpected;
if (tracks.hasAllTracks()) {
iterator.discard(boxSize - 8);
- return null;
+ return {type: 'nothing'};
}
if (
@@ -253,7 +328,7 @@ export const processBox = async ({
) {
Log.verbose(logLevel, 'Moov box already parsed, skipping');
iterator.discard(boxSize - 8);
- return null;
+ return {type: 'nothing'};
}
const box = await parseMoov({
@@ -267,7 +342,7 @@ export const processBox = async ({
tracks.setIsDone(logLevel);
- return box;
+ return {type: 'box', box};
}
if (boxType === 'trak') {
@@ -310,61 +385,82 @@ export const processBox = async ({
});
}
- return box;
+ return {type: 'box', box};
}
if (boxType === 'stts') {
- return parseStts({
- data: iterator,
- size: boxSize,
- fileOffset,
- });
+ return {
+ type: 'box',
+ box: await parseStts({
+ data: iterator,
+ size: boxSize,
+ fileOffset,
+ }),
+ };
}
if (boxType === 'avcC') {
- return parseAvcc({
- data: iterator,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseAvcc({
+ data: iterator,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'av1C') {
- return parseAv1C({
- data: iterator,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await parseAv1C({
+ data: iterator,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'hvcC') {
- return parseHvcc({
- data: iterator,
- size: boxSize,
- offset: fileOffset,
- });
+ return {
+ type: 'box',
+ box: await parseHvcc({
+ data: iterator,
+ size: boxSize,
+ offset: fileOffset,
+ }),
+ };
}
if (boxType === 'tfhd') {
- return getTfhd({
- iterator,
- offset: fileOffset,
- size: boxSize,
- });
+ return {
+ type: 'box',
+ box: await getTfhd({
+ iterator,
+ offset: fileOffset,
+ size: boxSize,
+ }),
+ };
}
if (boxType === 'mdhd') {
- return parseMdhd({
- data: iterator,
- size: boxSize,
- fileOffset,
- });
+ return {
+ type: 'box',
+ box: await parseMdhd({
+ data: iterator,
+ size: boxSize,
+ fileOffset,
+ }),
+ };
}
if (boxType === 'esds') {
- return parseEsds({
- data: iterator,
- size: boxSize,
- fileOffset,
- });
+ return {
+ type: 'box',
+ box: await parseEsds({
+ data: iterator,
+ size: boxSize,
+ fileOffset,
+ }),
+ };
}
if (boxType === 'moof') {
@@ -393,21 +489,27 @@ export const processBox = async ({
});
return {
- type: 'regular-box',
- boxType,
- boxSize,
- children,
- offset: fileOffset,
+ type: 'box',
+ box: {
+ type: 'regular-box',
+ boxType,
+ boxSize,
+ children,
+ offset: fileOffset,
+ },
};
}
iterator.discard(boxSize - 8);
return {
- type: 'regular-box',
- boxType,
- boxSize,
- children: [],
- offset: fileOffset,
+ type: 'box',
+ box: {
+ type: 'regular-box',
+ boxType,
+ boxSize,
+ children: [],
+ offset: fileOffset,
+ },
};
};
diff --git a/packages/media-parser/src/containers/iso-base-media/stsd/samples.ts b/packages/media-parser/src/containers/iso-base-media/stsd/samples.ts
index 1953f99790..b680128c9a 100644
--- a/packages/media-parser/src/containers/iso-base-media/stsd/samples.ts
+++ b/packages/media-parser/src/containers/iso-base-media/stsd/samples.ts
@@ -118,6 +118,7 @@ const audioTags = [
'.mp3',
'mp4a',
'ac-3',
+ 'Opus',
];
export const processIsoFormatBox = async ({
diff --git a/packages/media-parser/src/get-audio-codec.ts b/packages/media-parser/src/get-audio-codec.ts
index 156936287b..e0b41914c0 100644
--- a/packages/media-parser/src/get-audio-codec.ts
+++ b/packages/media-parser/src/get-audio-codec.ts
@@ -305,6 +305,10 @@ const getAudioCodecFromAudioCodecInfo = (
return 'ac3';
}
+ if (codec.format === 'Opus') {
+ return 'opus';
+ }
+
if (codec.format === 'mp4a') {
if (codec.primarySpecificator === 0x40) {
return 'aac';
diff --git a/packages/media-parser/src/parse-loop.ts b/packages/media-parser/src/parse-loop.ts
index 1198f5123d..d0506f28c1 100644
--- a/packages/media-parser/src/parse-loop.ts
+++ b/packages/media-parser/src/parse-loop.ts
@@ -78,17 +78,40 @@ export const parseLoop = async ({
await triggerInfoEmit(state);
await state.controller._internals.checkForAbortAndPause();
- const skip = await runParseIteration({
+ const result = await runParseIteration({
state,
});
- if (skip !== null) {
+ if (result !== null && result.action === 'fetch-more-data') {
+ Log.verbose(
+ state.logLevel,
+ `Need to fetch ${result.bytesNeeded} more bytes before we can continue`,
+ );
+ const startBytesRemaining = state.iterator.bytesRemaining();
+ while (true) {
+ const done = await fetchMoreData(state);
+ if (done) {
+ break;
+ }
+
+ if (
+ state.iterator.bytesRemaining() - startBytesRemaining >=
+ result.bytesNeeded
+ ) {
+ break;
+ }
+ }
+
+ continue;
+ }
+
+ if (result !== null && result.action === 'skip') {
state.increaseSkippedBytes(
- skip.skipTo - state.iterator.counter.getOffset(),
+ result.skipTo - state.iterator.counter.getOffset(),
);
- if (skip.skipTo === state.contentLength) {
+ if (result.skipTo === state.contentLength) {
state.iterator.discard(
- skip.skipTo - state.iterator.counter.getOffset(),
+ result.skipTo - state.iterator.counter.getOffset(),
);
Log.verbose(
state.logLevel,
@@ -99,7 +122,7 @@ export const parseLoop = async ({
const seekStart = Date.now();
await performSeek({
- seekTo: skip.skipTo,
+ seekTo: result.skipTo,
userInitiated: false,
controller: state.controller,
mediaSection: state.mediaSection,
diff --git a/packages/media-parser/src/parse-result.ts b/packages/media-parser/src/parse-result.ts
index 345c82445b..8a62f2820b 100644
--- a/packages/media-parser/src/parse-result.ts
+++ b/packages/media-parser/src/parse-result.ts
@@ -7,7 +7,7 @@ import type {TransportStreamBox} from './containers/transport-stream/boxes';
import type {WavStructure} from './containers/wav/types';
import type {MatroskaSegment} from './containers/webm/segments';
import type {MediaParserMetadataEntry} from './metadata/get-metadata';
-import type {Skip} from './skip';
+import type {FetchMoreData, Skip} from './skip';
type Mp3Id3Header = {
type: 'id3-header';
@@ -57,4 +57,4 @@ export type MediaParserStructureUnstable =
| M3uStructure
| FlacStructure;
-export type ParseResult = Skip | null;
+export type ParseResult = Skip | FetchMoreData | null;
diff --git a/packages/media-parser/src/skip.ts b/packages/media-parser/src/skip.ts
index 675c5b5fe7..8314d19d16 100644
--- a/packages/media-parser/src/skip.ts
+++ b/packages/media-parser/src/skip.ts
@@ -7,3 +7,13 @@ export const makeSkip = (skipTo: number): Skip => ({
action: 'skip',
skipTo,
});
+
+export type FetchMoreData = {
+ action: 'fetch-more-data';
+ bytesNeeded: number;
+};
+
+export const makeFetchMoreData = (bytesNeeded: number): FetchMoreData => ({
+ action: 'fetch-more-data',
+ bytesNeeded,
+});
diff --git a/packages/media-parser/src/test/very-big-mp4.test.ts b/packages/media-parser/src/test/very-big-mp4.test.ts
index a164590a38..7892bf5ca6 100644
--- a/packages/media-parser/src/test/very-big-mp4.test.ts
+++ b/packages/media-parser/src/test/very-big-mp4.test.ts
@@ -7,24 +7,37 @@ beforeAll(async () => {
await getRemoteExampleVideo('largeStsd');
});
-test('should process the stsd of a 2 hour long video', async () => {
- let videoSamples = 0;
+test(
+ 'should process the stsd of a 2 hour long video',
+ async () => {
+ let videoSamples = 0;
+ let audioSamples = 0;
- const {durationInSeconds} = await parseMedia({
- // Video is cropped to only the first few frames
- src: await getRemoteExampleVideo('largeStsd'),
- reader: nodeReader,
- fields: {
- durationInSeconds: true,
- },
- acknowledgeRemotionLicense: true,
- onVideoTrack: () => {
- return () => {
- videoSamples++;
- };
- },
- });
+ const {durationInSeconds} = await parseMedia({
+ // Video is cropped to only the first few frames
+ src: await getRemoteExampleVideo('largeStsd'),
+ reader: nodeReader,
+ fields: {
+ durationInSeconds: true,
+ },
+ acknowledgeRemotionLicense: true,
+ onVideoTrack: () => {
+ return () => {
+ videoSamples++;
+ };
+ },
+ onAudioTrack: () => {
+ return () => {
+ audioSamples++;
+ };
+ },
+ });
- expect(videoSamples).toBe(6);
- expect(durationInSeconds).toBe(22947.121);
-});
+ expect(videoSamples).toBe(6);
+ expect(audioSamples).toBe(11);
+ expect(durationInSeconds).toBe(22947.121);
+ },
+ {
+ timeout: 10000,
+ },
+);