SPB Git

Repository Public

media-compose.test.ts 25.4 KB 352 lines typescript

1import { readFile, rm, writeFile } from "node:fs/promises";2import path from "node:path";3import { afterAll, beforeAll, describe, expect, it } from "vitest";4import { FPS, FRAME_SIZES, MotionSpec, type Ratio } from "../src/lib/contracts";5import { assembleProgram, conformClip, finishMaster, programTimeline } from "../src/media/compose";6import { analyse, ff, probe } from "../src/media/ffmpeg";7import { hlsLadder, packageHls } from "../src/media/hls";8import { ingestMedia } from "../src/media/ingest";9import { renderMotion } from "../src/media/motion";10import { technicalChecks } from "../src/media/qc";11import { toVtt } from "../src/media/captions";12import { makeImage, makeTone, makeVideo, meanLuma, rmsDb, tmpDir } from "./fixtures/media";1314const T = 180_000;15let dir = "";16const f = (name: string) => path.join(dir, name);17const P = FRAME_SIZES["16:9"].preview;   // 854×480 : rapide ; les tailles finales exactes sont testées dans « finishMaster »1819beforeAll(async () => {20  dir = await tmpDir("compose");21  await makeVideo(f("src.mp4"), { width: 1280, height: 720, seconds: 12, fps: 25, audio: "sine", freq: 330 });22  await makeVideo(f("src-mute.mp4"), { width: 640, height: 480, seconds: 3, audio: "none" });23  await makeImage(f("img.jpg"));24}, T);25afterAll(async () => { if (dir && !process.env.SPCLIP_KEEP_TMP) await rm(dir, { recursive: true, force: true }); else console.log("tmp:", dir); });2627describe("ffmpeg.probe", () => {28  it("rapporte codecs, cadence, débit, canaux et fréquence d'échantillonnage", async () => {29    const p = await probe(f("src.mp4"));30    expect(p).toMatchObject({ width: 1280, height: 720, fps: 25, hasVideo: true, hasAudio: true, videoCodec: "h264", audioCodec: "aac", channels: 1, sampleRate: 48000, pixFmt: "yuv420p", isStill: false });31    expect(p.duration).toBeCloseTo(12, 1);32    expect(p.bitrate).toBeGreaterThan(10_000);33    const img = await probe(f("img.jpg"));34    expect(img).toMatchObject({ width: 2400, height: 1600, hasVideo: true, hasAudio: false, isStill: true });35  }, T);36});3738describe("conformClip", () => {39  it("vidéo : extrait, recadre, cadence constante, audio 48 kHz stéréo, titre bas d'écran", async () => {40    await conformClip({ input: f("src.mp4"), output: f("c-video.mkv"), srcIn: 2, seconds: 4, width: P.width, height: P.height, fps: FPS, sourceAudio: "duck", hasAudio: true, onScreenText: "Barrage Daniel-Johnson", language: "fr" });41    const p = await probe(f("c-video.mkv"));42    expect(p).toMatchObject({ width: P.width, height: P.height, fps: FPS, hasAudio: true, sampleRate: 48000, channels: 2, videoCodec: "h264", audioCodec: "pcm_s16le" });43    expect(p.duration).toBeCloseTo(4, 2);44    expect(p.tags?.sp_source_audio).toBe("duck");45    expect(await rmsDb(f("c-video.mkv"), 1, 2)).toBeGreaterThan(-30);46    // le titre incrusté modifie l'image : comparaison avec le même plan sans titre47    await conformClip({ input: f("src.mp4"), output: f("c-video-plain.mkv"), srcIn: 2, seconds: 4, width: P.width, height: P.height, fps: FPS, sourceAudio: "mute", hasAudio: true, language: "fr" });48    const log = await analyse(f("c-video.mkv"), ["-i", f("c-video-plain.mkv"), "-filter_complex", "[0:v][1:v]psnr", "-an"]);49    expect(Number(log.match(/average:([\d.]+)/)?.[1])).toBeLessThan(45);50    expect(await rmsDb(f("c-video-plain.mkv"), 1, 2)).toBeLessThan(-80);     // mute → silence51    expect((await probe(f("c-video-plain.mkv"))).tags?.sp_source_audio).toBe("mute");52  }, T);5354  it("vidéo sans piste audio, plus courte que demandé : image prolongée, silence", async () => {55    await conformClip({ input: f("src-mute.mp4"), output: f("c-short.mkv"), srcIn: 1, seconds: 5, width: 480, height: 854, fps: FPS, sourceAudio: "full", hasAudio: false, language: "en" });56    const p = await probe(f("c-short.mkv"));57    expect(p).toMatchObject({ width: 480, height: 854, hasAudio: true, channels: 2 });58    expect(p.duration).toBeCloseTo(5, 2);59    expect(p.tags?.sp_source_audio).toBe("mute");60  }, T);6162  it("image fixe : Ken Burns (l'image bouge) ou plan fixe", async () => {63    await conformClip({ input: f("img.jpg"), output: f("c-image.mkv"), srcIn: 0, seconds: 3, width: P.width, height: P.height, fps: FPS, sourceAudio: "mute", hasAudio: false, isImage: true, kenBurns: true, language: "fr" });64    const p = await probe(f("c-image.mkv"));65    expect(p).toMatchObject({ width: P.width, height: P.height, fps: FPS, hasAudio: true });66    expect(p.duration).toBeCloseTo(3, 2);67    const moving = async (file: string) => {68      await ff(["-ss", "0", "-i", file, "-frames:v", "1", f("a.png")]);69      await ff(["-ss", "2.9", "-i", file, "-frames:v", "1", f("b.png")]);70      const log = await analyse(f("a.png"), ["-i", f("b.png"), "-filter_complex", "[0:v][1:v]psnr"]);71      const v = log.match(/average:([\d.]+|inf)/)?.[1];72      return v === "inf" ? Infinity : Number(v);73    };74    expect(await moving(f("c-image.mkv"))).toBeLessThan(35);75    await conformClip({ input: f("img.jpg"), output: f("c-still.mkv"), srcIn: 0, seconds: 3, width: 480, height: 480, fps: FPS, sourceAudio: "mute", hasAudio: false, isImage: true, kenBurns: false, language: "fr" });76    expect(await moving(f("c-still.mkv"))).toBeGreaterThan(45);77  }, T);78});7980describe("renderMotion", () => {81  const specs: Record<string, unknown> = {82    title: { type: "title", title: "Le coût réel de l'énergie", subtitle: "Données publiques 2015–2025" },83    bullets: { type: "bullets", heading: "À retenir", items: ["Premier point", "Deuxième point, un peu plus long que le premier", "Troisième point"] },84    counter: { type: "counter", label: "Clients raccordés", to: 4381250 },85    bar_chart: { type: "bar_chart", title: "Production par source", unit: "%", bars: [{ label: "Hydraulique", value: 94.1 }, { label: "Éolien", value: 4.6 }, { label: "Autres", value: -1.3 }], sourceNote: "Hydro-Québec, 2024" },86    line_chart: { type: "line_chart", title: "Prix moyen", unit: "¢/kWh", points: Array.from({ length: 12 }, (_, i) => ({ x: String(2014 + i), y: 6 + Math.sin(i) + i * 0.2 })), sourceNote: "Régie de l'énergie" },87    timeline: { type: "timeline", title: "Jalons", events: [{ date: "1944", label: "Création" }, { date: "1963", label: "Nationalisation" }, { date: "1998", label: "Crise du verglas" }] },88    quote: { type: "quote", text: "L'énergie la moins chère est celle que l'on ne consomme pas.", attribution: "Adage" },89  };90  const cases: [string, Ratio, "sobre" | "modere" | "dynamique", "fr" | "en"][] = [];91  for (const [i, type] of Object.keys(specs).entries()) for (const ratio of ["16:9", "9:16", "1:1"] as Ratio[]) {92    if (ratio === "1:1" && i % 2) continue;93    cases.push([type, ratio, (["sobre", "modere", "dynamique"] as const)[(i + cases.length) % 3], i % 2 ? "en" : "fr"]);94  }95  it.each(cases)("%s en %s (%s, %s)", async (type, ratio, intensity, language) => {96    const size = FRAME_SIZES[ratio].preview;97    const out = f(`motion-${type}-${ratio.replace(":", "x")}.mkv`);98    await renderMotion(MotionSpec.parse(specs[type]), { ...size, seconds: 2.5, fps: FPS, language, intensity, output: out });99    const p = await probe(out);100    expect(p).toMatchObject({ width: size.width, height: size.height, fps: FPS, hasAudio: true, sampleRate: 48000, channels: 2 });101    expect(p.duration).toBeCloseTo(2.5, 2);102    // fond sombre de marque, et du contenu dessiné : la dernière image diffère de la première103    expect(await meanLuma(out, 0)).toBeLessThan(40);104    const [a, b] = [await meanLuma(out, 0), await meanLuma(out, 2.4)];105    expect(b - a).toBeGreaterThan(0.3);106    expect(b).toBeLessThan(90);107  }, T);108});109110describe("assembleProgram", () => {111  it("programTimeline : seul le fondu enchaîné raccourcit le programme", () => {112    const tl = programTimeline([{ seconds: 4, transition: "fade" }, { seconds: 3, transition: "dissolve" }, { seconds: 3, transition: "cut" }, { seconds: 1, transition: "dissolve" }], 30);113    expect(tl.overlaps).toEqual([0, 0.5, 0, 0.4]);114    expect(tl.starts).toEqual([0, 3.5, 6.5, 9.1]);115    expect(tl.seconds).toBeCloseTo(10.1, 6);116    expect(tl.mapTime(4.2)).toBeCloseTo(3.7, 6);117    expect(tl.mapTime(7)).toBeCloseTo(6.5, 6);118  });119120  it("enchaîne coupes, fondus et fondus enchaînés ; narration présente à la position remappée ; musique atténuée sous la voix", async () => {121    await conformClip({ input: f("src.mp4"), output: f("s1.mkv"), srcIn: 0, seconds: 4, width: P.width, height: P.height, fps: FPS, sourceAudio: "mute", hasAudio: true, language: "fr" });122    await conformClip({ input: f("img.jpg"), output: f("s2.mkv"), srcIn: 0, seconds: 3, width: P.width, height: P.height, fps: FPS, sourceAudio: "mute", hasAudio: false, isImage: true, language: "fr" });123    await renderMotion(MotionSpec.parse({ type: "title", title: "Titre" }), { ...P, seconds: 3, fps: FPS, language: "fr", intensity: "sobre", output: f("s3.mkv") });124    await conformClip({ input: f("src.mp4"), output: f("s4.mkv"), srcIn: 6, seconds: 3, width: P.width, height: P.height, fps: FPS, sourceAudio: "mute", hasAudio: true, language: "fr" });125    // la source lavfi `sine` sort à −18 dBFS : on remonte la voix à ≈ −6 dBFS et la musique à ≈ −2 dBFS126    await makeTone(f("narr.wav"), { seconds: 2, freq: 880, volume: 4 });127    await makeTone(f("music.wav"), { seconds: 5, freq: 110, volume: 6 });128    const scenes = [129      { file: f("s1.mkv"), seconds: 4, transition: "fade" as const },130      { file: f("s2.mkv"), seconds: 3, transition: "dissolve" as const },131      { file: f("s3.mkv"), seconds: 3, transition: "cut" as const },132      { file: f("s4.mkv"), seconds: 3, transition: "dissolve" as const },133    ];134    // voix prévue 0,5 s après le début NOMINAL de la scène 3 (4 + 3 + 0,5 = 7,5 s) → réel 7,0 s (un fondu enchaîné de 0,5 s avant elle)135    const r = await assembleProgram({ scenes, narration: [{ file: f("narr.wav"), at: 7.5 }], music: { file: f("music.wav") }, output: f("program.mkv"), workDir: f("work") });136    expect(r.seconds).toBeCloseTo(12, 1);                         // 13 s nominales − 2 × 0,5 s137    expect(r.narrationAt[0]).toBeCloseTo(7, 3);138    expect(r.sceneStarts).toEqual([0, 3.5, 6.5, 9]);139    const p = await probe(f("program.mkv"));140    expect(p).toMatchObject({ width: P.width, height: P.height, fps: FPS, sampleRate: 48000, channels: 2 });141    expect(p.duration).toBeCloseTo(12, 1);142    // ouverture au noir, puis image143    expect(await meanLuma(f("program.mkv"), 0)).toBeLessThan(8);144    expect(await meanLuma(f("program.mkv"), 1)).toBeGreaterThan(40);145    // la narration (880 Hz) est là où on l'attend, absente ailleurs146    const band = async (start: number) => {147      const log = await analyse(f("program.mkv"), ["-vn", "-af", `atrim=start=${start}:duration=1,bandpass=f=880:width_type=h:w=100,astats=measure_perchannel=none:measure_overall=RMS_level`]);148      const v = log.match(/RMS level dB:\s*(-?[\d.]+|-inf)/)?.[1];149      return v === "-inf" || v === undefined ? -200 : Number(v);150    };151    expect(await band(7.5)).toBeGreaterThan(-25);152    expect(await band(4)).toBeLessThan(-50);153    expect(await band(10.5)).toBeLessThan(-50);154    // ducking : la musique (110 Hz) est plus faible sous la voix qu'avant elle155    const low = async (start: number) => {156      const log = await analyse(f("program.mkv"), ["-vn", "-af", `atrim=start=${start}:duration=1,lowpass=f=200,lowpass=f=200,astats=measure_perchannel=none:measure_overall=RMS_level`]);157      return Number(log.match(/RMS level dB:\s*(-?[\d.]+)/)?.[1]);158    };159    const [before, under] = [await low(4.5), await low(7.6)];160    expect(before - under).toBeGreaterThan(6);161    // pas d'écrêtage162    const peak = await analyse(f("program.mkv"), ["-vn", "-af", "astats=measure_perchannel=none:measure_overall=Peak_level"]);163    expect(Number(peak.match(/Peak level dB:\s*(-?[\d.]+)/)?.[1])).toBeLessThanOrEqual(-0.9);164  }, T);165166  it("sans narration ni musique : coupes franches, durée = somme", async () => {167    const r = await assembleProgram({ scenes: [{ file: f("s1.mkv"), seconds: 4, transition: "cut" }, { file: f("s3.mkv"), seconds: 3, transition: "cut" }], narration: [], output: f("program-cut.mkv"), workDir: f("work2") });168    expect(r.seconds).toBeCloseTo(7, 1);169    expect((await probe(f("program-cut.mkv"))).hasAudio).toBe(true);170  }, T);171});172173describe("finishMaster", () => {174  it.each(["16:9", "9:16", "1:1"] as Ratio[])("master %s : durée = programme + carton, résolution exacte, H.264 High + AAC 48 kHz, sonie −14 LUFS", async (ratio) => {175    const size = FRAME_SIZES[ratio].final;176    const tag = ratio.replace(":", "x");177    await makeVideo(f(`prog-${tag}.mkv`), { width: size.width, height: size.height, seconds: 5, audio: "sine" });178    const r = await finishMaster({ program: f(`prog-${tag}.mkv`), output: f(`master-${tag}.mp4`), ...size, fps: FPS, ratio, language: "fr", endCard: { seconds: 2.5, tagline: "Essai" }, metadata: { title: "Titre d'essai" }, workDir: f(`fm-${tag}`) });179    const p = await probe(f(`master-${tag}.mp4`));180    expect(r.seconds).toBeCloseTo(7.5, 1);181    expect(p.duration).toBeCloseTo(7.5, 1);182    expect(p).toMatchObject({ width: size.width, height: size.height, fps: FPS, videoCodec: "h264", videoProfile: "High", pixFmt: "yuv420p", audioCodec: "aac", sampleRate: 48000, channels: 2 });183    expect(p.tags).toMatchObject({ title: "Titre d'essai", comment: "clip.spboucher.ai" });184    expect(r.watermark).toMatchObject({ text: "clip.spboucher.ai", ratio, endCardStart: 5, endCardSeconds: 2.5 });185    // +faststart : l'atome moov précède mdat186    const head = (await readFile(f(`master-${tag}.mp4`))).subarray(0, 4096).toString("latin1");187    expect(head.includes("moov")).toBe(true);188    // le carton de fin est bien là (fond sombre de marque) et le programme avant lui189    expect(await meanLuma(f(`master-${tag}.mp4`), 7)).toBeLessThan(45);190    expect(await meanLuma(f(`master-${tag}.mp4`), 2)).toBeGreaterThan(60);191    const log = await analyse(f(`master-${tag}.mp4`), ["-vn", "-af", "ebur128=peak=true"]);192    const s = log.slice(log.lastIndexOf("Summary:"));193    expect(Number(s.match(/I:\s*(-?[\d.]+)/)?.[1])).toBeGreaterThan(-15.5);194    expect(Number(s.match(/I:\s*(-?[\d.]+)/)?.[1])).toBeLessThan(-12.5);195    expect(Number(s.match(/Peak:\s*(-?[\d.]+)/)?.[1])).toBeLessThanOrEqual(-1);196  }, T);197198  it("aperçu : programme recadré vers la taille d'aperçu, plus léger ; sous-titres incrustés ; programme sans audio accepté", async () => {199    const size = FRAME_SIZES["16:9"];200    const r = await finishMaster({ program: f("prog-16x9.mkv"), output: f("preview.mp4"), ...size.preview, fps: FPS, ratio: "16:9", language: "en", endCard: { seconds: 2, tagline: "" }, preview: true, metadata: {}, workDir: f("fm-prev"),201      burnCaptions: [{ start: 1, end: 3, text: "Sous-titre incrusté\nsur deux lignes" }] });202    const p = await probe(f("preview.mp4"));203    expect(p).toMatchObject({ width: 854, height: 480 });204    expect(r.seconds).toBeCloseTo(7, 1);205    expect(r.watermark).toMatchObject({ preview: true, burnedCaptions: 1 });206    expect(p.size).toBeLessThan((await probe(f("master-16x9.mp4"))).size!);207    // la zone des sous-titres diffère du même aperçu sans sous-titres pendant la réplique (1–3 s), pas après208    await finishMaster({ program: f("prog-16x9.mkv"), output: f("preview-plain.mp4"), ...size.preview, fps: FPS, ratio: "16:9", language: "en", endCard: { seconds: 2, tagline: "" }, preview: true, metadata: {}, workDir: f("fm-prev2") });209    const bandDiff = async (at: number) => {210      const { runBinary } = await import("../src/media/ffmpeg");211      const grab = (file: string) => runBinary("ffmpeg", ["-v", "error", "-ss", String(at), "-i", file, "-frames:v", "1", "-vf", "crop=300:50:277:396,format=gray", "-f", "rawvideo", "-"]);212      const [a, b] = [await grab(f("preview.mp4")), await grab(f("preview-plain.mp4"))];213      let d = 0;214      for (let i = 0; i < a.length; i++) d += Math.abs(a[i] - b[i]);215      return d / a.length;216    };217    expect(await bandDiff(2)).toBeGreaterThan(25);218    expect(await bandDiff(4)).toBeLessThan(3);219    await makeVideo(f("prog-noaudio.mkv"), { width: 480, height: 480, seconds: 3, audio: "none" });220    const q = await finishMaster({ program: f("prog-noaudio.mkv"), output: f("noaudio.mp4"), ...FRAME_SIZES["1:1"].preview, fps: FPS, ratio: "1:1", language: "fr", endCard: { seconds: 2, tagline: "" }, preview: true, metadata: {}, workDir: f("fm-na") });221    expect(q.seconds).toBeCloseTo(5, 1);222    expect((await probe(f("noaudio.mp4"))).hasAudio).toBe(true);223  }, T);224});225226describe("packageHls", () => {227  it("échelle sans sur-échantillonnage", () => {228    expect(hlsLadder(1920, 1080).map((r) => `${r.width}x${r.height}`)).toEqual(["1920x1080", "1280x720", "854x480", "640x360"]);229    expect(hlsLadder(1080, 1920).map((r) => `${r.width}x${r.height}`)).toEqual(["1080x1920", "720x1280", "480x854", "360x640"]);230    expect(hlsLadder(1080, 1080).map((r) => r.height)).toEqual([1080, 720, 480, 360]);231    expect(hlsLadder(854, 480).map((r) => `${r.width}x${r.height}`)).toEqual(["854x480", "640x360"]);232    expect(hlsLadder(320, 240).map((r) => r.height)).toEqual([240]);233  });234235  it("master + variantes lisibles par ffprobe, segments de 4 s alignés sur les images clés, piste WebVTT référencée", async () => {236    const vtt = toVtt([{ start: 0.5, end: 2.5, text: "Bonjour" }, { start: 5, end: 7, text: "Carton" }]);237    const r = await packageHls({ input: f("master-16x9.mp4"), outDir: f("hls"), sourceHeight: 1080, captionsVtt: vtt, language: "fr" });238    expect(r.renditions.map((x) => x.height)).toEqual([1080, 720, 480, 360]);239    expect(r.renditions.every((x) => x.bitrate > 0)).toBe(true);240    const master = await readFile(r.master, "utf8");241    expect(master).toContain('#EXT-X-MEDIA:TYPE=SUBTITLES,GROUP-ID="subs",NAME="Français",LANGUAGE="fr"');242    expect(master.match(/#EXT-X-STREAM-INF:[^\n]*SUBTITLES="subs"/g)).toHaveLength(4);243    expect(master).toContain("RESOLUTION=640x360");244    expect(master).toMatch(/CODECS="avc1\.640028,mp4a\.40\.2"/);       // 1080p30 High → niveau 4.0245    expect(await readFile(f("hls/subs/captions.vtt"), "utf8")).toMatch(/^WEBVTT\nX-TIMESTAMP-MAP=MPEGTS:0,LOCAL:00:00:00\.000\n\n1\n00:00:00\.500 --> /);246    expect(await readFile(f("hls/subs/index.m3u8"), "utf8")).toContain("captions.vtt");247    const mp = await probe(r.master);248    expect(mp.hasVideo && mp.hasAudio).toBe(true);249    expect(mp.duration).toBeCloseTo(7.5, 0);250    for (const x of r.renditions) {251      const p = await probe(path.join(f("hls"), x.uri!));252      expect(p).toMatchObject({ height: x.height, width: x.width, videoCodec: "h264", audioCodec: "aac" });253      expect(p.duration).toBeCloseTo(7.5, 0);254      const pl = await readFile(path.join(f("hls"), x.uri!), "utf8");255      expect([...pl.matchAll(/#EXTINF:([\d.]+)/g)].map((m) => Number(m[1]))).toEqual([4, 3.5]);256      expect(pl).toContain('#EXT-X-MAP:URI="init.mp4"');257      expect(pl).toContain("#EXT-X-ENDLIST");258    }259  }, T);260});261262describe("technicalChecks", () => {263  const by = (checks: Awaited<ReturnType<typeof technicalChecks>>) => Object.fromEntries(checks.map((c) => [c.key, c]));264265  it("master conforme : tout est mesuré et passe", async () => {266    const c = by(await technicalChecks({ file: f("master-16x9.mp4"), expected: { width: 1920, height: 1080, minSeconds: 7, maxSeconds: 8 }, narrationWindows: [{ start: 1, end: 4 }] }));267    expect(Object.keys(c).sort()).toEqual(["black_frames", "clipping", "decodable", "duration", "loudness", "resolution", "silence"]);268    expect(c.decodable).toMatchObject({ status: "pass", blocking: true });269    expect(c.decodable.measured.decodedFrames).toBe(225);270    expect(c.duration).toMatchObject({ status: "pass", blocking: true });271    expect(c.resolution).toMatchObject({ status: "pass", blocking: true, measured: { width: 1920, height: 1080 } });272    expect(c.black_frames).toMatchObject({ status: "pass", blocking: false });       // le carton de fin (fond #0b0c0f) n'est pas compté comme noir273    expect(c.silence.status).toBe("pass");                                           // carton muet de 2,5 s : toléré274    expect(c.clipping.status).toBe("pass");275    expect(c.loudness.status).toBe("pass");276    expect(c.loudness.measured.integratedLufs as number).toBeGreaterThan(-15);277  }, T);278279  it("échecs bloquants : résolution et durée inattendues, fichier illisible", async () => {280    const c = by(await technicalChecks({ file: f("master-16x9.mp4"), expected: { width: 1080, height: 1920, minSeconds: 20, maxSeconds: 30 }, narrationWindows: [] }));281    expect(c.resolution).toMatchObject({ status: "fail", blocking: true });282    expect(c.duration).toMatchObject({ status: "fail", blocking: true });283    await writeFile(f("garbage.mp4"), "ceci n'est pas une vidéo");284    const g = by(await technicalChecks({ file: f("garbage.mp4"), expected: { width: 1920, height: 1080, minSeconds: 1, maxSeconds: 2 }, narrationWindows: [] }));285    expect(g.decodable).toMatchObject({ status: "fail", blocking: true });286    expect(g.resolution.status).toBe("not_measured");287    // fichier tronqué au milieu : le décodage complet échoue ou signale des erreurs288    const full = await readFile(f("src.mp4"));289    const broken = Buffer.from(full);290    broken.fill(0x55, Math.floor(full.length * 0.4), Math.floor(full.length * 0.7));291    await writeFile(f("broken.mp4"), broken);292    const b = by(await technicalChecks({ file: f("broken.mp4"), expected: { width: 1280, height: 720, minSeconds: 1, maxSeconds: 20 }, narrationWindows: [] }));293    expect(b.decodable.status).toBe("fail");294  }, T);295296  it("détecte une vidéo noire et un long silence", async () => {297    await makeVideo(f("black.mp4"), { source: "color=c=black", width: 640, height: 360, seconds: 8, audio: "silence" });298    const c = by(await technicalChecks({ file: f("black.mp4"), expected: { width: 640, height: 360, minSeconds: 7, maxSeconds: 9 }, narrationWindows: [] }));299    expect(c.decodable.status).toBe("pass");300    expect(c.black_frames.status).toBe("fail");301    expect(c.black_frames.measured.totalSeconds as number).toBeGreaterThan(7.5);302    expect(c.silence.status).toBe("warn");303    expect(c.silence.measured.longestOutsideNarrationSeconds as number).toBeGreaterThan(7.5);304    expect(c.loudness.status).toBe("warn");305    expect(c.loudness.measured).toMatchObject({ silent: true });306  }, T);307308  it("voix absente dans une fenêtre de narration → échec ; silence partiel et noir partiel → avertissements mesurés", async () => {309    // 0–4 s : image + son ; 4–10 s : noir + silence310    await ff(["-f", "lavfi", "-i", "testsrc2=s=640x360:r=30:d=4", "-f", "lavfi", "-i", "color=c=black:s=640x360:r=30:d=6", "-f", "lavfi", "-i", "sine=f=440:r=48000:d=4", "-f", "lavfi", "-i", "anullsrc=r=48000:cl=mono:d=6",311      "-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0[v];[2:a][3:a]concat=n=2:v=0:a=1[a]", "-map", "[v]", "-map", "[a]", "-t", "10", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-c:a", "aac", f("half.mp4")]);312    const c = by(await technicalChecks({ file: f("half.mp4"), expected: { width: 640, height: 360, minSeconds: 9, maxSeconds: 11 }, narrationWindows: [{ start: 0.5, end: 3.5 }, { start: 5, end: 9 }] }));313    expect(c.silence.status).toBe("fail");314    expect(c.silence.measured.insideNarrationSeconds as number).toBeGreaterThan(3.5);315    const ok = by(await technicalChecks({ file: f("half.mp4"), expected: { width: 640, height: 360, minSeconds: 9, maxSeconds: 11 }, narrationWindows: [{ start: 0.5, end: 3.5 }] }));316    expect(ok.silence.status).toBe("warn");317    expect(ok.silence.measured.longestOutsideNarrationSeconds as number).toBeCloseTo(6, 0);318    expect(ok.black_frames.status).toBe("fail");                 // 60 % de la durée en noir319    expect(ok.black_frames.measured.totalSeconds as number).toBeCloseTo(6, 0);320  }, T);321});322323describe("ingestMedia", () => {324  it("vidéo : sonde, proxy H.264 540p, miniature JPEG", async () => {325    const r = await ingestMedia({ file: f("src.mp4"), kind: "video", workDir: f("ing-v") });326    expect(r.probe).toMatchObject({ width: 1280, height: 720, videoCodec: "h264" });327    expect(await probe(r.proxy!)).toMatchObject({ width: 960, height: 540, videoCodec: "h264", audioCodec: "aac" });328    expect(await probe(r.thumb!)).toMatchObject({ width: 640, height: 360, videoCodec: "mjpeg" });329  }, T);330331  it("image et audio : miniature pour l'image, rien à fabriquer pour l'audio", async () => {332    const img = await ingestMedia({ file: f("img.jpg"), kind: "image", workDir: f("ing-i") });333    expect(img.proxy).toBeUndefined();334    expect(await probe(img.thumb!)).toMatchObject({ width: 540, height: 360 });335    await makeTone(f("tone.wav"), { seconds: 2 });336    const a = await ingestMedia({ file: f("tone.wav"), kind: "music", workDir: f("ing-a") });337    expect(a.probe).toMatchObject({ hasAudio: true, hasVideo: false, sampleRate: 48000 });338    expect(a.thumb).toBeUndefined();339  }, T);340341  it("rejette ce qui n'est pas un média décodable du type annoncé", async () => {342    await writeFile(f("fake.mp4"), "<html>pas une vidéo</html>");343    await expect(ingestMedia({ file: f("fake.mp4"), kind: "video", workDir: f("ing-x") })).rejects.toThrow(/illisible|refusé/i);344    await expect(ingestMedia({ file: f("img.jpg"), kind: "video", workDir: f("ing-x") })).rejects.toThrow(/refusé/i);345    await expect(ingestMedia({ file: f("src.mp4"), kind: "image", workDir: f("ing-x") })).rejects.toThrow(/refusé/i);346    await expect(ingestMedia({ file: f("src.mp4"), kind: "audio", workDir: f("ing-x") })).rejects.toThrow(/refusé/i);347    await expect(ingestMedia({ file: f("src-mute.mp4"), kind: "music", workDir: f("ing-x") })).rejects.toThrow(/refusé/i);348    await expect(ingestMedia({ file: f("tone.wav"), kind: "video", workDir: f("ing-x") })).rejects.toThrow(/refusé/i);349    await expect(ingestMedia({ file: f("absent.mov"), kind: "video", workDir: f("ing-x") })).rejects.toThrow(/illisible/i);350  }, T);351});352
Files main
Menu

Theme