PulseCanvas / website / scripts / optimize-videos.mjs
| 1 | import { rename, stat } from 'node:fs/promises'; |
| 2 | import { spawn } from 'node:child_process'; |
| 3 | import { resolve } from 'node:path'; |
| 4 | |
| 5 | // Creates 1080p60 website copies of the delivered 4K videos. Originals are never modified. |
| 6 | // Copies go to the Expand-drive folder that mirrors the R2 bucket; upload them from there |
| 7 | // (see "Website videos" in README.md). Filesystem paths are used only by this local script. |
| 8 | const outputDirectory = |
| 9 | process.env.PULSECANVAS_ASSET_DIR || |
| 10 | '/path/to/file'; |
| 11 | const websiteMediaDirectory = |
| 12 | process.env.PULSECANVAS_WEBSITE_MEDIA_DIR || |
| 13 | '/Volumes/Expand/Video/Library/website-media/pulsecanvas'; |
| 14 | const videos = [ |
| 15 | { |
| 16 | source: 'PulseCanvas-Marketing-4K-Revised.mp4', |
| 17 | destination: 'PulseCanvas-Feature.mp4', |
| 18 | video: ['-crf', '21', '-maxrate', '9000k', '-bufsize', '18000k'], |
| 19 | audio: '192k', |
| 20 | }, |
| 21 | { |
| 22 | source: 'PulseCanvas-Walkthrough-4K-Revised.mp4', |
| 23 | destination: 'PulseCanvas-Walkthrough-web.mp4', |
| 24 | video: ['-crf', '23', '-maxrate', '4500k', '-bufsize', '9000k'], |
| 25 | audio: '160k', |
| 26 | }, |
| 27 | ]; |
| 28 | |
| 29 | function run(args) { |
| 30 | return new Promise((accept, reject) => { |
| 31 | const process = spawn('ffmpeg', args, { stdio: 'inherit' }); |
| 32 | process.on('error', reject); |
| 33 | process.on('exit', (code) => (code === 0 ? accept() : reject(new Error(`FFmpeg exited ${code}`)))); |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | for (const { source, destination, video, audio } of videos) { |
| 38 | const input = resolve(outputDirectory, source); |
| 39 | const output = resolve(websiteMediaDirectory, destination); |
| 40 | if (!(await stat(input).catch(() => null))) { |
| 41 | console.log(`${destination}: no source available.`); |
| 42 | continue; |
| 43 | } |
| 44 | // Published R2 copies are cached for a year, so a new cut needs a new destination name. |
| 45 | if (await stat(output).catch(() => null)) { |
| 46 | console.log(`${destination}: already exists; give a new cut a new destination name.`); |
| 47 | continue; |
| 48 | } |
| 49 | const temporary = output.replace(/\.mp4$/, '.tmp.mp4'); |
| 50 | await run([ |
| 51 | '-y', '-hide_banner', '-loglevel', 'error', '-i', input, |
| 52 | '-vf', 'scale=1920:1080:flags=lanczos,format=yuv420p', |
| 53 | '-c:v', 'libx264', '-preset', 'slow', ...video, '-g', '120', '-profile:v', 'high', |
| 54 | '-c:a', 'aac', '-b:a', audio, '-movflags', '+faststart', temporary, |
| 55 | ]); |
| 56 | await rename(temporary, output); |
| 57 | console.log(`${destination}: website copy created; original preserved.`); |
| 58 | } |