SPB Git

Repository Public

media.ts 9.5 KB 153 lines typescript

1import { execFile } from "node:child_process";2import { open } from "node:fs/promises";3import { promisify } from "node:util";4import { env } from "@/lib/env";5import { clean } from "@/lib/text";67const run = promisify(execFile);89export type Kind = "flac" | "mp3" | "m4a" | "wav" | "aiff" | "ogg" | "dsf" | "dff" | "aac" | "zip" | "jpeg" | "png" | "webp";10export class MediaError extends Error { constructor(public code: string, message?: string) { super(message ?? code); } }1112/** Type from the first bytes of the content. The extension and the declared MIME type are never trusted. */13export async function sniff(file: string): Promise<Kind | null> {14  const fh = await open(file, "r");15  try {16    const b = Buffer.alloc(16);17    const { bytesRead } = await fh.read(b, 0, 16, 0);18    if (bytesRead < 12) return null;19    const s = (o: number, n: number) => b.toString("latin1", o, o + n);20    if (s(0, 4) === "fLaC") return "flac";21    if (s(0, 3) === "ID3") {22      // An ID3v2 tag may precede MP3, FLAC, AAC or AIFF data: look at what follows the tag.23      const hdr = Buffer.alloc(10); await fh.read(hdr, 0, 10, 0);24      const size = ((hdr[6] & 0x7f) << 21) | ((hdr[7] & 0x7f) << 14) | ((hdr[8] & 0x7f) << 7) | (hdr[9] & 0x7f);25      const after = Buffer.alloc(4); const r = await fh.read(after, 0, 4, 10 + size);26      if (r.bytesRead === 4 && after.toString("latin1") === "fLaC") return "flac";27      if (r.bytesRead >= 2 && after[0] === 0xff && (after[1] & 0xf6) === 0xf0) return "aac";28      return "mp3";29    }30    if (s(4, 4) === "ftyp") return "m4a";31    if (s(0, 4) === "RIFF" && s(8, 4) === "WAVE") return "wav";32    if (s(0, 4) === "RIFF" && s(8, 4) === "WEBP") return "webp";33    if (s(0, 4) === "FORM" && (s(8, 4) === "AIFF" || s(8, 4) === "AIFC")) return "aiff";34    if (s(0, 4) === "OggS") return "ogg";35    if (s(0, 4) === "DSD ") return "dsf";36    if (s(0, 4) === "FRM8") return "dff";37    if (s(0, 4) === "PK\u0003\u0004") return "zip";38    if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "jpeg";39    if (b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "png";40    if (b[0] === 0xff && (b[1] & 0xf6) === 0xf0) return "aac";       // ADTS41    if (b[0] === 0xff && (b[1] & 0xe0) === 0xe0) return "mp3";       // MPEG audio frame sync42    return null;43  } finally { await fh.close(); }44}4546export const AUDIO_KINDS: ReadonlySet<Kind> = new Set(["flac", "mp3", "m4a", "wav", "aiff", "ogg", "dsf", "dff", "aac"]);47const EXT: Record<string, string> = { flac: "flac", mp3: "mp3", m4a: "m4a", wav: "wav", aiff: "aiff", ogg: "ogg", dsf: "dsf", dff: "dff", aac: "aac" };48export const extFor = (k: Kind) => EXT[k] ?? "bin";4950export interface Probe {51  codec: string; container: string; durationMs: number; sampleRate: number | null; bitDepth: number | null; channels: number | null; bitrate: number | null;52  hasPicture: boolean;53  tags: { title: string; artist: string; album: string; albumArtist: string; trackNo: number | null; discNo: number | null; year: number | null; genre: string };54}5556/** ffprobe with an argument vector (no shell): a hostile file name cannot become a command. */57export async function probe(file: string): Promise<Probe> {58  let out: string;59  try {60    ({ stdout: out } = await run(env.ffprobe, ["-v", "error", "-hide_banner", "-show_format", "-show_streams", "-of", "json", "--", file], { timeout: 60_000, maxBuffer: 8 * 1024 * 1024 }));61  } catch { throw new MediaError("undecodable", "ffprobe could not read the file"); }62  let data: { streams?: Record<string, unknown>[]; format?: Record<string, unknown> };63  try { data = JSON.parse(out); } catch { throw new MediaError("undecodable"); }64  const streams = data.streams ?? [];65  const a = streams.find((s) => s.codec_type === "audio");66  if (!a) throw new MediaError("no_audio_stream", "The file holds no audio stream");67  if (streams.some((s) => s.codec_type === "video" && !(s.disposition as Record<string, number> | undefined)?.attached_pic)) throw new MediaError("not_audio", "Video files are not accepted");68  const fmt = data.format ?? {};69  const tagsRaw: Record<string, string> = {};70  for (const src of [fmt.tags, a.tags]) for (const [k, v] of Object.entries((src as Record<string, string>) ?? {})) if (typeof v === "string" && !(k.toLowerCase() in tagsRaw)) tagsRaw[k.toLowerCase()] = v;71  const tag = (...names: string[]) => { for (const n of names) if (tagsRaw[n]) return clean(tagsRaw[n]); return ""; };72  const num = (v: string) => { const m = v.match(/^\s*(\d{1,4})/); return m ? Number(m[1]) : null; };73  const yearM = tag("date", "year", "originaldate", "tyer", "tdrc").match(/(1\d{3}|2\d{3})/);74  const n = (v: unknown) => { const x = Number(v); return Number.isFinite(x) && x > 0 ? Math.round(x) : null; };75  const duration = Number(fmt.duration ?? a.duration);76  if (!Number.isFinite(duration) || duration <= 0) throw new MediaError("undecodable", "The audio stream has no measurable duration");77  const codec = String(a.codec_name ?? "");78  return {79    codec, container: String(fmt.format_name ?? "").split(",")[0],80    durationMs: Math.round(duration * 1000),81    sampleRate: n(a.sample_rate), channels: n(a.channels), bitrate: n(fmt.bit_rate ?? a.bit_rate),82    bitDepth: n(a.bits_per_raw_sample) ?? n(a.bits_per_sample) ?? (codec.startsWith("dsd") ? 1 : null),83    hasPicture: streams.some((s) => s.codec_type === "video"),84    tags: {85      title: tag("title"), artist: tag("artist"), album: tag("album"), albumArtist: tag("album_artist", "albumartist", "album artist"),86      trackNo: num(tag("track", "tracknumber")), discNo: num(tag("disc", "discnumber")), year: yearM ? Number(yearM[1]) : null, genre: tag("genre"),87    },88  };89}9091/**92 * Can browsers decode the original?93 *  yes  — FLAC, MP3, AAC, PCM WAV, Vorbis/Opus… (every current engine, Safari included for FLAC since 11)94 *  some — ALAC and AIFF: Safari only → an AAC rendition is prepared at import95 *  no   — DSD and anything else → original kept, rendition only under explicit configuration96 */97export function webPlayable(p: Pick<Probe, "codec" | "container">): "yes" | "some" | "no" {98  const c = p.codec;99  if (c.startsWith("dsd")) return "no";100  if (c === "alac") return "some";101  if (p.container === "aiff") return "some";102  if (c === "flac" || c === "mp3" || c === "aac") return "yes";103  if (p.container === "wav" && /^pcm_(s16le|s24le|u8|f32le|s32le)$/.test(c)) return "yes";104  // Safari decodes Ogg Vorbis/Opus only since 18.4: treat as partial so a rendition exists.105  if (c === "vorbis" || c === "opus") return "some";106  return "no";107}108109export function mimeFor(codec: string, container: string): string {110  if (codec === "flac") return "audio/flac";111  if (codec === "mp3") return "audio/mpeg";112  if (container === "wav") return "audio/wav";113  if (container === "aiff") return "audio/aiff";114  if (container === "ogg") return "audio/ogg";115  if (container === "aac") return "audio/aac";116  if (codec === "aac" || codec === "alac" || container === "mov") return "audio/mp4";117  if (codec.startsWith("dsd")) return "audio/x-dsd";118  return "application/octet-stream";119}120121/** AAC compatibility rendition. The original is only read. High-resolution sources are brought to 44.1/48 kHz. */122export async function transcodeAac(src: string, dest: string, sampleRate: number | null): Promise<void> {123  const rate = sampleRate && sampleRate % 44100 === 0 ? 44100 : sampleRate && sampleRate <= 48000 && sampleRate !== 44100 ? sampleRate : sampleRate && sampleRate > 48000 ? 48000 : 44100;124  try {125    await run(env.ffmpeg, ["-v", "error", "-hide_banner", "-nostdin", "-y", "-i", src, "-map", "0:a:0", "-vn", "-c:a", "aac", "-b:a", `${env.renditionBitrateK}k`, "-ar", String(rate), "-ac", "2", "-movflags", "+faststart", "-f", "ipod", dest], { timeout: 30 * 60_000, maxBuffer: 4 * 1024 * 1024 });126  } catch (e) { throw new MediaError("transcode_failed", String((e as { stderr?: string }).stderr ?? "").slice(0, 300)); }127}128129/** Embedded cover → file, stream-copied (the picture bytes are not re-encoded). Returns false when there is none. */130export async function extractCover(src: string, dest: string): Promise<boolean> {131  try { await run(env.ffmpeg, ["-v", "error", "-hide_banner", "-nostdin", "-y", "-i", src, "-an", "-map", "0:v:0", "-frames:v", "1", "-c:v", "copy", "-f", "image2", dest], { timeout: 60_000 }); return true; }132  catch { return false; }133}134135const MAX_IMAGE_PIXELS = 8000;136export async function imageSize(file: string): Promise<{ width: number; height: number }> {137  try {138    const { stdout } = await run(env.ffprobe, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height", "-of", "json", "--", file], { timeout: 30_000 });139    const s = JSON.parse(stdout).streams?.[0];140    const width = Number(s?.width), height = Number(s?.height);141    if (!(width > 0 && height > 0)) throw new Error();142    if (width > MAX_IMAGE_PIXELS || height > MAX_IMAGE_PIXELS) throw new MediaError("image_too_large", `Images are limited to ${MAX_IMAGE_PIXELS} px per side`);143    return { width, height };144  } catch (e) { if (e instanceof MediaError) throw e; throw new MediaError("bad_image", "The image could not be read"); }145}146147/** Square JPEG thumbnail (centre crop). The source image is left untouched. */148export async function makeThumb(src: string, dest: string, size: number): Promise<void> {149  try {150    await run(env.ffmpeg, ["-v", "error", "-hide_banner", "-nostdin", "-y", "-i", src, "-frames:v", "1", "-vf", `scale=${size}:${size}:force_original_aspect_ratio=increase:flags=lanczos,crop=${size}:${size}`, "-q:v", "3", "-f", "image2", "-c:v", "mjpeg", dest], { timeout: 60_000 });151  } catch { throw new MediaError("bad_image", "The image could not be converted"); }152}153
Files main
Menu

Theme