This commit is contained in:
Meghdad committed 2026-07-14 12:51:36 +03:30
commit f035fcef4f
134 files changed
+18678

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
{
"name": "@easy-stream/media",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest run",
"clean": "rm -rf dist"
},
"devDependencies": {
"@types/node": "^24.10.0",
"typescript": "^5.9.3",
"vitest": "^3.2.4"
}
}
+286
View File
@@ -0,0 +1,286 @@
import { randomUUID } from 'node:crypto';
import { lstat, opendir, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { assertWritableDestination, assertWritableRoot, isPathInside, UnsafePathError } from './paths.js';
const METADATA = '.cache-entry.json';
let lifecycleTail: Promise<void> = Promise.resolve();
async function serializeLifecycle<T>(operation: () => Promise<T>): Promise<T> {
const previous = lifecycleTail;
let release!: () => void;
lifecycleTail = new Promise<void>((resolve) => { release = resolve; });
await previous;
try {
return await operation();
} finally {
release();
}
}
export interface CacheEntryMetadata {
version: 1;
key: string;
bytes: number;
lastAccessedAt: string;
/** Do not evict before the latest playback grant expires. */
protectedUntil?: string;
active: boolean;
building: boolean;
pinned: boolean;
}
async function readCacheMetadata(directory: string): Promise<CacheEntryMetadata> {
const destination = path.join(directory, METADATA);
const details = await lstat(destination);
if (details.isSymbolicLink() || !details.isFile()) {
throw new UnsafePathError(`Cache metadata is not a regular file: ${destination}`);
}
return JSON.parse(await readFile(destination, 'utf8')) as CacheEntryMetadata;
}
async function assertSafeDeletion(root: string, directory: string): Promise<void> {
await assertWritableRoot(root);
await assertWritableDestination(root, directory);
const details = await lstat(directory);
if (details.isSymbolicLink() || !details.isDirectory()) {
throw new UnsafePathError(`Cache deletion target is not a regular directory: ${directory}`);
}
const [canonicalRoot, canonicalDirectory] = await Promise.all([realpath(root), realpath(directory)]);
if (!isPathInside(canonicalRoot, canonicalDirectory) || canonicalDirectory === canonicalRoot) {
throw new UnsafePathError(`Refusing unsafe cache deletion: ${directory}`);
}
}
async function directorySize(directory: string): Promise<number> {
let total = 0;
const handle = await opendir(directory);
for await (const entry of handle) {
const candidate = path.join(directory, entry.name);
const details = await lstat(candidate);
if (details.isSymbolicLink()) throw new Error(`Symlink found in media cache: ${candidate}`);
if (details.isDirectory()) total += await directorySize(candidate);
// Generation-local font hardlinks do not consume additional blocks while the global
// content-addressed store owns another link. Cross-device copy fallbacks have nlink=1.
else if (details.isFile()) total += details.nlink > 1 ? 0 : details.size;
}
return total;
}
export async function writeCacheMetadata(
cacheRoot: string,
entryDirectory: string,
metadata: Omit<CacheEntryMetadata, 'version' | 'bytes'> & { bytes?: number },
): Promise<CacheEntryMetadata> {
const directory = await assertWritableDestination(cacheRoot, entryDirectory);
const details = await stat(directory);
if (!details.isDirectory()) throw new Error('Cache entry is not a directory');
const value: CacheEntryMetadata = {
version: 1,
...metadata,
bytes: metadata.bytes ?? await directorySize(directory),
};
const destination = path.join(directory, METADATA);
try {
const existing = await lstat(destination);
if (existing.isSymbolicLink() || !existing.isFile()) {
throw new UnsafePathError(`Cache metadata is not a regular file: ${destination}`);
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
const temporary = `${destination}.${randomUUID()}.tmp`;
try {
await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o640, flag: 'wx' });
await rename(temporary, destination);
} finally {
await rm(temporary, { force: true });
}
return value;
}
export async function touchCacheEntry(cacheRoot: string, entryDirectory: string): Promise<void> {
const directory = await assertWritableDestination(cacheRoot, entryDirectory);
const value = await readCacheMetadata(directory);
await writeCacheMetadata(cacheRoot, directory, { ...value, lastAccessedAt: new Date().toISOString() });
}
export interface CacheTouchOptions {
accessedAt?: string;
protectedUntil?: string;
}
/** Updates one cache generation without allowing a caller-controlled filesystem path. */
export async function touchCacheGeneration(
cacheRoot: string,
generation: string,
options: CacheTouchOptions = {},
): Promise<boolean> {
return await serializeLifecycle(async () => await touchCacheGenerationUnlocked(cacheRoot, generation, options));
}
async function touchCacheGenerationUnlocked(
cacheRoot: string,
generation: string,
options: CacheTouchOptions,
): Promise<boolean> {
if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(generation)) throw new Error('Invalid generation identifier');
const accessedAt = options.accessedAt ?? new Date().toISOString();
if (!Number.isFinite(Date.parse(accessedAt))) throw new Error('Invalid cache access timestamp');
if (options.protectedUntil !== undefined && !Number.isFinite(Date.parse(options.protectedUntil))) {
throw new Error('Invalid cache protection timestamp');
}
await assertWritableRoot(cacheRoot);
const generationsRoot = path.join(path.resolve(cacheRoot), 'generations');
const directory = await assertWritableDestination(generationsRoot, path.join(generationsRoot, generation));
let value: CacheEntryMetadata;
try {
const details = await lstat(directory);
if (details.isSymbolicLink() || !details.isDirectory()) throw new Error('Cache generation is not a regular directory');
value = await readCacheMetadata(directory);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
throw error;
}
if (value.version !== 1 || value.key !== generation) throw new Error('Cache generation metadata does not match request');
const existingAccess = Date.parse(value.lastAccessedAt);
const requestedAccess = Date.parse(accessedAt);
const existingProtection = Date.parse(value.protectedUntil ?? '');
const requestedProtection = Date.parse(options.protectedUntil ?? '');
await writeCacheMetadata(generationsRoot, directory, {
...value,
lastAccessedAt: new Date(Math.max(
Number.isFinite(existingAccess) ? existingAccess : 0,
requestedAccess,
)).toISOString(),
...(Number.isFinite(existingProtection) || Number.isFinite(requestedProtection)
? {
protectedUntil: new Date(Math.max(
Number.isFinite(existingProtection) ? existingProtection : 0,
Number.isFinite(requestedProtection) ? requestedProtection : 0,
)).toISOString(),
}
: {}),
});
return true;
}
export interface EvictionOptions {
capacityBytes: number;
highWatermark?: number;
lowWatermark?: number;
protectedKeys?: ReadonlySet<string>;
/** Bytes owned by the cache but stored outside the per-generation directories. */
overheadBytes?: number;
now?: Date;
/** Grace window for newly built/touched entries while access events propagate. */
minimumRetentionMs?: number;
dryRun?: boolean;
}
export interface EvictionResult {
beforeBytes: number;
afterBytes: number;
evicted: string[];
}
export async function evictCacheGeneration(cacheRoot: string, generation: string): Promise<boolean> {
return await serializeLifecycle(async () => await evictCacheGenerationUnlocked(cacheRoot, generation));
}
async function evictCacheGenerationUnlocked(cacheRoot: string, generation: string): Promise<boolean> {
if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(generation)) throw new Error('Invalid generation identifier');
await assertWritableRoot(cacheRoot);
const generationsRoot = path.join(path.resolve(cacheRoot), 'generations');
const directory = await assertWritableDestination(generationsRoot, path.join(generationsRoot, generation));
let metadata: CacheEntryMetadata;
try {
const details = await lstat(directory);
if (details.isSymbolicLink() || !details.isDirectory()) throw new Error('Cache generation is not a regular directory');
metadata = await readCacheMetadata(directory);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;
throw error;
}
if (metadata.version !== 1 || metadata.key !== generation) throw new Error('Cache generation metadata does not match request');
if (metadata.active || metadata.building) throw new Error(`Cache generation is active: ${generation}`);
if (metadata.pinned) throw new Error(`Cache generation is pinned: ${generation}`);
if (isTimeProtected(metadata, Date.now())) throw new Error(`Cache generation has an active playback lease: ${generation}`);
await assertSafeDeletion(generationsRoot, directory);
await rm(directory, { recursive: true, force: false });
return true;
}
export async function evictCache(cacheRoot: string, options: EvictionOptions): Promise<EvictionResult> {
return await serializeLifecycle(async () => await evictCacheUnlocked(cacheRoot, options));
}
async function evictCacheUnlocked(cacheRoot: string, options: EvictionOptions): Promise<EvictionResult> {
const root = path.resolve(cacheRoot);
const high = options.highWatermark ?? 0.85;
const low = options.lowWatermark ?? 0.75;
if (!(options.capacityBytes > 0) || !(low >= 0 && low < high && high <= 1)) {
throw new RangeError('Invalid cache capacity or watermarks');
}
const entries: Array<{ directory: string; metadata: CacheEntryMetadata }> = [];
const overheadBytes = options.overheadBytes ?? 0;
if (!Number.isFinite(overheadBytes) || overheadBytes < 0) throw new RangeError('Invalid cache overhead');
const minimumRetentionMs = options.minimumRetentionMs ?? 0;
if (!Number.isFinite(minimumRetentionMs) || minimumRetentionMs < 0) {
throw new RangeError('Invalid cache retention window');
}
const now = (options.now ?? new Date()).getTime();
let beforeBytes = overheadBytes;
await assertWritableRoot(root);
try {
await lstat(root);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return { beforeBytes, afterBytes: beforeBytes, evicted: [] };
}
throw error;
}
const handle = await opendir(root);
for await (const entry of handle) {
if (entry.isSymbolicLink()) throw new UnsafePathError(`Symlink found in cache generations: ${path.join(root, entry.name)}`);
if (!entry.isDirectory()) continue;
const directory = path.join(root, entry.name);
try {
const metadata = await readCacheMetadata(directory);
if (metadata.version !== 1 || metadata.key !== entry.name
|| !Number.isFinite(metadata.bytes) || metadata.bytes < 0
|| !Number.isFinite(Date.parse(metadata.lastAccessedAt))) continue;
entries.push({ directory, metadata });
beforeBytes += metadata.bytes;
} catch (error) {
if (error instanceof UnsafePathError) throw error;
// Incomplete/unmanaged directories are never deleted by the LRU.
}
}
if (beforeBytes <= options.capacityBytes * high) return { beforeBytes, afterBytes: beforeBytes, evicted: [] };
entries.sort((left, right) => Date.parse(left.metadata.lastAccessedAt) - Date.parse(right.metadata.lastAccessedAt));
const target = options.capacityBytes * low;
let afterBytes = beforeBytes;
const evicted: string[] = [];
for (const entry of entries) {
if (afterBytes <= target) break;
const protectedEntry = entry.metadata.active || entry.metadata.building || entry.metadata.pinned
|| isTimeProtected(entry.metadata, now)
|| Date.parse(entry.metadata.lastAccessedAt) > now - minimumRetentionMs
|| options.protectedKeys?.has(entry.metadata.key) === true;
if (protectedEntry) continue;
await assertSafeDeletion(root, entry.directory);
if (options.dryRun !== true) await rm(entry.directory, { recursive: true, force: false });
afterBytes -= entry.metadata.bytes;
evicted.push(entry.metadata.key);
}
return { beforeBytes, afterBytes, evicted };
}
function isTimeProtected(metadata: CacheEntryMetadata, now: number): boolean {
if (metadata.protectedUntil === undefined) return false;
const protectedUntil = Date.parse(metadata.protectedUntil);
// Corrupt protection metadata fails closed: an operator can inspect/fix it rather than
// evicting files that might still be in use.
return !Number.isFinite(protectedUntil) || protectedUntil > now;
}
+103
View File
@@ -0,0 +1,103 @@
import { normalizeStreamLanguage } from './language.js';
import type { Classification, MediaProbe, NormalizedTrack, ProbeStream } from './types.js';
function isHdr(stream: ProbeStream): boolean {
const transfer = stream.color_transfer?.toLowerCase();
const primaries = stream.color_primaries?.toLowerCase();
if (transfer === 'smpte2084' || transfer === 'arib-std-b67' || primaries === 'bt2020') return true;
return (stream.side_data_list ?? []).some((data) => {
const encoded = JSON.stringify(data).toLowerCase();
return encoded.includes('dolby vision') || encoded.includes('hdr10+') || encoded.includes('mastering display');
});
}
function isCopySafeVideo(stream: ProbeStream): boolean {
const depth = Number.parseInt(stream.bits_per_raw_sample ?? '8', 10);
const profile = stream.profile?.toLowerCase() ?? '';
return stream.codec_name === 'h264'
&& ['yuv420p', 'yuvj420p'].includes(stream.pix_fmt ?? '')
&& (Number.isNaN(depth) || depth <= 8)
&& !profile.includes('high 10')
&& !profile.includes('high 4:2')
&& (stream.field_order === undefined || ['progressive', 'unknown'].includes(stream.field_order));
}
function isCopySafeAudio(stream: ProbeStream): boolean {
const profile = stream.profile?.toLowerCase();
return stream.codec_name === 'aac'
&& (profile === undefined || profile === 'lc' || profile.includes('low complexity'))
&& (stream.channels ?? 2) <= 6;
}
export interface ClassificationOptions {
maxCopySegmentDuration?: number;
measuredMaxGopSeconds?: number;
}
export function classifyMedia(probe: MediaProbe, options: ClassificationOptions = {}): Classification {
const videos = probe.streams.filter((stream) => stream.codec_type === 'video' && stream.disposition?.attached_pic !== 1);
const audios = probe.streams.filter((stream) => stream.codec_type === 'audio');
const reasons: string[] = [];
const duration = Number.parseFloat(probe.format.duration ?? 'NaN');
if (videos.length === 0) reasons.push('NO_VIDEO');
if (audios.length === 0) reasons.push('NO_AUDIO');
if (!Number.isFinite(duration) || duration <= 0) reasons.push('INVALID_DURATION');
if ((probe.format.probe_score ?? 100) < 25) reasons.push('LOW_PROBE_SCORE');
const video = videos[0];
if (video === undefined || audios.length === 0 || reasons.length > 0) {
return { class: 'INVALID', reasons, audioStreamIndexes: audios.map((stream) => stream.index) };
}
if (isHdr(video)) {
return { class: 'HOLD_HDR', reasons: ['HDR_UNSUPPORTED_V1'], videoStreamIndex: video.index, audioStreamIndexes: audios.map((stream) => stream.index) };
}
if (!isCopySafeVideo(video)) {
return {
class: 'VIDEO_TRANSCODE',
reasons: [`VIDEO_CODEC_UNSUPPORTED:${video.codec_name ?? 'unknown'}`, `VIDEO_PIXEL_FORMAT:${video.pix_fmt ?? 'unknown'}`],
videoStreamIndex: video.index,
audioStreamIndexes: audios.map((stream) => stream.index),
};
}
const maxGop = options.measuredMaxGopSeconds;
if (maxGop !== undefined && maxGop > (options.maxCopySegmentDuration ?? 18)) {
return {
class: 'VIDEO_TRANSCODE',
reasons: [`GOP_TOO_LONG:${maxGop.toFixed(3)}`],
videoStreamIndex: video.index,
audioStreamIndexes: audios.map((stream) => stream.index),
};
}
const unsupportedAudio = audios.filter((stream) => !isCopySafeAudio(stream));
if (unsupportedAudio.length > 0) {
return {
class: 'AUDIO_TRANSCODE',
reasons: unsupportedAudio.map((stream) => `AUDIO_CODEC_UNSUPPORTED:${stream.index}:${stream.codec_name ?? 'unknown'}`),
videoStreamIndex: video.index,
audioStreamIndexes: audios.map((stream) => stream.index),
};
}
return {
class: 'COPY',
reasons: [],
videoStreamIndex: video.index,
audioStreamIndexes: audios.map((stream) => stream.index),
};
}
export function normalizeTracks(probe: MediaProbe): NormalizedTrack[] {
return probe.streams.flatMap((stream): NormalizedTrack[] => {
if (!['video', 'audio', 'subtitle', 'attachment'].includes(stream.codec_type ?? '')) return [];
const type = stream.codec_type as NormalizedTrack['type'];
const language = normalizeStreamLanguage(stream);
return [{
index: stream.index,
type,
codec: stream.codec_name ?? 'unknown',
language,
...(stream.tags?.title === undefined ? {} : { label: stream.tags.title }),
default: type === 'subtitle' ? language === 'fa' : stream.disposition?.default === 1,
// Embedded flags are advisory; full-track ASS marked forced is common in this archive.
forced: false,
}];
});
}
+194
View File
@@ -0,0 +1,194 @@
import { randomUUID } from 'node:crypto';
import { rename, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { probeMedia } from './ffprobe.js';
import { fingerprintSource } from './fingerprint.js';
import { assessFfmpegWarnings, buildMasterPlaylist, validateMediaPlaylist, type MasterAudio } from './hls.js';
import { languageDisplayName, normalizeStreamLanguage } from './language.js';
import { assertWritableDestination, ensureWritableDirectory, resolveInside } from './paths.js';
import { runProcess } from './process.js';
import type { Classification, MediaProbe, PackageResult, SourceFingerprint } from './types.js';
export interface CompatibilityEncodeOptions {
archiveRoot: string;
derivedRoot: string;
sourcePath: string;
fingerprint: SourceFingerprint;
probe: MediaProbe;
classification: Classification;
generation: string;
ffmpegPath?: string;
ffprobePath?: string;
segmentSeconds?: number;
}
function frameRate(probe: MediaProbe, videoIndex: number): number {
const stream = probe.streams.find((candidate) => candidate.index === videoIndex);
const raw = stream?.avg_frame_rate ?? stream?.r_frame_rate ?? '24/1';
const [numeratorRaw, denominatorRaw] = raw.split('/');
const numerator = Number(numeratorRaw);
const denominator = Number(denominatorRaw ?? 1);
const value = numerator / denominator;
return Number.isFinite(value) && value > 0 && value <= 240 ? value : 24;
}
function renditions(probe: MediaProbe, indexes: readonly number[]): MasterAudio[] {
return indexes.map((streamIndex, index) => {
const stream = probe.streams.find((candidate) => candidate.index === streamIndex);
if (stream === undefined) throw new Error(`Audio stream ${streamIndex} is missing`);
const language = normalizeStreamLanguage(stream);
return {
streamIndex,
language,
name: languageDisplayName(language),
uri: `audio-${streamIndex}-${language.replace(/[^a-z0-9-]/giu, '') || 'und'}/index.m3u8`,
...(stream.channels === undefined ? {} : { channels: stream.channels }),
default: index === 0,
};
});
}
export function buildCompatibilityEncodeArguments(
source: string,
output: string,
probe: MediaProbe,
classification: Classification,
segmentSeconds = 6,
): string[] {
if (classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1');
if (classification.class === 'INVALID') throw new Error('INVALID_SOURCE');
const videoIndex = classification.videoStreamIndex;
if (videoIndex === undefined) throw new Error('No video stream selected');
const audio = renditions(probe, classification.audioStreamIndexes);
const gop = Math.max(1, Math.ceil(frameRate(probe, videoIndex) * segmentSeconds));
const args = [
'-hide_banner', '-loglevel', 'warning', '-nostdin', '-y',
'-i', source,
'-map', `0:${videoIndex}`,
];
for (const item of audio) args.push('-map', `0:${item.streamIndex}`);
args.push(
'-map_metadata', '-1', '-map_chapters', '-1', '-sn', '-dn',
'-c:v', 'libx264', '-crf', '18', '-preset', 'medium',
'-profile:v', 'high', '-pix_fmt', 'yuv420p', '-flags', '+cgop',
'-g', String(gop), '-keyint_min', String(gop), '-sc_threshold', '0',
'-force_key_frames', `expr:gte(t,n_forced*${segmentSeconds})`,
);
audio.forEach((item, index) => {
args.push(`-c:a:${index}`, 'aac', `-b:a:${index}`, (item.channels ?? 2) > 2 ? '384k' : '192k');
});
const variants = [
'v:0,agroup:audio,name:video',
...audio.map((item, index) => `a:${index},agroup:audio,language:${item.language},default:${item.default ? 'yes' : 'no'},name:${path.dirname(item.uri)}`),
].join(' ');
args.push(
'-f', 'hls', '-hls_time', String(segmentSeconds),
'-hls_segment_type', 'fmp4', '-hls_playlist_type', 'vod',
'-hls_flags', 'independent_segments+temp_file',
'-master_pl_name', 'master.ffmpeg.m3u8', '-var_stream_map', variants,
'-hls_fmp4_init_filename', 'init-%v.mp4',
'-hls_segment_filename', path.join(output, '%v', 'segment-%06d.m4s'),
path.join(output, '%v', 'index.m3u8'),
);
return args;
}
function outputProbe(source: MediaProbe, videoIndex: number): MediaProbe {
const { bit_rate: _ignoredBitrate, ...format } = source.format;
return {
...source,
streams: source.streams.map((stream) => {
if (stream.index === videoIndex) {
const pixels = (stream.width ?? 1920) * (stream.height ?? 1080);
return {
...stream,
codec_name: 'h264',
profile: 'High',
pix_fmt: 'yuv420p',
bits_per_raw_sample: '8',
mime_codec_string: 'avc1.640028',
bit_rate: String(pixels > 1920 * 1080 ? 20_000_000 : 8_000_000),
};
}
if (stream.codec_type === 'audio') return { ...stream, codec_name: 'aac', profile: 'LC', mime_codec_string: 'mp4a.40.2' };
return stream;
}),
format,
};
}
async function validateEncodedCodecs(videoPlaylist: string, audioPlaylists: readonly string[], ffprobePath: string): Promise<void> {
const video = await probeMedia(videoPlaylist, { ffprobePath, timeoutMs: 120_000 });
if (!video.streams.some((stream) => stream.codec_type === 'video' && stream.codec_name === 'h264' && stream.pix_fmt === 'yuv420p')) {
throw new Error('Compatibility output is not 8-bit H.264 yuv420p');
}
for (const playlist of audioPlaylists) {
const audio = await probeMedia(playlist, { ffprobePath, timeoutMs: 120_000 });
if (!audio.streams.some((stream) => stream.codec_type === 'audio' && stream.codec_name === 'aac')) {
throw new Error('Compatibility audio output is not AAC');
}
}
}
export async function prepareCompatibilityHls(options: CompatibilityEncodeOptions): Promise<PackageResult> {
if (options.classification.class === 'HOLD_HDR') throw new Error('HDR_UNSUPPORTED_V1');
if (options.classification.class !== 'VIDEO_TRANSCODE') {
throw new Error(`Compatibility video encode is not required for ${options.classification.class}`);
}
if (!/^[a-z0-9][a-z0-9._-]{7,127}$/u.test(options.generation)) throw new Error('Invalid generation identifier');
const source = await resolveInside(options.archiveRoot, options.sourcePath);
const videoIndex = options.classification.videoStreamIndex;
if (videoIndex === undefined) throw new Error('No video stream selected');
const audio = renditions(options.probe, options.classification.audioStreamIndexes);
const generationsRoot = path.join(options.derivedRoot, 'generations');
await ensureWritableDirectory(options.derivedRoot, generationsRoot);
const finalDirectory = await assertWritableDestination(options.derivedRoot, path.join(generationsRoot, options.generation));
try {
if ((await stat(path.join(finalDirectory, 'master.m3u8'))).isFile()) {
const videoPlaylist = await validateMediaPlaylist(path.join(finalDirectory, 'video', 'index.m3u8'), { requireEnded: true, maxTargetDuration: 7 });
const audioPlaylists = await Promise.all(audio.map((item) => validateMediaPlaylist(path.join(finalDirectory, item.uri), { requireEnded: true, maxTargetDuration: 7 })));
return { generation: options.generation, outputDirectory: finalDirectory, masterPlaylist: path.join(finalDirectory, 'master.m3u8'), videoPlaylist, audioPlaylists, knownAacRepairs: 0 };
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
const staging = await assertWritableDestination(options.derivedRoot, path.join(options.derivedRoot, `.building-${options.generation}-${randomUUID()}`));
await ensureWritableDirectory(options.derivedRoot, staging);
let moved = false;
try {
const result = await runProcess(options.ffmpegPath ?? 'ffmpeg', buildCompatibilityEncodeArguments(
source, staging, options.probe, options.classification, options.segmentSeconds ?? 6,
), { timeoutMs: 7 * 24 * 60 * 60 * 1000, maxOutputBytes: 64 * 1024 * 1024 });
const warnings = assessFfmpegWarnings(result.stderr);
if (warnings.unknown.length > 0) throw new Error(`Unrecognized FFmpeg warning(s): ${warnings.unknown.slice(0, 5).join(' | ')}`);
const videoStaging = path.join(staging, 'video', 'index.m3u8');
const audioStaging = audio.map((item) => path.join(staging, item.uri));
const [videoValidation, ...audioValidation] = await Promise.all([
validateMediaPlaylist(videoStaging, { requireEnded: true, maxTargetDuration: 7 }),
...audioStaging.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: 7 })),
]);
if (videoValidation === undefined) throw new Error('Encoded video playlist is missing');
for (const item of audioValidation) {
if (Math.abs(item.totalDuration - videoValidation.totalDuration) > 0.25) throw new Error('Encoded A/V durations differ by more than 250 ms');
}
await validateEncodedCodecs(videoStaging, audioStaging, options.ffprobePath ?? 'ffprobe');
const after = await fingerprintSource(options.archiveRoot, source, options.fingerprint.edgeBytes);
if (after.digest !== options.fingerprint.digest) throw new Error('Source changed during compatibility encoding');
const master = buildMasterPlaylist(outputProbe(options.probe, videoIndex), videoIndex, 'video/index.m3u8', audio);
await writeFile(path.join(staging, 'master.m3u8'), master, { encoding: 'utf8', mode: 0o640 });
await rename(staging, finalDirectory);
moved = true;
const videoPlaylist = await validateMediaPlaylist(path.join(finalDirectory, 'video', 'index.m3u8'), { requireEnded: true, maxTargetDuration: 7 });
const audioPlaylists = await Promise.all(audio.map((item) => validateMediaPlaylist(path.join(finalDirectory, item.uri), { requireEnded: true, maxTargetDuration: 7 })));
return {
generation: options.generation,
outputDirectory: finalDirectory,
masterPlaylist: path.join(finalDirectory, 'master.m3u8'),
videoPlaylist,
audioPlaylists,
knownAacRepairs: warnings.knownAacRepairs,
};
} finally {
if (!moved) await rm(staging, { recursive: true, force: true });
}
}
+51
View File
@@ -0,0 +1,51 @@
import { runProcess, type RunProcessOptions } from './process.js';
import type { MediaProbe, ProbeFormat, ProbeStream } from './types.js';
export interface ProbeOptions extends RunProcessOptions {
ffprobePath?: string;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function parseProbeJson(raw: string): MediaProbe {
let value: unknown;
try {
value = JSON.parse(raw);
} catch (error) {
throw new Error(`ffprobe returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
}
if (!isRecord(value) || !Array.isArray(value.streams) || !isRecord(value.format)) {
throw new Error('ffprobe JSON is missing streams or format');
}
const streams = value.streams.filter(isRecord) as unknown as ProbeStream[];
if (!streams.every((stream) => Number.isInteger(stream.index))) {
throw new Error('ffprobe returned a stream without a numeric index');
}
return {
streams,
format: value.format as ProbeFormat,
chapters: Array.isArray(value.chapters) ? value.chapters.filter(isRecord) : [],
};
}
export async function probeMedia(sourcePath: string, options: ProbeOptions = {}): Promise<MediaProbe> {
const result = await runProcess(options.ffprobePath ?? 'ffprobe', [
'-v', 'error',
'-print_format', 'json',
'-show_format',
'-show_streams',
'-show_chapters',
sourcePath,
], {
timeoutMs: options.timeoutMs ?? 120_000,
maxOutputBytes: options.maxOutputBytes ?? 64 * 1024 * 1024,
...(options.cwd === undefined ? {} : { cwd: options.cwd }),
...(options.env === undefined ? {} : { env: options.env }),
...(options.signal === undefined ? {} : { signal: options.signal }),
});
return parseProbeJson(result.stdout);
}
export { parseProbeJson };
+61
View File
@@ -0,0 +1,61 @@
import { createHash } from 'node:crypto';
import { open, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
import { isPathInside, UnsafePathError } from './paths.js';
import type { SourceFingerprint } from './types.js';
const DEFAULT_EDGE_BYTES = 4 * 1024 * 1024;
export async function fingerprintSource(
archiveRoot: string,
sourcePath: string,
edgeBytes = DEFAULT_EDGE_BYTES,
): Promise<SourceFingerprint> {
if (!Number.isSafeInteger(edgeBytes) || edgeBytes < 1 || edgeBytes > 64 * 1024 * 1024) {
throw new RangeError('edgeBytes must be between 1 byte and 64 MiB');
}
const [root, source] = await Promise.all([realpath(archiveRoot), realpath(sourcePath)]);
if (!isPathInside(root, source)) throw new UnsafePathError('Source is outside the archive root');
const before = await stat(source, { bigint: true });
if (!before.isFile()) throw new UnsafePathError('Source is not a regular file');
const size = before.size;
const chunkSize = Number(size < BigInt(edgeBytes) ? size : BigInt(edgeBytes));
const first = Buffer.alloc(chunkSize);
const last = Buffer.alloc(chunkSize);
const file = await open(source, 'r');
try {
await file.read(first, 0, chunkSize, 0);
const lastOffset = size > BigInt(chunkSize) ? size - BigInt(chunkSize) : 0n;
await file.read(last, 0, chunkSize, lastOffset);
} finally {
await file.close();
}
const after = await stat(source, { bigint: true });
if (after.size !== before.size || after.mtimeNs !== before.mtimeNs) {
throw new Error('Source changed while it was being fingerprinted');
}
const relativePath = path.relative(root, source).split(path.sep).join('/');
const hash = createHash('sha256');
hash.update('easy-stream-source-fingerprint-v1\0');
hash.update(relativePath);
hash.update('\0');
hash.update(size.toString());
hash.update('\0');
hash.update(before.mtimeNs.toString());
hash.update('\0');
hash.update(first);
hash.update('\0');
hash.update(last);
return {
version: 1,
algorithm: 'sha256',
relativePath,
size: size.toString(),
mtimeNs: before.mtimeNs.toString(),
edgeBytes: chunkSize,
digest: hash.digest('hex'),
};
}
+220
View File
@@ -0,0 +1,220 @@
import { createHash, randomUUID } from 'node:crypto';
import { constants } from 'node:fs';
import { access, copyFile, link, lstat, opendir, readFile, realpath, rm } from 'node:fs/promises';
import path from 'node:path';
import { assertWritableDestination, assertWritableRoot, ensureWritableDirectory, resolveInside, UnsafePathError } from './paths.js';
import { runProcess } from './process.js';
import type { ProcessResult, RunProcessOptions } from './process.js';
import type { MediaProbe, ProbeStream, StoredFont } from './types.js';
const MAX_FONT_BYTES = 10 * 1024 * 1024;
const MAX_FONT_COUNT = 128;
const MAX_TOTAL_FONT_BYTES = 128 * 1024 * 1024;
function attachmentLooksLikeFont(stream: ProbeStream): boolean {
const mime = stream.tags?.mimetype?.toLowerCase() ?? '';
const name = stream.tags?.filename?.toLowerCase() ?? '';
return stream.codec_type === 'attachment'
&& (stream.codec_name === 'ttf' || stream.codec_name === 'otf'
|| mime.includes('font') || mime.includes('truetype') || mime.includes('opentype')
|| /\.(?:ttf|otf)$/iu.test(name));
}
export function validateSfntFont(data: Buffer): 'ttf' | 'otf' {
if (data.length < 12 || data.length > MAX_FONT_BYTES) throw new Error('Font size is outside accepted bounds');
const signature = data.subarray(0, 4).toString('ascii');
let format: 'ttf' | 'otf';
if (data.readUInt32BE(0) === 0x00010000 || signature === 'true' || signature === 'typ1') format = 'ttf';
else if (signature === 'OTTO') format = 'otf';
else throw new Error(`Unsupported font signature ${JSON.stringify(signature)}`);
const numTables = data.readUInt16BE(4);
if (numTables < 1 || numTables > 256 || 12 + numTables * 16 > data.length) {
throw new Error('Malformed SFNT table directory');
}
for (let index = 0; index < numTables; index += 1) {
const record = 12 + index * 16;
const offset = data.readUInt32BE(record + 8);
const length = data.readUInt32BE(record + 12);
if (offset > data.length || length > data.length || offset + length > data.length) {
throw new Error('SFNT table points outside the attachment');
}
}
return format;
}
export interface FontExtractionOptions {
archiveRoot: string;
fontRoot: string;
ffmpegPath?: string;
sanitizerPath?: string;
timeoutMs?: number;
runner?: (binary: string, args: readonly string[], options?: RunProcessOptions) => Promise<ProcessResult>;
}
export function fontDumpArguments(streamIndex: number, destination: string, source: string): string[] {
return [
'-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
`-dump_attachment:${streamIndex}`, destination,
'-i', source,
// Attachment dumping happens as the input header opens. Do not decode the movie.
'-t', '0',
'-f', 'null', '-',
];
}
export async function extractAndStoreFonts(
sourcePath: string,
probe: MediaProbe,
options: FontExtractionOptions,
): Promise<StoredFont[]> {
const source = await resolveInside(options.archiveRoot, sourcePath);
const staging = await ensureWritableDirectory(options.fontRoot, path.join(options.fontRoot, '.staging'), 0o700);
const store = await ensureWritableDirectory(options.fontRoot, path.join(options.fontRoot, 'sha256'));
const attachments = probe.streams.filter(attachmentLooksLikeFont);
if (attachments.length > MAX_FONT_COUNT) throw new Error(`File has too many font attachments (${attachments.length})`);
const declaredTotal = attachments.reduce((sum, stream) => sum + (stream.extradata_size ?? 0), 0);
if (declaredTotal > MAX_TOTAL_FONT_BYTES) throw new Error('Declared font attachments exceed the total size limit');
const output: StoredFont[] = [];
const execute = options.runner ?? runProcess;
for (const attachment of attachments) {
if ((attachment.extradata_size ?? 0) > MAX_FONT_BYTES) {
throw new Error(`Font attachment ${attachment.index} exceeds ${MAX_FONT_BYTES} bytes`);
}
const temporary = path.join(staging, `${randomUUID()}.font`);
try {
await execute(
options.ffmpegPath ?? 'ffmpeg',
fontDumpArguments(attachment.index, temporary, source),
{ timeoutMs: options.timeoutMs ?? 120_000 },
);
const data = await readFile(temporary);
const format = validateSfntFont(data);
if (options.sanitizerPath !== undefined) {
await execute(options.sanitizerPath, [temporary], { timeoutMs: 30_000 });
}
const sha256 = createHash('sha256').update(data).digest('hex');
const destination = path.join(store, `${sha256}.${format}`);
try {
await link(temporary, destination);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code !== 'EEXIST') throw error;
}
const stored = await lstat(destination);
if (stored.isSymbolicLink() || !stored.isFile()) {
throw new UnsafePathError(`Stored font is not a regular file: ${destination}`);
}
await access(destination, constants.R_OK);
output.push({
streamIndex: attachment.index,
sha256,
path: destination,
originalName: path.basename(attachment.tags?.filename ?? `attachment-${attachment.index}`),
size: data.length,
format,
});
} finally {
await rm(temporary, { force: true });
}
}
return output;
}
/** Publishes hash-named generation-local font links while retaining one global content store. */
export async function publishGenerationFonts(
fonts: readonly StoredFont[],
mediaRoot: string,
generationDirectory: string,
): Promise<StoredFont[]> {
await assertWritableRoot(mediaRoot);
const root = await realpath(mediaRoot);
const generation = await resolveInside(root, generationDirectory);
const directory = await ensureWritableDirectory(root, path.join(generation, 'fonts'));
const published: StoredFont[] = [];
for (const font of fonts) {
const source = await resolveInside(root, font.path);
const destination = path.join(directory, `${font.sha256}.${font.format}`);
try {
await link(source, destination);
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (code === 'EXDEV') {
try {
await copyFile(source, destination, constants.COPYFILE_EXCL);
} catch (copyError) {
if ((copyError as NodeJS.ErrnoException).code !== 'EEXIST') throw copyError;
}
} else if (code !== 'EEXIST') {
throw error;
}
}
const details = await lstat(destination);
if (details.isSymbolicLink() || !details.isFile() || details.size !== font.size) {
throw new Error(`Published font failed verification: ${font.sha256}`);
}
published.push({ ...font, path: destination });
}
return published;
}
export interface FontPruneOptions {
/** Avoid racing a package that extracted a font but has not published its hardlink yet. */
minimumAgeMs?: number;
now?: Date;
}
export interface FontPruneResult {
removed: string[];
retainedBytes: number;
}
/** Removes aged content-store files that have no generation hardlinks. */
export async function pruneOrphanedFonts(
mediaRoot: string,
options: FontPruneOptions = {},
): Promise<FontPruneResult> {
const minimumAgeMs = options.minimumAgeMs ?? 60 * 60 * 1000;
if (!Number.isFinite(minimumAgeMs) || minimumAgeMs < 0) throw new RangeError('Invalid font prune age');
let root: string;
try {
await assertWritableRoot(mediaRoot);
root = await realpath(mediaRoot);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 };
throw error;
}
let store: string;
try {
const storeCandidate = path.join(root, 'assets', 'fonts', 'sha256');
await assertWritableDestination(root, storeCandidate);
store = await resolveInside(root, storeCandidate);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 };
throw error;
}
let handle: Awaited<ReturnType<typeof opendir>>;
try {
handle = await opendir(store);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { removed: [], retainedBytes: 0 };
throw error;
}
const cutoff = (options.now ?? new Date()).getTime() - minimumAgeMs;
const removed: string[] = [];
let retainedBytes = 0;
for await (const entry of handle) {
if (!/^[a-f0-9]{64}\.(?:ttf|otf)$/u.test(entry.name)) continue;
const candidate = path.join(store, entry.name);
const details = await lstat(candidate);
if (details.isSymbolicLink()) throw new Error(`Symlink found in global font store: ${candidate}`);
if (!details.isFile()) continue;
if (details.nlink <= 1 && details.mtimeMs <= cutoff) {
await rm(candidate, { force: false });
removed.push(entry.name);
} else {
retainedBytes += details.size;
}
}
return { removed, retainedBytes };
}
+185
View File
@@ -0,0 +1,185 @@
import { readFile, stat, writeFile, rename } from 'node:fs/promises';
import path from 'node:path';
import type { HlsPlaylistValidation, MediaProbe, ProbeStream } from './types.js';
const URI_PATTERN = /^(?![a-z][a-z0-9+.-]*:)(?!\/)(?!.*(?:^|\/)\.\.(?:\/|$))[^\0]+$/iu;
export interface ParsedMediaPlaylist {
targetDuration: number;
playlistType?: string;
mapUri?: string;
segments: Array<{ duration: number; uri: string }>;
ended: boolean;
}
function attribute(line: string, name: string): string | undefined {
const match = line.match(new RegExp(`(?:^|,)${name}=(?:"([^"]*)"|([^,]*))`, 'u'));
return match?.[1] ?? match?.[2];
}
export function parseMediaPlaylist(content: string): ParsedMediaPlaylist {
const lines = content.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
if (lines[0] !== '#EXTM3U') throw new Error('Playlist is missing EXTM3U');
let targetDuration = 0;
let playlistType: string | undefined;
let mapUri: string | undefined;
let pendingDuration: number | undefined;
const segments: ParsedMediaPlaylist['segments'] = [];
let ended = false;
for (const line of lines.slice(1)) {
if (line.startsWith('#EXT-X-TARGETDURATION:')) targetDuration = Number(line.slice(22));
else if (line.startsWith('#EXT-X-PLAYLIST-TYPE:')) playlistType = line.slice(21);
else if (line.startsWith('#EXT-X-MAP:')) mapUri = attribute(line.slice(11), 'URI');
else if (line.startsWith('#EXTINF:')) pendingDuration = Number(line.slice(8).split(',')[0]);
else if (line === '#EXT-X-ENDLIST') ended = true;
else if (!line.startsWith('#')) {
if (pendingDuration === undefined || !Number.isFinite(pendingDuration) || pendingDuration <= 0) {
throw new Error(`Segment URI has no valid EXTINF: ${line}`);
}
segments.push({ duration: pendingDuration, uri: line });
pendingDuration = undefined;
}
}
if (!Number.isInteger(targetDuration) || targetDuration < 1) throw new Error('Invalid HLS target duration');
if (mapUri === undefined) throw new Error('Fragmented MP4 playlist has no EXT-X-MAP');
return { targetDuration, ...(playlistType === undefined ? {} : { playlistType }), mapUri, segments, ended };
}
function assertSafeUri(uri: string): void {
if (!URI_PATTERN.test(uri)) throw new Error(`Unsafe or external HLS URI: ${uri}`);
}
export async function validateMediaPlaylist(
playlistPath: string,
options: { requireEnded?: boolean; maxTargetDuration?: number; minSegments?: number } = {},
): Promise<HlsPlaylistValidation> {
const content = await readFile(playlistPath, 'utf8');
const parsed = parseMediaPlaylist(content);
if (options.requireEnded === true && !parsed.ended) throw new Error(`${playlistPath} has no ENDLIST`);
if (parsed.targetDuration > (options.maxTargetDuration ?? 18)) {
throw new Error(`${playlistPath} target duration ${parsed.targetDuration} exceeds the compatibility limit`);
}
if (parsed.segments.length < (options.minSegments ?? 1)) throw new Error(`${playlistPath} has too few segments`);
const directory = path.dirname(playlistPath);
const mapUri = parsed.mapUri;
if (mapUri === undefined) throw new Error('Fragmented MP4 playlist has no EXT-X-MAP');
const referenced = [mapUri, ...parsed.segments.map((segment) => segment.uri)];
for (const uri of referenced) {
assertSafeUri(uri);
const file = path.resolve(directory, uri);
if (!file.startsWith(`${path.resolve(directory)}${path.sep}`)) throw new Error(`HLS URI escapes playlist directory: ${uri}`);
const details = await stat(file);
if (!details.isFile() || details.size === 0) throw new Error(`HLS resource is missing or empty: ${uri}`);
}
const durations = parsed.segments.map((segment) => segment.duration);
return {
path: playlistPath,
segmentCount: durations.length,
targetDuration: parsed.targetDuration,
minDuration: Math.min(...durations),
maxDuration: Math.max(...durations),
totalDuration: durations.reduce((sum, duration) => sum + duration, 0),
ended: parsed.ended,
};
}
export async function finalizeEventPlaylist(playlistPath: string): Promise<void> {
const content = await readFile(playlistPath, 'utf8');
const parsed = parseMediaPlaylist(content);
if (!parsed.ended) throw new Error('Cannot finalize an incomplete EVENT playlist');
const vod = content.replace('#EXT-X-PLAYLIST-TYPE:EVENT', '#EXT-X-PLAYLIST-TYPE:VOD');
const temporary = `${playlistPath}.vod.tmp`;
await writeFile(temporary, vod, { encoding: 'utf8', mode: 0o640 });
await rename(temporary, playlistPath);
}
function escapeAttribute(value: string): string {
return value.replace(/["\r\n]/gu, '');
}
function streamBitrate(stream: ProbeStream, fallback: number): number {
const raw = stream.bit_rate ?? stream.tags?.BPS ?? stream.tags?.bps;
const value = Number(raw);
return Number.isFinite(value) && value > 0 ? value : fallback;
}
export interface MasterAudio {
streamIndex: number;
language: string;
name: string;
uri: string;
channels?: number;
default: boolean;
}
export function buildMasterPlaylist(
probe: MediaProbe,
videoStreamIndex: number,
videoUri: string,
audio: readonly MasterAudio[],
): string {
const video = probe.streams.find((stream) => stream.index === videoStreamIndex);
if (video === undefined) throw new Error('Video stream is missing from probe');
if (audio.length === 0) throw new Error('At least one audio rendition is required');
const audioStreams = audio.map((item) => probe.streams.find((stream) => stream.index === item.streamIndex));
const audioBandwidth = Math.max(...audioStreams.map((stream) => stream === undefined ? 384_000 : streamBitrate(stream, 384_000)));
const containerBitrate = Number(probe.format.bit_rate);
const conservativeVideoFallback = Number.isFinite(containerBitrate) && containerBitrate > audioBandwidth
? containerBitrate - audioBandwidth
: 8_000_000;
const videoBandwidth = streamBitrate(video, conservativeVideoFallback);
const bandwidth = Math.ceil((videoBandwidth + audioBandwidth) * 1.15);
const average = videoBandwidth + audioBandwidth;
const codecs = [video.mime_codec_string ?? 'avc1.640028', 'mp4a.40.2'].join(',');
const resolution = video.width !== undefined && video.height !== undefined ? `,RESOLUTION=${video.width}x${video.height}` : '';
const lines = ['#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-INDEPENDENT-SEGMENTS'];
for (const item of audio) {
assertSafeUri(item.uri);
lines.push(
`#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="audio",NAME="${escapeAttribute(item.name)}",LANGUAGE="${escapeAttribute(item.language)}",AUTOSELECT=YES,DEFAULT=${item.default ? 'YES' : 'NO'}${item.channels === undefined ? '' : `,CHANNELS="${item.channels}"`},URI="${item.uri}"`,
);
}
assertSafeUri(videoUri);
lines.push(
`#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},AVERAGE-BANDWIDTH=${average}${resolution},CODECS="${escapeAttribute(codecs)}",AUDIO="audio"`,
videoUri,
'',
);
return lines.join('\n');
}
export interface WarningAssessment {
knownAacRepairs: number;
ignoredProbeWarnings: number;
unknown: string[];
}
/** Only the observed one-sample AAC rounding repair is accepted. */
export function assessFfmpegWarnings(stderr: string): WarningAssessment {
const lines = stderr.split(/\r?\n/u).map((line) => line.trim()).filter(Boolean);
let knownAacRepairs = 0;
let ignoredProbeWarnings = 0;
const unknown: string[] = [];
for (const line of lines) {
const packet = line.match(/Packet duration:\s*(-?\d+)\s*\/\s*dts:/u);
if (packet !== null) {
if (Number(packet[1]) === -32) knownAacRepairs += 1;
else unknown.push(line);
continue;
}
if (line.includes('Could not find codec parameters for stream') && line.includes('Attachment: none')) {
ignoredProbeWarnings += 1;
continue;
}
if (line.startsWith('Consider increasing the value for the \'analyzeduration\'')) {
ignoredProbeWarnings += 1;
continue;
}
if (line === 'Bandwidth info not available, set audio and video bitrates') {
ignoredProbeWarnings += 1;
continue;
}
unknown.push(line);
}
return { knownAacRepairs, ignoredProbeWarnings, unknown };
}
+14
View File
@@ -0,0 +1,14 @@
export * from './cache.js';
export * from './classify.js';
export * from './encode.js';
export * from './ffprobe.js';
export * from './fingerprint.js';
export * from './fonts.js';
export * from './hls.js';
export * from './language.js';
export * from './packager.js';
export * from './paths.js';
export * from './process.js';
export * from './single-flight.js';
export * from './subtitles.js';
export type * from './types.js';
+63
View File
@@ -0,0 +1,63 @@
import type { ProbeStream } from './types.js';
const LANGUAGE_ALIASES: Record<string, string> = {
ara: 'ar', ar: 'ar',
chi: 'zh', zho: 'zh', zh: 'zh',
dut: 'nl', nld: 'nl', nl: 'nl',
eng: 'en', en: 'en',
fas: 'fa', per: 'fa', fa: 'fa', pes: 'fa',
fre: 'fr', fra: 'fr', fr: 'fr',
ger: 'de', deu: 'de', de: 'de',
heb: 'he', he: 'he',
hin: 'hi', hi: 'hi',
ita: 'it', it: 'it',
jpn: 'ja', ja: 'ja',
kor: 'ko', ko: 'ko',
por: 'pt', pt: 'pt',
rus: 'ru', ru: 'ru',
spa: 'es', es: 'es',
tur: 'tr', tr: 'tr',
und: 'und', unknown: 'und', qad: 'und',
};
export function detectTextLanguage(text: string): string | undefined {
const clean = text.replace(/\{[^}]*\}/g, '').replace(/\\[Nnh]/g, ' ');
const arabicScript = (clean.match(/[\u0600-\u06ff]/gu) ?? []).length;
const persianSpecific = (clean.match(/[پچژگک‌ی]/gu) ?? []).length;
const kana = (clean.match(/[\u3040-\u30ff]/gu) ?? []).length;
const han = (clean.match(/[\u3400-\u9fff]/gu) ?? []).length;
const cjk = kana + han;
const hangul = (clean.match(/[\uac00-\ud7af]/gu) ?? []).length;
const cyrillic = (clean.match(/[\u0400-\u04ff]/gu) ?? []).length;
const latin = (clean.match(/[A-Za-z]/g) ?? []).length;
const largest = Math.max(arabicScript, cjk, hangul, cyrillic, latin);
if (largest < 12) return undefined;
if (largest === arabicScript) return persianSpecific >= 2 ? 'fa' : 'ar';
if (largest === cjk) return kana >= 2 ? 'ja' : 'zh';
if (largest === hangul) return 'ko';
if (largest === cyrillic) return 'ru';
return 'en';
}
export function normalizeLanguage(raw: string | undefined, content?: string): string {
const value = raw?.trim().toLowerCase().replaceAll('_', '-');
const primary = value?.split('-')[0];
const normalized = primary === undefined ? undefined : LANGUAGE_ALIASES[primary];
const detected = content === undefined ? undefined : detectTextLanguage(content);
if (normalized === undefined || normalized === 'und') return detected ?? 'und';
// Script evidence wins over unreliable private-use and plainly wrong archive tags.
if (detected !== undefined && detected !== normalized) return detected;
return normalized;
}
export function normalizeStreamLanguage(stream: ProbeStream, content?: string): string {
return normalizeLanguage(stream.tags?.language, content);
}
export function languageDisplayName(language: string, locale = 'en'): string {
try {
return new Intl.DisplayNames([locale], { type: 'language' }).of(language) ?? language;
} catch {
return language;
}
}
+355
View File
@@ -0,0 +1,355 @@
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { writeCacheMetadata } from './cache.js';
import { probeMedia } from './ffprobe.js';
import { fingerprintSource } from './fingerprint.js';
import {
assessFfmpegWarnings,
buildMasterPlaylist,
finalizeEventPlaylist,
validateMediaPlaylist,
type MasterAudio,
} from './hls.js';
import { languageDisplayName, normalizeStreamLanguage } from './language.js';
import { assertWritableDestination, ensureWritableDirectory, resolveInside } from './paths.js';
import { runProcess } from './process.js';
import { SingleFlight } from './single-flight.js';
import type { Classification, MediaProbe, PackageResult, SourceFingerprint } from './types.js';
const GENERATION_PATTERN = /^[a-z0-9][a-z0-9._-]{7,127}$/u;
export interface PackagingProgress {
state: 'PREPARING' | 'READY' | 'FAILED';
generation: string;
outputDirectory: string;
playable?: boolean;
error?: string;
}
export interface PackageHlsOptions {
archiveRoot: string;
cacheRoot: string;
sourcePath: string;
fingerprint: SourceFingerprint;
probe: MediaProbe;
classification: Classification;
generation?: string;
ffmpegPath?: string;
ffprobePath?: string;
segmentSeconds?: number;
maxTargetDuration?: number;
profileVersion?: string;
progressIntervalMs?: number;
activeBuildMaxAgeMs?: number;
onProgress?: (progress: PackagingProgress) => void | Promise<void>;
}
function buildGeneration(fingerprint: SourceFingerprint, profileVersion: string): string {
const profile = profileVersion.toLowerCase().replace(/[^a-z0-9._-]/gu, '-').slice(0, 32);
return `${profile}-${fingerprint.digest.slice(0, 32)}`;
}
function audioRenditions(probe: MediaProbe, indexes: readonly number[]): MasterAudio[] {
return indexes.map((streamIndex, index) => {
const stream = probe.streams.find((candidate) => candidate.index === streamIndex);
if (stream === undefined) throw new Error(`Audio stream ${streamIndex} is missing`);
const language = normalizeStreamLanguage(stream);
const safeLanguage = language.replace(/[^a-z0-9-]/giu, '').toLowerCase() || 'und';
return {
streamIndex,
language,
name: languageDisplayName(language),
uri: `audio-${streamIndex}-${safeLanguage}/index.m3u8`,
...(stream.channels === undefined ? {} : { channels: stream.channels }),
default: index === 0,
};
});
}
function ffmpegArguments(
source: string,
output: string,
videoIndex: number,
audio: readonly MasterAudio[],
classification: Classification,
segmentSeconds: number,
): string[] {
const arguments_: string[] = [
'-hide_banner', '-loglevel', 'warning', '-nostdin', '-y',
'-i', source,
'-map', `0:${videoIndex}`,
];
for (const item of audio) arguments_.push('-map', `0:${item.streamIndex}`);
arguments_.push('-map_metadata', '-1', '-map_chapters', '-1', '-sn', '-dn', '-c:v', 'copy');
if (classification.class === 'AUDIO_TRANSCODE') {
audio.forEach((item, index) => {
arguments_.push(`-c:a:${index}`, 'aac', `-b:a:${index}`, (item.channels ?? 2) > 2 ? '384k' : '192k');
});
} else {
arguments_.push('-c:a', 'copy');
}
const variants = [
'v:0,agroup:audio,name:video',
...audio.map((item, index) => {
const folder = path.dirname(item.uri);
return `a:${index},agroup:audio,language:${item.language},default:${item.default ? 'yes' : 'no'},name:${folder}`;
}),
].join(' ');
arguments_.push(
'-f', 'hls',
'-hls_time', String(segmentSeconds),
'-hls_segment_type', 'fmp4',
'-hls_playlist_type', 'event',
'-hls_flags', 'independent_segments+temp_file',
'-master_pl_name', 'master.live.m3u8',
'-var_stream_map', variants,
'-hls_fmp4_init_filename', 'init-%v.mp4',
'-hls_segment_filename', path.join(output, '%v', 'segment-%06d.m4s'),
path.join(output, '%v', 'index.m3u8'),
);
return arguments_;
}
export class GenerationBuildActiveError extends Error {
constructor(readonly generation: string) {
super(`Generation is already being built: ${generation}`);
this.name = 'GenerationBuildActiveError';
}
}
async function existingPackage(
generation: string,
outputDirectory: string,
masterPlaylist: string,
videoPlaylistPath: string,
audioPlaylistPaths: readonly string[],
ffprobePath: string,
maxTargetDuration: number,
): Promise<PackageResult | undefined> {
try {
const [videoPlaylist, ...audioPlaylists] = await Promise.all([
validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration }),
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration })),
]);
if (videoPlaylist === undefined) return undefined;
const master = await readFile(masterPlaylist, 'utf8');
if (!master.startsWith('#EXTM3U') || !master.includes('video/index.m3u8')) return undefined;
await validateCodecs(videoPlaylistPath, audioPlaylistPaths, ffprobePath);
return { generation, outputDirectory, masterPlaylist, videoPlaylist, audioPlaylists, knownAacRepairs: 0 };
} catch {
return undefined;
}
}
async function validateCodecs(videoPlaylist: string, audioPlaylists: readonly string[], ffprobePath: string): Promise<void> {
const video = await probeMedia(videoPlaylist, { ffprobePath, timeoutMs: 120_000 });
if (!video.streams.some((stream) => stream.codec_type === 'video' && stream.codec_name === 'h264')) {
throw new Error('Packaged video does not probe as H.264');
}
for (const playlist of audioPlaylists) {
const audio = await probeMedia(playlist, { ffprobePath, timeoutMs: 120_000 });
if (!audio.streams.some((stream) => stream.codec_type === 'audio' && stream.codec_name === 'aac')) {
throw new Error(`Packaged audio does not probe as AAC: ${playlist}`);
}
}
}
async function writeMaster(destination: string, content: string): Promise<void> {
const temporary = `${destination}.tmp`;
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o640 });
await rename(temporary, destination);
}
function delay(milliseconds: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
export async function packageProgressiveHls(options: PackageHlsOptions): Promise<PackageResult> {
if (!['COPY', 'AUDIO_TRANSCODE'].includes(options.classification.class)) {
throw new Error(`Source cannot be JIT packaged: ${options.classification.class}`);
}
const source = await resolveInside(options.archiveRoot, options.sourcePath);
const generation = options.generation ?? buildGeneration(options.fingerprint, options.profileVersion ?? 'cmaf-v1');
if (!GENERATION_PATTERN.test(generation)) throw new Error('Invalid generation identifier');
const generationsRoot = path.join(options.cacheRoot, 'generations');
await ensureWritableDirectory(options.cacheRoot, generationsRoot);
const outputDirectory = await assertWritableDestination(options.cacheRoot, path.join(generationsRoot, generation));
const videoIndex = options.classification.videoStreamIndex;
if (videoIndex === undefined) throw new Error('Classification selected no video stream');
const audio = audioRenditions(options.probe, options.classification.audioStreamIndexes);
const videoPlaylistPath = path.join(outputDirectory, 'video', 'index.m3u8');
const audioPlaylistPaths = audio.map((item) => path.join(outputDirectory, item.uri));
const masterPlaylist = path.join(outputDirectory, 'master.m3u8');
const master = buildMasterPlaylist(options.probe, videoIndex, 'video/index.m3u8', audio);
let outputExists = false;
try {
outputExists = (await stat(outputDirectory)).isDirectory();
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
if (outputExists) {
const ready = await existingPackage(
generation,
outputDirectory,
masterPlaylist,
videoPlaylistPath,
audioPlaylistPaths,
options.ffprobePath ?? 'ffprobe',
options.maxTargetDuration ?? 18,
);
if (ready !== undefined) {
await options.onProgress?.({ state: 'READY', generation, outputDirectory, playable: true });
return ready;
}
let building = false;
let lastAccessedAt = 0;
try {
const metadata = JSON.parse(await readFile(path.join(outputDirectory, '.cache-entry.json'), 'utf8')) as {
building?: boolean; lastAccessedAt?: string;
};
building = metadata.building === true;
lastAccessedAt = Date.parse(metadata.lastAccessedAt ?? '');
} catch {
// An unrecognized partial directory is treated as a failed build and archived.
}
if (building && Number.isFinite(lastAccessedAt)
&& Date.now() - lastAccessedAt < (options.activeBuildMaxAgeMs ?? 26 * 60 * 60 * 1000)) {
throw new GenerationBuildActiveError(generation);
}
const failedName = `failed-${Date.now()}-${generation}`;
const failedDirectory = path.join(generationsRoot, failedName);
await rename(outputDirectory, failedDirectory);
try {
await writeCacheMetadata(generationsRoot, failedDirectory, {
key: failedName,
lastAccessedAt: new Date().toISOString(),
active: false,
building: false,
pinned: false,
});
} catch {
// The archived directory remains diagnostic-only even without cache metadata.
}
}
try {
await mkdir(outputDirectory, { recursive: false, mode: 0o750 });
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'EEXIST') throw new GenerationBuildActiveError(generation);
throw error;
}
// This stable URL exists before playable=true; it references atomically published EVENT playlists.
await writeMaster(masterPlaylist, master);
await writeCacheMetadata(generationsRoot, outputDirectory, {
key: generation,
lastAccessedAt: new Date().toISOString(),
active: false,
building: true,
pinned: false,
bytes: 0,
});
await options.onProgress?.({ state: 'PREPARING', generation, outputDirectory, playable: false });
let settled = false;
let processResult: Awaited<ReturnType<typeof runProcess>> | undefined;
let processError: unknown;
const processPromise = runProcess(options.ffmpegPath ?? 'ffmpeg', ffmpegArguments(
source,
outputDirectory,
videoIndex,
audio,
options.classification,
options.segmentSeconds ?? 6,
), { timeoutMs: 24 * 60 * 60 * 1000, maxOutputBytes: 64 * 1024 * 1024 }).then(
(result) => { processResult = result; },
(error: unknown) => { processError = error; },
).finally(() => { settled = true; });
let playableReported = false;
try {
while (!settled && !playableReported) {
await delay(options.progressIntervalMs ?? 250);
try {
await Promise.all([
validateMediaPlaylist(videoPlaylistPath, { minSegments: 2, maxTargetDuration: options.maxTargetDuration ?? 18 }),
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { minSegments: 2, maxTargetDuration: options.maxTargetDuration ?? 18 })),
]);
playableReported = true;
await options.onProgress?.({ state: 'PREPARING', generation, outputDirectory, playable: true });
} catch {
// The producer publishes manifests and segments atomically; absence here means not ready yet.
}
}
await processPromise;
if (processError !== undefined) throw processError;
if (processResult === undefined) throw new Error('FFmpeg completed without a result');
const afterFingerprint = await fingerprintSource(options.archiveRoot, source, options.fingerprint.edgeBytes);
if (afterFingerprint.digest !== options.fingerprint.digest) throw new Error('Source changed during packaging');
const warnings = assessFfmpegWarnings(processResult.stderr);
if (warnings.unknown.length > 0) {
throw new Error(`Unrecognized FFmpeg warning(s): ${warnings.unknown.slice(0, 5).join(' | ')}`);
}
const initial = await Promise.all([
validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 }),
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 })),
]);
const [videoInitial, ...audioInitial] = initial;
if (videoInitial === undefined) throw new Error('Video playlist validation did not run');
for (const item of audioInitial) {
if (Math.abs(item.totalDuration - videoInitial.totalDuration) > 0.25) {
throw new Error(`A/V duration differs by more than 250 ms (${videoInitial.totalDuration} vs ${item.totalDuration})`);
}
}
await validateCodecs(videoPlaylistPath, audioPlaylistPaths, options.ffprobePath ?? 'ffprobe');
await Promise.all([videoPlaylistPath, ...audioPlaylistPaths].map(finalizeEventPlaylist));
const [videoPlaylist, ...audioPlaylists] = await Promise.all([
validateMediaPlaylist(videoPlaylistPath, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 }),
...audioPlaylistPaths.map((playlist) => validateMediaPlaylist(playlist, { requireEnded: true, maxTargetDuration: options.maxTargetDuration ?? 18 })),
]);
if (videoPlaylist === undefined) throw new Error('Final video playlist is missing');
await writeCacheMetadata(generationsRoot, outputDirectory, {
key: generation,
lastAccessedAt: new Date().toISOString(),
active: false,
building: false,
pinned: false,
});
await options.onProgress?.({ state: 'READY', generation, outputDirectory, playable: true });
return { generation, outputDirectory, masterPlaylist, videoPlaylist, audioPlaylists, knownAacRepairs: warnings.knownAacRepairs };
} catch (error) {
try {
const details = await stat(outputDirectory);
if (details.isDirectory()) {
await writeCacheMetadata(generationsRoot, outputDirectory, {
key: generation,
lastAccessedAt: new Date().toISOString(),
active: false,
building: false,
pinned: false,
});
}
} catch {
// Preserve the original packaging error.
}
await options.onProgress?.({
state: 'FAILED',
generation,
outputDirectory,
playable: false,
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
}
export class ProgressiveHlsPackager {
readonly #singleFlight = new SingleFlight();
package(options: PackageHlsOptions): Promise<PackageResult> {
const generation = options.generation ?? buildGeneration(options.fingerprint, options.profileVersion ?? 'cmaf-v1');
return this.#singleFlight.run(generation, async () => await packageProgressiveHls({ ...options, generation }));
}
}
export async function readGeneratedMaster(outputDirectory: string): Promise<string> {
return await readFile(path.join(outputDirectory, 'master.m3u8'), 'utf8');
}
+151
View File
@@ -0,0 +1,151 @@
import { lstat, mkdir, opendir, realpath, stat } from 'node:fs/promises';
import path from 'node:path';
export class UnsafePathError extends Error {
constructor(message: string) {
super(message);
this.name = 'UnsafePathError';
}
}
function withSeparator(value: string): string {
return value.endsWith(path.sep) ? value : `${value}${path.sep}`;
}
export function isPathInside(root: string, candidate: string): boolean {
const normalizedRoot = path.resolve(root);
const normalizedCandidate = path.resolve(candidate);
return normalizedCandidate === normalizedRoot || normalizedCandidate.startsWith(withSeparator(normalizedRoot));
}
export async function resolveInside(root: string, candidate: string): Promise<string> {
const realRoot = await realpath(root);
const realCandidate = await realpath(candidate);
if (!isPathInside(realRoot, realCandidate)) {
throw new UnsafePathError(`Path escapes configured root: ${candidate}`);
}
return realCandidate;
}
export async function assertWritableDestination(root: string, candidate: string): Promise<string> {
const resolvedRoot = path.resolve(root);
const resolvedCandidate = path.resolve(candidate);
if (resolvedCandidate === resolvedRoot || !isPathInside(resolvedRoot, resolvedCandidate)) {
throw new UnsafePathError(`Output must be a child of its configured root: ${candidate}`);
}
await assertWritableRoot(resolvedRoot);
let canonicalRoot: string;
try {
canonicalRoot = await realpath(resolvedRoot);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return resolvedCandidate;
throw error;
}
let current = canonicalRoot;
for (const component of path.relative(resolvedRoot, resolvedCandidate).split(path.sep)) {
current = path.join(current, component);
try {
const details = await lstat(current);
if (details.isSymbolicLink()) throw new UnsafePathError(`Symlink found in writable path: ${current}`);
if (!details.isDirectory()) throw new UnsafePathError(`Writable path component is not a directory: ${current}`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') break;
throw error;
}
}
return resolvedCandidate;
}
/** Rejects a configured writable root that is itself a symlink. Missing roots are allowed. */
export async function assertWritableRoot(root: string): Promise<string> {
const resolvedRoot = path.resolve(root);
try {
const details = await lstat(resolvedRoot);
if (details.isSymbolicLink()) throw new UnsafePathError(`Configured writable root is a symlink: ${resolvedRoot}`);
if (!details.isDirectory()) throw new UnsafePathError(`Configured writable root is not a directory: ${resolvedRoot}`);
await realpath(resolvedRoot);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
}
return resolvedRoot;
}
/** Creates a managed child directory one component at a time without following planted symlinks. */
export async function ensureWritableDirectory(
root: string,
candidate: string,
mode = 0o750,
): Promise<string> {
const resolvedRoot = path.resolve(root);
const resolvedCandidate = path.resolve(candidate);
if (resolvedCandidate === resolvedRoot || !isPathInside(resolvedRoot, resolvedCandidate)) {
throw new UnsafePathError(`Output must be a child of its configured root: ${candidate}`);
}
await assertWritableRoot(resolvedRoot);
try {
await lstat(resolvedRoot);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
await mkdir(resolvedRoot, { recursive: true, mode });
await assertWritableRoot(resolvedRoot);
}
const canonicalRoot = await realpath(resolvedRoot);
let current = canonicalRoot;
for (const component of path.relative(resolvedRoot, resolvedCandidate).split(path.sep)) {
current = path.join(current, component);
try {
const details = await lstat(current);
if (details.isSymbolicLink()) throw new UnsafePathError(`Symlink found in writable path: ${current}`);
if (!details.isDirectory()) throw new UnsafePathError(`Writable path component is not a directory: ${current}`);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
try {
await mkdir(current, { mode });
} catch (mkdirError) {
if ((mkdirError as NodeJS.ErrnoException).code !== 'EEXIST') throw mkdirError;
}
const details = await lstat(current);
if (details.isSymbolicLink() || !details.isDirectory()) {
throw new UnsafePathError(`Refusing unsafe writable directory: ${current}`);
}
}
}
// Re-check the complete chain after creation so callers never receive a path whose
// ancestor was replaced with a symlink while the components were being created.
await assertWritableDestination(resolvedRoot, resolvedCandidate);
return resolvedCandidate;
}
export interface WalkArchiveOptions {
extensions?: readonly string[];
maxDepth?: number;
}
/** Walks regular files only and never follows archive symlinks. */
export async function* walkArchive(
archiveRoot: string,
options: WalkArchiveOptions = {},
): AsyncGenerator<string> {
const root = await realpath(archiveRoot);
const rootStat = await stat(root);
if (!rootStat.isDirectory()) throw new UnsafePathError(`Archive root is not a directory: ${root}`);
const allowed = new Set((options.extensions ?? ['.mkv']).map((extension) => extension.toLowerCase()));
const maxDepth = options.maxDepth ?? 32;
async function* visit(directory: string, depth: number): AsyncGenerator<string> {
if (depth > maxDepth) throw new UnsafePathError(`Archive tree exceeds maximum depth ${maxDepth}`);
const handle = await opendir(directory);
for await (const entry of handle) {
const candidate = path.join(directory, entry.name);
if (entry.isSymbolicLink()) continue;
if (entry.isDirectory()) {
yield* visit(candidate, depth + 1);
} else if (entry.isFile() && allowed.has(path.extname(entry.name).toLowerCase())) {
const verified = await resolveInside(root, candidate);
yield verified;
}
}
}
yield* visit(root, 0);
}
+122
View File
@@ -0,0 +1,122 @@
import { spawn } from 'node:child_process';
export interface ProcessResult {
code: number;
stdout: string;
stderr: string;
}
export interface RunProcessOptions {
cwd?: string;
timeoutMs?: number;
maxOutputBytes?: number;
env?: NodeJS.ProcessEnv;
signal?: AbortSignal;
}
export class ProcessFailure extends Error {
constructor(
message: string,
readonly command: string,
readonly result?: ProcessResult,
) {
super(message);
this.name = 'ProcessFailure';
}
}
const MEDIA_PROCESS_ENV_KEYS = [
'PATH',
'HOME',
'TMPDIR',
'TMP',
'TEMP',
'LANG',
'LC_ALL',
'LD_LIBRARY_PATH',
'DYLD_LIBRARY_PATH',
'FONTCONFIG_FILE',
'FONTCONFIG_PATH',
'XDG_CACHE_HOME',
'SSL_CERT_FILE',
'SSL_CERT_DIR',
// Required for child-process startup on Windows development hosts.
'SystemRoot',
'WINDIR',
'PATHEXT',
'COMSPEC',
] as const;
/** Prevents FFmpeg/ffprobe from inheriting database, Redis, or application secrets. */
export function mediaProcessEnvironment(
source: NodeJS.ProcessEnv = process.env,
): NodeJS.ProcessEnv {
const environment: NodeJS.ProcessEnv = {};
for (const key of MEDIA_PROCESS_ENV_KEYS) {
const value = source[key];
if (value !== undefined) environment[key] = value;
}
return environment;
}
/** Runs a binary directly. Arguments never pass through a shell. */
export async function runProcess(
binary: string,
args: readonly string[],
options: RunProcessOptions = {},
): Promise<ProcessResult> {
const maxOutput = options.maxOutputBytes ?? 16 * 1024 * 1024;
return await new Promise<ProcessResult>((resolve, reject) => {
const child = spawn(binary, [...args], {
cwd: options.cwd,
env: options.env ?? mediaProcessEnvironment(),
shell: false,
windowsHide: true,
stdio: ['ignore', 'pipe', 'pipe'],
signal: options.signal,
});
let stdout = '';
let stderr = '';
let stdoutBytes = 0;
let stderrBytes = 0;
let overflow = false;
const append = (current: string, currentBytes: number, chunk: Buffer): [string, number] => {
if (currentBytes + chunk.length > maxOutput) {
overflow = true;
child.kill('SIGKILL');
return [current, currentBytes];
}
return [`${current}${chunk.toString('utf8')}`, currentBytes + chunk.length];
};
child.stdout.on('data', (chunk: Buffer) => {
[stdout, stdoutBytes] = append(stdout, stdoutBytes, chunk);
});
child.stderr.on('data', (chunk: Buffer) => {
[stderr, stderrBytes] = append(stderr, stderrBytes, chunk);
});
child.once('error', (error) => reject(error));
const timer = options.timeoutMs === undefined
? undefined
: setTimeout(() => child.kill('SIGKILL'), options.timeoutMs);
timer?.unref();
child.once('close', (code, signal) => {
if (timer !== undefined) clearTimeout(timer);
const result: ProcessResult = {
code: code ?? -1,
stdout,
stderr,
};
if (overflow) {
reject(new ProcessFailure(`Process output exceeded ${maxOutput} bytes`, binary, result));
} else if (code !== 0) {
reject(new ProcessFailure(`${binary} exited with ${String(code)} (${signal ?? 'no signal'})`, binary, result));
} else {
resolve(result);
}
});
});
}
+44
View File
@@ -0,0 +1,44 @@
export interface DistributedLease {
release(): Promise<void>;
}
export interface DistributedLock {
acquire(key: string, ttlMs: number): Promise<DistributedLease | undefined>;
}
export class SingleFlight {
readonly #running = new Map<string, Promise<unknown>>();
run<T>(key: string, operation: () => Promise<T>): Promise<T> {
const existing = this.#running.get(key);
if (existing !== undefined) return existing as Promise<T>;
const promise = operation().finally(() => {
if (this.#running.get(key) === promise) this.#running.delete(key);
});
this.#running.set(key, promise);
return promise;
}
has(key: string): boolean {
return this.#running.has(key);
}
get size(): number {
return this.#running.size;
}
}
export async function withDistributedSingleFlight<T>(
lock: DistributedLock,
key: string,
ttlMs: number,
operation: () => Promise<T>,
): Promise<T | undefined> {
const lease = await lock.acquire(key, ttlMs);
if (lease === undefined) return undefined;
try {
return await operation();
} finally {
await lease.release();
}
}
+127
View File
@@ -0,0 +1,127 @@
import { randomUUID } from 'node:crypto';
import { readFile, rename } from 'node:fs/promises';
import path from 'node:path';
import { normalizeStreamLanguage } from './language.js';
import { ensureWritableDirectory, resolveInside } from './paths.js';
import { runProcess } from './process.js';
import type { ExtractedSubtitle, MediaProbe } from './types.js';
const TEXT_SUBTITLE_CODECS = new Set(['ass', 'ssa', 'subrip', 'srt', 'webvtt', 'mov_text']);
export interface SubtitleExtractionOptions {
archiveRoot: string;
outputRoot: string;
generation: string;
ffmpegPath?: string;
timeoutMs?: number;
}
export function assDialogueText(ass: string): string {
return ass
.split(/\r?\n/u)
.filter((line) => /^Dialogue\s*:/iu.test(line))
.map((line) => line.split(',').slice(9).join(','))
.join('\n');
}
export function countAssCues(ass: string): number {
return ass.split(/\r?\n/u).filter((line) => /^Dialogue\s*:/iu.test(line)).length;
}
export interface SubtitleReadOptions {
archiveRoot: string;
ffmpegPath?: string;
timeoutMs?: number;
maxDurationSeconds?: number;
}
export function subtitleAssArguments(
source: string,
streamIndex: number,
maxDurationSeconds?: number,
): string[] {
if (!Number.isInteger(streamIndex) || streamIndex < 0) throw new RangeError('streamIndex must be non-negative');
if (maxDurationSeconds !== undefined
&& (!Number.isFinite(maxDurationSeconds) || maxDurationSeconds <= 0 || maxDurationSeconds > 86_400)) {
throw new RangeError('maxDurationSeconds must be greater than 0 and at most 86400');
}
return [
'-hide_banner', '-loglevel', 'error', '-nostdin',
'-i', source,
'-map', `0:${streamIndex}`,
...(maxDurationSeconds === undefined ? [] : ['-t', String(maxDurationSeconds)]),
'-c:s', 'ass',
'-f', 'ass',
'pipe:1',
];
}
export async function readSubtitleAsAss(
sourcePath: string,
streamIndex: number,
options: SubtitleReadOptions,
): Promise<string> {
const source = await resolveInside(options.archiveRoot, sourcePath);
const result = await runProcess(
options.ffmpegPath ?? 'ffmpeg',
subtitleAssArguments(source, streamIndex, options.maxDurationSeconds),
{ timeoutMs: options.timeoutMs ?? 120_000, maxOutputBytes: 16 * 1024 * 1024 },
);
return result.stdout;
}
async function atomicRename(temp: string, destination: string): Promise<void> {
await rename(temp, destination);
}
export async function extractSubtitleVariants(
sourcePath: string,
probe: MediaProbe,
options: SubtitleExtractionOptions,
): Promise<ExtractedSubtitle[]> {
const source = await resolveInside(options.archiveRoot, sourcePath);
const directory = await ensureWritableDirectory(
options.outputRoot,
path.join(options.outputRoot, options.generation, 'subtitles'),
);
const streams = probe.streams.filter(
(stream) => stream.codec_type === 'subtitle' && TEXT_SUBTITLE_CODECS.has(stream.codec_name ?? ''),
);
const extracted: ExtractedSubtitle[] = [];
for (const stream of streams) {
const token = randomUUID();
const tempAss = path.join(directory, `.${stream.index}-${token}.ass`);
const tempVtt = path.join(directory, `.${stream.index}-${token}.vtt`);
await runProcess(options.ffmpegPath ?? 'ffmpeg', [
'-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
'-i', source,
'-map', `0:${stream.index}`,
'-c:s', 'ass',
tempAss,
], { timeoutMs: options.timeoutMs ?? 120_000 });
const ass = await readFile(tempAss, 'utf8');
const language = normalizeStreamLanguage(stream, assDialogueText(ass));
const stem = `${String(stream.index).padStart(3, '0')}-${language}`;
const assPath = path.join(directory, `${stem}.ass`);
const vttPath = path.join(directory, `${stem}.vtt`);
await runProcess(options.ffmpegPath ?? 'ffmpeg', [
'-hide_banner', '-loglevel', 'error', '-nostdin', '-y',
'-i', tempAss,
'-c:s', 'webvtt',
tempVtt,
], { timeoutMs: options.timeoutMs ?? 120_000 });
await atomicRename(tempAss, assPath);
await atomicRename(tempVtt, vttPath);
extracted.push({
streamIndex: stream.index,
language,
assPath,
vttPath,
cueCount: countAssCues(ass),
default: language === 'fa',
forced: false,
});
}
return extracted;
}
+125
View File
@@ -0,0 +1,125 @@
export type CompatibilityClass =
| 'COPY'
| 'AUDIO_TRANSCODE'
| 'VIDEO_TRANSCODE'
| 'HOLD_HDR'
| 'INVALID';
export interface ProbeDisposition {
default?: number;
forced?: number;
attached_pic?: number;
[key: string]: number | undefined;
}
export interface ProbeStream {
index: number;
codec_name?: string;
codec_long_name?: string;
codec_type?: 'video' | 'audio' | 'subtitle' | 'attachment' | string;
profile?: string;
mime_codec_string?: string;
bit_rate?: string;
width?: number;
height?: number;
pix_fmt?: string;
level?: number;
field_order?: string;
avg_frame_rate?: string;
r_frame_rate?: string;
bits_per_raw_sample?: string;
sample_rate?: string;
channels?: number;
channel_layout?: string;
color_transfer?: string;
color_primaries?: string;
color_space?: string;
duration?: string;
extradata_size?: number;
disposition?: ProbeDisposition;
tags?: Record<string, string | undefined>;
side_data_list?: Array<Record<string, unknown>>;
[key: string]: unknown;
}
export interface ProbeFormat {
filename?: string;
format_name?: string;
duration?: string;
size?: string;
bit_rate?: string;
probe_score?: number;
tags?: Record<string, string | undefined>;
[key: string]: unknown;
}
export interface MediaProbe {
streams: ProbeStream[];
format: ProbeFormat;
chapters: Array<Record<string, unknown>>;
}
export interface SourceFingerprint {
version: 1;
algorithm: 'sha256';
relativePath: string;
size: string;
mtimeNs: string;
edgeBytes: number;
digest: string;
}
export interface NormalizedTrack {
index: number;
type: 'video' | 'audio' | 'subtitle' | 'attachment';
codec: string;
language: string;
label?: string;
default: boolean;
forced: boolean;
}
export interface Classification {
class: CompatibilityClass;
reasons: string[];
videoStreamIndex?: number;
audioStreamIndexes: number[];
}
export interface ExtractedSubtitle {
streamIndex: number;
language: string;
assPath: string;
vttPath: string;
cueCount: number;
default: boolean;
forced: boolean;
}
export interface StoredFont {
streamIndex: number;
sha256: string;
path: string;
originalName: string;
size: number;
format: 'ttf' | 'otf';
}
export interface HlsPlaylistValidation {
path: string;
segmentCount: number;
targetDuration: number;
minDuration: number;
maxDuration: number;
totalDuration: number;
ended: boolean;
}
export interface PackageResult {
generation: string;
outputDirectory: string;
masterPlaylist: string;
videoPlaylist: HlsPlaylistValidation;
audioPlaylists: HlsPlaylistValidation[];
knownAacRepairs: number;
}
@@ -0,0 +1,154 @@
import { mkdtemp, mkdir, readFile, stat, symlink, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import {
evictCache,
evictCacheGeneration,
SingleFlight,
touchCacheGeneration,
writeCacheMetadata,
} from '../src/index.js';
describe('single flight and cache pressure', () => {
it('shares one running promise per generation', async () => {
const flight = new SingleFlight();
let calls = 0;
const operation = async (): Promise<number> => {
calls += 1;
await new Promise((resolve) => setTimeout(resolve, 10));
return 42;
};
const [left, right] = await Promise.all([flight.run('generation', operation), flight.run('generation', operation)]);
expect([left, right]).toEqual([42, 42]);
expect(calls).toBe(1);
});
it('evicts oldest unprotected entries down to the low watermark', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-'));
for (const [key, date, pinned] of [['old', '2020-01-01T00:00:00.000Z', false], ['new', '2021-01-01T00:00:00.000Z', false], ['pin', '2019-01-01T00:00:00.000Z', true]] as const) {
const directory = path.join(root, key);
await mkdir(directory);
await writeFile(path.join(directory, 'data'), Buffer.alloc(40));
await writeCacheMetadata(root, directory, { key, lastAccessedAt: date, active: false, building: false, pinned, bytes: 40 });
}
const result = await evictCache(root, { capacityBytes: 100, highWatermark: 0.85, lowWatermark: 0.75 });
expect(result.evicted).toEqual(['old', 'new']);
expect(result.afterBytes).toBe(40);
});
it('evicts only inactive, unpinned cache generations', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-generation-'));
const generations = path.join(root, 'generations');
const active = path.join(generations, 'active-generation');
const ready = path.join(generations, 'ready-generation');
await Promise.all([mkdir(active, { recursive: true }), mkdir(ready, { recursive: true })]);
await Promise.all([writeFile(path.join(active, 'data'), 'active'), writeFile(path.join(ready, 'data'), 'ready')]);
await writeCacheMetadata(generations, active, { key: 'active-generation', lastAccessedAt: new Date().toISOString(), active: true, building: false, pinned: false });
await writeCacheMetadata(generations, ready, { key: 'ready-generation', lastAccessedAt: new Date().toISOString(), active: false, building: false, pinned: false });
await expect(evictCacheGeneration(root, 'active-generation')).rejects.toThrow('active');
expect(await evictCacheGeneration(root, 'ready-generation')).toBe(true);
await expect(stat(ready)).rejects.toMatchObject({ code: 'ENOENT' });
});
it('touches recency and keeps the longest playback protection window', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-generation-touch-'));
const generations = path.join(root, 'generations');
const generation = '11111111-1111-4111-8111-111111111111';
const directory = path.join(generations, generation);
await mkdir(directory, { recursive: true });
await writeFile(path.join(directory, 'data'), 'ready');
await writeCacheMetadata(generations, directory, {
key: generation,
lastAccessedAt: '2026-01-01T00:00:00.000Z',
protectedUntil: '2999-07-14T10:00:00.000Z',
active: false,
building: false,
pinned: false,
});
await touchCacheGeneration(root, generation, {
accessedAt: '2026-07-14T09:00:00.000Z',
protectedUntil: '2026-07-14T09:30:00.000Z',
});
const metadata = JSON.parse(await readFile(path.join(directory, '.cache-entry.json'), 'utf8'));
expect(metadata).toMatchObject({
lastAccessedAt: '2026-07-14T09:00:00.000Z',
protectedUntil: '2999-07-14T10:00:00.000Z',
});
await expect(evictCacheGeneration(root, generation)).rejects.toThrow('playback lease');
});
it('protects recently touched entries while evicting older pressure', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-retention-'));
for (const [key, date] of [
['old-entry', '2026-07-14T00:00:00.000Z'],
['recent-entry', '2026-07-14T09:59:00.000Z'],
] as const) {
const directory = path.join(root, key);
await mkdir(directory);
await writeFile(path.join(directory, 'data'), Buffer.alloc(60));
await writeCacheMetadata(root, directory, {
key,
lastAccessedAt: date,
active: false,
building: false,
pinned: false,
bytes: 60,
});
}
const result = await evictCache(root, {
capacityBytes: 100,
highWatermark: 0.85,
lowWatermark: 0.75,
minimumRetentionMs: 60 * 60 * 1000,
now: new Date('2026-07-14T10:00:00.000Z'),
});
expect(result.evicted).toEqual(['old-entry']);
expect(result.afterBytes).toBe(60);
});
it('rejects a planted writable-path symlink without writing outside the cache', async () => {
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-write-link-'));
const root = path.join(base, 'cache');
const outside = path.join(base, 'outside');
await Promise.all([mkdir(root), mkdir(outside)]);
const marker = path.join(outside, 'marker');
await writeFile(marker, 'untouched');
await symlink(outside, path.join(root, 'linked-entry'));
await expect(writeCacheMetadata(root, path.join(root, 'linked-entry'), {
key: 'linked-entry',
lastAccessedAt: new Date().toISOString(),
active: false,
building: false,
pinned: false,
bytes: 1,
})).rejects.toThrow(/Symlink found in writable path/u);
expect(await readFile(marker, 'utf8')).toBe('untouched');
await expect(stat(path.join(outside, '.cache-entry.json'))).rejects.toMatchObject({ code: 'ENOENT' });
});
it('rejects a planted generations symlink without deleting outside the cache', async () => {
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-cache-delete-link-'));
const root = path.join(base, 'cache');
const outside = path.join(base, 'outside');
const generation = '33333333-3333-4333-8333-333333333333';
const outsideGeneration = path.join(outside, generation);
await Promise.all([mkdir(root), mkdir(outsideGeneration, { recursive: true })]);
const marker = path.join(outsideGeneration, 'marker');
await writeFile(marker, 'untouched');
await writeCacheMetadata(outside, outsideGeneration, {
key: generation,
lastAccessedAt: '2020-01-01T00:00:00.000Z',
active: false,
building: false,
pinned: false,
});
await symlink(outside, path.join(root, 'generations'));
await expect(evictCacheGeneration(root, generation)).rejects.toThrow(/writable root is a symlink/u);
expect(await readFile(marker, 'utf8')).toBe('untouched');
await expect(stat(outsideGeneration)).resolves.toBeDefined();
});
});
+44
View File
@@ -0,0 +1,44 @@
import { describe, expect, it } from 'vitest';
import { classifyMedia, detectTextLanguage, normalizeLanguage } from '../src/index.js';
import { audio, probe, video } from './fixtures.js';
describe('media compatibility', () => {
it('copy-packages browser-safe H.264 and AAC-LC', () => {
expect(classifyMedia(probe())).toMatchObject({ class: 'COPY', videoStreamIndex: 0, audioStreamIndexes: [1] });
});
it('selects audio-only transcoding for DTS', () => {
expect(classifyMedia(probe([video(), audio({ codec_name: 'dts', profile: undefined })])).class)
.toBe('AUDIO_TRANSCODE');
});
it('selects video transcoding for HEVC SDR', () => {
expect(classifyMedia(probe([video({ codec_name: 'hevc', pix_fmt: 'yuv420p10le' }), audio()])).class)
.toBe('VIDEO_TRANSCODE');
});
it('holds HDR independently of codec', () => {
expect(classifyMedia(probe([video({ color_transfer: 'smpte2084', color_primaries: 'bt2020' }), audio()]))).toMatchObject({
class: 'HOLD_HDR', reasons: ['HDR_UNSUPPORTED_V1'],
});
});
it('rejects media without an audio stream', () => {
expect(classifyMedia(probe([video()]))).toMatchObject({ class: 'INVALID', reasons: ['NO_AUDIO'] });
});
});
describe('language normalization', () => {
it('maps ISO-639 aliases', () => {
expect(normalizeLanguage('per')).toBe('fa');
expect(normalizeLanguage('jpn')).toBe('ja');
});
it('uses script evidence for private or wrong tags', () => {
const english = 'This is enough English dialogue text for reliable script detection.';
expect(normalizeLanguage('qad', english)).toBe('en');
expect(normalizeLanguage('eng', 'این یک زیرنویس فارسی برای تشخیص زبان است')).toBe('fa');
expect(detectTextLanguage('این یک زیرنویس فارسی برای تشخیص زبان است')).toBe('fa');
expect(detectTextLanguage('هذا نص عربي واضح لاختبار اكتشاف لغة الترجمة العربية')).toBe('ar');
});
});
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it } from 'vitest';
import { buildCompatibilityEncodeArguments, classifyMedia } from '../src/index.js';
import { audio, probe, video } from './fixtures.js';
describe('offline compatibility encode profile', () => {
it('builds same-resolution H.264 CRF18 CMAF with bounded closed GOP and channel-aware AAC', () => {
const media = probe([
video({ codec_name: 'hevc', pix_fmt: 'yuv420p10le', avg_frame_rate: '24000/1001' }),
audio({ index: 1, codec_name: 'dts', channels: 2 }),
audio({ index: 2, codec_name: 'truehd', channels: 6, tags: { language: 'eng' } }),
]);
const classification = classifyMedia(media);
const args = buildCompatibilityEncodeArguments('/archive/source.mkv', '/derived/build', media, classification);
expect(args).toContain('libx264');
expect(args.slice(args.indexOf('-crf'), args.indexOf('-crf') + 2)).toEqual(['-crf', '18']);
expect(args.slice(args.indexOf('-pix_fmt'), args.indexOf('-pix_fmt') + 2)).toEqual(['-pix_fmt', 'yuv420p']);
expect(args.slice(args.indexOf('-g'), args.indexOf('-g') + 2)).toEqual(['-g', '144']);
expect(args).toContain('expr:gte(t,n_forced*6)');
expect(args.slice(args.indexOf('-b:a:0'), args.indexOf('-b:a:0') + 2)).toEqual(['-b:a:0', '192k']);
expect(args.slice(args.indexOf('-b:a:1'), args.indexOf('-b:a:1') + 2)).toEqual(['-b:a:1', '384k']);
expect(args).toContain('vod');
expect(args).toContain('fmp4');
});
it('hard-refuses HDR input', () => {
const media = probe([video({ codec_name: 'hevc', color_transfer: 'smpte2084' }), audio()]);
expect(() => buildCompatibilityEncodeArguments('/a', '/b', media, classifyMedia(media))).toThrow('HDR_UNSUPPORTED_V1');
});
});
+44
View File
@@ -0,0 +1,44 @@
import type { MediaProbe, ProbeStream } from '../src/index.js';
export function video(overrides: Partial<ProbeStream> = {}): ProbeStream {
return {
index: 0,
codec_type: 'video',
codec_name: 'h264',
profile: 'High',
mime_codec_string: 'avc1.64001f',
width: 1280,
height: 720,
pix_fmt: 'yuv420p',
bits_per_raw_sample: '8',
field_order: 'progressive',
tags: { BPS: '652016' },
...overrides,
};
}
export function audio(overrides: Partial<ProbeStream> = {}): ProbeStream {
return {
index: 1,
codec_type: 'audio',
codec_name: 'aac',
profile: 'LC',
channels: 2,
sample_rate: '48000',
tags: { language: 'jpn', BPS: '200416' },
...overrides,
};
}
export function probe(streams: ProbeStream[] = [video(), audio()]): MediaProbe {
return {
streams,
format: {
format_name: 'matroska,webm',
duration: '1420.095',
bit_rate: '899640',
probe_score: 100,
},
chapters: [],
};
}
+93
View File
@@ -0,0 +1,93 @@
import { link, mkdtemp, mkdir, readFile, readdir, realpath, stat, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import {
extractAndStoreFonts,
fontDumpArguments,
pruneOrphanedFonts,
publishGenerationFonts,
validateSfntFont,
} from '../src/index.js';
import { probe } from './fixtures.js';
function minimalSfnt(): Buffer {
const data = Buffer.alloc(28);
data.writeUInt32BE(0x00010000, 0);
data.writeUInt16BE(1, 4);
data.write('head', 12, 'ascii');
data.writeUInt32BE(28, 20);
data.writeUInt32BE(0, 24);
return data;
}
describe('font attachment safety', () => {
it('validates the SFNT directory rather than trusting an extension', () => {
expect(validateSfntFont(minimalSfnt())).toBe('ttf');
expect(() => validateSfntFont(Buffer.from('not a font'))).toThrow();
});
it('builds a header-only FFmpeg dump command', () => {
const args = fontDumpArguments(4, '/cache/font', '/archive/movie.mkv');
expect(args).toContain('-dump_attachment:4');
expect(args.slice(args.indexOf('-i') + 2)).toContain('-t');
expect(args[args.indexOf('-t') + 1]).toBe('0');
});
it('cleans staging data when extracted font validation fails', async () => {
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-'));
const archive = path.join(base, 'archive');
const fontRoot = path.join(base, 'fonts');
await mkdir(archive);
const source = path.join(archive, 'movie.mkv');
await writeFile(source, 'archive');
const mediaProbe = probe([{ index: 4, codec_type: 'attachment', codec_name: 'ttf', extradata_size: 10, tags: { filename: 'bad.ttf' } }]);
await expect(extractAndStoreFonts(source, mediaProbe, {
archiveRoot: archive,
fontRoot,
async runner(_binary, args) {
const destination = args[args.indexOf('-dump_attachment:4') + 1];
if (destination === undefined) throw new Error('Missing mock destination');
await writeFile(destination, 'invalid');
return { code: 0, stdout: '', stderr: '' };
},
})).rejects.toThrow('Font size');
expect(await readdir(path.join(fontRoot, '.staging'))).toEqual([]);
});
it('publishes deduplicated fonts under the signed generation path', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-publish-'));
const sourceDirectory = path.join(root, 'assets', 'fonts', 'sha256');
const generation = path.join(root, 'generations', '11111111-1111-4111-8111-111111111111');
await Promise.all([mkdir(sourceDirectory, { recursive: true }), mkdir(generation, { recursive: true })]);
const data = minimalSfnt();
const sha256 = 'a'.repeat(64);
const source = path.join(sourceDirectory, `${sha256}.ttf`);
await writeFile(source, data);
const font = { streamIndex: 4, sha256, path: source, originalName: 'source.ttf', size: data.length, format: 'ttf' as const };
const first = await publishGenerationFonts([font], root, generation);
const second = await publishGenerationFonts([font], root, generation);
expect(first[0]?.path).toBe(path.join(await realpath(generation), 'fonts', `${sha256}.ttf`));
expect(second[0]?.path).toBe(first[0]?.path);
expect(await readFile(first[0]!.path)).toEqual(data);
});
it('prunes only global fonts with no generation hardlinks', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-font-prune-'));
const store = path.join(root, 'assets', 'fonts', 'sha256');
const generationFonts = path.join(root, 'generations', 'generation-id', 'fonts');
await Promise.all([mkdir(store, { recursive: true }), mkdir(generationFonts, { recursive: true })]);
const orphan = `${'a'.repeat(64)}.ttf`;
const retained = `${'b'.repeat(64)}.otf`;
await Promise.all([
writeFile(path.join(store, orphan), minimalSfnt()),
writeFile(path.join(store, retained), minimalSfnt()),
]);
await link(path.join(store, retained), path.join(generationFonts, retained));
const result = await pruneOrphanedFonts(root, { minimumAgeMs: 0, now: new Date(Date.now() + 1000) });
expect(result.removed).toEqual([orphan]);
expect(result.retainedBytes).toBe(minimalSfnt().length);
await expect(stat(path.join(store, orphan))).rejects.toMatchObject({ code: 'ENOENT' });
expect((await stat(path.join(store, retained))).nlink).toBe(2);
});
});
+71
View File
@@ -0,0 +1,71 @@
import { mkdtemp, mkdir, readFile, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import {
assessFfmpegWarnings,
buildMasterPlaylist,
finalizeEventPlaylist,
parseMediaPlaylist,
validateMediaPlaylist,
} from '../src/index.js';
import { audio, probe, video } from './fixtures.js';
async function playlistFixture(): Promise<string> {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-hls-'));
await Promise.all([
writeFile(path.join(directory, 'init.mp4'), 'init'),
writeFile(path.join(directory, 'segment-000.m4s'), 'one'),
writeFile(path.join(directory, 'segment-001.m4s'), 'two'),
]);
const playlist = path.join(directory, 'index.m3u8');
await writeFile(playlist, [
'#EXTM3U', '#EXT-X-VERSION:7', '#EXT-X-TARGETDURATION:10', '#EXT-X-PLAYLIST-TYPE:EVENT',
'#EXT-X-MAP:URI="init.mp4"', '#EXTINF:9.2,', 'segment-000.m4s', '#EXTINF:4.0,',
'segment-001.m4s', '#EXT-X-ENDLIST', '',
].join('\n'));
return playlist;
}
describe('HLS validation', () => {
it('checks all local fMP4 references and finalizes EVENT to VOD atomically', async () => {
const playlist = await playlistFixture();
const result = await validateMediaPlaylist(playlist, { requireEnded: true, minSegments: 2, maxTargetDuration: 18 });
expect(result).toMatchObject({ segmentCount: 2, maxDuration: 9.2, totalDuration: 13.2 });
await finalizeEventPlaylist(playlist);
expect(await readFile(playlist, 'utf8')).toContain('#EXT-X-PLAYLIST-TYPE:VOD');
});
it('rejects traversal and remote segment URIs', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-hls-unsafe-'));
await writeFile(path.join(directory, 'init.mp4'), 'init');
const traversal = path.join(directory, 'traversal.m3u8');
await writeFile(traversal, '#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:5,\n../secret.m4s');
await expect(validateMediaPlaylist(traversal)).rejects.toThrow('Unsafe or external HLS URI');
const remote = path.join(directory, 'remote.m3u8');
await writeFile(remote, '#EXTM3U\n#EXT-X-TARGETDURATION:6\n#EXT-X-MAP:URI="init.mp4"\n#EXTINF:5,\nhttps://evil.invalid/a.m4s');
await expect(validateMediaPlaylist(remote)).rejects.toThrow('Unsafe or external HLS URI');
});
it('permits only the bounded -32 AAC rounding warning', () => {
const known = assessFfmpegWarnings('[mp4 @ a] Packet duration: -32 / dts: 580456 in stream 0 is out of range');
expect(known).toMatchObject({ knownAacRepairs: 1, unknown: [] });
expect(assessFfmpegWarnings('[mp4 @ a] Packet duration: -64 / dts: 10 in stream 0 is out of range').unknown)
.toHaveLength(1);
expect(assessFfmpegWarnings('Non-monotonous DTS').unknown).toHaveLength(1);
});
it('uses declared/container bitrate and a conservative video fallback', () => {
const declared = buildMasterPlaylist(probe(), 0, 'video/index.m3u8', [{
streamIndex: 1, language: 'ja', name: 'Japanese', uri: 'audio/index.m3u8', default: true,
}]);
expect(declared).toContain('AVERAGE-BANDWIDTH=852432');
const missing = probe([video({ tags: {}, bit_rate: undefined }), audio({ tags: {}, bit_rate: undefined })]);
missing.format.bit_rate = undefined;
const conservative = buildMasterPlaylist(missing, 0, 'video/index.m3u8', [{
streamIndex: 1, language: 'ja', name: 'Japanese', uri: 'audio/index.m3u8', default: true,
}]);
const bandwidth = Number(conservative.match(/BANDWIDTH=(\d+)/u)?.[1]);
expect(bandwidth).toBeGreaterThan(8_000_000);
});
});
@@ -0,0 +1,34 @@
import { mkdtemp, mkdir, realpath, symlink, writeFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { fingerprintSource, isPathInside, walkArchive } from '../src/index.js';
describe('archive boundaries', () => {
it('walks regular MKV files without following symlinks', async () => {
const base = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-walk-'));
const root = path.join(base, 'archive');
const outside = path.join(base, 'outside');
await Promise.all([mkdir(path.join(root, 'series'), { recursive: true }), mkdir(outside)]);
await writeFile(path.join(root, 'series', 'one.mkv'), 'safe');
await writeFile(path.join(outside, 'secret.mkv'), 'secret');
await symlink(path.join(outside, 'secret.mkv'), path.join(root, 'linked.mkv'));
const files: string[] = [];
for await (const file of walkArchive(root)) files.push(file);
expect(files).toEqual([await realpath(path.join(root, 'series', 'one.mkv'))]);
expect(isPathInside(root, path.join(root, 'series', 'one.mkv'))).toBe(true);
expect(isPathInside(root, path.join(outside, 'secret.mkv'))).toBe(false);
});
it('fingerprints path, stat and both file edges', async () => {
const root = await mkdtemp(path.join(os.tmpdir(), 'easy-stream-fingerprint-'));
const source = path.join(root, 'movie.mkv');
await writeFile(source, 'HEAD-middle-TAIL');
const first = await fingerprintSource(root, source, 4);
const same = await fingerprintSource(root, source, 4);
expect(same.digest).toBe(first.digest);
await writeFile(source, 'HEAd-middle-TAIL');
const changed = await fingerprintSource(root, source, 4);
expect(changed.digest).not.toBe(first.digest);
});
});
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest';
import { mediaProcessEnvironment } from '../src/index.js';
describe('media child process environment', () => {
it('keeps runtime paths but strips application secrets', () => {
expect(mediaProcessEnvironment({
PATH: '/usr/bin',
LD_LIBRARY_PATH: '/opt/ffmpeg/lib',
DATABASE_URL: 'postgres://secret',
REDIS_URL: 'redis://secret',
PLAYBACK_SIGNING_SECRET: 'secret',
})).toEqual({
PATH: '/usr/bin',
LD_LIBRARY_PATH: '/opt/ffmpeg/lib',
});
});
});
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, it } from 'vitest';
import { subtitleAssArguments } from '../src/index.js';
describe('bounded subtitle inspection', () => {
it('adds a numeric output duration only when requested', () => {
const bounded = subtitleAssArguments('/archive/movie.mkv', 3, 600);
expect(bounded.slice(bounded.indexOf('-t'), bounded.indexOf('-t') + 2)).toEqual(['-t', '600']);
expect(bounded).toContain('0:3');
expect(subtitleAssArguments('/archive/movie.mkv', 3)).not.toContain('-t');
});
it('rejects invalid stream and duration values before invoking FFmpeg', () => {
expect(() => subtitleAssArguments('/archive/movie.mkv', -1, 600)).toThrow('streamIndex');
expect(() => subtitleAssArguments('/archive/movie.mkv', 2, Number.POSITIVE_INFINITY)).toThrow('maxDurationSeconds');
expect(() => subtitleAssArguments('/archive/movie.mkv', 2, 86_401)).toThrow('maxDurationSeconds');
});
});
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"types": ["node"]
},
"include": ["src/**/*.ts"],
"exclude": ["src/**/*.test.ts"]
}