🎥 Make videos programmatically with React
restructuring
Jonny Burgerab7a23e1fccb
diff --git a/packages/renderer/src/assets/assets.ts b/packages/renderer/src/assets/assets.tsdeleted file mode 100644index bbbb6e5645..0000000000--- a/packages/renderer/src/assets/assets.ts+++ /dev/null@@ -1,110 +0,0 @@-import execa from 'execa';-import pLimit from 'p-limit';-import {TAsset} from 'remotion';-import {getActualConcurrency} from '../get-concurrency';--type UnsafeAsset = TAsset & {- startInVideo: number;- duration: number | null;-};--type MediaAsset = Omit<UnsafeAsset, 'duration'> & {- duration: number;-};--export type AssetAudioDetails = {- channels: number;-};--export type Assets = MediaAsset[];--const areEqual = (a: TAsset, b: TAsset) => {- return a.type === b.type && a.src === b.src;-};--const findFrom = (target: TAsset[], asset: TAsset) => {- const index = target.findIndex((a) => areEqual(a, asset));- if (index === -1) {- return false;- } else {- target.splice(index, 1);- return true;- }-};--export const calculateAssetsPosition = (frames: TAsset[][]): Assets => {- const assets: UnsafeAsset[] = [];-- for (let frame = 0; frame < frames.length; frame++) {- const prev = (frames[frame - 1] ?? []).slice();- const current = frames[frame];- const next = (frames[frame + 1] ?? []).slice();-- for (const asset of current) {- if (!findFrom(prev, asset)) {- assets.push({- ...asset,- duration: null,- startInVideo: frame,- });- }-- if (!findFrom(next, asset)) {- const found = assets.find(- (a) => a.duration === null && areEqual(a, asset)- );- if (!found) throw new Error('something wrong');- found.duration = frame - found.startInVideo - 1;- }- }- }-- for (const asset of assets) {- if (asset.duration === null) {- throw new Error('duration is unexpectedly null');- }- }- return assets as MediaAsset[];-};--export async function getAudioChannels(path: string) {- const args = [- ['-v', 'error'],- ['-show_entries', 'stream=channels'],- ['-of', 'default=nw=1'],- [path],- ]- .reduce<(string | null)[]>((acc, val) => acc.concat(val), [])- .filter(Boolean) as string[];-- const task = await execa('ffprobe', args);- if (!task.stdout.includes('channels=')) {- return 0;- }- const channels = parseInt(task.stdout.replace('channels=', ''), 10);- if (isNaN(channels)) {- throw new TypeError('Unexpected result from ffprobe for channel probing: ');- }- return channels;-}--export async function getAssetAudioDetails(options: {- assetPaths: string[];- parallelism?: number | null;-}): Promise<Map<string, AssetAudioDetails>> {- const uniqueAssets = [...new Set(options.assetPaths)];- const actualParallelism = getActualConcurrency(options.parallelism ?? null);- const parallelLimit = pLimit(actualParallelism);- const audioChannelTasks = uniqueAssets.map((path) =>- parallelLimit(() => getAudioChannels(path))- );- const result = await Promise.all(audioChannelTasks);-- const mappedResults: [string, AssetAudioDetails][] = result.map(- (channels, index) => {- return [uniqueAssets[index], {channels}];- }- );-- return new Map<string, AssetAudioDetails>(mappedResults);-}diff --git a/packages/renderer/src/assets/calculate-asset-positions.ts b/packages/renderer/src/assets/calculate-asset-positions.tsnew file mode 100644index 0000000000..ada9bb93ac--- /dev/null+++ b/packages/renderer/src/assets/calculate-asset-positions.ts@@ -0,0 +1,51 @@+import {TAsset} from 'remotion';+import {Assets, MediaAsset, UnsafeAsset} from './types';++const areEqual = (a: TAsset, b: TAsset) => {+ return a.type === b.type && a.src === b.src;+};++const findFrom = (target: TAsset[], asset: TAsset) => {+ const index = target.findIndex((a) => areEqual(a, asset));+ if (index === -1) {+ return false;+ } else {+ target.splice(index, 1);+ return true;+ }+};++export const calculateAssetPositions = (frames: TAsset[][]): Assets => {+ const assets: UnsafeAsset[] = [];++ for (let frame = 0; frame < frames.length; frame++) {+ const prev = (frames[frame - 1] ?? []).slice();+ const current = frames[frame];+ const next = (frames[frame + 1] ?? []).slice();++ for (const asset of current) {+ if (!findFrom(prev, asset)) {+ assets.push({+ ...asset,+ duration: null,+ startInVideo: frame,+ });+ }++ if (!findFrom(next, asset)) {+ const found = assets.find(+ (a) => a.duration === null && areEqual(a, asset)+ );+ if (!found) throw new Error('something wrong');+ found.duration = frame - found.startInVideo - 1;+ }+ }+ }++ for (const asset of assets) {+ if (asset.duration === null) {+ throw new Error('duration is unexpectedly null');+ }+ }+ return assets as MediaAsset[];+};diff --git a/packages/renderer/src/assets/get-asset-audio-details.ts b/packages/renderer/src/assets/get-asset-audio-details.tsnew file mode 100644index 0000000000..82e35be24e--- /dev/null+++ b/packages/renderer/src/assets/get-asset-audio-details.ts@@ -0,0 +1,25 @@+import pLimit from 'p-limit';+import {getActualConcurrency} from '../get-concurrency';+import {getAudioChannels} from './get-audio-channels';+import {AssetAudioDetails} from './types';++export async function getAssetAudioDetails(options: {+ assetPaths: string[];+ parallelism?: number | null;+}): Promise<Map<string, AssetAudioDetails>> {+ const uniqueAssets = [...new Set(options.assetPaths)];+ const actualParallelism = getActualConcurrency(options.parallelism ?? null);+ const parallelLimit = pLimit(actualParallelism);+ const audioChannelTasks = uniqueAssets.map((path) =>+ parallelLimit(() => getAudioChannels(path))+ );+ const result = await Promise.all(audioChannelTasks);++ const mappedResults: [string, AssetAudioDetails][] = result.map(+ (channels, index) => {+ return [uniqueAssets[index], {channels}];+ }+ );++ return new Map<string, AssetAudioDetails>(mappedResults);+}diff --git a/packages/renderer/src/assets/get-audio-channels.ts b/packages/renderer/src/assets/get-audio-channels.tsnew file mode 100644index 0000000000..58e841ce8e--- /dev/null+++ b/packages/renderer/src/assets/get-audio-channels.ts@@ -0,0 +1,22 @@+import execa from 'execa';++export async function getAudioChannels(path: string) {+ const args = [+ ['-v', 'error'],+ ['-show_entries', 'stream=channels'],+ ['-of', 'default=nw=1'],+ [path],+ ]+ .reduce<(string | null)[]>((acc, val) => acc.concat(val), [])+ .filter(Boolean) as string[];++ const task = await execa('ffprobe', args);+ if (!task.stdout.includes('channels=')) {+ return 0;+ }+ const channels = parseInt(task.stdout.replace('channels=', ''), 10);+ if (isNaN(channels)) {+ throw new TypeError('Unexpected result from ffprobe for channel probing: ');+ }+ return channels;+}diff --git a/packages/renderer/src/assets/types.ts b/packages/renderer/src/assets/types.tsnew file mode 100644index 0000000000..de97142881--- /dev/null+++ b/packages/renderer/src/assets/types.ts@@ -0,0 +1,16 @@+import {TAsset} from 'remotion';++export type UnsafeAsset = TAsset & {+ startInVideo: number;+ duration: number | null;+};++export type MediaAsset = Omit<UnsafeAsset, 'duration'> & {+ duration: number;+};++export type AssetAudioDetails = {+ channels: number;+};++export type Assets = MediaAsset[];diff --git a/packages/renderer/src/render.ts b/packages/renderer/src/render.tsindex 87abff6207..a55443936b 100644--- a/packages/renderer/src/render.ts+++ b/packages/renderer/src/render.ts@@ -1,8 +1,9 @@import path from 'path';import {Browser, FrameRange, Internals, VideoConfig} from 'remotion';import {openBrowser, provideScreenshot} from '.';-import {Assets, calculateAssetsPosition} from './assets/assets';+import {calculateAssetPositions} from './assets/calculate-asset-positions';import {mapLocalhostAssetToFile} from './assets/map-localhost-to-file';+import {Assets} from './assets/types';import {getActualConcurrency} from './get-concurrency';import {getFrameCount} from './get-frame-range';import {getFrameToRender} from './get-frame-to-render';@@ -124,7 +125,7 @@ export const renderFrames = async ({}));await Promise.all([browserInstance.close(), close()]);- const assetPositions = calculateAssetsPosition(assetsFrames);+ const assetPositions = calculateAssetPositions(assetsFrames);return {assetPositions,diff --git a/packages/renderer/src/stitcher.ts b/packages/renderer/src/stitcher.tsindex 3bf8cd2828..0e72614df9 100644--- a/packages/renderer/src/stitcher.ts+++ b/packages/renderer/src/stitcher.ts@@ -2,7 +2,8 @@ import execa from 'execa';import fs from 'fs';import {Codec, Internals, PixelFormat} from 'remotion';import url from 'url';-import {AssetAudioDetails, Assets, getAssetAudioDetails} from './assets/assets';+import {getAssetAudioDetails} from './assets/get-asset-audio-details';+import {AssetAudioDetails, Assets} from './assets/types';import {DEFAULT_IMAGE_FORMAT, ImageFormat} from './image-format';import {parseFfmpegProgress} from './parse-ffmpeg-progress';import {validateFfmpeg} from './validate-ffmpeg';diff --git a/packages/renderer/src/test/get-audio-channels.test.ts b/packages/renderer/src/test/get-audio-channels.test.tsindex 1d285203ea..a522ad2c84 100644--- a/packages/renderer/src/test/get-audio-channels.test.ts+++ b/packages/renderer/src/test/get-audio-channels.test.ts@@ -1,6 +1,6 @@import {existsSync} from 'fs';import path from 'path';-import {getAudioChannels} from '../assets/assets';+import {getAudioChannels} from '../assets/get-audio-channels';test('Get audio channels for video', async () => {const videoWithoutAudio = path.join(