Skip to content

🎥 Make videos programmatically with React

download

Jonny Burger41f428083daf
diff --git a/packages/cli/src/download-progress.ts b/packages/cli/src/download-progress.ts
index ef7ec00f8d..12d5d7cf7a 100644
--- a/packages/cli/src/download-progress.ts
+++ b/packages/cli/src/download-progress.ts
@@ -1,6 +1,13 @@
+import {formatBytes} from './format-bytes';
import {makeProgressBar} from './make-progress-bar';
import type {DownloadProgress} from './progress-bar';
+export const getFileSizeDownloadBar = (downloaded: number) => {
+ const desiredLength = makeProgressBar(0).length;
+
+ return formatBytes(downloaded).padEnd(desiredLength, ' ');
+};
+
export const makeMultiDownloadProgress = (progresses: DownloadProgress[]) => {
if (progresses.length === 0) {
return null;
@@ -14,16 +21,27 @@ export const makeMultiDownloadProgress = (progresses: DownloadProgress[]) => {
: progress.name;
return [
` +`,
- makeProgressBar(progress.progress),
+ progress.progress
+ ? makeProgressBar(progress.progress)
+ : getFileSizeDownloadBar(progress.downloaded),
`Downloading ${truncatedFileName}`,
].join(' ');
}
+ const everyFileHasContentLength = progresses.every(
+ (p) => p.totalBytes !== null
+ );
+
return [
` +`,
- makeProgressBar(
- progresses.reduce((a, b) => a + b.progress, 0) / progresses.length
- ),
+ everyFileHasContentLength
+ ? makeProgressBar(
+ progresses.reduce((a, b) => a + (b.progress as number), 0) /
+ progresses.length
+ )
+ : getFileSizeDownloadBar(
+ progresses.reduce((a, b) => a + b.downloaded, 0)
+ ),
`Downloading ${progresses.length} files`,
].join(' ');
};
diff --git a/packages/lambda/src/cli/helpers/format-bytes.ts b/packages/cli/src/format-bytes.ts
similarity index 100%
rename from packages/lambda/src/cli/helpers/format-bytes.ts
rename to packages/cli/src/format-bytes.ts
diff --git a/packages/cli/src/index.tsx b/packages/cli/src/index.tsx
index c885686403..98acd4d632 100644
--- a/packages/cli/src/index.tsx
+++ b/packages/cli/src/index.tsx
@@ -1,6 +1,8 @@
import {chalk} from './chalk';
import {checkNodeVersion} from './check-version';
import {listCompositionsCommand} from './compositions';
+import {getFileSizeDownloadBar} from './download-progress';
+import {formatBytes} from './format-bytes';
import {getCliOptions} from './get-cli-options';
import {loadConfig} from './get-config-file-name';
import {handleCommonError} from './handle-common-errors';
@@ -88,4 +90,6 @@ export const CliInternals = {
quietFlagProvided,
parsedCli,
handleCommonError,
+ formatBytes,
+ getFileSizeDownloadBar,
};
diff --git a/packages/cli/src/progress-bar.ts b/packages/cli/src/progress-bar.ts
index b5902113fc..bd47ab82fa 100644
--- a/packages/cli/src/progress-bar.ts
+++ b/packages/cli/src/progress-bar.ts
@@ -109,7 +109,9 @@ export const makeStitchingProgress = ({
export type DownloadProgress = {
name: string;
id: number;
- progress: number;
+ progress: number | null;
+ totalBytes: number | null;
+ downloaded: number;
};
export const makeRenderingAndStitchingProgress = ({
diff --git a/packages/cli/src/render.tsx b/packages/cli/src/render.tsx
index 85a4c502e3..bac091b136 100644
--- a/packages/cli/src/render.tsx
+++ b/packages/cli/src/render.tsx
@@ -105,11 +105,15 @@ export const render = async () => {
id,
name: src,
progress: 0,
+ downloaded: 0,
+ totalBytes: null,
};
downloads.push(download);
updateRenderProgress();
- return ({percent}) => {
+ return ({percent, downloaded, totalSize}) => {
download.progress = percent;
+ download.totalBytes = totalSize;
+ download.downloaded = downloaded;
updateRenderProgress();
};
};
diff --git a/packages/cli/src/still.ts b/packages/cli/src/still.ts
index 958ed5dc76..a847c8b8f0 100644
--- a/packages/cli/src/still.ts
+++ b/packages/cli/src/still.ts
@@ -164,6 +164,8 @@ export const still = async () => {
id,
name: src,
progress: 0,
+ downloaded: 0,
+ totalBytes: null,
};
downloads.push(download);
updateProgress();
diff --git a/packages/lambda/src/api/download-media.ts b/packages/lambda/src/api/download-media.ts
index 61d210c394..f55c0ecc54 100644
--- a/packages/lambda/src/api/download-media.ts
+++ b/packages/lambda/src/api/download-media.ts
@@ -2,11 +2,8 @@ import {RenderInternals} from '@remotion/renderer';
import path from 'path';
import {getExpectedOutName} from '../functions/helpers/expected-out-name';
import {getRenderMetadata} from '../functions/helpers/get-render-metadata';
-import type {
- LambdaReadFileProgress} from '../functions/helpers/read-with-progress';
-import {
- lambdaDownloadFileWithProgress
-} from '../functions/helpers/read-with-progress';
+import type {LambdaReadFileProgress} from '../functions/helpers/read-with-progress';
+import {lambdaDownloadFileWithProgress} from '../functions/helpers/read-with-progress';
import type {AwsRegion} from '../pricing/aws-regions';
import {getAccountId} from '../shared/get-account-id';
diff --git a/packages/lambda/src/cli/commands/render/progress.ts b/packages/lambda/src/cli/commands/render/progress.ts
index 23f64f3f32..db1e6fde09 100644
--- a/packages/lambda/src/cli/commands/render/progress.ts
+++ b/packages/lambda/src/cli/commands/render/progress.ts
@@ -1,8 +1,11 @@
import {CliInternals} from '@remotion/cli';
import {Internals} from 'remotion';
-import type {CleanupInfo, EncodingProgress, RenderProgress} from '../../../defaults';
+import type {
+ CleanupInfo,
+ EncodingProgress,
+ RenderProgress,
+} from '../../../defaults';
import type {ChunkRetry} from '../../../functions/helpers/get-retry-stats';
-import {formatBytes} from '../../helpers/format-bytes';
type LambdaInvokeProgress = {
totalLambdas: number | null;
@@ -130,14 +133,21 @@ const makeDownloadProgress = (
return [
'💾',
`(5/${totalSteps})`,
- CliInternals.makeProgressBar(
- downloadInfo.downloaded / downloadInfo.totalSize
- ),
+ downloadInfo.totalSize === null
+ ? CliInternals.getFileSizeDownloadBar(downloadInfo.downloaded)
+ : CliInternals.makeProgressBar(
+ downloadInfo.downloaded / downloadInfo.totalSize
+ ),
`${downloadInfo.doneIn === null ? 'Downloading' : 'Downloaded'} video`,
downloadInfo.doneIn === null
- ? `${formatBytes(downloadInfo.downloaded)}/${formatBytes(
- downloadInfo.totalSize
- )}`
+ ? [
+ `${CliInternals.formatBytes(downloadInfo.downloaded)}`,
+ downloadInfo.totalSize === null
+ ? null
+ : `${CliInternals.formatBytes(downloadInfo.totalSize)}`,
+ ]
+ .filter(Internals.truthy)
+ .join('/')
: CliInternals.chalk.gray(`${downloadInfo.doneIn}ms`),
].join(' ');
};
@@ -168,7 +178,7 @@ export const makeMultiProgressFromStatus = (
};
type DownloadedInfo = {
- totalSize: number;
+ totalSize: number | null;
downloaded: number;
doneIn: number | null;
};
diff --git a/packages/lambda/src/cli/commands/render/render.ts b/packages/lambda/src/cli/commands/render/render.ts
index d563395325..211c74fa5e 100644
--- a/packages/lambda/src/cli/commands/render/render.ts
+++ b/packages/lambda/src/cli/commands/render/render.ts
@@ -16,7 +16,6 @@ import {validateMaxRetries} from '../../../shared/validate-retries';
import {parsedLambdaCli} from '../../args';
import {getAwsRegion} from '../../get-aws-region';
import {findFunctionName} from '../../helpers/find-function-name';
-import {formatBytes} from '../../helpers/format-bytes';
import {getCloudwatchStreamUrl} from '../../helpers/get-cloudwatch-stream-url';
import {quit} from '../../helpers/quit';
import {Log} from '../../log';
@@ -205,7 +204,7 @@ export const renderCommand = async (args: string[]) => {
);
Log.info();
Log.info();
- Log.info('Done!', outputPath, formatBytes(sizeInBytes));
+ Log.info('Done!', outputPath, CliInternals.formatBytes(sizeInBytes));
} else {
Log.info();
Log.info();
diff --git a/packages/lambda/src/cli/commands/sites/ls.ts b/packages/lambda/src/cli/commands/sites/ls.ts
index c1ceae52d6..33ce94710f 100644
--- a/packages/lambda/src/cli/commands/sites/ls.ts
+++ b/packages/lambda/src/cli/commands/sites/ls.ts
@@ -3,7 +3,6 @@ import {Log} from '@remotion/cli/dist/log';
import {getSites} from '../../../api/get-sites';
import {getAwsRegion} from '../../get-aws-region';
import {dateString} from '../../helpers/date-string';
-import {formatBytes} from '../../helpers/format-bytes';
export const SITES_LS_SUBCOMMAND = 'ls';
@@ -54,7 +53,7 @@ export const sitesLsSubcommand = async () => {
logRow([
site.id,
site.bucketName,
- formatBytes(site.sizeInBytes),
+ CliInternals.formatBytes(site.sizeInBytes),
site.lastModified ? dateString(new Date(site.lastModified)) : 'n/a',
])
);
diff --git a/packages/lambda/src/cli/commands/sites/rm.ts b/packages/lambda/src/cli/commands/sites/rm.ts
index cfbc290478..172c2ee14e 100644
--- a/packages/lambda/src/cli/commands/sites/rm.ts
+++ b/packages/lambda/src/cli/commands/sites/rm.ts
@@ -4,7 +4,6 @@ import {getRemotionS3Buckets} from '../../../api/get-buckets';
import {getSites} from '../../../api/get-sites';
import {getAwsRegion} from '../../get-aws-region';
import {confirmCli} from '../../helpers/confirm';
-import {formatBytes} from '../../helpers/format-bytes';
import {quit} from '../../helpers/quit';
import {Log} from '../../log';
export const SITES_RM_COMMAND = 'rm';
@@ -60,9 +59,9 @@ export const sitesRmSubcommand = async (args: string[]) => {
}
await confirmCli({
- delMessage: `Site ${site.id} in bucket ${site.bucketName} (${formatBytes(
- site.sizeInBytes
- )}): Delete? (Y/n)`,
+ delMessage: `Site ${site.id} in bucket ${
+ site.bucketName
+ } (${CliInternals.formatBytes(site.sizeInBytes)}): Delete? (Y/n)`,
allowForceFlag: true,
});
@@ -76,7 +75,9 @@ export const sitesRmSubcommand = async (args: string[]) => {
});
Log.info(
- `Deleted site ${siteName} and freed up ${formatBytes(totalSize)}.`
+ `Deleted site ${siteName} and freed up ${CliInternals.formatBytes(
+ totalSize
+ )}.`
);
}
};
diff --git a/packages/lambda/src/cli/commands/sites/rmall.ts b/packages/lambda/src/cli/commands/sites/rmall.ts
index f3ed7494a8..c7c37bdacc 100644
--- a/packages/lambda/src/cli/commands/sites/rmall.ts
+++ b/packages/lambda/src/cli/commands/sites/rmall.ts
@@ -4,7 +4,6 @@ import {getRemotionS3Buckets} from '../../../api/get-buckets';
import {getSites} from '../../../api/get-sites';
import {getAwsRegion} from '../../get-aws-region';
import {confirmCli} from '../../helpers/confirm';
-import {formatBytes} from '../../helpers/format-bytes';
import {quit} from '../../helpers/quit';
import {Log} from '../../log';
@@ -39,9 +38,9 @@ export const sitesRmallSubcommand = async () => {
for (const site of deployedSites.sites) {
await confirmCli({
- delMessage: `Site ${site.id} in bucket ${site.bucketName} (${formatBytes(
- site.sizeInBytes
- )}): Delete? (Y/n)`,
+ delMessage: `Site ${site.id} in bucket ${
+ site.bucketName
+ } (${CliInternals.formatBytes(site.sizeInBytes)}): Delete? (Y/n)`,
allowForceFlag: true,
});
@@ -54,6 +53,10 @@ export const sitesRmallSubcommand = async () => {
},
});
- Log.info(`Deleted site ${site.id} and freed up ${formatBytes(totalSize)}.`);
+ Log.info(
+ `Deleted site ${site.id} and freed up ${CliInternals.formatBytes(
+ totalSize
+ )}.`
+ );
}
};
diff --git a/packages/lambda/src/cli/commands/still.ts b/packages/lambda/src/cli/commands/still.ts
index b744aeb380..84405ac5c7 100644
--- a/packages/lambda/src/cli/commands/still.ts
+++ b/packages/lambda/src/cli/commands/still.ts
@@ -14,7 +14,6 @@ import {validateMaxRetries} from '../../shared/validate-retries';
import {parsedLambdaCli} from '../args';
import {getAwsRegion} from '../get-aws-region';
import {findFunctionName} from '../helpers/find-function-name';
-import {formatBytes} from '../helpers/format-bytes';
import {getCloudwatchStreamUrl} from '../helpers/get-cloudwatch-stream-url';
import {quit} from '../helpers/quit';
import {Log} from '../log';
@@ -113,7 +112,7 @@ export const stillCommand = async (args: string[]) => {
region: getAwsRegion(),
renderId: res.renderId,
});
- Log.info('Done!', outputPath, formatBytes(sizeInBytes));
+ Log.info('Done!', outputPath, CliInternals.formatBytes(sizeInBytes));
} else {
Log.info(`Finished still!`);
Log.info();
diff --git a/packages/lambda/src/cli/helpers/progress-bar.ts b/packages/lambda/src/cli/helpers/progress-bar.ts
index 091818c4e4..f76ced07f9 100644
--- a/packages/lambda/src/cli/helpers/progress-bar.ts
+++ b/packages/lambda/src/cli/helpers/progress-bar.ts
@@ -1,6 +1,5 @@
import {CliInternals} from '@remotion/cli';
import {Internals} from 'remotion';
-import {formatBytes} from './format-bytes';
export type BundleProgress = {
progress: number;
@@ -64,7 +63,9 @@ export const makeDeployProgressBar = ({
`${doneIn === null ? 'Uploading' : 'Uploaded'} to S3`,
doneIn === null
? typeof totalSize === 'number'
- ? `${formatBytes(sizeUploaded)}/${formatBytes(totalSize)}`
+ ? `${CliInternals.formatBytes(sizeUploaded)}/${CliInternals.formatBytes(
+ totalSize
+ )}`
: ''
: CliInternals.chalk.gray(`${doneIn}ms`),
]
diff --git a/packages/lambda/src/functions/helpers/read-with-progress.ts b/packages/lambda/src/functions/helpers/read-with-progress.ts
index a859feeb96..bb38566058 100644
--- a/packages/lambda/src/functions/helpers/read-with-progress.ts
+++ b/packages/lambda/src/functions/helpers/read-with-progress.ts
@@ -5,9 +5,9 @@ import type {AwsRegion} from '../../pricing/aws-regions';
import {getS3Client} from '../../shared/aws-clients';
export type LambdaReadFileProgress = (progress: {
- totalSize: number;
+ totalSize: number | null;
downloaded: number;
- progress: number;
+ percent: number | null;
}) => unknown;
export const lambdaDownloadFileWithProgress = async ({
@@ -24,7 +24,7 @@ export const lambdaDownloadFileWithProgress = async ({
expectedBucketOwner: string;
outputPath: string;
onProgress: LambdaReadFileProgress;
-}): Promise<{sizeInBytes: number}> => {
+}): Promise<{sizeInBytes: number; to: string}> => {
const client = getS3Client(region);
const command = new GetObjectCommand({
Bucket: bucketName,
@@ -34,5 +34,11 @@ export const lambdaDownloadFileWithProgress = async ({
const presigned = await getSignedUrl(client, command);
- return RenderInternals.downloadFile(presigned, outputPath, onProgress);
+ const {to, sizeInBytes} = await RenderInternals.downloadFile({
+ url: presigned,
+ onProgress,
+ to: () => outputPath,
+ });
+
+ return {sizeInBytes, to};
};
diff --git a/packages/renderer/src/assets/download-and-map-assets-to-file.ts b/packages/renderer/src/assets/download-and-map-assets-to-file.ts
index cfe2983a9e..8229c6f42c 100644
--- a/packages/renderer/src/assets/download-and-map-assets-to-file.ts
+++ b/packages/renderer/src/assets/download-and-map-assets-to-file.ts
@@ -8,7 +8,14 @@ import {sanitizeFilePath} from './sanitize-filepath';
export type RenderMediaOnDownload = (
src: string
-) => ((progress: {percent: number}) => void) | undefined | void;
+) =>
+ | ((progress: {
+ percent: number | null;
+ downloaded: number;
+ totalSize: number | null;
+ }) => void)
+ | undefined
+ | void;
const isDownloadingMap: {
[src: string]: {[downloadDir: string]: boolean} | undefined;
@@ -192,12 +199,11 @@ export const downloadAsset = async ({
const {to} = await downloadFile({
url: src,
- downloadDir,
- onProgress: ({progress}) => {
- onProgress?.({
- percent: progress,
- });
+ onProgress: (progress) => {
+ onProgress?.(progress);
},
+ to: (contentDisposition) =>
+ getSanitizedFilenameForAssetUrl({contentDisposition, downloadDir, src}),
});
notifyAssetIsDownloaded({src, downloadDir, to});
diff --git a/packages/renderer/src/assets/download-file.ts b/packages/renderer/src/assets/download-file.ts
index 401782f4fb..f56a667dbb 100644
--- a/packages/renderer/src/assets/download-file.ts
+++ b/packages/renderer/src/assets/download-file.ts
@@ -1,20 +1,19 @@
import {createWriteStream} from 'fs';
import {ensureOutputDirectory} from '../ensure-output-directory';
-import {getSanitizedFilenameForAssetUrl} from './download-and-map-assets-to-file';
import {readFile} from './read-file';
export const downloadFile = ({
onProgress,
url,
- downloadDir,
+ to: toFn,
}: {
url: string;
- downloadDir: string;
+ to: (contentDisposition: string | null) => string;
onProgress:
| ((progress: {
- progress: number;
+ percent: number | null;
downloaded: number;
- totalSize: number;
+ totalSize: number | null;
}) => void)
| undefined;
}) => {
@@ -22,28 +21,27 @@ export const downloadFile = ({
readFile(url)
.then((res) => {
const contentDisposition = res.headers['content-disposition'] ?? null;
- const to = getSanitizedFilenameForAssetUrl({
- downloadDir,
- src: url,
- contentDisposition,
- });
+ const to = toFn(contentDisposition);
ensureOutputDirectory(to);
- const totalSize = Number(res.headers['content-length']);
+ const sizeHeader = res.headers['content-length'];
+
+ const totalSize =
+ typeof sizeHeader === 'undefined' ? null : Number(sizeHeader);
const writeStream = createWriteStream(to);
+ let downloaded = 0;
// Listen to 'close' event instead of more
// concise method to avoid this problem
// https://github.com/remotion-dev/remotion/issues/384#issuecomment-844398183
- writeStream.on('close', () => resolve({sizeInBytes: totalSize, to}));
+ writeStream.on('close', () => resolve({sizeInBytes: downloaded, to}));
writeStream.on('error', (err) => reject(err));
- let downloaded = 0;
res.pipe(writeStream).on('error', (err) => reject(err));
res.on('data', (d) => {
downloaded += d.length;
onProgress?.({
downloaded,
- progress: downloaded / totalSize,
+ percent: totalSize === null ? null : downloaded / totalSize,
totalSize,
});
});
diff --git a/packages/renderer/src/test/download-file.test.ts b/packages/renderer/src/test/download-file.test.ts
index e4a12003ea..59c7bace7b 100644
--- a/packages/renderer/src/test/download-file.test.ts
+++ b/packages/renderer/src/test/download-file.test.ts
@@ -1,12 +1,19 @@
import fs from 'fs';
import {tmpdir} from 'os';
+import {getSanitizedFilenameForAssetUrl} from '../assets/download-and-map-assets-to-file';
import {downloadFile} from '../assets/download-file';
test('Should be able to download file', async () => {
const downloadDir = tmpdir();
const {to} = await downloadFile({
url: 'https://example.net/',
- downloadDir,
+ to: (contentDisposition) => {
+ return getSanitizedFilenameForAssetUrl({
+ contentDisposition,
+ downloadDir,
+ src: 'https://example.net/',
+ });
+ },
onProgress: () => undefined,
});
const data = await fs.promises.readFile(to, 'utf8');
@@ -20,7 +27,13 @@ test('Should fail to download invalid files', async () => {
const downloadDir = tmpdir();
await expect(() =>
downloadFile({
- downloadDir,
+ to: (contentDisposition) => {
+ return getSanitizedFilenameForAssetUrl({
+ contentDisposition,
+ downloadDir,
+ src: 'https://thisdomain.doesnotexist',
+ });
+ },
url: 'https://thisdomain.doesnotexist',
onProgress: () => undefined,
})