ffprobe can succeed on audio-only or broken containers while webCopyArgs still maps 0:v:0, which exits 234. Refuse those sources as VideoUnsupported and mark FAILED without useless retries. Paperclip-Issue: BIT-31622 Paperclip-Run: 46c787aa-ef6c-4036-be34-af93b4bfd23d
231 lines
10 KiB
TypeScript
231 lines
10 KiB
TypeScript
import { spawn } from "node:child_process";
|
|
import { createReadStream, existsSync } from "node:fs";
|
|
import { readdir, stat } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import type { FastifyReply } from "fastify";
|
|
import sharp from "sharp";
|
|
|
|
/**
|
|
* Videos in the archive (docs/archive.md, "Vídeos"). The original stays on the cloud; the archive keeps a web copy
|
|
* every browser plays (H.264 + AAC in MP4, the short side at most 1080 px, faststart so it starts before it has
|
|
* all arrived), a poster for the large view and a thumbnail for the grid. Made with ffmpeg on the worker.
|
|
*/
|
|
export const VIDEO = /\.(mp4|m4v|mov|mts|m2ts|mkv|avi|webm)$/i;
|
|
|
|
/** The files of a video's web copy, inside its storage folder. */
|
|
export const VIDEO_FILES = { web: "web.mp4", poster: "poster.jpg", thumb: "thumb.jpg" } as const;
|
|
export type VideoVariant = keyof typeof VIDEO_FILES | "download";
|
|
export const VIDEO_VARIANTS = ["web", "poster", "thumb", "download"] as const satisfies readonly VideoVariant[];
|
|
|
|
/** Long side of the poster (the large view before play) and of the grid's thumbnail. */
|
|
const POSTER_SIZE = 1280;
|
|
const THUMB_SIZE = 480;
|
|
/** The short side of the web copy: 1080p for a landscape video, 1080 wide for a phone's portrait one. */
|
|
export const WEB_SHORT_SIDE = 1080;
|
|
|
|
export class VideoToolMissing extends Error {
|
|
constructor(tool: string) {
|
|
super(`${tool}_missing`);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Source has no usable video stream (audio-only, corrupt container, wrong extension).
|
|
* Indexing should mark FAILED without retry — ffmpeg `-map 0:v:0` cannot succeed.
|
|
*/
|
|
export class VideoUnsupported extends Error {
|
|
constructor(reason = "no_video_stream") {
|
|
super(reason);
|
|
this.name = "VideoUnsupported";
|
|
}
|
|
}
|
|
|
|
export interface VideoTools {
|
|
ffmpeg: string;
|
|
ffprobe: string;
|
|
}
|
|
|
|
export interface VideoInfo {
|
|
durationMs: number | null;
|
|
width: number | null;
|
|
height: number | null;
|
|
capturedAt: Date | null;
|
|
hasAudio: boolean;
|
|
hasVideo: boolean;
|
|
}
|
|
|
|
/**
|
|
* The tools to use: the ones named in the configuration; with the defaults ("ffmpeg" on PATH), the static build the
|
|
* deploy puts in the user's home (`~/.local/ffmpeg`, infra/deploy/deploy.sh) when it is there.
|
|
*/
|
|
export function findVideoTools(configured: VideoTools, home: string, exists: (file: string) => boolean = existsSync): VideoTools {
|
|
const local = (name: "ffmpeg" | "ffprobe") => {
|
|
const file = path.join(home, ".local", "ffmpeg", name);
|
|
return configured[name] === name && exists(file) ? file : configured[name];
|
|
};
|
|
return { ffmpeg: local("ffmpeg"), ffprobe: local("ffprobe") };
|
|
}
|
|
|
|
/** ffmpeg's arguments for the web copy (tested on their own). */
|
|
export function webCopyArgs(input: string, output: string, opts: { audio: boolean }): string[] {
|
|
// Scales down only: the short side to WEB_SHORT_SIDE at most, the other to keep the shape (even, as H.264 needs).
|
|
// ffmpeg turns a phone's rotated video upright on the way (autorotate), so width and height are as shown.
|
|
const s = WEB_SHORT_SIDE;
|
|
const scale = `scale=w='if(gte(iw,ih),-2,min(${s},iw))':h='if(gte(iw,ih),min(${s},ih),-2)'`;
|
|
return [
|
|
"-hide_banner",
|
|
"-nostdin",
|
|
"-loglevel",
|
|
"error",
|
|
"-y",
|
|
"-i",
|
|
input,
|
|
"-map",
|
|
"0:v:0",
|
|
...(opts.audio ? ["-map", "0:a:0"] : []),
|
|
"-vf",
|
|
`${scale},format=yuv420p`,
|
|
"-c:v",
|
|
"libx264",
|
|
"-preset",
|
|
"veryfast",
|
|
"-crf",
|
|
"23",
|
|
"-profile:v",
|
|
"high",
|
|
...(opts.audio ? ["-c:a", "aac", "-b:a", "128k", "-ac", "2"] : ["-an"]),
|
|
"-movflags",
|
|
"+faststart",
|
|
"-max_muxing_queue_size",
|
|
"1024",
|
|
output,
|
|
];
|
|
}
|
|
|
|
/** Where to take the poster from: a second in, or a tenth of a short clip. */
|
|
export function posterAt(durationMs: number | null): number {
|
|
if (!durationMs || durationMs <= 0) return 0;
|
|
return Math.min(1, durationMs / 10000);
|
|
}
|
|
|
|
function run(bin: string, args: string[], tool: string): Promise<string> {
|
|
return new Promise((resolve, reject) => {
|
|
const child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
let out = "";
|
|
let err = "";
|
|
child.stdout.on("data", (d: Buffer) => (out += d.toString()));
|
|
child.stderr.on("data", (d: Buffer) => {
|
|
// Only the end matters (ffmpeg says why it stopped last).
|
|
err = (err + d.toString()).slice(-4000);
|
|
});
|
|
child.on("error", (e: NodeJS.ErrnoException) => reject(e.code === "ENOENT" ? new VideoToolMissing(tool) : e));
|
|
child.on("close", (code) => (code === 0 ? resolve(out) : reject(new Error(`${tool} exited ${code}: ${err.trim().split("\n").slice(-3).join(" | ")}`))));
|
|
});
|
|
}
|
|
|
|
interface ProbeJson {
|
|
format?: { duration?: string; tags?: Record<string, string> };
|
|
streams?: { codec_type?: string; width?: number; height?: number; duration?: string; tags?: Record<string, string> }[];
|
|
}
|
|
|
|
/** What ffprobe says of a file: length, size as stored, the camera's time, whether it has sound. */
|
|
export async function probe(tools: VideoTools, file: string): Promise<VideoInfo> {
|
|
const json = JSON.parse(await run(tools.ffprobe, ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", file], "ffprobe")) as ProbeJson;
|
|
return readProbe(json);
|
|
}
|
|
|
|
export function readProbe(json: ProbeJson): VideoInfo {
|
|
const streams = json.streams ?? [];
|
|
const video = streams.find((s) => s.codec_type === "video");
|
|
const seconds = Number(json.format?.duration ?? video?.duration);
|
|
const tags = { ...(video?.tags ?? {}), ...(json.format?.tags ?? {}) };
|
|
// Apple's own tag keeps the time zone; creation_time is UTC. A camera that never had its clock set says 1970 or 1904.
|
|
const raw = tags["com.apple.quicktime.creationdate"] ?? tags.creation_time ?? null;
|
|
const when = raw ? new Date(raw) : null;
|
|
const capturedAt = when && !Number.isNaN(when.getTime()) && when.getUTCFullYear() >= 2000 && when.getTime() < Date.now() + 86_400_000 ? when : null;
|
|
return {
|
|
durationMs: Number.isFinite(seconds) && seconds > 0 ? Math.round(seconds * 1000) : null,
|
|
width: video?.width ?? null,
|
|
height: video?.height ?? null,
|
|
capturedAt,
|
|
hasAudio: streams.some((s) => s.codec_type === "audio"),
|
|
hasVideo: !!video,
|
|
};
|
|
}
|
|
|
|
/** Refuse sources with no video stream before ffmpeg `-map 0:v:0` (cryptic exit 234). */
|
|
export function requireVideoStream(info: Pick<VideoInfo, "hasVideo">): void {
|
|
if (!info.hasVideo) throw new VideoUnsupported();
|
|
}
|
|
|
|
/**
|
|
* The web copy, poster and thumbnail of `input`, written into `dir`. What it answers is read from the copy (its
|
|
* size is the one shown, upright), with the original's camera time.
|
|
*/
|
|
export async function makeWebCopy(tools: VideoTools, input: string, dir: string): Promise<VideoInfo & { webBytes: number }> {
|
|
const original = await probe(tools, input);
|
|
requireVideoStream(original);
|
|
const web = path.join(dir, VIDEO_FILES.web);
|
|
await run(tools.ffmpeg, webCopyArgs(input, web, { audio: original.hasAudio }), "ffmpeg");
|
|
const copy = await probe(tools, web);
|
|
const frame = path.join(dir, "frame.jpg");
|
|
// The most typical frame among the first ones after the start (thumbnail filter), not a black first frame.
|
|
await run(tools.ffmpeg, ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-ss", String(posterAt(copy.durationMs)), "-i", web, "-vf", "thumbnail=30", "-frames:v", "1", "-q:v", "2", frame], "ffmpeg");
|
|
await sharp(frame).resize(POSTER_SIZE, POSTER_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 85 }).toFile(path.join(dir, VIDEO_FILES.poster));
|
|
await sharp(frame).resize(THUMB_SIZE, THUMB_SIZE, { fit: "inside", withoutEnlargement: true }).jpeg({ quality: 80 }).toFile(path.join(dir, VIDEO_FILES.thumb));
|
|
return { ...copy, capturedAt: original.capturedAt, webBytes: (await stat(web)).size };
|
|
}
|
|
|
|
/**
|
|
* Frames of a video at `fps` a second (JPEG, the video's own size), for face analysis: the files in time order;
|
|
* frame i is at i / fps seconds from the start of the part read (`part`: from, and how long; the whole video
|
|
* without it).
|
|
*/
|
|
export async function extractFrames(tools: VideoTools, input: string, dir: string, fps: number, part?: { fromMs: number; lengthMs: number }): Promise<string[]> {
|
|
const window = part ? ["-ss", (part.fromMs / 1000).toFixed(3), "-t", (part.lengthMs / 1000).toFixed(3)] : [];
|
|
await run(tools.ffmpeg, ["-hide_banner", "-nostdin", "-loglevel", "error", "-y", ...window, "-i", input, "-vf", `fps=${fps}`, "-q:v", "3", path.join(dir, "frame_%06d.jpg")], "ffmpeg");
|
|
return (await readdir(dir)).filter((f) => /^frame_\d+\.jpg$/.test(f)).sort().map((f) => path.join(dir, f));
|
|
}
|
|
|
|
/** A `Range: bytes=…` header against a file's size: the part to send, `null` for the whole file, `"bad"` when it cannot be met. */
|
|
export function parseRange(header: string | undefined, size: number): { start: number; end: number } | null | "bad" {
|
|
if (!header) return null;
|
|
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
|
// Several ranges at once are not worth it for a player: the whole file.
|
|
if (!m) return header.includes(",") ? null : "bad";
|
|
const [, a, b] = m;
|
|
if (a === "" && b === "") return "bad";
|
|
let start: number;
|
|
let end: number;
|
|
if (a === "") {
|
|
// The last N bytes.
|
|
const n = Number(b);
|
|
if (!n) return "bad";
|
|
start = Math.max(0, size - n);
|
|
end = size - 1;
|
|
} else {
|
|
start = Number(a);
|
|
end = b === "" ? size - 1 : Math.min(Number(b), size - 1);
|
|
}
|
|
if (start >= size || start > end) return "bad";
|
|
return { start, end };
|
|
}
|
|
|
|
/**
|
|
* Sends a file the way video players ask for it: whole, or the part named by `Range` (206), so the player can
|
|
* start at once and jump to any moment.
|
|
*/
|
|
export async function sendFile(reply: FastifyReply, file: string, range: string | undefined, headers: Record<string, string>): Promise<FastifyReply> {
|
|
const size = (await stat(file)).size;
|
|
for (const [k, v] of Object.entries(headers)) reply.header(k, v);
|
|
reply.header("accept-ranges", "bytes");
|
|
const part = parseRange(range, size);
|
|
if (part === "bad") return reply.code(416).header("content-range", `bytes */${size}`).send();
|
|
if (!part) return reply.header("content-length", String(size)).send(createReadStream(file));
|
|
return reply
|
|
.code(206)
|
|
.header("content-range", `bytes ${part.start}-${part.end}/${size}`)
|
|
.header("content-length", String(part.end - part.start + 1))
|
|
.send(createReadStream(file, { start: part.start, end: part.end }));
|
|
}
|