Cotton code
110 lines · 6.2 KB · TypeScriptRaw
/** * The seed's films are MADE WHEN IT RUNS: a few seconds of ffmpeg's test * picture (`testsrc`) and a test tone (`sine`), H.264 and AAC — an MP4 the * phone plays as it is, an MKV that waits for the Mac, or an HLS folder as * the Mac lays one (a master, fMP4 segments in `video/`, an English WebVTT * track), which this writes around ffmpeg's segments. Nobody's film, no * file checked in, and the same video asked twice is the same bytes on one * Mac (bit-exact flags, no metadata). * * ffmpeg is not optional here: a Mac without it is refused with how to get * it, never seeded without the films. */import { spawnSync } from "node:child_process";import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join, relative } from "node:path";import { SeedRefusal } from "./client.ts";import type { SeedMedia, SeedVideo } from "./life.ts";/** What ffmpeg answered: its exit, and why it could not run at all. */export interface RunAnswer {  status: number | null;  error?: Error;  stderr: string;}export type Run = (args: string[]) => RunAnswer;export const FFMPEG = process.env.FFMPEG ?? (existsSync("/opt/homebrew/bin/ffmpeg") ? "/opt/homebrew/bin/ffmpeg" : "ffmpeg");/** ffmpeg on this Mac. */export const runFfmpeg: Run = (args) => {  const r = spawnSync(FFMPEG, args, { encoding: "utf8" });  return { status: r.status, ...(r.error ? { error: r.error } : {}), stderr: r.stderr ?? "" };};/** ffmpeg is there, or the seed stops before it touches the Worker. */export function requireFfmpeg(run: Run = runFfmpeg): void {  const r = run(["-hide_banner", "-version"]);  if (r.error || r.status !== 0) throw new SeedRefusal(`the seed makes its films with ffmpeg, which does not run here (${r.error?.message ?? `exit ${r.status}`}): brew install ffmpeg`);}/** The ffmpeg arguments that write `video` to `out`. */export function videoArgs(video: SeedVideo, out: string): string[] {  return [    "-hide_banner", "-nostdin", "-y", "-loglevel", "error",    "-f", "lavfi", "-i", `testsrc=duration=${video.seconds}:size=320x240:rate=24`,    "-f", "lavfi", "-i", `sine=frequency=${video.tone}:duration=${video.seconds}`,    "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest",    ...(video.container === "hls" ? ["-profile:v", "main", "-level:v", "3.0", "-g", "48", "-keyint_min", "48", "-sc_threshold", "0"] : []),    "-map_metadata", "-1", "-fflags", "+bitexact", "-flags:v", "+bitexact", "-flags:a", "+bitexact",    ...(video.container === "mp4"      ? ["-movflags", "+faststart", "-f", "mp4"]      : video.container === "hls"        ? ["-f", "hls", "-hls_segment_type", "fmp4", "-hls_time", "2", "-hls_playlist_type", "vod", "-hls_flags", "independent_segments", "-hls_fmp4_init_filename", "init.mp4", "-hls_segment_filename", join(out, "..", "seg%05d.m4s")]        : ["-f", "matroska"]),    out,  ];}/** Every cue of the seed's English track: one line each two seconds, over the whole film. */export function englishCues(seconds: number): string {  const at = (s: number) => `00:${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}.000`;  const cues = Array.from({ length: Math.floor(seconds / 2) }, (_, i) => `${at(i * 2)} --> ${at(i * 2 + 2)}\nThe ferry's lantern, line ${i + 1}.\n`);  return ["WEBVTT", "X-TIMESTAMP-MAP=MPEGTS:0,LOCAL:00:00:00.000", "", ...cues].join("\n");}/** The folder around ffmpeg's segments, as the Mac lays it: the subtitle playlist and the master that names both. */export function layHls(folder: string, seconds: number): void {  writeFileSync(join(folder, "sub-en.vtt"), englishCues(seconds));  writeFileSync(join(folder, "sub-en.m3u8"), ["#EXTM3U", "#EXT-X-VERSION:3", `#EXT-X-TARGETDURATION:${seconds}`, "#EXT-X-PLAYLIST-TYPE:VOD", `#EXTINF:${seconds}.000,`, "sub-en.vtt", "#EXT-X-ENDLIST", ""].join("\n"));  writeFileSync(join(folder, "master.m3u8"), [    "#EXTM3U", "#EXT-X-VERSION:7", "#EXT-X-INDEPENDENT-SEGMENTS",    '#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="English",LANGUAGE="en",DEFAULT=NO,AUTOSELECT=YES,FORCED=NO,URI="sub-en.m3u8"',    '#EXT-X-STREAM-INF:BANDWIDTH=400000,CODECS="avc1.4d401e,mp4a.40.2",RESOLUTION=320x240,FRAME-RATE=24.000,SUBTITLES="subs"',    "video/index.m3u8", "",  ].join("\n"));}const TYPES: Record<string, string> = { m3u8: "application/vnd.apple.mpegurl", m4s: "video/iso.segment", mp4: "video/mp4", vtt: "text/vtt" };/** Every file of a laid folder, under the master's folder key, the master last. */function folderMedia(folder: string, masterKey: string): SeedMedia[] {  const base = masterKey.slice(0, masterKey.lastIndexOf("/") + 1);  const walk = (at: string): string[] => readdirSync(at, { withFileTypes: true }).flatMap((d) => (d.isDirectory() ? walk(join(at, d.name)) : [join(at, d.name)]));  const rel = walk(folder).map((f) => relative(folder, f)).sort((a, b) => Number(a === "master.m3u8") - Number(b === "master.m3u8") || a.localeCompare(b));  return rel.map((r) => ({ key: base + r, contentType: TYPES[r.split(".").at(-1)!] ?? "application/octet-stream", bytes: new Uint8Array(readFileSync(join(folder, r))) }));}/** Each video made in a scratch folder (gone afterwards) and read back as the media the seed sends. */export function renderVideos(videos: SeedVideo[], run: Run = runFfmpeg): SeedMedia[] {  if (!videos.length) return [];  requireFfmpeg(run);  const dir = mkdtempSync(join(tmpdir(), "dev-seed-films-"));  try {    return videos.flatMap((video, i) => {      const folder = join(dir, String(i));      const out = video.container === "hls" ? join(folder, "video", "index.m3u8") : join(dir, `${i}.${video.container}`);      if (video.container === "hls") mkdirSync(join(folder, "video"), { recursive: true });      const r = run(videoArgs(video, out));      if (r.error || r.status !== 0 || !existsSync(out)) throw new SeedRefusal(`ffmpeg could not make ${video.key}: ${r.error?.message ?? r.stderr.trim().split("\n").slice(-3).join(" | ")}`);      if (video.container !== "hls") return [{ key: video.key, contentType: video.contentType, bytes: new Uint8Array(readFileSync(out)) }];      layHls(folder, video.seconds);      return folderMedia(folder, video.key);    });  } finally {    rmSync(dir, { recursive: true, force: true });  }}