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

197 lines • 9.29 kB
import { createReadStream } from 'node:fs'; import { mkdir, readdir, stat } from 'node:fs/promises'; import { join } from 'node:path'; import { streamArtifactContentType } from '../streaming.js'; import { loadMediabunny } from './mediabunny_loader.js'; import { withSourceFile } from './source_file.js'; /** * Detect how (whether) WebCodecs is available: `'native'` when the runtime already exposes * `VideoEncoder`, `'injected'` when a {@link WebCodecsProvider} supplies one, `'absent'` otherwise. */ export async function resolveWebCodecsSupport(provider) { if (globalThis.VideoEncoder !== undefined) return 'native'; if (provider && (await provider()).VideoEncoder !== undefined) return 'injected'; return 'absent'; } /** File name of the HLS master playlist a {@link VideoTransformer} writes. */ export const VIDEO_HLS_ENTRY = 'index.m3u8'; /** File name of the storyboard WebVTT a {@link VideoTransformer} writes with `storyboard`. */ export const VIDEO_STORYBOARD = 'storyboard.vtt'; /** Defaults of {@link VideoStoryboardOptions}: a thumbnail every 5 s, 160 px wide, 10×10 a sheet. */ export const VIDEO_STORYBOARD_DEFAULTS = { interval: 5, width: 160, columns: 10, rows: 10, }; /** File name of the DASH manifest a {@link VideoTransformer} writes. */ export const VIDEO_DASH_MANIFEST = 'manifest.mpd'; /** * The built-in video {@link Transformer}: packages a stored video for adaptive streaming — * segments plus an HLS master playlist and/or a DASH manifest — persisted as * `record.conversions['video']`. * * - **CMAF by default.** Fragmented-MP4 segments are the one format both HLS and DASH play, so * `formats: ['hls', 'dash']` (the default) writes the video once and describes it twice. * - **TS when you need it.** `segments: 'ts'` writes MPEG-TS segments, HLS only, for players * that predate fMP4 HLS. * - **No ffmpeg needed.** The default engine (mediabunny) remuxes in pure JS; `engines.ffmpeg()` * transcodes, ladder included, where the host has ffmpeg. * * Serve it with `media.access.streamRoute()` and play it with `useMediaStream`. */ export class VideoTransformer { name; eager; formats; segments; targetDuration; engine; webcodecs; storyboard; constructor(options = {}) { this.name = options.name ?? 'video'; this.eager = options.eager ?? false; this.formats = [...new Set(options.formats ?? ['hls', 'dash'])]; this.segments = options.segments ?? 'cmaf'; this.targetDuration = options.targetDuration ?? 4; this.engine = options.engine; this.webcodecs = options.webcodecs; // Fail at config time, not on the first upload hours later. if (this.formats.length === 0) { throw new Error(`transformers.video({ name: '${this.name}' }): \`formats\` is empty.`); } for (const format of this.formats) { if (format !== 'hls' && format !== 'dash') { throw new Error(`transformers.video({ name: '${this.name}' }): unknown format '${format}' — use 'hls' and/or 'dash'.`); } } if (this.segments !== 'cmaf' && this.segments !== 'ts') { throw new Error(`transformers.video({ name: '${this.name}' }): unknown segments '${this.segments}' — use 'cmaf' or 'ts'.`); } this.storyboard = resolveStoryboard(this.name, options); if (this.segments === 'ts' && this.formats.includes('dash')) { throw new Error(`transformers.video({ name: '${this.name}' }): DASH cannot use TS segments — players ` + "only play DASH over fragmented MP4. Use `formats: ['hls']` with `segments: 'ts'`, or " + "keep the default `segments: 'cmaf'` (which serves both formats)."); } } async transform(context) { const engine = this.engine ?? (await loadMediabunny(this.name)).createVideoEngine(); const hls = this.formats.includes('hls'); const dash = this.formats.includes('dash'); return withSourceFile(context, async ({ sourcePath, tempDir }) => { const outputDir = join(tempDir, 'video'); await mkdir(outputDir, { recursive: true }); const summary = await engine.package({ sourcePath, outputDir, segments: this.segments, hlsEntry: hls ? VIDEO_HLS_ENTRY : undefined, dashManifest: dash ? VIDEO_DASH_MANIFEST : undefined, targetDuration: this.targetDuration, webcodecs: this.webcodecs, storyboard: this.storyboard, }); // Upload the whole package — manifests and segments — streaming each file (a segment never // has to fit in memory), a few at a time. Sorted for a deterministic `conversions[name].files`. const files = []; for (const file of (await readdir(outputDir, { recursive: true })).sort()) { const local = join(outputDir, file); const info = await stat(local); if (info.isFile()) files.push({ relative: file.split('\\').join('/'), local, size: info.size }); } await forEachBounded(files, VIDEO_UPLOAD_CONCURRENCY, ({ relative, local, size }) => { const contentType = streamArtifactContentType(relative); return context.write(relative, createReadStream(local), { contentLength: size, ...(contentType !== undefined ? { contentType } : {}), }); }); const written = new Set(files.map((file) => file.relative)); let segmentCount = 0; for (const relative of written) { if (/\.(m4s|ts)$/i.test(relative) && !/(^|\/)init[^/]*$/i.test(relative)) { segmentCount += 1; } } for (const [format, manifest] of [ ['hls', hls ? VIDEO_HLS_ENTRY : undefined], ['dash', dash ? VIDEO_DASH_MANIFEST : undefined], ['storyboard', this.storyboard?.vtt], ]) { if (manifest && !written.has(manifest)) { throw new Error(`The video engine did not write the ${format.toUpperCase()} manifest "${manifest}".`); } } return { entry: hls ? VIDEO_HLS_ENTRY : VIDEO_DASH_MANIFEST, meta: compactMeta({ ...summary, segments: this.segments, segmentCount, targetDuration: this.targetDuration, hlsEntry: hls ? VIDEO_HLS_ENTRY : undefined, dashManifest: dash ? VIDEO_DASH_MANIFEST : undefined, storyboard: this.storyboard?.vtt, }), }; }); } } /** Resolve and validate `storyboard` at config time (the engine check included). */ function resolveStoryboard(name, options) { if (!options.storyboard) return undefined; if (!options.engine?.storyboard) { throw new Error(`transformers.video({ name: '${name}' }): \`storyboard\` needs an engine that writes it — ` + '`engines.ffmpeg()`. The mediabunny engines (the default included) do not.'); } const resolved = { ...VIDEO_STORYBOARD_DEFAULTS, ...(options.storyboard === true ? {} : options.storyboard), }; for (const key of ['interval', 'width', 'columns', 'rows']) { const value = resolved[key]; const valid = key === 'interval' ? Number.isFinite(value) && value > 0 : Number.isInteger(value) && value > 0; if (!valid) { throw new Error(`transformers.video({ name: '${name}' }): storyboard.${key} must be a positive ${key === 'interval' ? 'number' : 'integer'}, got ${String(value)}.`); } } return { ...resolved, vtt: VIDEO_STORYBOARD }; } /** Package files uploaded at once: enough to hide per-request latency, few enough not to flood the disk. */ const VIDEO_UPLOAD_CONCURRENCY = 6; /** * Run `task` over `items`, at most `limit` at a time. On the first failure no further item starts, * and the error is rethrown only once every task already running has settled — so a caller * cleaning up after the failure never races an upload still in flight. */ export async function forEachBounded(items, limit, task) { let next = 0; let failure; const worker = async () => { while (failure === undefined && next < items.length) { const index = next++; try { await task(items[index], index); } catch (error) { failure ??= { error }; } } }; await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker)); if (failure !== undefined) throw failure.error; } /** Drop `undefined` values so the persisted meta round-trips identically through JSON stores. */ export function compactMeta(meta) { return Object.fromEntries(Object.entries(meta).filter(([, value]) => value !== undefined)); } //# sourceMappingURL=video.js.map