The swiss army knife of lossless video/audio editing
Feature media: social media versions with captions, zooms, intro and outro
Claude84c72c7d7b4f
diff --git a/script/featureMedia.ts b/script/featureMedia.tsindex f711e3e0..0e12aa4f 100644--- a/script/featureMedia.ts+++ b/script/featureMedia.ts@@ -1,6 +1,6 @@// Records screenshots and a video of a feature demo (see script/featureMedia/scenarios.ts and AGENTS.md "Feature media").// Linux only (captures the X display), e.g. in a cloud session. Run `yarn build` and `yarn download-ffmpeg-linux-x64` first, then:-// xvfb-run -a -s "-screen 0 1024x640x24" node script/featureMedia.ts <scenario> [--clips dir]+// xvfb-run -a -s "-screen 0 1024x640x24" node script/featureMedia.ts <scenario> [--clips dir] [--music audio file]import assert from 'node:assert';import { createWriteStream } from 'node:fs';import { access, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';@@ -13,10 +13,11 @@ import { parseArgs } from 'node:util';import { execa } from 'execa';import clipSources from './featureMedia/clips.ts';import scenarios from './featureMedia/scenarios.ts';+import { renderSocialVideo, type Caption, type Rect, type Zoom } from './featureMedia/socialVideo.ts';-const { values: { clips = 'dist/feature-media-clips' }, positionals: [scenarioName] } = parseArgs({ allowPositionals: true, options: { clips: { type: 'string' } } });+const { values: { clips = 'dist/feature-media-clips', music }, positionals: [scenarioName] } = parseArgs({ allowPositionals: true, options: { clips: { type: 'string' }, music: { type: 'string' } } });const scenario = scenarioName != null ? scenarios[scenarioName] : undefined;-assert(scenario != null, `Usage: node script/featureMedia.ts <scenario> [--clips dir]. Scenarios: ${Object.keys(scenarios).join(', ')}`);+assert(scenario != null, `Usage: node script/featureMedia.ts <scenario> [--clips dir] [--music audio file]. Scenarios: ${Object.keys(scenarios).join(', ')}`);const display = process.env['DISPLAY'];assert(process.platform === 'linux' && display != null, 'Run under Xvfb on Linux, see the top of this file');@@ -27,6 +28,7 @@ const port = 8099;const { stdout: screenSize } = await execa('xdotool', ['getdisplaygeometry']);assert(screenSize === `${width} ${height}`, `The screen is ${screenSize}, run Xvfb with -screen 0 ${width}x${height}x24`);const ffmpeg = 'ffmpeg/linux-x64/lib/ffmpeg';+const ffprobe = 'ffmpeg/linux-x64/lib/ffprobe';const outDir = 'dist/feature-media';await mkdir(outDir, { recursive: true });await mkdir(clips, { recursive: true });@@ -92,7 +94,10 @@ try {// Lossless while recording, re-encoded belowconst recorder = execa(ffmpeg, ['-v', 'error', ...grab, '-c:v', 'libx264', '-preset', 'ultrafast', '-qp', '0', rawVideo], { reject: false, stderr: 'inherit' });const recordingStarted = performance.now();+ const now = () => (performance.now() - recordingStarted) / 1000;let videoStart = 0;+ const captionEvents: { time: number, text: string | undefined }[] = [];+ const zoomEvents: { time: number, rect: Rect | undefined }[] = [];await timers.setTimeout(500);const action = async (name: string, args?: unknown) => {@@ -132,7 +137,13 @@ try {},wait: async (ms) => timers.setTimeout(ms),startVideo: () => {- videoStart = (performance.now() - recordingStarted) / 1000;+ videoStart = now();+ },+ caption: (text) => {+ captionEvents.push({ time: now(), text });+ },+ zoom: (rect) => {+ zoomEvents.push({ time: now(), rect });},});} finally {@@ -144,7 +155,18 @@ try {// A high quality master (web versions are made from it elsewhere), with the index at the start for streamingconst videoPath = join(outDir, `${scenarioName}.mp4`);await execa(ffmpeg, ['-v', 'error', '-y', '-ss', String(videoStart), '-i', rawVideo, '-c:v', 'libx264', '-preset', 'slow', '-crf', '18', '-tune', 'animation', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', videoPath]);- console.log('Wrote', videoPath, 'and screenshots in', outDir);++ // The social media versions start just before the first caption (after the intro card, the opening of the file isn't needed)+ const socialStart = Math.max(videoStart, (captionEvents[0]?.time ?? 0) - 0.5);+ const { stdout: rawDuration } = await execa(ffprobe, ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', rawVideo]);+ const duration = Number(rawDuration) - socialStart;+ const captions: Caption[] = captionEvents.flatMap(({ time, text }, i) => (text == null ? [] : [{ text, start: Math.max(0, time - socialStart), end: Math.min((captionEvents[i + 1]?.time ?? Infinity) - socialStart, duration) }]));+ const zooms: Zoom[] = zoomEvents.map(({ time, rect }) => ({ time: time - socialStart, rect }));+ for (const format of ['landscape', 'vertical'] as const) {+ // eslint-disable-next-line no-await-in-loop+ await renderSocialVideo({ ffmpeg, rawVideo, videoStart: socialStart, duration, captions, zooms, description: scenario.description, music, windowWidth: width, windowHeight: height, format, tmpDir: configDir, outPath: join(outDir, `${scenarioName}-${format}.mp4`) });+ }+ console.log('Wrote', videoPath, 'the social media versions and screenshots in', outDir);} finally {app.kill();await app;diff --git a/script/featureMedia/scenarios.ts b/script/featureMedia/scenarios.tsindex 41d252a1..87a1410b 100644--- a/script/featureMedia/scenarios.ts+++ b/script/featureMedia/scenarios.ts@@ -46,10 +46,11 @@ const scenarios: Record<string, Scenario> = {'cut-segments': {description: 'Mark and label two segments to keep, play them and export',clips: ['DJI_0759.MP4'],- async run({ open, action, actionWithDialog, shot, wait }) {+ async run({ open, action, actionWithDialog, shot, wait, caption, zoom }) {await open('DJI_0759.MP4');await wait(2000);await shot('opened');+ caption('Mark the parts you want to keep');// Setting a start after the last segment starts a new segmentfor (const [start, end, label] of [['00:00:03', '00:00:08', 'Sunset'], ['00:00:14', '00:00:20', 'Cliffs']] as const) {await action('goToTimecodeDirect', { time: start });@@ -62,14 +63,22 @@ const scenarios: Record<string, Scenario> = {await wait(800);}await shot('segments');+ // The segment list+ caption('Each part becomes a segment');+ zoom({ x: 780, y: 60, w: 244, h: 280 });+ await wait(2500);+ zoom();+ caption('Preview only the selected parts');await action('togglePlaySelectedSegments');- await wait(12000);+ await wait(8000);await action('pause');+ caption('Export without re-encoding');// Shows the export confirmation, then exportsawait action('export');await wait(2000);await shot('export');await action('export');+ caption('Done in seconds, with the original quality');await wait(3000);await shot('exported');},@@ -77,16 +86,18 @@ const scenarios: Record<string, Scenario> = {'split-segments': {description: 'Split the video into segments while it plays',clips: ['DJI_0740.MP4'],- async run({ open, action, shot, wait }) {+ async run({ open, action, shot, wait, caption }) {await open('DJI_0740.MP4');await wait(2000);+ caption('Split it into parts while it plays');await action('play');for (let i = 0; i < 4; i += 1) {await wait(2500);await action('splitCurrentSegment');}await action('pause');- await wait(1500);+ caption('Each part can be exported on its own');+ await wait(2500);await shot('segments');},},@@ -95,14 +106,16 @@ const scenarios: Record<string, Scenario> = {clips: ['DJI_0009.MOV', 'DJI_0121.MOV', 'DJI_0740.MP4', 'DJI_0759.MP4'],// The simple mode merge dialog checks the files, which shows nicerconfig: { simpleMode: true },- async run({ open, action, shot, wait }) {+ async run({ open, action, shot, wait, caption }) {+ caption('Open several files at once');await open('DJI_0009.MOV', 'DJI_0121.MOV', 'DJI_0740.MP4', 'DJI_0759.MP4');await wait(1500);await action('batchOpenSelectedFile');await wait(2000);await shot('batch');+ caption('Merge them into one, without re-encoding');await action('concatBatch');- await wait(3000);+ await wait(3500);await shot('merge');},},@@ -110,12 +123,17 @@ const scenarios: Record<string, Scenario> = {description: 'Choose which tracks to keep, then export',clips: ['tears-of-steel.mkv'],config: { waveformMode: 'waveform' },- async run({ open, action, click, shot, wait }) {+ async run({ open, action, click, shot, wait, caption, zoom }) {await open('tears-of-steel.mkv');await wait(3000);+ caption('See every track in the file');await action('toggleStreamsSelector');await wait(2000);await shot('tracks');+ caption('Choose the ones to keep');+ // The Keep column, the codecs and the titles+ zoom({ x: 60, y: 230, w: 560, h: 300 });+ await wait(800);// The Keep buttons of the 5.1 track and the last 4 subtitlesfor (const y of [325, 417, 443, 469, 495]) {await click(97, y);@@ -123,7 +141,9 @@ const scenarios: Record<string, Scenario> = {}await wait(1000);await shot('selected');+ zoom();await action('toggleStreamsSelector');+ caption('Export with only those tracks');await wait(1000);// Shows the export confirmation, then exportsawait action('export');@@ -137,7 +157,7 @@ const scenarios: Record<string, Scenario> = {description: 'Edit the metadata of a track',clips: ['tears-of-steel.mkv'],config: { waveformMode: 'waveform' },- async run({ open, action, click, key, type, shot, wait }) {+ async run({ open, action, click, key, type, shot, wait, caption, zoom }) {await open('tears-of-steel.mkv');await wait(3000);await action('toggleStreamsSelector');@@ -145,7 +165,10 @@ const scenarios: Record<string, Scenario> = {// The menu button of track 2, then "Edit track metadata"await click(909, 300);await wait(1000);+ caption('Edit the metadata of any track');await click(905, 376);+ // The dialog+ zoom({ x: 193, y: 95, w: 640, h: 480 });await wait(1500);await shot('dialog');// Edit the title@@ -160,6 +183,7 @@ const scenarios: Record<string, Scenario> = {await click(791, 315);await wait(1500);await shot('edited');+ zoom();await click(761, 528);await wait(1500);await shot('tracks');@@ -169,27 +193,32 @@ const scenarios: Record<string, Scenario> = {description: 'Create segments from the scene changes',clips: ['tears-of-steel.mkv'],config: { waveformMode: 'waveform' },- async run({ open, actionWithDialog, shot, wait }) {+ async run({ open, actionWithDialog, shot, wait, caption }) {await open('tears-of-steel.mkv');await wait(3000);+ caption('Find the scene changes automatically');// Confirm the parameters dialog with the defaultsawait actionWithDialog('detectSceneChanges');- await wait(5000);+ await wait(2000);+ caption('Every scene becomes a segment');+ await wait(3000);await shot('segments');},},waveform: {description: 'Show the audio waveform while playing',clips: ['tears-of-steel.mkv'],- async run({ open, action, shot, wait }) {+ async run({ open, action, shot, wait, caption }) {await open('tears-of-steel.mkv');await wait(3000);// First the waveform above the timeline, then the full-screen waveform+ caption('See the audio waveform');await action('toggleWaveformMode');await action('goToTimecodeDirect', { time: '00:00:03' });await action('play');await wait(5000);await shot('waveform');+ caption('Or make it full-screen');await action('toggleWaveformMode');await wait(6000);await action('pause');@@ -199,23 +228,28 @@ const scenarios: Record<string, Scenario> = {rotate: {description: 'Rotate a video losslessly',clips: ['DJI_0740.MP4'],- async run({ open, action, shot, wait }) {+ async run({ open, action, shot, wait, caption }) {await open('DJI_0740.MP4');await wait(2000);await shot('original');+ caption('Rotate a video');+ await wait(1000);// The first press sets 0° (to override the file's rotation), the next one 90°await action('increaseRotation');await action('increaseRotation');- await wait(5000);+ await wait(2000);+ caption('Losslessly, without re-encoding');+ await wait(3000);await shot('rotated');},},'invert-segments': {description: 'Mark the parts to remove, then invert to keep the rest',clips: ['DJI_0759.MP4'],- async run({ open, action, shot, wait }) {+ async run({ open, action, shot, wait, caption }) {await open('DJI_0759.MP4');await wait(2000);+ caption('Mark the parts you don\'t want');for (const [start, end] of [['00:00:05', '00:00:09'], ['00:00:16', '00:00:19']]) {await action('goToTimecodeDirect', { time: start });await action('setCutStart');@@ -224,8 +258,9 @@ const scenarios: Record<string, Scenario> = {await wait(1000);}await shot('marked');+ caption('Invert to keep the rest');await action('invertAllSegments');- await wait(2000);+ await wait(2500);await shot('inverted');},},@@ -233,9 +268,10 @@ const scenarios: Record<string, Scenario> = {description: 'Cut out three parts and merge them into one file',clips: ['DJI_0759.MP4'],config: { autoMerge: true },- async run({ open, action, actionWithDialog, shot, wait }) {+ async run({ open, action, actionWithDialog, shot, wait, caption }) {await open('DJI_0759.MP4');await wait(2000);+ caption('Mark the parts you want to keep');for (const [start, end, label] of [['00:00:02', '00:00:05', 'Sea'], ['00:00:10', '00:00:13', 'Cliffs'], ['00:00:18', '00:00:22', 'Sunset']] as const) {await action('goToTimecodeDirect', { time: start });await action('setCutStart');@@ -246,11 +282,13 @@ const scenarios: Record<string, Scenario> = {await wait(800);}await shot('segments');+ caption('Merge them into one file');// Shows the export confirmation (with "Merge cuts"), then exportsawait action('export');await wait(2500);await shot('export');await action('export');+ caption('Done in seconds, without re-encoding');await wait(4000);await shot('exported');},@@ -258,11 +296,13 @@ const scenarios: Record<string, Scenario> = {'fixed-duration-segments': {description: 'Split a video into 5 second parts, e.g. for stories',clips: ['DJI_0759.MP4'],- async run({ open, actionWithDialog, shot, wait }) {+ async run({ open, actionWithDialog, shot, wait, caption }) {await open('DJI_0759.MP4');await wait(2000);+ caption('Split it into equal parts, e.g. for stories');await actionWithDialog('createFixedDurationSegments', '00:00:05');- await wait(2000);+ caption('Each part is 5 seconds');+ await wait(2500);await shot('segments');},},@@ -270,9 +310,10 @@ const scenarios: Record<string, Scenario> = {description: 'Label parts of a video and get YouTube chapters',clips: ['tears-of-steel.mkv'],config: { waveformMode: 'waveform' },- async run({ open, action, actionWithDialog, key, shot, wait }) {+ async run({ open, action, actionWithDialog, key, shot, wait, caption, zoom }) {await open('tears-of-steel.mkv');await wait(3000);+ caption('Split a video into parts and name them');await actionWithDialog('createNumSegments', '3');await wait(1000);for (const [i, label] of ['On the bridge', '40 years later', 'In the lab'].entries()) {@@ -282,10 +323,14 @@ const scenarios: Record<string, Scenario> = {await wait(800);}await shot('labels');+ caption('Get chapters to paste into YouTube');// The dialog stays open until it's closedconst showing = action('exportYouTube');+ // The dialog+ zoom({ x: 260, y: 250, w: 500, h: 320 });await wait(3000);await shot('chapters');+ zoom();await key('Escape');await showing;},@@ -293,22 +338,30 @@ const scenarios: Record<string, Scenario> = {'keyboard-shortcuts': {description: 'Every action has a keyboard shortcut that you can change',clips: ['DJI_0759.MP4'],- async run({ open, action, shot, wait }) {+ async run({ open, action, shot, wait, caption, zoom }) {await open('DJI_0759.MP4');await wait(2000);+ caption('Every action has a keyboard shortcut');await action('toggleKeyboardShortcuts');- await wait(3000);+ // The dialog+ zoom({ x: 193, y: 75, w: 640, h: 520 });+ await wait(2000);+ caption('And you can change them all');+ await wait(2000);await shot('shortcuts');},},'dark-mode': {description: 'Switch between dark and light mode',clips: ['DJI_0759.MP4'],- async run({ open, action, shot, wait }) {+ async run({ open, action, shot, wait, caption }) {await open('DJI_0759.MP4');await wait(2000);+ caption('Dark mode');await shot('dark');+ await wait(1500);await action('toggleDarkMode');+ caption('Or light mode');await wait(2000);await shot('light');await action('toggleDarkMode');diff --git a/script/featureMedia/socialVideo.ts b/script/featureMedia/socialVideo.tsnew file mode 100644index 00000000..a6f73f72--- /dev/null+++ b/script/featureMedia/socialVideo.ts@@ -0,0 +1,169 @@+// Makes the social media versions of a feature demo from its raw recording: captions, zooms (as set by the scenario),+// an intro and outro card and optional music, in landscape (16:10) and vertical (9:16, for Reels, TikTok and Shorts).+import { join } from 'node:path';+import { execa } from 'execa';+import sharp from 'sharp';++export interface Rect { x: number, y: number, w: number, h: number }+export interface Caption { start: number, end: number, text: string }+export interface Zoom { time: number, rect: Rect | undefined }++const fps = 30;+const introDuration = 1.8;+const outroDuration = 2.5;+const fadeDuration = 0.4;+const zoomDuration = 0.7;+const maxZoom = 2.5;+const iconPath = 'src/renderer/src/icon.svg';++const formats = {+ landscape: { width: 1280, height: 800, video: { width: 1280, height: 800, y: 0 }, captionSize: 34, captionY: () => 28 },+ // The captions go at the top in landscape, over the menu and tool bars, which matter least.+ // In vertical, the video is in the middle, on a blurred copy of itself, with the captions above it where they don't cover the UI+ vertical: { width: 1080, height: 1920, video: { width: 1080, height: 675, y: 622 }, captionSize: 52, captionY: (captionHeight: number) => 622 - captionHeight - 60 },+} as const;+export type Format = keyof typeof formats;++const escapeMarkup = (text: string) => text.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');++async function renderText(markup: string, size: number, width: number) {+ return sharp({ text: { text: `<span foreground="white">${markup}</span>`, font: `Inter ${size}`, width, align: 'centre', dpi: 72, rgba: true } }).png().toBuffer({ resolveWithObject: true });+}++// A caption: white text on a dark rounded box+async function renderCaption(text: string, size: number, maxWidth: number, path: string) {+ const { data, info } = await renderText(`<b>${escapeMarkup(text)}</b>`, size, maxWidth);+ const padX = Math.round(size * 0.8);+ const padY = Math.round(size * 0.45);+ const width = info.width + 2 * padX;+ const height = info.height + 2 * padY;+ const box = `<svg width="${width}" height="${height}"><rect width="${width}" height="${height}" rx="${Math.round(size * 0.5)}" fill="#111" fill-opacity="0.85"/></svg>`;+ await sharp(Buffer.from(box)).composite([{ input: data, left: padX, top: padY }]).png().toFile(path);+ return { width, height };+}++// The intro and outro: the icon and two lines of text on a dark background+async function renderCard({ width, height }: { width: number, height: number }, title: string, subtitle: string, path: string) {+ const scale = Math.min(width, height) / 800;+ const iconSize = Math.round(180 * scale);+ const icon = await sharp(iconPath, { density: 300 }).resize(iconSize, iconSize).png().toBuffer();+ const titleText = await renderText(`<b>${escapeMarkup(title)}</b>`, Math.round(64 * scale), width - 100);+ const subtitleText = await renderText(`<span foreground="#bbbbbb">${escapeMarkup(subtitle)}</span>`, Math.round(34 * scale), width - 100);+ const gap = Math.round(36 * scale);+ const totalHeight = iconSize + gap + titleText.info.height + Math.round(gap / 2) + subtitleText.info.height;+ let top = Math.round((height - totalHeight) / 2);+ const layers = [icon, titleText.data, subtitleText.data].map((input, i) => {+ const layerWidth = [iconSize, titleText.info.width, subtitleText.info.width][i]!;+ const layer = { input, left: Math.round((width - layerWidth) / 2), top };+ top += [iconSize + gap, titleText.info.height + Math.round(gap / 2), 0][i]!;+ return layer;+ });+ const background = `<svg width="${width}" height="${height}"><defs><radialGradient id="g" cx="50%" cy="40%" r="75%"><stop offset="0" stop-color="#33363d"/><stop offset="1" stop-color="#121316"/></radialGradient></defs><rect width="${width}" height="${height}" fill="url(#g)"/></svg>`;+ await sharp(Buffer.from(background)).composite(layers).png().toFile(path);+}++// An ffmpeg expression for a value that eases from one setting to the next at each time+function easedExpression(times: number[], values: number[], initial: number): string {+ const build = (i: number, previous: number): string => {+ if (i === times.length) return String(previous);+ const start = times[i]!;+ const value = values[i]!;+ const progress = `clip((it-${start})/${zoomDuration},0,1)`;+ const eased = `${previous}+(${value - previous})*${progress}*${progress}*(3-2*${progress})`;+ return `if(lt(it,${start}),${previous},if(lt(it,${start + zoomDuration}),${eased},${build(i + 1, value)}))`;+ };+ return build(0, initial);+}++// zoompan settings that follow the zooms. The input is scaled up 2x first, which makes slow zooms smoother.+// zoompan's output timestamps can be off (with the raw recording), which makes xfade buffer frames without end, so they're renumbered+function zoomFilter(zooms: Zoom[], { windowWidth, windowHeight }: { windowWidth: number, windowHeight: number }, outWidth: number, outHeight: number) {+ const times = zooms.map(({ time }) => time);+ const targets = zooms.map(({ rect }) => {+ if (rect == null) return { z: 1, cx: windowWidth / 2, cy: windowHeight / 2 };+ const z = Math.max(1, Math.min(maxZoom, windowWidth / rect.w, windowHeight / rect.h));+ return { z, cx: rect.x + rect.w / 2, cy: rect.y + rect.h / 2 };+ });+ const z = easedExpression(times, targets.map((t) => t.z), 1);+ // The centre, in the 2x input's pixels, kept inside the frame+ const cx = easedExpression(times, targets.map((t) => t.cx * 2), windowWidth);+ const cy = easedExpression(times, targets.map((t) => t.cy * 2), windowHeight);+ return `scale=${windowWidth * 2}:${windowHeight * 2}:flags=lanczos,zoompan=z='${z}':x='clip(${cx}-iw/zoom/2,0,iw-iw/zoom)':y='clip(${cy}-ih/zoom/2,0,ih-ih/zoom)':d=1:s=${outWidth}x${outHeight}:fps=${fps},setpts=N/${fps}/TB`;+}++export async function renderSocialVideo({ ffmpeg, rawVideo, videoStart, duration, captions, zooms, description, music, windowWidth, windowHeight, format, tmpDir, outPath }: {+ ffmpeg: string,+ rawVideo: string,+ videoStart: number,+ /** Of the video after videoStart */+ duration: number,+ captions: Caption[],+ zooms: Zoom[],+ description: string,+ /** An audio file, or undefined for no music */+ music: string | undefined,+ windowWidth: number,+ windowHeight: number,+ format: Format,+ tmpDir: string,+ outPath: string,+}) {+ const { width, height, video, captionSize, captionY } = formats[format];+ const introPath = join(tmpDir, `${format}-intro.png`);+ const outroPath = join(tmpDir, `${format}-outro.png`);+ await renderCard({ width, height }, 'LosslessCut', description, introPath);+ await renderCard({ width, height }, 'losslesscut.app', 'Free and open source · Windows, macOS and Linux', outroPath);++ const inputs = [+ '-ss', String(videoStart), '-t', String(duration), '-i', rawVideo,+ '-loop', '1', '-framerate', String(fps), '-t', String(introDuration), '-i', introPath,+ '-loop', '1', '-framerate', String(fps), '-t', String(outroDuration), '-i', outroPath,+ ];+ const normalize = `fps=${fps},format=yuv420p,setsar=1,settb=AVTB`;+ const filters = [`[0:v]${zoomFilter(zooms, { windowWidth, windowHeight }, video.width, video.height)}[zoomed]`];+ if (format === 'vertical') {+ filters.push(+ '[zoomed]split[fg][bgsrc]',+ `[bgsrc]scale=-2:${height},crop=${width}:${height},gblur=sigma=40,eq=brightness=-0.2[bg]`,+ `[bg][fg]overlay=0:${video.y}[v0]`,+ );+ } else {+ filters.push('[zoomed]null[v0]');+ }++ let last = 'v0';+ for (const [i, { start, end, text }] of captions.entries()) {+ const path = join(tmpDir, `${format}-caption-${i}.png`);+ // eslint-disable-next-line no-await-in-loop+ const { width: captionWidth, height: captionHeight } = await renderCaption(text, captionSize, width - 120, path);+ const length = end - start;+ const input = 3 + i;+ inputs.push('-loop', '1', '-framerate', String(fps), '-t', String(length), '-i', path);+ filters.push(+ `[${input}:v]format=rgba,fade=in:st=0:d=0.25:alpha=1,fade=out:st=${Math.max(0, length - 0.25)}:d=0.25:alpha=1,setpts=PTS+${start}/TB[c${i}]`,+ `[${last}][c${i}]overlay=x=${Math.round((width - captionWidth) / 2)}:y=${captionY(captionHeight)}:eof_action=pass[v${i + 1}]`,+ );+ last = `v${i + 1}`;+ }++ const mainOffset = introDuration - fadeDuration;+ const outroOffset = mainOffset + duration - fadeDuration;+ const total = outroOffset + outroDuration;+ filters.push(+ `[${last}]${normalize}[main]`,+ `[1:v]${normalize}[intro]`,+ `[2:v]${normalize}[outro]`,+ `[intro][main]xfade=transition=fade:duration=${fadeDuration}:offset=${mainOffset}[im]`,+ `[im][outro]xfade=transition=fade:duration=${fadeDuration}:offset=${outroOffset}[out]`,+ );++ const audio: string[] = [];+ if (music != null) {+ const musicInput = inputs.filter((arg) => arg === '-i').length;+ inputs.push('-stream_loop', '-1', '-i', music);+ filters.push(`[${musicInput}:a]atrim=0:${total},afade=in:d=0.5,afade=out:st=${total - 1.5}:d=1.5,loudnorm=I=-14:TP=-1.5:LRA=11[aout]`);+ audio.push('-map', '[aout]', '-c:a', 'aac', '-b:a', '192k', '-ar', '48000');+ }++ await execa(ffmpeg, ['-v', 'error', '-y', ...inputs, '-filter_complex', filters.join(';'), '-map', '[out]', ...audio, '-c:v', 'libx264', '-preset', 'slow', '-crf', '18', '-pix_fmt', 'yuv420p', '-r', String(fps), '-t', String(total), '-movflags', '+faststart', outPath]);+}diff --git a/script/featureMedia/types.ts b/script/featureMedia/types.tsindex 2eb355f7..f829e7eb 100644--- a/script/featureMedia/types.ts+++ b/script/featureMedia/types.ts@@ -1,3 +1,5 @@+import type { Rect } from './socialVideo.ts';+export interface ScenarioContext {/** Opens clips from the clips folder (several go to the batch list) */open: (...clips: string[]) => Promise<void>,@@ -16,6 +18,10 @@ export interface ScenarioContext {wait: (ms: number) => Promise<void>,/** Starts the video here instead of at the beginning, e.g. after opening the file */startVideo: () => void,+ /** Shows a caption in the social media versions from now until the next one (or none with no text) */+ caption: (text?: string) => void,+ /** Zooms the social media versions in on a part of the window (as for click), or back out with no rect */+ zoom: (rect?: Rect) => void,}export interface Scenario {