Files

130 lines
7.0 KiB
TypeScript
Raw Permalink Normal View History

import { describe, test, expect, afterAll } from 'bun:test';
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describeMedia, liveEncodePlan, prepareForWeb, probe } from '../src/web-prep.js';
import type { ProbeStream } from '../src/web-prep.js';
const hasFfmpeg = Bun.which('ffmpeg') !== null && Bun.which('ffprobe') !== null;
const dirs: string[] = [];
afterAll(async () => {
for (const d of dirs) await rm(d, { recursive: true, force: true });
});
async function ff(args: string[]): Promise<void> {
const p = Bun.spawn(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', ...args], { stderr: 'inherit' });
if ((await p.exited) !== 0) throw new Error('ffmpeg failed');
}
describe.skipIf(!hasFfmpeg)('prepareForWeb (media put --web)', () => {
test('HEVC + AC-3 5.1 + AAC + two embedded SubRip tracks → H.264/AAC MP4 and two .srt', async () => {
const dir = await mkdtemp(join(tmpdir(), 'shade-webprep-'));
dirs.push(dir);
await writeFile(join(dir, 'no.srt'), '1\n00:00:00,500 --> 00:00:01,500\nHei på deg\n');
await writeFile(join(dir, 'en.srt'), '1\n00:00:00,500 --> 00:00:01,500\nHello there\n');
const mkv = join(dir, 'Film.mkv');
await ff([
'-f', 'lavfi', '-i', 'testsrc=size=320x240:rate=25,format=yuv420p',
'-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000',
'-f', 'lavfi', '-i', 'sine=frequency=660:sample_rate=48000',
'-i', join(dir, 'no.srt'), '-i', join(dir, 'en.srt'),
'-t', '2', '-map', '0', '-map', '1', '-map', '2', '-map', '3', '-map', '4',
'-c:v', 'libx265', '-preset', 'ultrafast', '-x265-params', 'log-level=none',
'-c:a:0', 'ac3', '-ac:a:0', '6', '-c:a:1', 'aac',
'-c:s', 'srt',
'-metadata:s:a:0', 'language=eng', '-metadata:s:a:1', 'language=nor',
'-metadata:s:s:0', 'language=nor', '-metadata:s:s:0', 'title=Norsk', '-metadata:s:s:1', 'language=eng',
mkv,
]);
const work = await mkdtemp(join(tmpdir(), 'shade-webprep-out-'));
dirs.push(work);
const prep = await prepareForWeb(mkv, work);
const out = await probe(prep.file);
expect(out.filter((s) => s.codec_type === 'video').map((s) => s.codec_name)).toEqual(['h264']);
expect(out.filter((s) => s.codec_type === 'audio').map((s) => [s.codec_name, s.channels, s.tags?.language])).toEqual([
['aac', 6, 'eng'],
['aac', 1, 'nor'], // the source is mono; copied, not upmixed
]);
expect(out.some((s) => s.codec_type === 'subtitle')).toBe(false);
// Index first: playback starts without fetching the end of the file.
const head = new TextDecoder().decode((await readFile(prep.file)).subarray(0, 64 * 1024));
expect(head.indexOf('moov')).toBeGreaterThan(-1);
expect(head.indexOf('moov')).toBeLessThan(Math.max(head.indexOf('mdat'), 0) || Infinity);
expect(prep.subtitles.map((s) => [s.lang, s.title])).toEqual([['no', 'Norsk'], ['en', undefined]]);
expect(await readFile(prep.subtitles[0]!.path, 'utf8')).toContain('Hei på deg');
expect(await readFile(prep.subtitles[1]!.path, 'utf8')).toContain('Hello there');
expect(prep.notes.join('\n')).toMatch(/hevc → H\.264/);
expect(prep.notes.join('\n')).toMatch(/ac3 \(eng\) → AAC/);
}, 60_000);
test('a file browsers already play is only remuxed', async () => {
const dir = await mkdtemp(join(tmpdir(), 'shade-webprep-'));
dirs.push(dir);
const mkv = join(dir, 'Clip.mkv');
await ff(['-f', 'lavfi', '-i', 'testsrc=size=160x120:rate=25,format=yuv420p', '-f', 'lavfi', '-i', 'sine', '-t', '1', '-c:v', 'libx264', '-preset', 'ultrafast', '-c:a', 'aac', mkv]);
const work = await mkdtemp(join(tmpdir(), 'shade-webprep-out-'));
dirs.push(work);
const prep = await prepareForWeb(mkv, work);
expect(prep.notes).toEqual([]);
expect((await probe(prep.file)).map((s) => s.codec_name)).toEqual(['h264', 'aac']);
}, 30_000);
});
describe('liveEncodePlan (live video --input)', () => {
const v = (codec: string): ProbeStream => ({ index: 0, codec_type: 'video', codec_name: codec });
const a = (codec: string, channels = 2): ProbeStream => ({ index: 1, codec_type: 'audio', codec_name: codec, channels });
const after = (args: string[], flag: string) => args[args.indexOf(flag) + 1];
test("a camera's H.264/AAC is copied; RTSP goes over TCP; not paced", () => {
const p = liveEncodePlan('rtsp://cam.local/stream1', [v('h264'), a('aac')], { realtime: false });
expect(after(p.args, '-c:v')).toBe('copy');
expect(after(p.args, '-c:a')).toBe('copy');
expect(after(p.args, '-rtsp_transport')).toBe('tcp');
expect(p.args).not.toContain('-re');
expect(p.args.slice(-1)).toEqual(['pipe:1']);
expect(after(p.args, '-movflags')).toBe('frag_keyframe+empty_moov+default_base_moof');
});
test('a film in HEVC with 7.1 DTS is encoded, paced, with a keyframe every 2 s', () => {
const p = liveEncodePlan('/films/x.mkv', [v('hevc'), a('dts', 8), { index: 2, codec_type: 'subtitle', codec_name: 'subrip' }], { realtime: true });
expect(p.args).toContain('-re');
expect(after(p.args, '-c:v')).toBe('libx264');
expect(after(p.args, '-force_key_frames')).toBe('expr:gte(t,n_forced*2)');
expect(after(p.args, '-c:a')).toBe('aac');
expect(after(p.args, '-ac')).toBe('6');
expect(p.args).toContain('-sn');
expect(p.notes).toEqual(['video hevc → H.264 (a keyframe every 2 s)', 'audio dts → AAC']);
});
test('a webcam device is opened as v4l2; sound alone is fine; nothing at all is refused', () => {
expect(after(liveEncodePlan('/dev/video0', [v('mjpeg')], { realtime: false }).args, '-f')).toBe('v4l2');
const radio = liveEncodePlan('http://radio.example/stream.mp3', [a('mp3')], { realtime: false });
expect(radio.args).not.toContain('-c:v');
expect(() => liveEncodePlan('x', [], { realtime: false })).toThrow(/no audio or video/);
});
});
describe.skipIf(!hasFfmpeg)('describeMedia (the meta media put seals)', () => {
test('a film has length and size, a sound only length, a picture only size', async () => {
const dir = await mkdtemp(join(tmpdir(), 'shade-describe-'));
dirs.push(dir);
const film = join(dir, 'film.mp4');
const sound = join(dir, 'sound.ogg');
const still = join(dir, 'still.webp');
await ff(['-f', 'lavfi', '-i', 'testsrc=size=320x180:rate=25', '-t', '2.5', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', film]);
await ff(['-f', 'lavfi', '-i', 'sine=frequency=440:sample_rate=48000', '-t', '1.5', '-c:a', 'libvorbis', sound]);
await ff(['-f', 'lavfi', '-i', 'testsrc=size=64x48', '-frames:v', '1', still]);
const f = await describeMedia(film);
expect([f.width, f.height]).toEqual([320, 180]);
expect(Math.abs(f.durationMs! - 2500)).toBeLessThan(80);
const a = await describeMedia(sound);
expect(a.width).toBeUndefined();
expect(Math.abs(a.durationMs! - 1500)).toBeLessThan(80);
expect(await describeMedia(still)).toEqual({ width: 64, height: 48 });
expect(await describeMedia(join(dir, 'missing.mp4'))).toEqual({});
}, 30_000);
});