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

@@ -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');
});
});