Skip to content

πŸŽ₯ Make videos programmatically with React

base media refactor going well

Jonny Burger59f0d4dde653
diff --git a/packages/media-parser/src/boxes/iso-base-media/get-children.ts b/packages/media-parser/src/boxes/iso-base-media/get-children.ts
index 09ca91d12f..d26e643510 100644
--- a/packages/media-parser/src/boxes/iso-base-media/get-children.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/get-children.ts
@@ -1,63 +1,37 @@
import type {BufferIterator} from '../../buffer-iterator';
-import type {LogLevel} from '../../log';
-import type {Options, ParseMediaFields} from '../../options';
import type {IsoBaseMediaBox} from '../../parse-result';
import type {ParserState} from '../../state/parser-state';
-import {parseIsoBaseMediaBoxes} from './parse-boxes';
+import {processBox} from './process-box';
-export const getChildren = async ({
- boxType,
+export const getIsoBaseMediaChildren = async ({
iterator,
- bytesRemainingInBox,
state,
- signal,
- logLevel,
- fields,
+ size,
}: {
- boxType: string;
iterator: BufferIterator;
- bytesRemainingInBox: number;
state: ParserState;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
+ size: number;
}): Promise<IsoBaseMediaBox[]> => {
- const parseChildren =
- boxType === 'mdia' ||
- boxType === 'minf' ||
- boxType === 'stbl' ||
- boxType === 'udta' ||
- boxType === 'moof' ||
- boxType === 'dims' ||
- boxType === 'meta' ||
- boxType === 'wave' ||
- boxType === 'traf' ||
- boxType === 'stsb';
+ const boxes: IsoBaseMediaBox[] = [];
+ const initial = iterator.counter.getOffset();
- if (parseChildren) {
- const boxes: IsoBaseMediaBox[] = [];
- const parsed = await parseIsoBaseMediaBoxes({
+ while (iterator.counter.getOffset() < size + initial) {
+ const parsed = await processBox({
iterator,
- maxBytes: bytesRemainingInBox,
- allowIncompleteBoxes: false,
- initialBoxes: boxes,
state,
- signal,
- logLevel,
- fields,
});
-
- if (parsed.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
+ if (!parsed.box) {
+ throw new Error('Expected box');
}
- return boxes;
+ boxes.push(parsed.box);
}
- if (bytesRemainingInBox < 0) {
- throw new Error('Box size is too big ' + JSON.stringify({boxType}));
+ if (iterator.counter.getOffset() > size + initial) {
+ throw new Error(
+ `read too many bytes - size: ${size}, read: ${iterator.counter.getOffset() - initial}. initial offset: ${initial}`,
+ );
}
- iterator.discard(bytesRemainingInBox);
- return [];
+ return boxes;
};
diff --git a/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts b/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts
index 7b6631d06f..bf2ac2e98e 100644
--- a/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/mdat/mdat.ts
@@ -1,80 +1,36 @@
import type {BufferIterator} from '../../../buffer-iterator';
import {convertAudioOrVideoSampleToWebCodecsTimestamps} from '../../../convert-audio-or-video-sample';
import {getHasTracks, getTracks} from '../../../get-tracks';
-import type {IsoBaseMediaBox} from '../../../parse-result';
-import type {PartialMdatBox} from '../../../parse-video';
+import {maySkipVideoData} from '../../../may-skip-video-data/may-skip-video-data';
+import type {IsoBaseMediaStructure} from '../../../parse-result';
import type {ParserState} from '../../../state/parser-state';
import {getSamplePositionsFromTrack} from '../get-sample-positions-from-track';
import type {TrakBox} from '../trak/trak';
import {getMoofBox} from '../traversal';
-type MdatStatus =
- | {
- status: 'samples-buffered';
- }
- | {
- status: 'samples-skipped';
- }
- | {
- status: 'samples-processed';
- };
-
-export type MdatBox = {
- type: 'mdat-box';
- boxSize: number;
- fileOffset: number;
-} & MdatStatus;
-
-export const parseMdat = async ({
- data,
- size,
- fileOffset,
- existingBoxes,
+export const parseMdatSection = async ({
+ iterator,
state,
- signal,
- maySkipSampleProcessing,
}: {
- data: BufferIterator;
- size: number;
- fileOffset: number;
- existingBoxes: IsoBaseMediaBox[];
+ iterator: BufferIterator;
state: ParserState;
- signal: AbortSignal | null;
- maySkipSampleProcessing: boolean;
-}): Promise<MdatBox | PartialMdatBox> => {
- const alreadyHas = getHasTracks(
- {
- type: 'iso-base-media',
- boxes: existingBoxes,
- },
- state,
- );
+}): Promise<void> => {
+ const alreadyHas = getHasTracks(state.structure.getStructure(), state);
if (!alreadyHas) {
- if (maySkipSampleProcessing) {
- data.discard(size - (data.counter.getOffset() - fileOffset));
- return Promise.resolve({
- type: 'mdat-box',
- boxSize: size,
- status: 'samples-skipped',
- fileOffset,
- });
+ if (maySkipVideoData({state})) {
+ const videoSection = state.videoSection.getVideoSection();
+ iterator.discard(
+ videoSection.size + videoSection.start - iterator.counter.getOffset(),
+ );
+ return;
}
- data.discard(size - (data.counter.getOffset() - fileOffset));
- data.disallowDiscard();
-
- return Promise.resolve({
- type: 'mdat-box',
- boxSize: size,
- status: 'samples-buffered',
- fileOffset,
- });
+ throw new Error(
+ 'Source does not support reading partially, but metadata is at the end of the file. This would require buffering the entire file in memory, leading to a leak. Remotion does not currently support this scenario, make sure to pass a source that supports Content-Range.',
+ );
}
- const tracks = getTracks(
- {type: 'iso-base-media', boxes: existingBoxes},
- state,
- );
+ const tracks = getTracks(state.structure.getStructure(), state);
const allTracks = [
...tracks.videoTracks,
...tracks.audioTracks,
@@ -85,7 +41,9 @@ export const parseMdat = async ({
.map((track) => {
const samplePositions = getSamplePositionsFromTrack(
track.trakBox as TrakBox,
- getMoofBox(existingBoxes),
+ getMoofBox(
+ (state.structure.getStructure() as IsoBaseMediaStructure).boxes,
+ ),
);
if (!samplePositions) {
throw new Error('No sample positions');
@@ -100,116 +58,88 @@ export const parseMdat = async ({
})
.flat(1);
- while (true) {
- if (signal && signal.aborted) {
- break;
- }
-
- const samplesWithIndex = flatSamples.find((sample) => {
- return sample.samplePosition.offset === data.counter.getOffset();
- });
- if (!samplesWithIndex) {
- // There are various reasons why in mdat we find weird stuff:
- // - iphonevideo.hevc has a fake hoov atom which is not mapped
- // - corrupted.mp4 has a corrupt table
- const nextSample_ = flatSamples
- .filter((s) => s.samplePosition.offset > data.counter.getOffset())
- .sort((a, b) => a.samplePosition.offset - b.samplePosition.offset)[0];
- if (nextSample_) {
- data.discard(
- nextSample_.samplePosition.offset - data.counter.getOffset(),
- );
- continue;
- } else {
- const bytesRemaining = size + fileOffset - data.counter.getOffset();
- data.discard(bytesRemaining);
- break;
- }
- }
-
- if (data.bytesRemaining() < samplesWithIndex.samplePosition.size) {
- break;
- }
-
- const bytes = data.getSlice(samplesWithIndex.samplePosition.size);
-
- const {cts, dts, duration, isKeyframe, offset} =
- samplesWithIndex.samplePosition;
-
- if (samplesWithIndex.track.type === 'audio') {
- await state.callbacks.onAudioSample(
- samplesWithIndex.track.trackId,
- convertAudioOrVideoSampleToWebCodecsTimestamps(
- {
- data: bytes,
- timestamp: cts,
- duration,
- cts,
- dts,
- trackId: samplesWithIndex.track.trackId,
- type: isKeyframe ? 'key' : 'delta',
- offset,
- timescale: samplesWithIndex.track.timescale,
- },
- samplesWithIndex.track.timescale,
- ),
+ const samplesWithIndex = flatSamples.find((sample) => {
+ return sample.samplePosition.offset === iterator.counter.getOffset();
+ });
+ if (!samplesWithIndex) {
+ // There are various reasons why in mdat we find weird stuff:
+ // - iphonevideo.hevc has a fake hoov atom which is not mapped
+ // - corrupted.mp4 has a corrupt table
+ const nextSample_ = flatSamples
+ .filter((s) => s.samplePosition.offset > iterator.counter.getOffset())
+ .sort((a, b) => a.samplePosition.offset - b.samplePosition.offset)[0];
+ if (nextSample_) {
+ iterator.discard(
+ nextSample_.samplePosition.offset - iterator.counter.getOffset(),
);
+ return;
}
- if (samplesWithIndex.track.type === 'video') {
- // https://remotion-assets.s3.eu-central-1.amazonaws.com/example-videos/sei_checkpoint.mp4
- // Position in file 0x0001aba615
- // https://github.com/remotion-dev/remotion/issues/4680
- // In Chrome, we may not treat recovery points as keyframes
- // otherwise "a keyframe is required after flushing"
- const nalUnitType = bytes[4] & 0b00011111;
- let isRecoveryPoint = false;
- // SEI (Supplemental enhancement information)
- if (nalUnitType === 6) {
- const seiType = bytes[5];
- isRecoveryPoint = seiType === 6;
- }
+ // guess we reached the end!
+ return;
+ }
- await state.callbacks.onVideoSample(
- samplesWithIndex.track.trackId,
- convertAudioOrVideoSampleToWebCodecsTimestamps(
- {
- data: bytes,
- timestamp: cts,
- duration,
- cts,
- dts,
- trackId: samplesWithIndex.track.trackId,
- type: isKeyframe && !isRecoveryPoint ? 'key' : 'delta',
- offset,
- timescale: samplesWithIndex.track.timescale,
- },
- samplesWithIndex.track.timescale,
- ),
- );
- }
+ if (iterator.bytesRemaining() < samplesWithIndex.samplePosition.size) {
+ return;
+ }
- const remaining = size - (data.counter.getOffset() - fileOffset);
- data.removeBytesRead();
- if (remaining === 0) {
- break;
- }
+ const bytes = iterator.getSlice(samplesWithIndex.samplePosition.size);
+
+ const {cts, dts, duration, isKeyframe, offset} =
+ samplesWithIndex.samplePosition;
+
+ if (samplesWithIndex.track.type === 'audio') {
+ await state.callbacks.onAudioSample(
+ samplesWithIndex.track.trackId,
+ convertAudioOrVideoSampleToWebCodecsTimestamps(
+ {
+ data: bytes,
+ timestamp: cts,
+ duration,
+ cts,
+ dts,
+ trackId: samplesWithIndex.track.trackId,
+ type: isKeyframe ? 'key' : 'delta',
+ offset,
+ timescale: samplesWithIndex.track.timescale,
+ },
+ samplesWithIndex.track.timescale,
+ ),
+ );
}
- const expectedOffsetNow = size + fileOffset;
- const actualOffsetNow = data.counter.getOffset();
- if (expectedOffsetNow !== actualOffsetNow) {
- return Promise.resolve({
- type: 'partial-mdat-box',
- boxSize: size,
- fileOffset,
- });
+ if (samplesWithIndex.track.type === 'video') {
+ // https://remotion-assets.s3.eu-central-1.amazonaws.com/example-videos/sei_checkpoint.mp4
+ // Position in file 0x0001aba615
+ // https://github.com/remotion-dev/remotion/issues/4680
+ // In Chrome, we may not treat recovery points as keyframes
+ // otherwise "a keyframe is required after flushing"
+ const nalUnitType = bytes[4] & 0b00011111;
+ let isRecoveryPoint = false;
+ // SEI (Supplemental enhancement information)
+ if (nalUnitType === 6) {
+ const seiType = bytes[5];
+ isRecoveryPoint = seiType === 6;
+ }
+
+ await state.callbacks.onVideoSample(
+ samplesWithIndex.track.trackId,
+ convertAudioOrVideoSampleToWebCodecsTimestamps(
+ {
+ data: bytes,
+ timestamp: cts,
+ duration,
+ cts,
+ dts,
+ trackId: samplesWithIndex.track.trackId,
+ type: isKeyframe && !isRecoveryPoint ? 'key' : 'delta',
+ offset,
+ timescale: samplesWithIndex.track.timescale,
+ },
+ samplesWithIndex.track.timescale,
+ ),
+ );
}
- return Promise.resolve({
- type: 'mdat-box',
- boxSize: size,
- status: 'samples-processed',
- fileOffset,
- });
+ iterator.removeBytesRead();
};
diff --git a/packages/media-parser/src/boxes/iso-base-media/moov/moov.ts b/packages/media-parser/src/boxes/iso-base-media/moov/moov.ts
index 99146e9648..a94645f86f 100644
--- a/packages/media-parser/src/boxes/iso-base-media/moov/moov.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/moov/moov.ts
@@ -1,10 +1,8 @@
import type {BufferIterator} from '../../../buffer-iterator';
-import type {LogLevel} from '../../../log';
-import type {Options, ParseMediaFields} from '../../../options';
-import type {AnySegment, IsoBaseMediaBox} from '../../../parse-result';
+import type {AnySegment} from '../../../parse-result';
import type {ParserState} from '../../../state/parser-state';
import type {BaseBox} from '../base-type';
-import {parseIsoBaseMediaBoxes} from '../parse-boxes';
+import {getIsoBaseMediaChildren} from '../get-children';
export interface MoovBox extends BaseBox {
type: 'moov-box';
@@ -16,39 +14,22 @@ export const parseMoov = async ({
offset,
size,
state,
- signal,
- logLevel,
- fields,
}: {
iterator: BufferIterator;
offset: number;
size: number;
state: ParserState;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
}): Promise<MoovBox> => {
- const boxes: IsoBaseMediaBox[] = [];
-
- const children = await parseIsoBaseMediaBoxes({
+ const children = await getIsoBaseMediaChildren({
iterator,
- maxBytes: size - (iterator.counter.getOffset() - offset),
- allowIncompleteBoxes: false,
- initialBoxes: boxes,
state,
- signal,
- logLevel,
- fields,
+ size: size - 8,
});
- if (children.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
-
return {
offset,
boxSize: size,
type: 'moov-box',
- children: boxes,
+ children,
};
};
diff --git a/packages/media-parser/src/boxes/iso-base-media/parse-boxes.ts b/packages/media-parser/src/boxes/iso-base-media/parse-boxes.ts
index 0e6feadc23..a98a2315b8 100644
--- a/packages/media-parser/src/boxes/iso-base-media/parse-boxes.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/parse-boxes.ts
@@ -1,172 +1,60 @@
import type {BufferIterator} from '../../buffer-iterator';
-import {continueMdatRoutine} from '../../continue-mdat-routine';
-import {hasAllInfo} from '../../has-all-info';
-import type {LogLevel} from '../../log';
-import {maySkipVideoData} from '../../may-skip-video-data/may-skip-video-data';
-import type {Options, ParseMediaFields} from '../../options';
-import type {IsoBaseMediaBox, ParseResult} from '../../parse-result';
+import type {IsoBaseMediaStructure, ParseResult} from '../../parse-result';
import type {ParserState} from '../../state/parser-state';
import {processBox} from './process-box';
-import {getMdatBox} from './traversal';
-export const parseIsoBaseMediaBoxes = async ({
+export const parseIsoBaseMedia = async ({
iterator,
- maxBytes,
- allowIncompleteBoxes,
- initialBoxes,
state,
- signal,
- logLevel,
- fields,
}: {
iterator: BufferIterator;
- maxBytes: number;
- allowIncompleteBoxes: boolean;
- initialBoxes: IsoBaseMediaBox[];
+
state: ParserState;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
}): Promise<ParseResult> => {
- const initialOffset = iterator.counter.getOffset();
-
const continueParsing = () => {
- return parseIsoBaseMediaBoxes({
+ return parseIsoBaseMedia({
iterator,
- maxBytes,
- allowIncompleteBoxes,
- initialBoxes,
state,
- signal,
- logLevel,
- fields,
});
};
- const alreadyHasMdat = state.structure
- .getStructureOrNull()
- ?.boxes.find((b) => b.type === 'mdat-box');
-
- while (
- iterator.bytesRemaining() > 0 &&
- iterator.counter.getOffset() - initialOffset < maxBytes
- ) {
- const result = await processBox({
- iterator,
- allowIncompleteBoxes,
- parsedBoxes: initialBoxes,
- state,
- signal,
- logLevel,
- fields,
- });
-
- if (result.type === 'incomplete') {
- if (Number.isFinite(maxBytes)) {
- throw new Error('maxBytes must be Infinity for top-level boxes');
- }
-
- return {
- status: 'incomplete',
- continueParsing,
- skipTo: null,
- };
- }
-
- if (result.type === 'partial-mdat-box') {
- return {
- status: 'incomplete',
- continueParsing: () => {
- return Promise.resolve(
- continueMdatRoutine({
- iterator,
- maxBytes,
- allowIncompleteBoxes,
- initialBoxes,
- state,
- continueMdat: result,
- signal,
- logLevel,
- fields,
- }),
- );
- },
- skipTo: null,
- };
- }
-
- if (result.box.type === 'mdat-box' && alreadyHasMdat) {
- initialBoxes = initialBoxes.filter((b) => b.type !== 'mdat-box');
- initialBoxes.push(result.box);
- iterator.allowDiscard();
-
- break;
- } else {
- initialBoxes.push(result.box);
- if (hasAllInfo({fields, state})) {
- return {
- status: 'done',
- };
- }
- }
-
- if (result.skipTo !== null) {
- if (!state.supportsContentRange) {
- throw new Error(
- 'Content-Range header is not supported by the reader, but was asked to seek',
- );
- }
-
- return {
- status: 'incomplete',
- continueParsing,
- skipTo: result.skipTo,
- };
- }
+ const result = await processBox({
+ iterator,
+ state,
+ });
+ if (result.box) {
+ (state.structure.getStructure() as IsoBaseMediaStructure).boxes.push(
+ result.box,
+ );
+ }
- if (iterator.bytesRemaining() < 0) {
- return {
- status: 'incomplete',
- continueParsing,
- skipTo: null,
- };
+ if (result.skipTo !== null) {
+ if (!state.supportsContentRange) {
+ throw new Error(
+ 'Content-Range header is not supported by the reader, but was asked to seek',
+ );
}
- iterator.removeBytesRead();
+ return {
+ status: 'incomplete',
+ continueParsing,
+ skipTo: result.skipTo,
+ };
}
- const mdatState = getMdatBox(initialBoxes);
- const skipped =
- mdatState?.status === 'samples-skipped' &&
- !maySkipVideoData({state}) &&
- state.supportsContentRange;
- const buffered =
- mdatState?.status === 'samples-buffered' && !maySkipVideoData({state});
-
- if (skipped || buffered) {
+ if (iterator.bytesRemaining() < 0) {
return {
status: 'incomplete',
- continueParsing: () => {
- if (buffered) {
- iterator.skipTo(mdatState.fileOffset, false);
- }
-
- return parseIsoBaseMediaBoxes({
- iterator,
- maxBytes,
- allowIncompleteBoxes: false,
- initialBoxes,
- state,
- signal,
- logLevel,
- fields,
- });
- },
- skipTo: skipped ? mdatState.fileOffset : null,
+ continueParsing,
+ skipTo: null,
};
}
+ iterator.removeBytesRead();
+
return {
- status: 'done',
+ status: 'incomplete',
+ continueParsing,
+ skipTo: null,
};
};
diff --git a/packages/media-parser/src/boxes/iso-base-media/parse-mdat-partially.ts b/packages/media-parser/src/boxes/iso-base-media/parse-mdat-partially.ts
deleted file mode 100644
index d3cae79f97..0000000000
--- a/packages/media-parser/src/boxes/iso-base-media/parse-mdat-partially.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type {BufferIterator} from '../../buffer-iterator';
-import type {IsoBaseMediaBox} from '../../parse-result';
-import type {BoxAndNext} from '../../parse-video';
-import type {ParserState} from '../../state/parser-state';
-import {parseMdat} from './mdat/mdat';
-
-export const parseMdatPartially = async ({
- iterator,
- boxSize,
- fileOffset,
- parsedBoxes,
- state,
- signal,
-}: {
- iterator: BufferIterator;
- boxSize: number;
- fileOffset: number;
- parsedBoxes: IsoBaseMediaBox[];
- state: ParserState;
- signal: AbortSignal | null;
-}): Promise<BoxAndNext> => {
- const box = await parseMdat({
- data: iterator,
- size: boxSize,
- fileOffset,
- existingBoxes: parsedBoxes,
- state,
- signal,
- maySkipSampleProcessing: state.supportsContentRange,
- });
- if (box.type === 'partial-mdat-box') {
- return box;
- }
-
- if (
- (box.status === 'samples-processed' || box.status === 'samples-buffered') &&
- box.fileOffset + boxSize === iterator.counter.getOffset()
- ) {
- return {
- type: 'complete',
- box,
- size: boxSize,
- skipTo: null,
- };
- }
-
- return {
- type: 'partial-mdat-box',
- boxSize,
- fileOffset,
- };
-};
diff --git a/packages/media-parser/src/boxes/iso-base-media/process-box.ts b/packages/media-parser/src/boxes/iso-base-media/process-box.ts
index 1061e965a2..99286b3870 100644
--- a/packages/media-parser/src/boxes/iso-base-media/process-box.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/process-box.ts
@@ -1,23 +1,21 @@
import type {BufferIterator} from '../../buffer-iterator';
import {getHasTracks} from '../../get-tracks';
-import type {LogLevel} from '../../log';
+import {Log} from '../../log';
import {maySkipVideoData} from '../../may-skip-video-data/may-skip-video-data';
-import type {Options, ParseMediaFields} from '../../options';
-import type {IsoBaseMediaBox} from '../../parse-result';
+import type {IsoBaseMediaStructure} from '../../parse-result';
import type {BoxAndNext} from '../../parse-video';
import {registerTrack} from '../../register-track';
import type {ParserState} from '../../state/parser-state';
import {parseEsds} from './esds/esds';
import {parseFtyp} from './ftyp';
-import {getChildren} from './get-children';
+import {getIsoBaseMediaChildren} from './get-children';
import {makeBaseMediaTrack} from './make-track';
-import {parseMdat} from './mdat/mdat';
+import {parseMdatSection} from './mdat/mdat';
import {parseMdhd} from './mdhd';
import {parseHdlr} from './meta/hdlr';
import {parseIlstBox} from './meta/ilst';
import {parseMoov} from './moov/moov';
import {parseMvhd} from './mvhd';
-import {parseMdatPartially} from './parse-mdat-partially';
import {parseAv1C} from './stsd/av1c';
import {parseAvcc} from './stsd/avcc';
import {parseColorParameterBox} from './stsd/colr';
@@ -40,20 +38,10 @@ import {parseTrun} from './trun';
export const processBox = async ({
iterator,
- allowIncompleteBoxes,
- parsedBoxes,
state,
- signal,
- logLevel,
- fields,
}: {
iterator: BufferIterator;
- allowIncompleteBoxes: boolean;
- parsedBoxes: IsoBaseMediaBox[];
state: ParserState;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
}): Promise<BoxAndNext> => {
const fileOffset = iterator.counter.getOffset();
const bytesRemaining = iterator.bytesRemaining();
@@ -62,7 +50,6 @@ export const processBox = async ({
if (boxSizeRaw === 0) {
return {
- type: 'complete',
box: {
type: 'void-box',
boxSize: 0,
@@ -78,74 +65,56 @@ export const processBox = async ({
iterator.bytesRemaining() < 4
) {
iterator.counter.decrement(iterator.counter.getOffset() - fileOffset);
- if (!allowIncompleteBoxes) {
- throw new Error(
- `Expected box size of ${bytesRemaining}, got ${boxSizeRaw}. Incomplete boxes are not allowed.`,
- );
- }
-
- return {
- type: 'incomplete',
- };
+ throw new Error(
+ `Expected box size of ${bytesRemaining}, got ${boxSizeRaw}. Incomplete boxes are not allowed.`,
+ );
}
const boxType = iterator.getByteString(4, false);
+ Log.trace(state.logLevel, 'Found box', boxType);
const boxSize = boxSizeRaw === 1 ? iterator.getEightByteNumber() : boxSizeRaw;
+ if (boxType === 'mdat') {
+ state.videoSection.setVideoSection({
+ size: boxSize,
+ start: iterator.counter.getOffset(),
+ });
+ }
+
if (bytesRemaining < boxSize) {
if (boxType !== 'mdat') {
- iterator.counter.decrement(iterator.counter.getOffset() - fileOffset);
- if (!allowIncompleteBoxes) {
- throw new Error(
- `Expected box size of ${bytesRemaining}, got ${boxSize}. Incomplete boxes are not allowed.`,
- );
- }
-
- return {
- type: 'incomplete',
- };
+ throw new Error(
+ `Expected box size of ${bytesRemaining}, got ${boxSize} for ${boxType}. Incomplete boxes are not allowed.`,
+ );
}
// Check if the moov atom is at the end
const shouldSkip =
maySkipVideoData({state}) ||
- (!getHasTracks({type: 'iso-base-media', boxes: parsedBoxes}, state) &&
+ (!getHasTracks(
+ state.structure.getStructure() as IsoBaseMediaStructure,
+ state,
+ ) &&
state.supportsContentRange);
if (shouldSkip) {
- const skipTo = fileOffset + boxSize;
- const bytesToSkip = skipTo - iterator.counter.getOffset();
-
- // If there is a huge mdat chunk, we can skip it because we don't need it for the metadata
- if (bytesToSkip > 1_000_000) {
- return {
- type: 'complete',
- box: {
- type: 'mdat-box',
- boxSize,
- fileOffset,
- status: 'samples-skipped',
- },
- size: boxSize,
- skipTo: fileOffset + boxSize,
- };
- }
- } else {
- return parseMdatPartially({
- iterator,
- boxSize,
- fileOffset,
- parsedBoxes,
- state,
- signal,
- });
+ return {
+ skipTo: fileOffset + boxSize,
+ box: null,
+ size: 0,
+ };
}
+
+ return {
+ box: null,
+ size: 0,
+ skipTo: null,
+ };
}
if (boxType === 'ftyp') {
const box = parseFtyp({iterator, size: boxSize, offset: fileOffset});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -158,7 +127,6 @@ export const processBox = async ({
size: boxSize,
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -169,7 +137,6 @@ export const processBox = async ({
const box = parseMvhd({iterator, offset: fileOffset, size: boxSize});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -180,7 +147,6 @@ export const processBox = async ({
const box = parseTkhd({iterator, offset: fileOffset, size: boxSize});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -191,7 +157,6 @@ export const processBox = async ({
const box = parseTrun({iterator, offset: fileOffset, size: boxSize});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -202,7 +167,6 @@ export const processBox = async ({
const box = parseTfdt({iterator, size: boxSize, offset: fileOffset});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -215,12 +179,9 @@ export const processBox = async ({
offset: fileOffset,
size: boxSize,
state,
- signal,
- fields,
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -235,7 +196,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -251,7 +211,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -266,7 +225,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -281,7 +239,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -296,7 +253,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -311,7 +267,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -324,12 +279,9 @@ export const processBox = async ({
offset: fileOffset,
size: boxSize,
state,
- signal,
- fields,
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -340,7 +292,6 @@ export const processBox = async ({
const box = await parseHdlr({iterator, size: boxSize, offset: fileOffset});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -351,7 +302,6 @@ export const processBox = async ({
const box = parseKeys({iterator, size: boxSize, offset: fileOffset});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -366,7 +316,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -379,15 +328,11 @@ export const processBox = async ({
offset: fileOffset,
size: boxSize,
state,
- signal,
- logLevel,
- fields,
});
state.callbacks.tracks.setIsDone();
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -400,9 +345,6 @@ export const processBox = async ({
size: boxSize,
offsetAtStart: fileOffset,
state,
- signal,
- logLevel,
- fields,
});
const transformedTrack = makeBaseMediaTrack(box);
if (transformedTrack) {
@@ -414,7 +356,6 @@ export const processBox = async ({
}
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -429,7 +370,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -443,7 +383,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -457,7 +396,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -472,7 +410,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -487,7 +424,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -502,7 +438,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -517,7 +452,6 @@ export const processBox = async ({
});
return {
- type: 'complete',
box,
size: boxSize,
skipTo: null,
@@ -525,47 +459,61 @@ export const processBox = async ({
}
if (boxType === 'mdat') {
- const box = await parseMdat({
- data: iterator,
+ state.videoSection.setVideoSection({
size: boxSize,
- fileOffset,
- existingBoxes: parsedBoxes,
+ start: iterator.counter.getOffset(),
+ });
+ await parseMdatSection({
+ iterator,
state,
- signal,
- maySkipSampleProcessing: state.supportsContentRange,
});
- if (box.type === 'partial-mdat-box') {
- return box;
- }
return {
- type: 'complete',
- box,
+ box: null,
size: boxSize,
skipTo: null,
};
}
- const bytesRemainingInBox =
- boxSize - (iterator.counter.getOffset() - fileOffset);
+ if (
+ boxType === 'mdia' ||
+ boxType === 'minf' ||
+ boxType === 'stbl' ||
+ boxType === 'udta' ||
+ boxType === 'moof' ||
+ boxType === 'dims' ||
+ boxType === 'meta' ||
+ boxType === 'wave' ||
+ boxType === 'traf' ||
+ boxType === 'stsb'
+ ) {
+ const children = await getIsoBaseMediaChildren({
+ iterator,
+ state,
+ size: boxSize - 8,
+ });
+
+ return {
+ box: {
+ type: 'regular-box',
+ boxType,
+ boxSize,
+ children,
+ offset: fileOffset,
+ },
+ size: boxSize,
+ skipTo: null,
+ };
+ }
- const children = await getChildren({
- boxType,
- iterator,
- bytesRemainingInBox,
- state,
- signal,
- logLevel,
- fields,
- });
+ iterator.discard(boxSize - 8);
return {
- type: 'complete',
box: {
type: 'regular-box',
boxType,
boxSize,
- children,
+ children: [],
offset: fileOffset,
},
size: boxSize,
diff --git a/packages/media-parser/src/boxes/iso-base-media/stsd/mebx.ts b/packages/media-parser/src/boxes/iso-base-media/stsd/mebx.ts
index ad1e7f8b23..4e94d64106 100644
--- a/packages/media-parser/src/boxes/iso-base-media/stsd/mebx.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/stsd/mebx.ts
@@ -1,9 +1,8 @@
import type {BufferIterator} from '../../../buffer-iterator';
-import type {Options, ParseMediaFields} from '../../../options';
-import type {AnySegment, IsoBaseMediaBox} from '../../../parse-result';
+import type {AnySegment} from '../../../parse-result';
import type {ParserState} from '../../../state/parser-state';
import type {BaseBox} from '../base-type';
-import {parseIsoBaseMediaBoxes} from '../parse-boxes';
+import {getIsoBaseMediaChildren} from '../get-children';
export interface MebxBox extends BaseBox {
type: 'mebx-box';
@@ -17,43 +16,29 @@ export const parseMebx = async ({
offset,
size,
state,
- signal,
- fields,
}: {
iterator: BufferIterator;
offset: number;
size: number;
state: ParserState;
- signal: AbortSignal | null;
- fields: Options<ParseMediaFields>;
}): Promise<MebxBox> => {
// reserved, 6 bit
iterator.discard(6);
const dataReferenceIndex = iterator.getUint16();
- const boxes: IsoBaseMediaBox[] = [];
- const children = await parseIsoBaseMediaBoxes({
+ const children = await getIsoBaseMediaChildren({
iterator,
- maxBytes: iterator.counter.getOffset() - offset,
- allowIncompleteBoxes: false,
- initialBoxes: boxes,
state,
- signal,
- logLevel: 'info',
- fields,
+ size: size - 8,
});
- if (children.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
-
return {
type: 'mebx-box',
boxSize: size,
offset,
dataReferenceIndex,
format: 'mebx',
- children: boxes,
+ children,
};
};
diff --git a/packages/media-parser/src/boxes/iso-base-media/stsd/samples.ts b/packages/media-parser/src/boxes/iso-base-media/stsd/samples.ts
index 7e1a777f48..ec742d5156 100644
--- a/packages/media-parser/src/boxes/iso-base-media/stsd/samples.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/stsd/samples.ts
@@ -1,13 +1,7 @@
import type {BufferIterator} from '../../../buffer-iterator';
-import type {LogLevel} from '../../../log';
-import type {Options, ParseMediaFields} from '../../../options';
-import type {
- AnySegment,
- IsoBaseMediaBox,
- ParseResult,
-} from '../../../parse-result';
+import type {AnySegment, IsoBaseMediaBox} from '../../../parse-result';
import type {ParserState} from '../../../state/parser-state';
-import {parseIsoBaseMediaBoxes} from '../parse-boxes';
+import {getIsoBaseMediaChildren} from '../get-children';
type SampleBase = {
format: string;
@@ -58,7 +52,7 @@ type UnknownSample = SampleBase & {
export type Sample = AudioSample | VideoSample | UnknownSample;
-type SampleAndNext = {
+type FormatBoxAndNext = {
sample: Sample | null;
};
@@ -124,19 +118,13 @@ const audioTags = [
'ac-3',
];
-export const processSample = async ({
+export const processIsoFormatBox = async ({
iterator,
- state: options,
- signal,
- logLevel,
- fields,
+ state,
}: {
iterator: BufferIterator;
state: ParserState;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
-}): Promise<SampleAndNext> => {
+}): Promise<FormatBoxAndNext> => {
const fileOffset = iterator.counter.getOffset();
const bytesRemaining = iterator.bytesRemaining();
const boxSize = iterator.getUint32();
@@ -184,26 +172,12 @@ export const processSample = async ({
const packetSize = iterator.getUint16();
const sampleRate = iterator.getFixedPointUnsigned1616Number();
- const bytesRemainingInBox =
- boxSize - (iterator.counter.getOffset() - fileOffset);
-
- const initialBoxes: IsoBaseMediaBox[] = [];
-
- const children = await parseIsoBaseMediaBoxes({
+ const children = await getIsoBaseMediaChildren({
iterator,
- allowIncompleteBoxes: false,
- maxBytes: bytesRemainingInBox,
- initialBoxes,
- state: options,
- signal,
- logLevel,
- fields,
+ state,
+ size: boxSize - (iterator.counter.getOffset() - fileOffset),
});
- if (children.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
-
return {
sample: {
format: boxFormat,
@@ -223,7 +197,7 @@ export const processSample = async ({
bytesPerPacket: null,
bytesPerFrame: null,
bitsPerSample: null,
- children: initialBoxes,
+ children,
},
};
}
@@ -241,25 +215,12 @@ export const processSample = async ({
const bytesPerFrame = iterator.getUint32();
const bytesPerSample = iterator.getUint32();
- const bytesRemainingInBox =
- boxSize - (iterator.counter.getOffset() - fileOffset);
-
- const initialBoxes: IsoBaseMediaBox[] = [];
- const children = await parseIsoBaseMediaBoxes({
+ const children = await getIsoBaseMediaChildren({
iterator,
- allowIncompleteBoxes: false,
- maxBytes: bytesRemainingInBox,
- initialBoxes,
- state: options,
- signal,
- logLevel,
- fields,
+ state,
+ size: boxSize - (iterator.counter.getOffset() - fileOffset),
});
- if (children.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
-
return {
sample: {
format: boxFormat,
@@ -279,7 +240,7 @@ export const processSample = async ({
bytesPerPacket,
bytesPerFrame,
bitsPerSample: bytesPerSample,
- children: initialBoxes,
+ children,
},
};
}
@@ -300,25 +261,12 @@ export const processSample = async ({
const bytesPerFrame = iterator.getUint32();
const samplesPerPacket = iterator.getUint32();
- const bytesRemainingInBox =
- boxSize - (iterator.counter.getOffset() - fileOffset);
-
- const children = await parseIsoBaseMediaBoxes({
+ const children = await getIsoBaseMediaChildren({
iterator,
- allowIncompleteBoxes: false,
- maxBytes: bytesRemainingInBox,
- initialBoxes: [],
- state: options,
- signal,
- logLevel,
- fields,
+ state,
+ size: boxSize - (iterator.counter.getOffset() - fileOffset),
});
- if (children.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
-
- const initialBoxes: IsoBaseMediaBox[] = [];
return {
sample: {
format: boxFormat,
@@ -338,7 +286,7 @@ export const processSample = async ({
bytesPerPacket: null,
bytesPerFrame,
bitsPerSample: bitsPerChannel,
- children: initialBoxes,
+ children,
},
};
}
@@ -364,25 +312,15 @@ export const processSample = async ({
const bytesRemainingInBox =
boxSize - (iterator.counter.getOffset() - fileOffset);
- const initialBoxes: IsoBaseMediaBox[] = [];
- const children: ParseResult =
+ const children: IsoBaseMediaBox[] =
bytesRemainingInBox > 8
- ? await parseIsoBaseMediaBoxes({
+ ? await getIsoBaseMediaChildren({
iterator,
- allowIncompleteBoxes: false,
- maxBytes: bytesRemainingInBox,
- initialBoxes,
- state: options,
- signal,
- logLevel,
- fields,
+ state,
+ size: bytesRemainingInBox,
})
- : (iterator.discard(bytesRemainingInBox), {status: 'done'});
-
- if (children.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
+ : (iterator.discard(bytesRemainingInBox), []);
return {
sample: {
@@ -405,7 +343,7 @@ export const processSample = async ({
compressorName,
depth,
colorTableId,
- descriptors: initialBoxes,
+ descriptors: children,
},
};
}
@@ -413,20 +351,14 @@ export const processSample = async ({
throw new Error(`Unknown sample format ${boxFormat}`);
};
-export const parseSamples = async ({
+export const parseIsoFormatBoxes = async ({
iterator,
maxBytes,
state,
- signal,
- logLevel,
- fields,
}: {
iterator: BufferIterator;
maxBytes: number;
state: ParserState;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
}): Promise<Sample[]> => {
const samples: Sample[] = [];
const initialOffset = iterator.counter.getOffset();
@@ -435,12 +367,9 @@ export const parseSamples = async ({
iterator.bytesRemaining() > 0 &&
iterator.counter.getOffset() - initialOffset < maxBytes
) {
- const {sample} = await processSample({
+ const {sample} = await processIsoFormatBox({
iterator,
state,
- signal,
- logLevel,
- fields,
});
if (sample) {
diff --git a/packages/media-parser/src/boxes/iso-base-media/stsd/stsd.ts b/packages/media-parser/src/boxes/iso-base-media/stsd/stsd.ts
index 4628e747f7..cd0ee5cb82 100644
--- a/packages/media-parser/src/boxes/iso-base-media/stsd/stsd.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/stsd/stsd.ts
@@ -1,9 +1,8 @@
import type {BufferIterator} from '../../../buffer-iterator';
-import type {Options, ParseMediaFields} from '../../../options';
import type {ParserState} from '../../../state/parser-state';
import type {BaseBox} from '../base-type';
import type {Sample} from './samples';
-import {parseSamples} from './samples';
+import {parseIsoFormatBoxes} from './samples';
export interface StsdBox extends BaseBox {
type: 'stsd-box';
@@ -16,15 +15,11 @@ export const parseStsd = async ({
offset,
size,
state,
- signal,
- fields,
}: {
iterator: BufferIterator;
offset: number;
size: number;
state: ParserState;
- signal: AbortSignal | null;
- fields: Options<ParseMediaFields>;
}): Promise<StsdBox> => {
const version = iterator.getUint8();
if (version !== 0) {
@@ -38,13 +33,10 @@ export const parseStsd = async ({
const bytesRemainingInBox = size - (iterator.counter.getOffset() - offset);
- const boxes = await parseSamples({
+ const boxes = await parseIsoFormatBoxes({
iterator,
maxBytes: bytesRemainingInBox,
state,
- signal,
- logLevel: 'info',
- fields,
});
if (boxes.length !== numberOfEntries) {
diff --git a/packages/media-parser/src/boxes/iso-base-media/trak/trak.ts b/packages/media-parser/src/boxes/iso-base-media/trak/trak.ts
index 407bd562ee..6b11975efd 100644
--- a/packages/media-parser/src/boxes/iso-base-media/trak/trak.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/trak/trak.ts
@@ -1,10 +1,8 @@
import type {BufferIterator} from '../../../buffer-iterator';
-import type {LogLevel} from '../../../log';
-import type {Options, ParseMediaFields} from '../../../options';
-import type {AnySegment, IsoBaseMediaBox} from '../../../parse-result';
+import type {AnySegment} from '../../../parse-result';
import type {ParserState} from '../../../state/parser-state';
import type {BaseBox} from '../base-type';
-import {parseIsoBaseMediaBoxes} from '../parse-boxes';
+import {getIsoBaseMediaChildren} from '../get-children';
export interface TrakBox extends BaseBox {
type: 'trak-box';
@@ -16,38 +14,22 @@ export const parseTrak = async ({
size,
offsetAtStart,
state: options,
- signal,
- logLevel,
- fields,
}: {
data: BufferIterator;
size: number;
offsetAtStart: number;
state: ParserState;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
}): Promise<TrakBox> => {
- const initialBoxes: IsoBaseMediaBox[] = [];
- const result = await parseIsoBaseMediaBoxes({
+ const children = await getIsoBaseMediaChildren({
iterator: data,
- maxBytes: size - (data.counter.getOffset() - offsetAtStart),
- allowIncompleteBoxes: false,
- initialBoxes,
state: options,
- signal,
- logLevel,
- fields,
+ size: size - 8,
});
- if (result.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
-
return {
offset: offsetAtStart,
boxSize: size,
type: 'trak-box',
- children: initialBoxes,
+ children,
};
};
diff --git a/packages/media-parser/src/boxes/iso-base-media/traversal.ts b/packages/media-parser/src/boxes/iso-base-media/traversal.ts
index 849d44ef4e..c1f9b58685 100644
--- a/packages/media-parser/src/boxes/iso-base-media/traversal.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/traversal.ts
@@ -1,6 +1,5 @@
import type {AnySegment, IsoBaseMediaBox, RegularBox} from '../../parse-result';
import type {FtypBox} from './ftyp';
-import type {MdatBox} from './mdat/mdat';
import type {MdhdBox} from './mdhd';
import type {MoovBox} from './moov/moov';
import type {MvhdBox} from './mvhd';
@@ -280,16 +279,3 @@ export const getTrunBoxes = (segment: IsoBaseMediaBox): TrunBox[] => {
return trunBoxes as TrunBox[];
};
-
-export const getMdatBox = (anySegment: AnySegment[]): MdatBox | null => {
- const mdat = anySegment.find((b) => b.type === 'mdat-box');
- if (!mdat) {
- return null;
- }
-
- if (mdat.type !== 'mdat-box') {
- throw new Error('Expected mdat-box');
- }
-
- return mdat;
-};
diff --git a/packages/media-parser/src/boxes/mp3/parse-mp3.ts b/packages/media-parser/src/boxes/mp3/parse-mp3.ts
index 4970977f66..e8a1017cb1 100644
--- a/packages/media-parser/src/boxes/mp3/parse-mp3.ts
+++ b/packages/media-parser/src/boxes/mp3/parse-mp3.ts
@@ -18,12 +18,6 @@ export const parseMp3 = async ({
return parseMp3({iterator, structure, state});
};
- if (iterator.bytesRemaining() === 0) {
- return Promise.resolve({
- status: 'done',
- });
- }
-
if (iterator.bytesRemaining() < 3) {
return {
status: 'incomplete',
diff --git a/packages/media-parser/src/buffer-iterator.ts b/packages/media-parser/src/buffer-iterator.ts
index eacde8e274..2196b251ae 100644
--- a/packages/media-parser/src/buffer-iterator.ts
+++ b/packages/media-parser/src/buffer-iterator.ts
@@ -77,7 +77,6 @@ export const getArrayBufferIterator = (
let view = new DataView(data.buffer);
const counter = makeOffsetCounter();
- let discardAllowed = true;
const startCheckpoint = () => {
const checkpoint = counter.getOffset();
@@ -99,14 +98,6 @@ export const getArrayBufferIterator = (
return value;
};
- const disallowDiscard = () => {
- discardAllowed = false;
- };
-
- const allowDiscard = () => {
- discardAllowed = true;
- };
-
const discard = (length: number) => {
counter.increment(length);
};
@@ -260,10 +251,6 @@ export const getArrayBufferIterator = (
};
const removeBytesRead = () => {
- if (!discardAllowed) {
- return;
- }
-
const bytesToRemove = counter.getDiscardedOffset();
// Only do this operation if it is really worth it πŸ˜‡
@@ -645,8 +632,6 @@ export const getArrayBufferIterator = (
getInt32Le,
getInt32,
destroy,
- disallowDiscard,
- allowDiscard,
startBox,
readExpGolomb,
startCheckpoint,
diff --git a/packages/media-parser/src/continue-mdat-routine.ts b/packages/media-parser/src/continue-mdat-routine.ts
deleted file mode 100644
index e42455c089..0000000000
--- a/packages/media-parser/src/continue-mdat-routine.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import {parseIsoBaseMediaBoxes} from './boxes/iso-base-media/parse-boxes';
-import {parseMdatPartially} from './boxes/iso-base-media/parse-mdat-partially';
-import {getMdatBox} from './boxes/iso-base-media/traversal';
-import type {BufferIterator} from './buffer-iterator';
-import {hasAllInfo} from './has-all-info';
-import type {LogLevel} from './log';
-import {maySkipVideoData} from './may-skip-video-data/may-skip-video-data';
-import type {Options, ParseMediaFields} from './options';
-import type {IsoBaseMediaBox, ParseResult} from './parse-result';
-import type {PartialMdatBox} from './parse-video';
-import type {ParserState} from './state/parser-state';
-
-export const continueMdatRoutine = async ({
- iterator,
- maxBytes,
- allowIncompleteBoxes,
- initialBoxes,
- state,
- continueMdat,
- signal,
- logLevel,
- fields,
-}: {
- iterator: BufferIterator;
- maxBytes: number;
- allowIncompleteBoxes: boolean;
- initialBoxes: IsoBaseMediaBox[];
- state: ParserState;
- continueMdat: PartialMdatBox;
- signal: AbortSignal | null;
- logLevel: LogLevel;
- fields: Options<ParseMediaFields>;
-}): Promise<ParseResult> => {
- const initialOffset = iterator.counter.getOffset();
-
- while (
- iterator.bytesRemaining() > 0 &&
- iterator.counter.getOffset() - initialOffset < maxBytes
- ) {
- const result = await parseMdatPartially({
- iterator,
- boxSize: continueMdat.boxSize,
- fileOffset: continueMdat.fileOffset,
- parsedBoxes: initialBoxes,
- state,
- signal,
- });
-
- if (result.type === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed in this routine');
- }
-
- if (result.type === 'partial-mdat-box') {
- return {
- status: 'incomplete',
- continueParsing: () => {
- return Promise.resolve(
- continueMdatRoutine({
- iterator,
- maxBytes,
- allowIncompleteBoxes,
- initialBoxes,
- state,
- continueMdat: result,
- signal,
- logLevel,
- fields,
- }),
- );
- },
- skipTo: null,
- };
- }
-
- const alreadyHasMdat = state.structure
- .getStructureOrNull()
- ?.boxes.find((b) => b.type === 'mdat-box');
-
- if (result.box.type === 'mdat-box' && alreadyHasMdat) {
- initialBoxes = initialBoxes.filter((b) => b.type !== 'mdat-box');
- initialBoxes.push(result.box);
- iterator.allowDiscard();
-
- break;
- } else {
- initialBoxes.push(result.box);
- if (hasAllInfo({fields, state})) {
- return {
- status: 'done',
- };
- }
- }
-
- iterator.removeBytesRead();
- }
-
- const mdatState = getMdatBox(initialBoxes);
- const skipped =
- mdatState?.status === 'samples-skipped' &&
- !maySkipVideoData({state}) &&
- state.supportsContentRange;
- const buffered =
- mdatState?.status === 'samples-buffered' && !maySkipVideoData({state});
-
- if (skipped || buffered) {
- return {
- status: 'incomplete',
- continueParsing: () => {
- if (buffered) {
- iterator.skipTo(mdatState.fileOffset, false);
- }
-
- return parseIsoBaseMediaBoxes({
- iterator,
- maxBytes,
- allowIncompleteBoxes: false,
- initialBoxes,
- state,
- signal,
- logLevel,
- fields,
- });
- },
- skipTo: skipped ? mdatState.fileOffset : null,
- };
- }
-
- return {
- status: 'done',
- };
-};
diff --git a/packages/media-parser/src/index.ts b/packages/media-parser/src/index.ts
index 8222482d96..5856b81f20 100644
--- a/packages/media-parser/src/index.ts
+++ b/packages/media-parser/src/index.ts
@@ -1,7 +1,7 @@
import {createAacCodecPrivate} from './aac-codecprivate';
import {parseFtyp} from './boxes/iso-base-media/ftyp';
import {parseMvhd} from './boxes/iso-base-media/mvhd';
-import {processSample} from './boxes/iso-base-media/stsd/samples';
+import {processIsoFormatBox} from './boxes/iso-base-media/stsd/samples';
import {parseStsd} from './boxes/iso-base-media/stsd/stsd';
import {parseTkhd} from './boxes/iso-base-media/tkhd';
import {parseEbml} from './boxes/webm/parse-ebml';
@@ -67,7 +67,7 @@ export const MediaParserInternals = {
getArrayBufferIterator,
parseStsd,
makeParserState,
- processSample,
+ processSample: processIsoFormatBox,
parseFtyp,
parseEbml,
parseMvhd,
diff --git a/packages/media-parser/src/parse-media.ts b/packages/media-parser/src/parse-media.ts
index 296ee26258..eda253c06f 100644
--- a/packages/media-parser/src/parse-media.ts
+++ b/packages/media-parser/src/parse-media.ts
@@ -72,6 +72,7 @@ export const parseMedia: ParseMedia = async function <
onVideoTrack: onVideoTrack ?? null,
supportsContentRange,
contentLength,
+ logLevel,
});
let currentReader = reader;
@@ -122,9 +123,8 @@ export const parseMedia: ParseMedia = async function <
}
if (iterator.counter.getOffset() === contentLength) {
- Log.verbose(logLevel, 'Reached end of file', contentLength);
- // TODO: Make it possible for ISO base media too
- return state.structure.getStructureOrNull()?.type !== 'iso-base-media';
+ Log.verbose(logLevel, 'Reached end of file');
+ return true;
}
return false;
@@ -183,7 +183,6 @@ export const parseMedia: ParseMedia = async function <
parseResult = await parseVideo({
iterator,
state,
- signal: signal ?? null,
logLevel,
fields,
mimeType: contentType,
@@ -227,6 +226,7 @@ export const parseMedia: ParseMedia = async function <
}
didProgress = iterator.counter.getOffset() > offsetBefore;
+ iterator.removeBytesRead();
}
Log.verbose(logLevel, 'Finished parsing file');
diff --git a/packages/media-parser/src/parse-result.ts b/packages/media-parser/src/parse-result.ts
index 369e11c859..ff10bc2cc7 100644
--- a/packages/media-parser/src/parse-result.ts
+++ b/packages/media-parser/src/parse-result.ts
@@ -1,7 +1,6 @@
import type {BaseBox} from './boxes/iso-base-media/base-type';
import type {EsdsBox} from './boxes/iso-base-media/esds/esds';
import type {FtypBox} from './boxes/iso-base-media/ftyp';
-import type {MdatBox} from './boxes/iso-base-media/mdat/mdat';
import type {MdhdBox} from './boxes/iso-base-media/mdhd';
import type {HdlrBox} from './boxes/iso-base-media/meta/hdlr';
import type {IlstBox} from './boxes/iso-base-media/meta/ilst';
@@ -54,7 +53,6 @@ export type IsoBaseMediaBox =
| MdhdBox
| IlstBox
| EsdsBox
- | MdatBox
| StszBox
| StcoBox
| StscBox
diff --git a/packages/media-parser/src/parse-video.ts b/packages/media-parser/src/parse-video.ts
index d50ccd4837..7b87417087 100644
--- a/packages/media-parser/src/parse-video.ts
+++ b/packages/media-parser/src/parse-video.ts
@@ -1,4 +1,4 @@
-import {parseIsoBaseMediaBoxes} from './boxes/iso-base-media/parse-boxes';
+import {parseIsoBaseMedia} from './boxes/iso-base-media/parse-boxes';
import {parseMp3} from './boxes/mp3/parse-mp3';
import {parseRiff} from './boxes/riff/parse-riff';
import {parseTransportStream} from './boxes/transport-stream/parse-transport-stream';
@@ -16,28 +16,15 @@ import type {Options, ParseMediaFields} from './options';
import type {IsoBaseMediaBox, Mp3Structure, ParseResult} from './parse-result';
import type {ParserState} from './state/parser-state';
-export type PartialMdatBox = {
- type: 'partial-mdat-box';
- boxSize: number;
- fileOffset: number;
+export type BoxAndNext = {
+ box: IsoBaseMediaBox | null;
+ size: number;
+ skipTo: number | null;
};
-export type BoxAndNext =
- | {
- type: 'complete';
- box: IsoBaseMediaBox;
- size: number;
- skipTo: number | null;
- }
- | {
- type: 'incomplete';
- }
- | PartialMdatBox;
-
export const parseVideo = ({
iterator,
state,
- signal,
logLevel,
fields,
mimeType,
@@ -46,7 +33,6 @@ export const parseVideo = ({
}: {
iterator: BufferIterator;
state: ParserState;
- signal: AbortSignal | null;
logLevel: LogLevel;
fields: Options<ParseMediaFields>;
mimeType: string | null;
@@ -71,21 +57,14 @@ export const parseVideo = ({
if (fileType.type === 'iso-base-media') {
Log.verbose(logLevel, 'Detected ISO Base Media container');
- const initialBoxes: IsoBaseMediaBox[] = [];
state.structure.setStructure({
type: 'iso-base-media',
- boxes: initialBoxes,
+ boxes: [],
});
- return parseIsoBaseMediaBoxes({
+ return parseIsoBaseMedia({
iterator,
- maxBytes: Infinity,
- allowIncompleteBoxes: true,
- initialBoxes,
state,
- signal,
- logLevel,
- fields,
});
}
diff --git a/packages/media-parser/src/state/parser-state.ts b/packages/media-parser/src/state/parser-state.ts
index 1eaffbaa1f..26dc1d0007 100644
--- a/packages/media-parser/src/state/parser-state.ts
+++ b/packages/media-parser/src/state/parser-state.ts
@@ -1,5 +1,6 @@
import type {AvcPPs, AvcProfileInfo} from '../boxes/avc/parse-avc';
import type {BufferIterator} from '../buffer-iterator';
+import type {LogLevel} from '../log';
import type {Options, ParseMediaFields} from '../options';
import type {OnAudioTrack, OnVideoTrack} from '../webcodec-sample-types';
import {emittedState} from './emitted-fields';
@@ -34,6 +35,7 @@ export const makeParserState = ({
onVideoTrack,
supportsContentRange,
contentLength,
+ logLevel,
}: {
hasAudioTrackHandlers: boolean;
hasVideoTrackHandlers: boolean;
@@ -44,6 +46,7 @@ export const makeParserState = ({
onAudioTrack: OnAudioTrack | null;
onVideoTrack: OnVideoTrack | null;
contentLength: number | null;
+ logLevel: LogLevel;
}) => {
let skippedBytes: number = 0;
@@ -89,6 +92,7 @@ export const makeParserState = ({
contentLength,
images,
videoSection: videoSectionState(),
+ logLevel,
};
};
diff --git a/packages/media-parser/src/test/content-range.test.ts b/packages/media-parser/src/test/content-range.test.ts
index 6f6ed9be8c..2423045bf7 100644
--- a/packages/media-parser/src/test/content-range.test.ts
+++ b/packages/media-parser/src/test/content-range.test.ts
@@ -3,19 +3,21 @@ import {expect, test} from 'bun:test';
import {parseMedia} from '../parse-media';
import {nodeReader} from '../readers/from-node';
-test('Should get samples of HEVC video if file can only be read forward', async () => {
+test('Should get samples of HEVC video if file can only be read forward', () => {
let videoSamples = 0;
process.env.DISABLE_CONTENT_RANGE = 'true';
- await parseMedia({
- src: exampleVideos.iphonehevc,
- onVideoTrack: () => {
- return () => {
- videoSamples++;
- };
- },
- reader: nodeReader,
- });
+ expect(
+ parseMedia({
+ src: exampleVideos.iphonehevc,
+ onVideoTrack: () => {
+ return () => {
+ videoSamples++;
+ };
+ },
+ reader: nodeReader,
+ }),
+ ).rejects.toThrowError(/Source does not support reading partially/);
- expect(videoSamples).toBe(102);
+ expect(videoSamples).toBe(0);
process.env.DISABLE_CONTENT_RANGE = 'false';
});
diff --git a/packages/media-parser/src/test/fast-mehmet.test.ts b/packages/media-parser/src/test/fast-mehmet.test.ts
index 141ae63ad1..2c14d21a97 100644
--- a/packages/media-parser/src/test/fast-mehmet.test.ts
+++ b/packages/media-parser/src/test/fast-mehmet.test.ts
@@ -9,6 +9,7 @@ test('mehmet video should be fast', async () => {
await parseMedia({
src: exampleVideos.iphonelivefoto,
reader: nodeReader,
+ logLevel: 'trace',
fields: {
structure: true,
},
diff --git a/packages/media-parser/src/test/parse-video.test.ts b/packages/media-parser/src/test/parse-video.test.ts
index b1a6b655c9..fd7824d521 100644
--- a/packages/media-parser/src/test/parse-video.test.ts
+++ b/packages/media-parser/src/test/parse-video.test.ts
@@ -65,7 +65,7 @@ test('Parse a full video', async () => {
});
if (!data) throw new Error('No data');
- const [first, second, third] = data.structure.boxes;
+ const [first, second] = data.structure.boxes;
expect(first).toEqual({
offset: 0,
@@ -82,12 +82,6 @@ test('Parse a full video', async () => {
type: 'regular-box',
children: [],
});
- expect(third).toEqual({
- type: 'mdat-box',
- boxSize: 57014,
- status: 'samples-skipped',
- fileOffset: 40,
- });
});
test('Should warn if missing node reader', () => {