Skip to content

🎥 Make videos programmatically with React

cluster samples

Jonny Burger4a8f29eca921
diff --git a/packages/media-parser/src/boxes/webm/get-sample-from-block.ts b/packages/media-parser/src/boxes/webm/get-sample-from-block.ts
new file mode 100644
index 0000000000..e0f658db47
--- /dev/null
+++ b/packages/media-parser/src/boxes/webm/get-sample-from-block.ts
@@ -0,0 +1,111 @@
+import {getArrayBufferIterator} from '../../buffer-iterator';
+import type {ParserContext} from '../../parser-context';
+import type {AudioSample, VideoSample} from '../../webcodec-sample-types';
+import type {BlockSegment, SimpleBlockSegment} from './segments/all-segments';
+import {matroskaElements} from './segments/all-segments';
+import {parseBlockFlags} from './segments/block-simple-block-flags';
+
+type SampleResult =
+ | {
+ type: 'video-sample';
+ videoSample: VideoSample;
+ }
+ | {
+ type: 'audio-sample';
+ audioSample: AudioSample;
+ }
+ | {
+ type: 'partial-video-sample';
+ partialVideoSample: Omit<VideoSample, 'type'>;
+ }
+ | {
+ type: 'no-sample';
+ };
+
+export const getSampleFromBlock = (
+ ebml: BlockSegment | SimpleBlockSegment,
+ parserContext: ParserContext,
+ offset: number,
+): SampleResult => {
+ const iterator = getArrayBufferIterator(ebml.value);
+ const trackNumber = iterator.getVint();
+ if (trackNumber === null) {
+ throw new Error('Not enough data to get track number, should not happen');
+ }
+
+ const timecodeRelativeToCluster = iterator.getUint16();
+
+ const {keyframe} = parseBlockFlags(iterator, matroskaElements.Block);
+
+ const {codec, trackTimescale} =
+ parserContext.parserState.getTrackInfoByNumber(trackNumber);
+
+ const clusterOffset =
+ parserContext.parserState.getTimestampOffsetForByteOffset(offset);
+
+ const timescale = parserContext.parserState.getTimescale();
+
+ if (clusterOffset === undefined) {
+ throw new Error('Could not find offset for byte offset ' + offset);
+ }
+
+ // https://github.com/hubblec4/Matroska-Chapters-Specs/blob/master/notes.md/#timestampscale
+ // The TimestampScale Element is used to calculate the Raw Timestamp of a Block. The timestamp is obtained by adding the Block's timestamp to the Cluster's Timestamp Element, and then multiplying that result by the TimestampScale. The result will be the Block's Raw Timestamp in nanoseconds.
+ const timecodeInNanoSeconds =
+ (timecodeRelativeToCluster + clusterOffset) *
+ timescale *
+ (trackTimescale ?? 1);
+
+ // Timecode should be in microseconds
+ const timecodeInMicroseconds = timecodeInNanoSeconds / 1000;
+
+ if (!codec) {
+ throw new Error('Could not find codec for track ' + trackNumber);
+ }
+
+ const remainingNow = ebml.value.length - (iterator.counter.getOffset() - 0);
+
+ if (codec.startsWith('V_')) {
+ const partialVideoSample: Omit<VideoSample, 'type'> = {
+ data: iterator.getSlice(remainingNow),
+ cts: null,
+ dts: null,
+ duration: undefined,
+ trackId: trackNumber,
+ timestamp: timecodeInMicroseconds,
+ };
+
+ if (keyframe === null) {
+ return {
+ type: 'partial-video-sample',
+ partialVideoSample,
+ };
+ }
+
+ const sample: VideoSample = {
+ ...partialVideoSample,
+ type: keyframe ? 'key' : 'delta',
+ };
+
+ return {
+ type: 'video-sample',
+ videoSample: sample,
+ };
+ }
+
+ if (codec.startsWith('A_')) {
+ return {
+ type: 'audio-sample',
+ audioSample: {
+ data: iterator.getSlice(remainingNow),
+ trackId: trackNumber,
+ timestamp: timecodeInMicroseconds,
+ type: 'key',
+ },
+ };
+ }
+
+ return {
+ type: 'no-sample',
+ };
+};
diff --git a/packages/media-parser/src/boxes/webm/parse-ebml.ts b/packages/media-parser/src/boxes/webm/parse-ebml.ts
index 78bad20d44..708e6c1a89 100644
--- a/packages/media-parser/src/boxes/webm/parse-ebml.ts
+++ b/packages/media-parser/src/boxes/webm/parse-ebml.ts
@@ -1,6 +1,8 @@
import {registerTrack} from '../../add-new-matroska-tracks';
-import type {BufferIterator} from '../../buffer-iterator';
+import {type BufferIterator} from '../../buffer-iterator';
import type {ParserContext} from '../../parser-context';
+import type {VideoSample} from '../../webcodec-sample-types';
+import {getSampleFromBlock} from './get-sample-from-block';
import {getTrack} from './get-track';
import type {PossibleEbml} from './segments/all-segments';
import {ebmlMap} from './segments/all-segments';
@@ -145,4 +147,53 @@ export const postprocessEbml = async (
if (ebml.type === 'Timestamp') {
parserContext.parserState.setTimestampOffset(offset, ebml.value);
}
+
+ if (ebml.type === 'Block') {
+ const sample = getSampleFromBlock(ebml, parserContext, offset);
+
+ if (sample.type === 'video-sample') {
+ await parserContext.parserState.onVideoSample(
+ sample.videoSample.trackId,
+ sample.videoSample,
+ );
+ }
+
+ if (sample.type === 'audio-sample') {
+ await parserContext.parserState.onAudioSample(
+ sample.audioSample.trackId,
+ sample.audioSample,
+ );
+ }
+ }
+
+ if (ebml.type === 'BlockGroup') {
+ // Blocks don't have information about keyframes.
+ // https://ffmpeg.org/pipermail/ffmpeg-devel/2015-June/173825.html
+ // "For Blocks, keyframes is
+ // inferred by the absence of ReferenceBlock element (as done by matroskadec).""
+
+ const block = ebml.value.find(
+ (c) => c.type === 'SimpleBlock' || c.type === 'Block',
+ );
+ if (!block || (block.type !== 'SimpleBlock' && block.type !== 'Block')) {
+ throw new Error('Expected block segment');
+ }
+
+ const hasReferenceBlock = ebml.value.find(
+ (c) => c.type === 'ReferenceBlock',
+ );
+
+ const sample = getSampleFromBlock(block, parserContext, offset);
+
+ if (sample.type === 'partial-video-sample') {
+ const completeFrame: VideoSample = {
+ ...sample.partialVideoSample,
+ type: hasReferenceBlock ? 'delta' : 'key',
+ };
+ await parserContext.parserState.onVideoSample(
+ sample.partialVideoSample.trackId,
+ completeFrame,
+ );
+ }
+ }
};
diff --git a/packages/media-parser/src/boxes/webm/segments.ts b/packages/media-parser/src/boxes/webm/segments.ts
index 5a715d3cc4..022927b106 100644
--- a/packages/media-parser/src/boxes/webm/segments.ts
+++ b/packages/media-parser/src/boxes/webm/segments.ts
@@ -1,28 +1,13 @@
import type {BufferIterator} from '../../buffer-iterator';
import type {ParseResult} from '../../parse-result';
import type {ParserContext} from '../../parser-context';
-import type {VideoSample} from '../../webcodec-sample-types';
import {parseEbml, postprocessEbml} from './parse-ebml';
import type {PossibleEbml, TrackEntrySegment} from './segments/all-segments';
-import {matroskaElements} from './segments/all-segments';
import {type MainSegment} from './segments/main';
import {expectChildren} from './segments/parse-children';
-import type {
- BlockGroupSegment,
- ClusterSegment,
- SimpleBlockOrBlockSegment,
-} from './segments/track-entry';
-import {
- parseBlockGroupSegment,
- parseSimpleBlockOrBlockSegment,
-} from './segments/track-entry';
-
-export type MatroskaSegment =
- | MainSegment
- | ClusterSegment
- | SimpleBlockOrBlockSegment
- | BlockGroupSegment
- | PossibleEbml;
+import type {ClusterSegment} from './segments/track-entry';
+
+export type MatroskaSegment = MainSegment | ClusterSegment | PossibleEbml;
export type OnTrackEntrySegment = (trackEntry: TrackEntrySegment) => void;
@@ -43,57 +28,6 @@ const parseSegment = async ({
throw new Error(`Expected length of ${segmentId} to be greater than 0`);
}
- if (
- segmentId === matroskaElements.SimpleBlock ||
- segmentId === matroskaElements.Block
- ) {
- return parseSimpleBlockOrBlockSegment({
- iterator,
- length,
- parserContext,
- type: segmentId,
- });
- }
-
- if (segmentId === '0xa0') {
- const blockGroup = await parseBlockGroupSegment(
- iterator,
- length,
- parserContext,
- );
-
- // Blocks don't have information about keyframes.
- // https://ffmpeg.org/pipermail/ffmpeg-devel/2015-June/173825.html
- // "For Blocks, keyframes is
- // inferred by the absence of ReferenceBlock element (as done by matroskadec).""
-
- const block = blockGroup.children.find(
- (c) => c.type === 'simple-block-or-block-segment',
- );
- if (!block || block.type !== 'simple-block-or-block-segment') {
- throw new Error('Expected block segment');
- }
-
- const hasReferenceBlock = blockGroup.children.find(
- (c) => c.type === 'ReferenceBlock',
- );
-
- const partialVideoSample = block.videoSample;
-
- if (partialVideoSample) {
- const completeFrame: VideoSample = {
- ...partialVideoSample,
- type: hasReferenceBlock ? 'delta' : 'key',
- };
- await parserContext.parserState.onVideoSample(
- partialVideoSample.trackId,
- completeFrame,
- );
- }
-
- return blockGroup;
- }
-
iterator.counter.decrement(headerReadSoFar);
const offset = iterator.counter.getOffset();
diff --git a/packages/media-parser/src/boxes/webm/segments/all-segments.ts b/packages/media-parser/src/boxes/webm/segments/all-segments.ts
index beea38bf48..aafb712274 100644
--- a/packages/media-parser/src/boxes/webm/segments/all-segments.ts
+++ b/packages/media-parser/src/boxes/webm/segments/all-segments.ts
@@ -654,6 +654,22 @@ export const timestampEntry = {
type: 'uint',
} as const satisfies Ebml;
+export const block = {
+ name: 'Block',
+ type: 'uint8array',
+} as const satisfies Ebml;
+
+export const simpleBlock = {
+ name: 'SimpleBlock',
+ type: 'uint8array',
+} as const satisfies Ebml;
+
+export const blockGroup = {
+ name: 'BlockGroup',
+ type: 'children',
+ children: [],
+} as const satisfies Ebml;
+
export type CodecIdSegment = EbmlParsed<typeof codecID>;
export type TrackTypeSegment = EbmlParsed<typeof trackType>;
export type WidthSegment = EbmlParsed<typeof widthType>;
@@ -666,6 +682,8 @@ export type TrackNumberSegment = EbmlParsed<typeof trackNumber>;
export type AudioSegment = EbmlParsed<typeof audioSegment>;
export type VideoSegment = EbmlParsed<typeof videoSegment>;
export type TrackEntrySegment = EbmlParsed<typeof trackEntry>;
+export type BlockSegment = EbmlParsed<typeof block>;
+export type SimpleBlockSegment = EbmlParsed<typeof simpleBlock>;
export type EbmlValue<T extends Ebml> = T extends EbmlWithUint8
? number
@@ -788,6 +806,9 @@ export const ebmlMap = {
type: 'uint',
},
[matroskaElements.Tracks]: tracks,
+ [matroskaElements.Block]: block,
+ [matroskaElements.SimpleBlock]: simpleBlock,
+ [matroskaElements.BlockGroup]: blockGroup,
} as const satisfies Partial<Record<MatroskaElement, Ebml>>;
export type PossibleEbml = Prettify<
diff --git a/packages/media-parser/src/boxes/webm/segments/track-entry.ts b/packages/media-parser/src/boxes/webm/segments/track-entry.ts
index ea3cfa1d7e..cdfeb9d80a 100644
--- a/packages/media-parser/src/boxes/webm/segments/track-entry.ts
+++ b/packages/media-parser/src/boxes/webm/segments/track-entry.ts
@@ -1,10 +1,5 @@
-import type {BufferIterator} from '../../../buffer-iterator';
-import type {ParserContext} from '../../../parser-context';
-import type {VideoSample} from '../../../webcodec-sample-types';
import type {MatroskaSegment} from '../segments';
-import type {TrackEntrySegment, matroskaElements} from './all-segments';
-import {parseBlockFlags} from './block-simple-block-flags';
-import {expectChildren} from './parse-children';
+import type {TrackEntrySegment} from './all-segments';
export type TrackInfo = {
codec: string;
@@ -46,148 +41,4 @@ export type ClusterSegment = {
children: MatroskaSegment[];
};
-export type SimpleBlockOrBlockSegment = {
- type: 'simple-block-or-block-segment';
- length: number;
- trackNumber: number;
- timecodeInMicroseconds: number;
- keyframe: boolean | null;
- lacing: number;
- invisible: boolean;
- videoSample: Omit<VideoSample, 'type'> | null;
-};
-
export type GetTracks = () => TrackEntrySegment[];
-
-export const parseSimpleBlockOrBlockSegment = async ({
- iterator,
- length,
- parserContext,
- type,
-}: {
- iterator: BufferIterator;
- length: number;
- parserContext: ParserContext;
- type:
- | (typeof matroskaElements)['Block']
- | (typeof matroskaElements)['SimpleBlock'];
-}): Promise<SimpleBlockOrBlockSegment> => {
- const start = iterator.counter.getOffset();
- const trackNumber = iterator.getVint();
- if (trackNumber === null) {
- throw new Error('Not enough data to get track number, should not happen');
- }
-
- const timecodeRelativeToCluster = iterator.getUint16();
-
- const {invisible, lacing, keyframe} = parseBlockFlags(iterator, type);
-
- const {codec, trackTimescale} =
- parserContext.parserState.getTrackInfoByNumber(trackNumber);
-
- const clusterOffset =
- parserContext.parserState.getTimestampOffsetForByteOffset(
- iterator.counter.getOffset(),
- );
-
- const timescale = parserContext.parserState.getTimescale();
-
- if (clusterOffset === undefined) {
- throw new Error(
- 'Could not find offset for byte offset ' + iterator.counter.getOffset(),
- );
- }
-
- // https://github.com/hubblec4/Matroska-Chapters-Specs/blob/master/notes.md/#timestampscale
- // The TimestampScale Element is used to calculate the Raw Timestamp of a Block. The timestamp is obtained by adding the Block's timestamp to the Cluster's Timestamp Element, and then multiplying that result by the TimestampScale. The result will be the Block's Raw Timestamp in nanoseconds.
- const timecodeInNanoSeconds =
- (timecodeRelativeToCluster + clusterOffset) *
- timescale *
- (trackTimescale ?? 1);
-
- // Timecode should be in microseconds
- const timecodeInMicroseconds = timecodeInNanoSeconds / 1000;
-
- if (!codec) {
- throw new Error('Could not find codec for track ' + trackNumber);
- }
-
- const remainingNow = length - (iterator.counter.getOffset() - start);
-
- let videoSample: Omit<VideoSample, 'type'> | null = null;
-
- if (codec.startsWith('V_')) {
- const partialVideoSample: Omit<VideoSample, 'type'> = {
- data: iterator.getSlice(remainingNow),
- cts: null,
- dts: null,
- duration: undefined,
- trackId: trackNumber,
- timestamp: timecodeInMicroseconds,
- };
-
- if (keyframe === null) {
- // If we don't know if this is a keyframe, we know after we emit the BlockGroup
- videoSample = partialVideoSample;
- } else {
- const sample: VideoSample = {
- ...partialVideoSample,
- type: keyframe ? 'key' : 'delta',
- };
-
- await parserContext.parserState.onVideoSample(trackNumber, sample);
- }
- }
-
- if (codec.startsWith('A_')) {
- await parserContext.parserState.onAudioSample(trackNumber, {
- data: iterator.getSlice(remainingNow),
- trackId: trackNumber,
- timestamp: timecodeInMicroseconds,
- type: 'key',
- });
- }
-
- const remainingNowAfter = length - (iterator.counter.getOffset() - start);
- if (remainingNowAfter > 0) {
- iterator.discard(remainingNowAfter);
- }
-
- return {
- type: 'simple-block-or-block-segment',
- length,
- trackNumber,
- timecodeInMicroseconds,
- keyframe,
- lacing,
- invisible,
- videoSample,
- };
-};
-
-export type BlockGroupSegment = {
- type: 'block-group-segment';
- children: MatroskaSegment[];
-};
-
-export const parseBlockGroupSegment = async (
- iterator: BufferIterator,
- length: number,
- parserContext: ParserContext,
-): Promise<BlockGroupSegment> => {
- const children = await expectChildren({
- iterator,
- length,
- initialChildren: [],
- wrap: null,
- parserContext,
- });
- if (children.status === 'incomplete') {
- throw new Error('Incomplete boxes are not allowed');
- }
-
- return {
- type: 'block-group-segment',
- children: children.segments as MatroskaSegment[],
- };
-};
diff --git a/packages/media-parser/src/test/matroska.test.ts b/packages/media-parser/src/test/matroska.test.ts
index 4586a50b24..00acbfaaab 100644
--- a/packages/media-parser/src/test/matroska.test.ts
+++ b/packages/media-parser/src/test/matroska.test.ts
@@ -216,265 +216,7 @@ test('Should get duration of AV1 video', async () => {
},
],
},
- {
- type: 'cluster-segment',
- children: [
- {
- type: 'Timestamp',
- value: 0,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 279307,
- trackNumber: 1,
- timecodeInMicroseconds: 0,
- keyframe: true,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 96,
- trackNumber: 1,
- timecodeInMicroseconds: 40000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 556,
- trackNumber: 1,
- timecodeInMicroseconds: 80000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 948,
- trackNumber: 1,
- timecodeInMicroseconds: 120000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 577,
- trackNumber: 1,
- timecodeInMicroseconds: 160000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 779,
- trackNumber: 1,
- timecodeInMicroseconds: 200000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 793,
- trackNumber: 1,
- timecodeInMicroseconds: 240000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 740,
- trackNumber: 1,
- timecodeInMicroseconds: 280000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 1095,
- trackNumber: 1,
- timecodeInMicroseconds: 320000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 1097,
- trackNumber: 1,
- timecodeInMicroseconds: 360000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 1155,
- trackNumber: 1,
- timecodeInMicroseconds: 400000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 1526,
- trackNumber: 1,
- timecodeInMicroseconds: 440000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 1487,
- trackNumber: 1,
- timecodeInMicroseconds: 480000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 2046,
- trackNumber: 1,
- timecodeInMicroseconds: 520000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 1372,
- trackNumber: 1,
- timecodeInMicroseconds: 560000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 1441,
- trackNumber: 1,
- timecodeInMicroseconds: 600000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 2947,
- trackNumber: 1,
- timecodeInMicroseconds: 640000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 2652,
- trackNumber: 1,
- timecodeInMicroseconds: 680000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 4199,
- trackNumber: 1,
- timecodeInMicroseconds: 720000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 3998,
- trackNumber: 1,
- timecodeInMicroseconds: 760000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 6373,
- trackNumber: 1,
- timecodeInMicroseconds: 800000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 5955,
- trackNumber: 1,
- timecodeInMicroseconds: 840000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 7943,
- trackNumber: 1,
- timecodeInMicroseconds: 880000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 8241,
- trackNumber: 1,
- timecodeInMicroseconds: 920000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- {
- type: 'simple-block-or-block-segment',
- length: 9506,
- trackNumber: 1,
- timecodeInMicroseconds: 960000,
- keyframe: false,
- lacing: 0,
- invisible: false,
- videoSample: null,
- },
- ],
- },
+
{
type: 'Cues',
value: undefined,