UNPKG

@adonis-agora/media

Version:

Media-library for AdonisJS — owner collections (MIME whitelist, single-file replace, ordering), image conversions (eager/lazy), pluggable content transformers (HLS video via mediabunny, metadata probe, image blur-up placeholder), and column attachments, a

402 lines • 19.7 kB
import { spawn } from 'node:child_process'; import { readdir, readFile, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { FfmpegFailedError, HlsSourceUnsupportedError, TransformerRuntimeMissingError, } from '../errors.js'; /** The rendition name ffmpeg's `%v` expands to; playlist `playlist-0.m3u8`, segments `segment-0-3.ts`. */ const PLAYLIST_PATTERN = 'playlist-%v.m3u8'; const SEGMENT_PATTERN = 'segment-%v-%d.ts'; /** Ready-made ladders. */ export const ladders = { /** 360p / 720p / 1080p — a sane default for course videos. */ standard: [ { height: 360, videoBitrate: '800k', audioBitrate: '96k' }, { height: 720, videoBitrate: '2800k' }, { height: 1080, videoBitrate: '5000k' }, ], /** 360p / 720p — lighter on storage and encode time. */ compact: [ { height: 360, videoBitrate: '800k', audioBitrate: '96k' }, { height: 720, videoBitrate: '2800k' }, ], }; /** Run a binary to completion, collecting stdout and the tail of stderr. */ function run(binary, args, transformerName) { return new Promise((resolve, reject) => { const child = spawn(binary, args, { stdio: ['ignore', 'pipe', 'pipe'] }); const out = []; let err = ''; child.stdout.on('data', (chunk) => out.push(chunk)); child.stderr.on('data', (chunk) => { // ffmpeg is chatty on stderr; only the end explains a failure. err = (err + chunk.toString()).slice(-4000); }); child.on('error', (error) => { if (error.code === 'ENOENT') { reject(new TransformerRuntimeMissingError(transformerName, `the '${binary}' binary`, 'Install ffmpeg on the host (e.g. `apt-get install ffmpeg`, `apk add ffmpeg`) or point `ffmpegPath`/`ffprobePath` at it.')); } else { reject(error); } }); child.on('close', (code) => { if (code === 0) resolve({ stdout: Buffer.concat(out).toString(), stderr: err }); else reject(new FfmpegFailedError(binary, code, err)); }); }); } async function probeSource(ffprobePath, sourcePath, transformerName) { const { stdout } = await run(ffprobePath, ['-v', 'error', '-print_format', 'json', '-show_format', '-show_streams', sourcePath], transformerName); let parsed; try { parsed = JSON.parse(stdout); } catch { throw new FfmpegFailedError(ffprobePath, 0, `unparseable ffprobe output: ${stdout.slice(0, 200)}`); } const streams = parsed.streams ?? []; const video = streams.find((s) => s.codec_type === 'video'); const audio = streams.find((s) => s.codec_type === 'audio'); const summary = { hasVideo: Boolean(video), hasAudio: Boolean(audio) }; if (parsed.format?.format_name) summary.format = parsed.format.format_name; const duration = Number(parsed.format?.duration); if (Number.isFinite(duration)) summary.durationSeconds = duration; if (video) { // Phone videos store landscape frames plus a rotation; report the size as displayed. const rotation = Math.abs(Number(video.side_data_list?.find((d) => d.rotation !== undefined)?.rotation ?? video.tags?.rotate ?? 0)); const swap = rotation === 90 || rotation === 270; if (video.width !== undefined && video.height !== undefined) { summary.width = swap ? video.height : video.width; summary.height = swap ? video.width : video.height; } summary.videoCodec = video.codec_name ?? null; } if (audio) { summary.audioCodec = audio.codec_name ?? null; const sampleRate = Number(audio.sample_rate); if (Number.isFinite(sampleRate)) summary.audioSampleRate = sampleRate; if (audio.channels !== undefined) summary.audioChannels = audio.channels; } return summary; } /** The rungs actually encoded for a source of `sourceHeight` px: never upscale, never empty. */ export function effectiveLadder(ladder, sourceHeight) { const sorted = [...ladder].sort((a, b) => a.height - b.height); if (!sourceHeight) return sorted; const fitting = sorted.filter((r) => r.height <= sourceHeight); if (fitting.length > 0) return fitting; const smallest = sorted[0]; return smallest ? [{ ...smallest, height: sourceHeight - (sourceHeight % 2) }] : []; } /** * Build the ffmpeg argument list for one HLS run with TS segments. Exported for tests and for anyone wrapping the * engine; `renditions` empty means remux. */ export function buildHlsArgs(input) { const { sourcePath, outputDir, entryName, targetDuration, hasAudio, renditions, preset } = input; const args = ['-hide_banner', '-y', '-i', sourcePath]; const streamMap = []; if (renditions.length === 0) { args.push('-map', '0:v:0'); if (hasAudio) args.push('-map', '0:a:0'); args.push('-c', 'copy'); streamMap.push(hasAudio ? 'v:0,a:0' : 'v:0'); } else { const n = renditions.length; const splits = renditions.map((_, i) => `[v${i}]`).join(''); const scales = renditions.map((r, i) => `[v${i}]scale=-2:${r.height}[v${i}o]`).join(';'); args.push('-filter_complex', `[0:v:0]split=${n}${splits};${scales}`); renditions.forEach((r, i) => { const peak = `${Math.round(parseBitrate(r.videoBitrate) * 1.5)}`; args.push('-map', `[v${i}o]`, `-c:v:${i}`, 'libx264', `-b:v:${i}`, r.videoBitrate, `-maxrate:v:${i}`, peak, `-bufsize:v:${i}`, `${Number(peak) * 2}`); if (hasAudio) { args.push('-map', '0:a:0', `-c:a:${i}`, 'aac', `-b:a:${i}`, r.audioBitrate ?? '128k'); } streamMap.push(hasAudio ? `v:${i},a:${i}` : `v:${i}`); }); // Segment boundaries must land on keyframes for every rendition to switch cleanly. args.push('-preset', preset, '-pix_fmt', 'yuv420p', '-sc_threshold', '0', '-force_key_frames', `expr:gte(t,n_forced*${targetDuration})`); } args.push(...input.extraArgs, '-f', 'hls', '-hls_time', String(targetDuration), '-hls_playlist_type', 'vod', '-hls_segment_filename', join(outputDir, SEGMENT_PATTERN), '-master_pl_name', entryName, '-var_stream_map', streamMap.join(' '), join(outputDir, PLAYLIST_PATTERN)); return args; } /** * Validate a ladder while the config is in hand — a bad rung would otherwise fail deep inside * libx264 with a cryptic error on the first transcode. */ /** Check a ladder at config time: even positive heights, parseable bitrates. Exported for the other engines. */ export function validateLadder(ladder) { for (const r of ladder ?? []) { if (!Number.isInteger(r.height) || r.height <= 0 || r.height % 2 !== 0) { throw new Error(`Invalid rendition height ${r.height} (expected a positive even integer — h264 needs even dimensions)`); } parseBitrate(r.videoBitrate); if (r.audioBitrate !== undefined) parseBitrate(r.audioBitrate); } } /** `'2800k'` → 2_800_000. Plain numbers pass through. */ /** `'800k'` → `800000`, `'5M'` → `5000000`. Exported for the other engines. */ export function parseBitrate(value) { const match = /^(\d+(?:\.\d+)?)([kKmM]?)$/.exec(value.trim()); if (!match) throw new Error(`Invalid bitrate "${value}" (expected e.g. '800k', '5M', '128000')`); const n = Number(match[1]); const unit = match[2]?.toLowerCase(); return unit === 'k' ? n * 1_000 : unit === 'm' ? n * 1_000_000 : n; } /** Segment names of a CMAF package; `$…$` are DASH template identifiers ffmpeg fills in. */ const DASH_INIT_PATTERN = 'init-$RepresentationID$.m4s'; const DASH_SEGMENT_PATTERN = 'chunk-$RepresentationID$-$Number%05d$.m4s'; /** Sprite sheet file names of a storyboard: `storyboard-001.jpg`, `storyboard-002.jpg`… */ const STORYBOARD_SHEET_PATTERN = 'storyboard-%03d.jpg'; const STORYBOARD_SHEET_RE = /^storyboard-(\d{3,})\.jpg$/; /** Thumbnail height for `width` px wide, keeping the source aspect ratio, rounded to even. */ export function storyboardTileHeight(width, source) { const ratio = source.width && source.height ? source.height / source.width : 9 / 16; return Math.max(2, Math.round((width * ratio) / 2) * 2); } /** * Build the ffmpeg argument list that writes a storyboard's sprite sheets: one frame every * `interval` seconds, scaled to `width`×`height`, tiled `columns`×`rows` per JPEG. Exported for * tests. */ export function buildStoryboardArgs(input) { const { interval, width, columns, rows } = input.storyboard; return [ '-hide_banner', '-y', '-i', input.sourcePath, '-map', '0:v:0', '-an', '-vf', `fps=1/${interval},scale=${width}:${input.height},tile=${columns}x${rows}`, '-q:v', '5', join(input.outputDir, STORYBOARD_SHEET_PATTERN), ]; } /** `3725.5` → `01:02:05.500`. */ function vttTime(seconds) { const totalMs = Math.max(0, Math.round(seconds * 1000)); const pad = (value, size = 2) => String(value).padStart(size, '0'); const totalSeconds = Math.floor(totalMs / 1000); return `${pad(Math.floor(totalSeconds / 3600))}:${pad(Math.floor(totalSeconds / 60) % 60)}:${pad(totalSeconds % 60)}.${pad(totalMs % 1000, 3)}`; } /** * The storyboard WebVTT: one cue per thumbnail, `[i·interval, (i+1)·interval)` (the last one ends * at `durationSeconds`), pointing at its tile with a media fragment * (`storyboard-002.jpg#xywh=320,90,160,90`). Thumbnails are capped at what the written sheets * hold, so a cue never points past the last tile. Exported for tests. */ export function buildStoryboardVtt(input) { const { interval, width, columns, rows } = input.storyboard; const perSheet = columns * rows; const capacity = input.sheets * perSheet; const count = input.durationSeconds !== undefined && input.durationSeconds > 0 ? Math.min(Math.ceil(input.durationSeconds / interval), capacity) : capacity; const cues = []; for (let i = 0; i < count; i++) { const start = i * interval; const end = input.durationSeconds !== undefined && input.durationSeconds > 0 ? Math.min((i + 1) * interval, input.durationSeconds) : (i + 1) * interval; if (end <= start) break; const sheet = String(Math.floor(i / perSheet) + 1).padStart(3, '0'); const tile = i % perSheet; const x = (tile % columns) * width; const y = Math.floor(tile / columns) * input.height; cues.push(`${vttTime(start)} --> ${vttTime(end)}\nstoryboard-${sheet}.jpg#xywh=${x},${y},${width},${input.height}`); } return `${['WEBVTT', ...cues].join('\n\n')}\n`; } /** * Write a storyboard into `outputDir`: the sprite sheets (one ffmpeg run) and the WebVTT, built * from the sheets ffmpeg actually wrote. */ async function writeStoryboard(ffmpegPath, request, source) { const height = storyboardTileHeight(request.storyboard.width, source); await run(ffmpegPath, buildStoryboardArgs({ sourcePath: request.sourcePath, outputDir: request.outputDir, storyboard: request.storyboard, height, }), 'video'); const sheets = (await readdir(request.outputDir)).filter((file) => STORYBOARD_SHEET_RE.test(file)).length; await writeFile(join(request.outputDir, request.storyboard.vtt), buildStoryboardVtt({ storyboard: request.storyboard, height, sheets, durationSeconds: source.durationSeconds, })); } /** * Build the ffmpeg argument list for one DASH (CMAF) run — one manifest, fragmented-MP4 segments * and, with `hlsEntryName`, an HLS master playlist over the same segments. Exported for tests and * for anyone wrapping the engine; `renditions` empty means remux. */ export function buildDashArgs(input) { const { sourcePath, outputDir, targetDuration, hasAudio, renditions } = input; const args = ['-hide_banner', '-y', '-i', sourcePath]; if (renditions.length === 0) { args.push('-map', '0:v:0'); if (hasAudio) args.push('-map', '0:a:0'); args.push('-c', 'copy'); } else { const n = renditions.length; const splits = renditions.map((_, i) => `[v${i}]`).join(''); const scales = renditions.map((r, i) => `[v${i}]scale=-2:${r.height}[v${i}o]`).join(';'); args.push('-filter_complex', `[0:v:0]split=${n}${splits};${scales}`); renditions.forEach((r, i) => { const peak = `${Math.round(parseBitrate(r.videoBitrate) * 1.5)}`; args.push('-map', `[v${i}o]`, `-c:v:${i}`, 'libx264', `-b:v:${i}`, r.videoBitrate, `-maxrate:v:${i}`, peak, `-bufsize:v:${i}`, `${Number(peak) * 2}`); }); // DASH shares one audio track across the video rungs (its own adaptation set). if (hasAudio) args.push('-map', '0:a:0', '-c:a', 'aac', '-b:a', input.audioBitrate); args.push('-preset', input.preset, '-pix_fmt', 'yuv420p', '-sc_threshold', '0', '-force_key_frames', `expr:gte(t,n_forced*${targetDuration})`); } args.push(...input.extraArgs, '-f', 'dash', '-seg_duration', String(targetDuration), '-use_template', '1', '-use_timeline', '1', '-adaptation_sets', hasAudio ? 'id=0,streams=v id=1,streams=a' : 'id=0,streams=v', '-init_seg_name', DASH_INIT_PATTERN, '-media_seg_name', DASH_SEGMENT_PATTERN); if (input.hlsEntryName) { args.push('-hls_playlist', '1', '-hls_master_name', input.hlsEntryName); } args.push(join(outputDir, input.manifestName)); return args; } /** * {@link VideoPackagingEngine} backed by the system ffmpeg: remux by default, or an * adaptive-bitrate ladder when `ladder` is set. * * - CMAF segments go through ffmpeg's DASH muxer, which writes the MPD and (for HLS) a master * playlist over the same fragmented-MP4 segments — one audio track shared by every rung. * - TS segments go through the HLS muxer, every rendition carrying its own audio. * * Needs ffmpeg ≥ 4.3 (`-hls_master_name`). */ export function ffmpegVideoEngine(options = {}) { const ffmpegPath = options.ffmpegPath ?? 'ffmpeg'; const ffprobePath = options.ffprobePath ?? 'ffprobe'; validateLadder(options.ladder); if (options.audioBitrate !== undefined) parseBitrate(options.audioBitrate); const audioBitrate = options.audioBitrate ?? [...(options.ladder ?? [])] .map((r) => r.audioBitrate) .filter((b) => b !== undefined) .sort((a, b) => parseBitrate(b) - parseBitrate(a))[0] ?? '128k'; return { storyboard: true, async package(request) { const summary = await probeSource(ffprobePath, request.sourcePath, 'video'); // Same definitive signal the mediabunny engine gives for an unusable source, so callers // branch on one error regardless of engine (and don't retry an audio-only file forever). if (!summary.hasVideo) { throw new HlsSourceUnsupportedError('the source has no video stream', 'Video packaging needs a video track; this file is audio-only or not a video.'); } const renditions = options.ladder ? effectiveLadder(options.ladder, summary.height) : []; const common = { sourcePath: request.sourcePath, outputDir: request.outputDir, targetDuration: request.targetDuration, hasAudio: summary.hasAudio, renditions, preset: options.preset ?? 'veryfast', extraArgs: options.extraArgs ?? [], }; const packaging = async () => { if (request.segments === 'ts') { if (!request.hlsEntry) { throw new Error('TS segments only play over HLS: the request needs an `hlsEntry`.'); } await run(ffmpegPath, buildHlsArgs({ ...common, entryName: request.hlsEntry }), 'video'); } else { // The DASH muxer always writes an MPD; an HLS-only package drops it afterwards. const manifestName = request.dashManifest ?? 'manifest.mpd'; await run(ffmpegPath, buildDashArgs({ ...common, manifestName, hlsEntryName: request.hlsEntry, audioBitrate, }), 'video'); if (!request.dashManifest) await rm(join(request.outputDir, manifestName)); if (request.hlsEntry) await normalizeVodPlaylists(request.outputDir); } }; // The storyboard is a second, light decode of the same source: run it alongside the encode // (one ffmpeg process does not use every core) rather than after it. const storyboard = request.storyboard; await Promise.all([ packaging(), storyboard ? writeStoryboard(ffmpegPath, { ...request, storyboard }, summary) : undefined, ]); const result = {}; if (summary.durationSeconds !== undefined) result.durationSeconds = summary.durationSeconds; if (summary.width !== undefined) result.width = summary.width; if (summary.height !== undefined) result.height = summary.height; result.videoCodec = renditions.length > 0 ? 'h264' : (summary.videoCodec ?? null); if (summary.hasAudio) result.audioCodec = renditions.length > 0 ? 'aac' : (summary.audioCodec ?? null); return result; }, }; } /** * Make the HLS playlists ffmpeg's DASH muxer writes plain VOD playlists. It carries over two * live-stream details that mean nothing for a VOD and that players read differently: * * - `#EXT-X-PROGRAM-DATE-TIME` stamps the wall-clock time of the TRANSCODE — a player mapping * the timeline to it reports a duration of decades; * - `#EXT-X-MEDIA-SEQUENCE:1` (it numbers segments like the MPD's `startNumber`) — a player * reading the sequence as elapsed segments (mediabunny) starts the video one segment late. * Without the tag the sequence is 0 for everyone. */ async function normalizeVodPlaylists(outputDir) { for (const file of await readdir(outputDir)) { if (!file.toLowerCase().endsWith('.m3u8')) continue; const path = join(outputDir, file); const content = await readFile(path, 'utf8'); const lines = content.split(/(?<=\n)/); const kept = lines.filter((line) => !line.startsWith('#EXT-X-PROGRAM-DATE-TIME') && !line.startsWith('#EXT-X-MEDIA-SEQUENCE')); if (kept.length !== lines.length) await writeFile(path, kept.join('')); } } /** * {@link MediaProbeEngine} backed by the system ffprobe. Differences from the mediabunny probe: * `format` is ffprobe's `format_name` (e.g. `'mov,mp4,m4a,3gp,3g2,mj2'`), and `mimeType` is not * reported — ffprobe has no MIME/codecs-string notion; the record's own `mimeType` still applies. */ export function ffprobeEngine(options = {}) { const ffprobePath = options.ffprobePath ?? 'ffprobe'; return { async probe(sourcePath) { return probeSource(ffprobePath, sourcePath, 'probe'); }, }; } //# sourceMappingURL=ffmpeg.js.map