Skip to content

🎥 Make videos programmatically with React

fix rotation

Jonny Burgerb5dd72e9692c
diff --git a/packages/example/src/EncoderDemo.tsx b/packages/example/src/EncoderDemo.tsx
index 7b6ce6f6d5..a3e328a37a 100644
--- a/packages/example/src/EncoderDemo.tsx
+++ b/packages/example/src/EncoderDemo.tsx
@@ -31,6 +31,7 @@ export const EncoderDemo: React.FC = () => {
<SrcEncoder src={staticFile('matroska-mp3.mkv')} />
<SrcEncoder src={staticFile('vid1.mp4')} />
<SrcEncoder src={staticFile('whip.mp3')} />
+ <SrcEncoder src={staticFile('iphone-hevc.mov')} />
<SrcEncoder src={staticFile('sample.aac')} />
<SrcEncoder src={staticFile('stretched-vp8.webm')} />
<SrcEncoder src={staticFile('opus.webm')} />
diff --git a/packages/media-parser/src/boxes/iso-base-media/make-track.ts b/packages/media-parser/src/boxes/iso-base-media/make-track.ts
index b2ddc0585f..716cb61969 100644
--- a/packages/media-parser/src/boxes/iso-base-media/make-track.ts
+++ b/packages/media-parser/src/boxes/iso-base-media/make-track.ts
@@ -10,6 +10,7 @@ import {
} from '../../get-fps';
import {
applyAspectRatios,
+ applyTkhdBox,
getDisplayAspectRatio,
getSampleAspectRatio,
getVideoSample,
@@ -39,6 +40,7 @@ export const makeBaseMediaTrack = (
const sttsBox = getSttsBox(trakBox);
const tkhdBox = getTkhdBox(trakBox);
const cttsBox = getCttsBox(trakBox);
+
const videoDescriptors = getVideoDescriptors(trakBox);
const timescaleAndDuration = getTimescaleAndDuration(trakBox);
@@ -116,7 +118,7 @@ export const makeBaseMediaTrack = (
const sampleAspectRatio = getSampleAspectRatio(trakBox);
- const applied = applyAspectRatios({
+ const aspectRatioApplied = applyAspectRatios({
dimensions: videoSample,
sampleAspectRatio,
displayAspectRatio: getDisplayAspectRatio({
@@ -125,6 +127,9 @@ export const makeBaseMediaTrack = (
}),
});
+ const {displayAspectHeight, displayAspectWidth, height, rotation, width} =
+ applyTkhdBox(aspectRatioApplied, tkhdBox);
+
const codec = getVideoCodecString(trakBox);
if (!codec) {
@@ -139,12 +144,14 @@ export const makeBaseMediaTrack = (
timescale: timescaleAndDuration.timescale,
codec,
sampleAspectRatio: getSampleAspectRatio(trakBox),
- width: applied.width,
- height: applied.height,
+ width,
+ height,
codedWidth: videoSample.width,
codedHeight: videoSample.height,
- displayAspectWidth: applied.width,
- displayAspectHeight: applied.height,
+ // Repeating those keys because they get picked up by VideoDecoder
+ displayAspectWidth,
+ displayAspectHeight,
+ rotation,
};
return track;
};
diff --git a/packages/media-parser/src/boxes/webm/get-track.ts b/packages/media-parser/src/boxes/webm/get-track.ts
index 8b9677dbfe..3392b3d1bd 100644
--- a/packages/media-parser/src/boxes/webm/get-track.ts
+++ b/packages/media-parser/src/boxes/webm/get-track.ts
@@ -223,6 +223,7 @@ export const getTrack = ({
displayAspectWidth: displayWidth
? displayWidth.displayWidth
: width.width,
+ rotation: 0,
};
}
diff --git a/packages/media-parser/src/get-dimensions.ts b/packages/media-parser/src/get-dimensions.ts
index c735ca49ea..cc563d501a 100644
--- a/packages/media-parser/src/get-dimensions.ts
+++ b/packages/media-parser/src/get-dimensions.ts
@@ -1,8 +1,6 @@
-import type {MainSegment} from './boxes/webm/segments/main';
-import {trakBoxContainsVideo} from './get-fps';
-import {getVideoSample} from './get-sample-aspect-ratio';
+import {getTracks} from './get-tracks';
import type {AnySegment} from './parse-result';
-import {getMoovBox, getStsdBox, getTkhdBox, getTraks} from './traversal';
+import type {ParserState} from './parser-state';
export type Dimensions = {
width: number;
@@ -15,114 +13,34 @@ export type ExpandedDimensions = Dimensions & {
unrotatedHeight: number;
};
-const getDimensionsFromMatroska = (
- segments: MainSegment,
+export const getDimensions = (
+ boxes: AnySegment[],
+ state: ParserState,
): ExpandedDimensions => {
- const tracksSegment = segments.children.find(
- (b) => b.type === 'tracks-segment',
- );
- if (!tracksSegment || tracksSegment.type !== 'tracks-segment') {
- throw new Error('No tracks segment');
+ const {videoTracks} = getTracks(boxes, state);
+ if (!videoTracks.length) {
+ throw new Error('Expected video track');
}
- const trackEntrySegment = tracksSegment.children.find((b) => {
- if (b.type !== 'track-entry-segment') {
- return false;
- }
-
- return (
- b.children.find(
- (c) => c.type === 'codec-segment' && c.codec.startsWith('V_'),
- ) !== undefined
- );
- });
- if (!trackEntrySegment || trackEntrySegment.type !== 'track-entry-segment') {
- throw new Error('No track entry segment');
- }
-
- const videoSegment = trackEntrySegment.children.find(
- (b) => b.type === 'video-segment',
- );
- if (!videoSegment || videoSegment.type !== 'video-segment') {
- throw new Error('No video segment');
- }
-
- const widthSegment = videoSegment.children.find(
- (b) => b.type === 'width-segment',
- );
- if (!widthSegment || widthSegment.type !== 'width-segment') {
- throw new Error('No width segment');
- }
-
- const heightSegment = videoSegment.children.find(
- (b) => b.type === 'height-segment',
- );
- if (!heightSegment || heightSegment.type !== 'height-segment') {
- throw new Error('No height segment');
- }
-
- return {
- width: widthSegment.width,
- height: heightSegment.height,
- rotation: 0,
- unrotatedHeight: heightSegment.height,
- unrotatedWidth: widthSegment.width,
- };
-};
-
-export const getDimensions = (boxes: AnySegment[]): ExpandedDimensions => {
- const matroskaBox = boxes.find((b) => b.type === 'main-segment');
- if (matroskaBox && matroskaBox.type === 'main-segment') {
- return getDimensionsFromMatroska(matroskaBox);
- }
-
- const moovBox = getMoovBox(boxes);
- if (!moovBox) {
- throw new Error('Expected moov box');
- }
-
- const trakBox = getTraks(moovBox).filter((t) => trakBoxContainsVideo(t))[0];
-
- if (!trakBox) {
- throw new Error('Expected trak box');
- }
-
- const tkhdBox = getTkhdBox(trakBox);
- if (tkhdBox) {
- return {
- width: tkhdBox.width,
- height: tkhdBox.height,
- rotation: tkhdBox.rotation,
- unrotatedHeight: tkhdBox.unrotatedHeight,
- unrotatedWidth: tkhdBox.unrotatedWidth,
- };
- }
-
- const stsdBox = getStsdBox(trakBox);
-
- if (!stsdBox) {
- throw new Error('Expected stsd box');
- }
-
- const videoSample = getVideoSample(trakBox);
- if (!videoSample) {
- throw new Error('Expected video sample');
- }
+ const firstVideoTrack = videoTracks[0];
return {
- width: videoSample.width,
- height: videoSample.height,
- rotation: 0,
- unrotatedHeight: videoSample.height,
- unrotatedWidth: videoSample.width,
+ width: firstVideoTrack.width,
+ height: firstVideoTrack.height,
+ rotation: firstVideoTrack.rotation,
+ unrotatedHeight: firstVideoTrack.displayAspectHeight,
+ unrotatedWidth: firstVideoTrack.displayAspectWidth,
};
};
// TODO: An audio track should return 'hasDimensions' = true on an audio file
// and stop parsing
-export const hasDimensions = (boxes: AnySegment[]): boolean => {
+export const hasDimensions = (
+ boxes: AnySegment[],
+ state: ParserState,
+): boolean => {
try {
- return getDimensions(boxes) !== null;
+ return getDimensions(boxes, state) !== null;
} catch (err) {
return false;
}
diff --git a/packages/media-parser/src/get-sample-aspect-ratio.ts b/packages/media-parser/src/get-sample-aspect-ratio.ts
index e9326008a3..c1ed4cb6f5 100644
--- a/packages/media-parser/src/get-sample-aspect-ratio.ts
+++ b/packages/media-parser/src/get-sample-aspect-ratio.ts
@@ -4,6 +4,7 @@ import type {ColorParameterBox} from './boxes/iso-base-media/stsd/colr';
import type {HvccBox} from './boxes/iso-base-media/stsd/hvcc';
import type {PaspBox} from './boxes/iso-base-media/stsd/pasp';
import type {VideoSample} from './boxes/iso-base-media/stsd/samples';
+import type {TkhdBox} from './boxes/iso-base-media/tkhd';
import type {TrakBox} from './boxes/iso-base-media/trak/trak';
import type {Dimensions} from './get-dimensions';
import {getStsdBox} from './traversal';
@@ -115,6 +116,35 @@ export const getColrBox = (
return colrBox;
};
+export const applyTkhdBox = (
+ aspectRatioApplied: Dimensions,
+ tkhdBox: TkhdBox,
+): {
+ displayAspectWidth: number;
+ displayAspectHeight: number;
+ width: number;
+ height: number;
+ rotation: number;
+} => {
+ if (tkhdBox === null || tkhdBox.rotation === 0) {
+ return {
+ displayAspectWidth: aspectRatioApplied.width,
+ displayAspectHeight: aspectRatioApplied.height,
+ width: aspectRatioApplied.width,
+ height: aspectRatioApplied.height,
+ rotation: 0,
+ };
+ }
+
+ return {
+ width: tkhdBox.width,
+ height: tkhdBox.height,
+ rotation: tkhdBox.rotation,
+ displayAspectWidth: aspectRatioApplied.width,
+ displayAspectHeight: aspectRatioApplied.height,
+ };
+};
+
export const applyAspectRatios = ({
dimensions,
sampleAspectRatio,
diff --git a/packages/media-parser/src/get-tracks.ts b/packages/media-parser/src/get-tracks.ts
index 3a5d5f2728..0c8e6b60b5 100644
--- a/packages/media-parser/src/get-tracks.ts
+++ b/packages/media-parser/src/get-tracks.ts
@@ -26,6 +26,7 @@ export type VideoTrack = {
displayAspectHeight: number;
codedWidth: number;
codedHeight: number;
+ rotation: number;
};
export type AudioTrack = {
diff --git a/packages/media-parser/src/has-all-info.ts b/packages/media-parser/src/has-all-info.ts
index b29872e2f0..299fb04493 100644
--- a/packages/media-parser/src/has-all-info.ts
+++ b/packages/media-parser/src/has-all-info.ts
@@ -6,6 +6,7 @@ import {hasTracks} from './get-tracks';
import {hasVideoCodec} from './get-video-codec';
import type {Options} from './options';
import type {ParseResult} from './parse-result';
+import type {ParserState} from './parser-state';
export const hasAllInfo = (
options: Options<
@@ -21,6 +22,7 @@ export const hasAllInfo = (
boolean
>,
parseResult: ParseResult,
+ state: ParserState,
) => {
const keys = Object.entries(options)
.filter(([, value]) => value)
@@ -51,7 +53,7 @@ export const hasAllInfo = (
key === 'rotation' ||
key === 'unrotatedDimension'
) {
- return hasDimensions(parseResult.segments);
+ return hasDimensions(parseResult.segments, state);
}
if (key === 'fps') {
diff --git a/packages/media-parser/src/parse-media.ts b/packages/media-parser/src/parse-media.ts
index 5665a5004e..f3d040577f 100644
--- a/packages/media-parser/src/parse-media.ts
+++ b/packages/media-parser/src/parse-media.ts
@@ -83,7 +83,7 @@ export const parseMedia: ParseMedia = async ({
// TODO Better: Check if no active listeners are registered
// Also maybe check for canSkipVideoData
if (
- hasAllInfo(fields ?? {}, parseResult) &&
+ hasAllInfo(fields ?? {}, parseResult, state) &&
!onVideoTrack &&
!onAudioTrack
) {
@@ -117,7 +117,7 @@ export const parseMedia: ParseMedia = async ({
}
if (fields?.dimensions) {
- const dimensions = getDimensions(parseResult.segments);
+ const dimensions = getDimensions(parseResult.segments, state);
returnValue.dimensions = {
width: dimensions.width,
height: dimensions.height,
@@ -125,7 +125,7 @@ export const parseMedia: ParseMedia = async ({
}
if (fields?.unrotatedDimension) {
- const dimensions = getDimensions(parseResult.segments);
+ const dimensions = getDimensions(parseResult.segments, state);
returnValue.unrotatedDimension = {
width: dimensions.unrotatedWidth,
height: dimensions.unrotatedHeight,
@@ -133,7 +133,7 @@ export const parseMedia: ParseMedia = async ({
}
if (fields?.rotation) {
- const dimensions = getDimensions(parseResult.segments);
+ const dimensions = getDimensions(parseResult.segments, state);
returnValue.rotation = dimensions.rotation;
}
diff --git a/packages/media-parser/src/test/stream-local.test.ts b/packages/media-parser/src/test/stream-local.test.ts
index 903b0f9693..62cfc51f22 100644
--- a/packages/media-parser/src/test/stream-local.test.ts
+++ b/packages/media-parser/src/test/stream-local.test.ts
@@ -147,6 +147,7 @@ test('Should stream AV1', async () => {
width: 1920,
displayAspectHeight: 1080,
displayAspectWidth: 1920,
+ rotation: 0,
});
expect(parsed.audioTracks.length).toBe(0);
expect(videoTracks).toBe(1);
@@ -299,6 +300,7 @@ test('Should stream variable fps video', async () => {
width: 1280,
displayAspectHeight: 720,
displayAspectWidth: 1280,
+ rotation: 0,
});
expect(parsed.audioTracks.length).toBe(1);
expect(parsed.audioTracks[0]).toEqual({
@@ -462,7 +464,7 @@ test('Custom DAR', async () => {
});
expect(parsed.dimensions).toEqual({
height: 720,
- width: 404.9717559814453,
+ width: 405,
});
expect(parsed.durationInSeconds).toBe(5.725);
expect(parsed.fps).toBe(30);
@@ -477,7 +479,7 @@ test('Custom DAR', async () => {
expect(parsed.rotation).toBe(0);
expect(parsed.unrotatedDimension).toEqual({
height: 720,
- width: 404.9717559814453,
+ width: 405,
});
});
@@ -587,6 +589,7 @@ test('Stretched VP8', async () => {
width: 1920,
displayAspectHeight: 1080,
displayAspectWidth: 1920,
+ rotation: 0,
},
]);
});
diff --git a/packages/media-parser/src/test/stream-samples.test.ts b/packages/media-parser/src/test/stream-samples.test.ts
index b9ab124479..28f0880b3c 100644
--- a/packages/media-parser/src/test/stream-samples.test.ts
+++ b/packages/media-parser/src/test/stream-samples.test.ts
@@ -119,6 +119,7 @@ test('Stream samples', async () => {
codedHeight: 1080,
displayAspectHeight: 1080,
displayAspectWidth: 1080,
+ rotation: 0,
},
]);