🎥 Make videos programmatically with React
frame range
Jonny Burgerefe003f033ba
diff --git a/packages/docs/docs/lambda-changelog.md b/packages/docs/docs/lambda-changelog.mdindex 0cd0b0073c..898102f982 100644--- a/packages/docs/docs/lambda-changelog.md+++ b/packages/docs/docs/lambda-changelog.md@@ -16,9 +16,11 @@ Keep track of changes to the APIs of Remotion Lambda here.## Unreleased+- Support rendering a video partially using `frameRange` / `--frame-range` option+- Improve Setup guide+- Improve CLI documentation- Deleted `save-browser-logs` function in favour of the new CloudWatch solution. Pass `--log=verbose` instead and see CloudWatch for more detailed logs.- Retry if the AWS rate limit is exceeded for `npx remotion lambda permissions validate` command and for `validatePermissions()` function.-- Improve Setup guide- New Fonts: `Noto Sans JP`, `Noto Sans Simplified Chinese`, `Noto Sans Traditional Chinese`, `Noto Sans Korean` both in Regular and Bold.## November 28th, 2021diff --git a/packages/lambda/remotionlambda.zip b/packages/lambda/remotionlambda.zipindex 123dcd1d4e..5776bd92a1 100644Binary files a/packages/lambda/remotionlambda.zip and b/packages/lambda/remotionlambda.zip differdiff --git a/packages/lambda/src/api/render-video-on-lambda.ts b/packages/lambda/src/api/render-video-on-lambda.tsindex 1034275317..f94e61eb44 100644--- a/packages/lambda/src/api/render-video-on-lambda.ts+++ b/packages/lambda/src/api/render-video-on-lambda.ts@@ -1,4 +1,11 @@-import {ImageFormat, LogLevel, PixelFormat, ProResProfile} from 'remotion';+import {+ FrameRange,+ ImageFormat,+ LogLevel,+ PixelFormat,+ ProResProfile,+} from 'remotion';+import {DEFAULT_LOG_LEVEL} from 'remotion/src/config/log';import {AwsRegion} from '../pricing/aws-regions';import {callLambda} from '../shared/call-lambda';import {@@ -46,6 +53,7 @@ export const renderVideoOnLambda = async ({privacy,enableChunkOptimization,logLevel,+ frameRange,}: {region: AwsRegion;functionName: string;@@ -64,6 +72,7 @@ export const renderVideoOnLambda = async ({framesPerLambda?: number;enableChunkOptimization?: boolean;logLevel?: LogLevel;+ frameRange?: FrameRange;}) => {validateFramesPerLambda(framesPerLambda);const res = await callLambda({@@ -84,7 +93,8 @@ export const renderVideoOnLambda = async ({maxRetries,privacy,enableChunkOptimization,- logLevel,+ logLevel: logLevel ?? DEFAULT_LOG_LEVEL,+ frameRange: frameRange ?? null,},region,});diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.tsindex d9242efc7f..6788a19630 100644--- a/packages/lambda/src/cli/commands/render/render.ts+++ b/packages/lambda/src/cli/commands/render/render.ts@@ -81,6 +81,7 @@ export const renderCommand = async (args: string[]) => {privacy,logLevel: cliOptions.logLevel,enableChunkOptimization: !parsedLambdaCli['disable-chunk-optimization'],+ frameRange: cliOptions.frameRange ?? undefined,});const totalSteps = outName ? 5 : 4;diff --git a/packages/lambda/src/functions/chunk-optimization/can-use-optimization.ts b/packages/lambda/src/functions/chunk-optimization/can-use-optimization.tsindex 8cd1cbc6c7..615db266a2 100644--- a/packages/lambda/src/functions/chunk-optimization/can-use-optimization.ts+++ b/packages/lambda/src/functions/chunk-optimization/can-use-optimization.ts@@ -4,11 +4,11 @@ import {OptimizationProfile} from './types';export const canUseOptimization = ({optimization,framesPerLambda,- frameCount,+ frameRange,}: {optimization: OptimizationProfile | null;framesPerLambda: number;- frameCount: number;+ frameRange: [number, number];}) => {if (!optimization) {return false;@@ -18,11 +18,15 @@ export const canUseOptimization = ({return false;}- if (optimization.frameCount !== frameCount) {+ if (optimization.lambdaVersion !== CURRENT_VERSION) {return false;}- if (optimization.lambdaVersion !== CURRENT_VERSION) {+ if (optimization.frameRange[0] !== frameRange[0]) {+ return false;+ }++ if (optimization.frameRange[1] !== frameRange[1]) {return false;}diff --git a/packages/lambda/src/functions/chunk-optimization/plan-frame-ranges.ts b/packages/lambda/src/functions/chunk-optimization/plan-frame-ranges.tsindex a9115807c4..a1da8abf71 100644--- a/packages/lambda/src/functions/chunk-optimization/plan-frame-ranges.ts+++ b/packages/lambda/src/functions/chunk-optimization/plan-frame-ranges.ts@@ -4,31 +4,37 @@ import {OptimizationProfile} from './types';export const planFrameRanges = ({chunkCount,framesPerLambda,- frameCount,optimization,shouldUseOptimization,+ frameRange,}: {chunkCount: number;framesPerLambda: number;- frameCount: number;optimization: OptimizationProfile | null;shouldUseOptimization: boolean;+ frameRange: [number, number];}): {chunks: [number, number][]; didUseOptimization: boolean} => {if (- canUseOptimization({optimization, framesPerLambda, frameCount}) &&+ canUseOptimization({+ optimization,+ framesPerLambda,+ frameRange,+ }) &&shouldUseOptimization) {return {- chunks: (optimization as OptimizationProfile).frameRange,+ chunks: (optimization as OptimizationProfile).ranges,didUseOptimization: true,};}+ const frameCount = frameRange[1] - frameRange[0] + 1;+return {chunks: new Array(chunkCount).fill(1).map((_, i) => {return [- i * framesPerLambda,- Math.min(frameCount, (i + 1) * framesPerLambda) - 1,+ i * framesPerLambda + frameRange[0],+ Math.min(frameCount, (i + 1) * framesPerLambda) - 1 + frameRange[0],];}),didUseOptimization: false,diff --git a/packages/lambda/src/functions/chunk-optimization/types.ts b/packages/lambda/src/functions/chunk-optimization/types.tsindex 07ea11d1db..8477ce4d3c 100644--- a/packages/lambda/src/functions/chunk-optimization/types.ts+++ b/packages/lambda/src/functions/chunk-optimization/types.ts@@ -16,7 +16,8 @@ export type ChunkTimingData = Omit<ObjectChunkTimingData, 'timings'> & {export type TimingProfile = ChunkTimingData[];export type OptimizationProfile = {- frameRange: [number, number][];+ ranges: [number, number][];+ frameRange: [number, number];oldTiming: number;newTiming: number;frameCount: number;diff --git a/packages/lambda/src/functions/launch.ts b/packages/lambda/src/functions/launch.tsindex 1890083cb2..d4d5095fa2 100644--- a/packages/lambda/src/functions/launch.ts+++ b/packages/lambda/src/functions/launch.ts@@ -90,17 +90,25 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {Internals.validateFps(comp.fps, 'passed to <Component />');Internals.validateDimension(comp.height, 'height', 'passed to <Component />');Internals.validateDimension(comp.width, 'width', 'passed to <Component />');+validatePrivacy(params.privacy);+ // TODO: Validate frame rangeconst {framesPerLambda} = params;- const chunkCount = Math.ceil(comp.durationInFrames / framesPerLambda);++ const realFrameRange = RenderInternals.getRealFrameRange(+ comp.durationInFrames,+ params.frameRange+ );+ const durationInFrames = realFrameRange[1] - realFrameRange[0] + 1;+ const chunkCount = Math.ceil(durationInFrames / framesPerLambda);const {chunks, didUseOptimization} = planFrameRanges({chunkCount,framesPerLambda,- frameCount: comp.durationInFrames,optimization,shouldUseOptimization: params.enableChunkOptimization,+ frameRange: realFrameRange,});const sortedChunks = chunks.slice().sort((a, b) => a[0] - b[0]);const invokers = Math.round(Math.sqrt(chunks.length));@@ -116,7 +124,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {fps: comp.fps,height: comp.height,width: comp.width,- durationInFrames: comp.durationInFrames,+ durationInFrames,bucketName: params.bucketName,retriesLeft: params.maxRetries,inputProps: params.inputProps,@@ -196,7 +204,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {let encodingStop: number | null = null;const onProgress = (framesEncoded: number, start: number) => {- const relativeProgress = framesEncoded / comp.durationInFrames;+ const relativeProgress = framesEncoded / durationInFrames;const deltaSinceLastProgressUploaded =relativeProgress - lastProgressUploaded;if (relativeProgress === 1) {@@ -211,7 +219,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {const encodingProgress: EncodingProgress = {framesEncoded,- totalFrames: comp.durationInFrames,+ totalFrames: durationInFrames,doneIn: encodingStop ? encodingStop - start : null,timeToInvoke: null,};@@ -248,7 +256,7 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {bucket: params.bucketName,expectedFiles: chunkCount,onProgress,- numberOfFrames: comp.durationInFrames,+ numberOfFrames: durationInFrames,renderId: params.renderId,region: getCurrentRegionInFunction(),codec: params.codec,@@ -287,13 +295,14 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {? writeOptimization({bucketName: params.bucketName,optimization: {- frameRange: optimizedFrameRange,+ ranges: optimizedFrameRange,oldTiming: getProfileDuration(chunkData),newTiming: getProfileDuration(optimizedProfile),- frameCount: comp.durationInFrames,+ frameCount: durationInFrames,createdFromRenderId: params.renderId,framesPerLambda,lambdaVersion: CURRENT_VERSION,+ frameRange: realFrameRange,},expectedBucketOwner: options.expectedBucketOwner,compositionId: params.composition,@@ -313,8 +322,8 @@ const innerLaunchHandler = async (params: LambdaPayload, options: Options) => {}),]);const finalEncodingProgress: EncodingProgress = {- framesEncoded: comp.durationInFrames,- totalFrames: comp.durationInFrames,+ framesEncoded: durationInFrames,+ totalFrames: durationInFrames,doneIn: encodingStop ? encodingStop - encodingStart : null,timeToInvoke: getLambdasInvokedStats(contents,diff --git a/packages/lambda/src/functions/start.ts b/packages/lambda/src/functions/start.tsindex a40c5a7875..a72721419b 100644--- a/packages/lambda/src/functions/start.ts+++ b/packages/lambda/src/functions/start.ts@@ -44,6 +44,7 @@ export const startHandler = async (params: LambdaPayload) => {privacy: params.privacy,enableChunkOptimization: params.enableChunkOptimization !== false,logLevel: params.logLevel ?? Internals.Logging.DEFAULT_LOG_LEVEL,+ frameRange: params.frameRange,};await getLambdaClient(getCurrentRegionInFunction()).send(new InvokeCommand({diff --git a/packages/lambda/src/shared/constants.ts b/packages/lambda/src/shared/constants.tsindex 0040de802e..796c3e0658 100644--- a/packages/lambda/src/shared/constants.ts+++ b/packages/lambda/src/shared/constants.ts@@ -1,5 +1,6 @@import {Codec,+ FrameRange,ImageFormat,LogLevel,PixelFormat,@@ -160,7 +161,8 @@ export type LambdaPayloads = {maxRetries: number;privacy: Privacy;enableChunkOptimization: boolean | undefined;- logLevel?: LogLevel;+ logLevel: LogLevel;+ frameRange: FrameRange | null;};launch: {type: LambdaRoutines.launch;@@ -181,6 +183,7 @@ export type LambdaPayloads = {privacy: Privacy;enableChunkOptimization: boolean;logLevel: LogLevel;+ frameRange: FrameRange | null;};fire: {type: LambdaRoutines.fire;diff --git a/packages/renderer/src/get-frame-range.ts b/packages/renderer/src/get-frame-range.tsdeleted file mode 100644index 616350553c..0000000000--- a/packages/renderer/src/get-frame-range.ts+++ /dev/null@@ -1,36 +0,0 @@-import {FrameRange, Internals} from 'remotion';--export const getFrameCount = (- totalDuration: number,- frameRange: FrameRange | null-): number => {- Internals.validateFrameRange(frameRange);-- if (!frameRange) {- return totalDuration;- }-- if (typeof frameRange === 'number') {- if (frameRange < 0 || frameRange >= totalDuration) {- throw new Error(- `Frame number is out of range, must be between 0 and ${- totalDuration - 1- } but got ${frameRange}`- );- }-- return 1;- }-- const [start, end] = frameRange;-- if (frameRange[1] >= totalDuration || frameRange[0] < 0) {- throw new Error(- `Frame range ${frameRange.join('-')} is not in between 0-${- totalDuration - 1- }`- );- }-- return end - start + 1;-};diff --git a/packages/renderer/src/get-frame-to-render.ts b/packages/renderer/src/get-frame-to-render.tsindex 67564e3a26..481c1deaa6 100644--- a/packages/renderer/src/get-frame-to-render.ts+++ b/packages/renderer/src/get-frame-to-render.ts@@ -1,16 +1,32 @@import {FrameRange} from 'remotion';-export const getFrameToRender = (- frameRange: FrameRange | null,- index: number-) => {- if (typeof frameRange === 'object' && frameRange !== null) {- return index + frameRange[0];+export const getRealFrameRange = (+ durationInFrames: number,+ frameRange: FrameRange | null+): [number, number] => {+ if (frameRange === null) {+ return [0, durationInFrames - 1];}if (typeof frameRange === 'number') {- return frameRange;+ if (frameRange < 0 || frameRange >= durationInFrames) {+ throw new Error(+ `Frame number is out of range, must be between 0 and ${+ durationInFrames - 1+ } but got ${frameRange}`+ );+ }++ return [frameRange, frameRange];+ }++ if (frameRange[1] >= durationInFrames || frameRange[0] < 0) {+ throw new Error(+ `Frame range ${frameRange.join('-')} is not in between 0-${+ durationInFrames - 1+ }`+ );}- return index;+ return frameRange;};diff --git a/packages/renderer/src/index.ts b/packages/renderer/src/index.tsindex 92c21c8530..c6e4af7b18 100644--- a/packages/renderer/src/index.ts+++ b/packages/renderer/src/index.ts@@ -20,6 +20,7 @@ import {prepareServer} from './prepare-server';import {isServeUrl} from './is-serve-url';import {ensureOutputDirectory} from './ensure-output-directory';import got from 'got';+import {getRealFrameRange} from './get-frame-to-render';declare global {interface Window {@@ -68,4 +69,5 @@ export const RenderInternals = {isServeUrl,ensureOutputDirectory,gotStream: got.stream,+ getRealFrameRange,};diff --git a/packages/renderer/src/render.ts b/packages/renderer/src/render.tsindex 85feba68e6..5409274071 100644--- a/packages/renderer/src/render.ts+++ b/packages/renderer/src/render.ts@@ -19,8 +19,7 @@ import {import {BrowserLog} from './browser-log';import {cycleBrowserTabs} from './cycle-browser-tabs';import {getActualConcurrency} from './get-concurrency';-import {getFrameCount} from './get-frame-range';-import {getFrameToRender} from './get-frame-to-render';+import {getRealFrameRange} from './get-frame-to-render';import {DEFAULT_IMAGE_FORMAT} from './image-format';import {getServeUrlWithFallback,@@ -116,6 +115,12 @@ export const innerRenderFrames = async ({}}+ const realFrameRange = getRealFrameRange(+ composition.durationInFrames,+ frameRange ?? null+ );+ const frameCount = realFrameRange[1] - realFrameRange[0] + 1;+const pages = new Array(actualParallelism).fill(true).map(async () => {const page = await puppeteerInstance.newPage();pagesArray.push(page);@@ -162,12 +167,7 @@ export const innerRenderFrames = async ({const puppeteerPages = await Promise.all(pages);const pool = new Pool(puppeteerPages);- const frameCount = getFrameCount(- composition.durationInFrames,- frameRange ?? null- );- const firstFrameIndex = getFrameToRender(frameRange ?? null, 0);- const lastFrameIndex = getFrameToRender(frameRange ?? null, frameCount - 1);+ const [firstFrameIndex, lastFrameIndex] = realFrameRange;// Substract one because 100 frames will be 00-99// --> 2 digitsconst filePadLength = String(lastFrameIndex).length;@@ -182,7 +182,7 @@ export const innerRenderFrames = async ({.fill(Boolean).map((x, i) => i).map(async (index) => {- const frame = getFrameToRender(frameRange ?? null, index);+ const frame = realFrameRange[0] + index;const freePage = await pool.acquire();const paddedIndex = String(frame).padStart(filePadLength, '0');diff --git a/packages/renderer/src/test/frame-range.test.ts b/packages/renderer/src/test/frame-range.test.tsdeleted file mode 100644index e2208a3728..0000000000--- a/packages/renderer/src/test/frame-range.test.ts+++ /dev/null@@ -1,7 +0,0 @@-import {getFrameToRender} from '../get-frame-to-render';--test('Should parse the frame range at least', () => {- expect(getFrameToRender(null, 0)).toBe(0);- expect(getFrameToRender(0, 0)).toBe(0);- expect(getFrameToRender([0, 150], 0)).toBe(0);-});