SPB Git

Repository Public

audio.ts 12.2 KB 182 lines typescript

1import { rm } from "node:fs/promises";2import { rng } from "./canvas";3import { ff, run } from "./ffmpeg";45/**6 * SON ORIGINAL de SP CLIP — tout est SYNTHÉTISÉ par FFmpeg (lavfi `aevalsrc` : sommes de sinus avec enveloppes ; `anoisesrc` filtré7 * pour les souffles), à partir des formules de ce fichier : aucune boucle, aucun échantillon ni enregistrement tiers. Les fichiers8 * produits appartiennent donc entièrement à l'opérateur (aucune licence à acquitter, aucune attribution).9 *10 *  - `renderMusicBed` : nappe musicale (accords tenus, basse, arpège discret, pulsation légère en « dynamique »), conçue pour passer11 *    SOUS une voix : registre médium dégagé (peu d'énergie entre 1 et 4 kHz), pas de mélodie qui attire l'oreille, niveau constant.12 *  - `renderSfx` : petits effets (souffle de transition, tic d'apparition).13 *  - `renderSting` : signature sonore du carton de fin.14 * Déterminisme : mêmes paramètres (et même `seed`) → même fichier, à l'échantillon près pour une version donnée de FFmpeg.15 */1617export type MusicMood = "calme" | "neutre" | "dynamique";1819const SR = 48000;20const hz = (midi: number) => 440 * 2 ** ((midi - 69) / 12);21const n4 = (x: number) => x.toFixed(4);2223/** Accords (demi-tons autour de la tonique T) : voix serrées, conduite de voix minimale → enchaînements sans heurt, aucune dissonance dure. */24const CHORDS: Record<string, { notes: number[]; bass: number }> = {25  I: { notes: [0, 4, 7, 14], bass: -24 },        // majeur + 9e26  V: { notes: [-1, 2, 7, 14], bass: -17 },       // dominante, premier renversement27  vi: { notes: [0, 4, 9, 16], bass: -15 },       // relatif mineur 728  IV: { notes: [0, 5, 9, 16], bass: -19 },       // sous-dominante maj729  Vs: { notes: [0, 2, 7, 14], bass: -17 },       // dominante suspendue (résolution douce)30  iii: { notes: [-1, 4, 7, 11], bass: -20 },     // médiante mineure 731};32const PROGRESSIONS: string[][] = [33  ["I", "V", "vi", "IV", "I", "iii", "IV", "Vs"],34  ["vi", "IV", "I", "V", "vi", "IV", "I", "Vs"],35  ["IV", "I", "vi", "Vs", "IV", "I", "iii", "Vs"],36  ["I", "vi", "IV", "Vs", "I", "iii", "IV", "V"],37];38const MOODS: Record<MusicMood, { bpm: number; beatsPerChord: number; arpDiv: number; arpGain: number; padGain: number; bassGain: number; kick: number; lowpass: number; attack: number }> = {39  calme: { bpm: 60, beatsPerChord: 8, arpDiv: 0.5, arpGain: 0.085, padGain: 0.105, bassGain: 0.085, kick: 0, lowpass: 3600, attack: 1.3 },40  neutre: { bpm: 84, beatsPerChord: 8, arpDiv: 1, arpGain: 0.115, padGain: 0.095, bassGain: 0.085, kick: 0, lowpass: 4600, attack: 0.9 },41  dynamique: { bpm: 108, beatsPerChord: 8, arpDiv: 2, arpGain: 0.125, padGain: 0.085, bassGain: 0.08, kick: 0.13, lowpass: 5600, attack: 0.6 },42};4344/** Expression `aevalsrc` (un canal) de la boucle musicale. `side` = ±1 : léger désaccord opposé par canal (largeur stéréo). */45function bedExpression(o: { mood: MusicMood; seed: number; side: 1 | -1 }): { expr: string; period: number; beat: number } {46  const m = MOODS[o.mood];47  const r = rng(0xbed0 + o.seed * 977);48  const tonic = [57, 58, 60, 62, 55][Math.floor(r() * 5)];                 // la, si bémol, do, ré, sol49  const prog = PROGRESSIONS[Math.floor(r() * PROGRESSIONS.length)];50  const patterns = [[0, 2, 1, 3], [0, 1, 2, 3], [3, 1, 2, 0], [0, 2, 3, 1]];51  const pattern = patterns[Math.floor(r() * patterns.length)];52  const beat = Math.round((60 / m.bpm) * SR) / SR;53  const C = beat * m.beatsPerChord, n = prog.length, P = C * n;54  const A = Math.min(m.attack, C * 0.45);55  const det = 1 + o.side * 0.0016;56  const step = beat / m.arpDiv;57  const parts: string[] = [`st(0,mod(t,${P.toFixed(6)}))*0`];58  prog.forEach((name, k) => {59    const ch = CHORDS[name];60    const tau = `ld(${k + 1})`;61    // fenêtre de l'accord : montée et descente en cosinus qui se croisent avec les voisins (somme constante)62    const win = `if(lt(${tau},${n4(A)}),0.5-0.5*cos(PI*${tau}/${n4(A)}),if(lt(${tau},${n4(C)}),1,0.5+0.5*cos(PI*(${tau}-${n4(C)})/${n4(A)})))`;63    const pad = ch.notes.map((s, i) => {64      const f = hz(tonic + s) * (i % 2 ? det : 2 - det);65      // LFO lent par voix (fréquence multiple de 1/P : la boucle se referme sans saut)66      const lfo = `(0.82+0.18*sin(2*PI*${n4((2 + i) / P)}*ld(0)+${n4(i * 1.7 + k)}))`;67      return `${lfo}*(sin(2*PI*${n4(f)}*${tau})+0.36*sin(2*PI*${n4(2 * f)}*${tau})+0.15*sin(2*PI*${n4(3 * f)}*${tau})+0.07*sin(2*PI*${n4(4 * f)}*${tau}))`;68    }).join("+");69    const fb = hz(tonic + ch.bass + (tonic + ch.bass < 33 ? 12 : 0));70    const bass = `${n4(m.bassGain)}*(sin(2*PI*${n4(fb)}*${tau})+0.6*sin(2*PI*${n4(2 * fb)}*${tau})+0.2*sin(2*PI*${n4(3 * fb)}*${tau}))`;71    let layer = `${win}*(${n4(m.padGain)}*(${pad})+${bass})`;72    if (m.arpGain > 0) {73      // arpège : notes de l'accord (une octave au-dessus), attaque douce, décroissance exponentielle ; le motif s'inverse au second passage74      const order = k >= n / 2 ? [...pattern].reverse() : pattern;75      const j = `floor(${tau}/${n4(step)})`;76      const uu = `(${tau}-${j}*${n4(step)})`;77      const freq = order.map((idx, q) => `eq(mod(${j},4),${q})*${n4(hz(tonic + ch.notes[idx] + 12) * (o.side > 0 ? 1.0007 : 0.9993))}`).join("+");78      const pan = o.side > 0 ? `(0.7+0.3*eq(mod(${j},2),0))` : `(0.7+0.3*eq(mod(${j},2),1))`;79      layer += `+lt(${tau},${n4(C)})*${n4(m.arpGain)}*${pan}*(sin(2*PI*(${freq})*${uu})+0.3*sin(4*PI*(${freq})*${uu})*exp(-${n4(3 / step)}*${uu}))*exp(-${n4(3.2 / step)}*${uu})*(1-exp(-260*${uu}))`;80    }81    parts.push(`st(${k + 1},mod(ld(0)-${n4(k * C)}+${P.toFixed(6)},${P.toFixed(6)}))*0+if(lt(${tau},${n4(C + A)}),${layer},0)`);82  });83  if (m.kick > 0) {84    // pulsation : battement grave très doux sur chaque temps (sinus dont la hauteur chute), accent sur le premier temps de chaque accord85    const ub = `mod(ld(0),${n4(beat)})`;86    parts.push(`${n4(m.kick)}*(0.7+0.3*lt(mod(ld(0),${n4(C)}),${n4(beat)}))*sin(2*PI*(46*${ub}+1.6*(1-exp(-24*${ub}))))*exp(-7.5*${ub})*(1-exp(-400*${ub}))`);87  }88  return { expr: parts.join("+"), period: P, beat };89}9091async function integratedLufs(file: string): Promise<number> {92  const { stderr } = await run("ffmpeg", ["-hide_banner", "-nostdin", "-i", file, "-af", "ebur128", "-f", "null", "-"], 600_000);93  const s = stderr.slice(stderr.lastIndexOf("Summary:"));94  return Number(s.match(/I:\s*(-?[\d.]+)\s*LUFS/)?.[1] ?? NaN);95}9697/** Niveau de sortie de la nappe : −20 LUFS intégrés (cohérent d'une ambiance et d'une graine à l'autre), crêtes sous −3 dBFS. */98export const MUSIC_BED_LUFS = -20;99100/**101 * Synthétise une nappe musicale ORIGINALE (WAV PCM 16 bits, 48 kHz stéréo) de `seconds` secondes.102 *  - `calme`     : 60 bpm, accords de 8 s, arpège rare et lointain ;103 *  - `neutre`    : 84 bpm, arpège à la noire ;104 *  - `dynamique` : 108 bpm, arpège à la croche, pulsation grave douce sur chaque temps.105 * Huit accords diatoniques par boucle (tonalité, progression et motif d'arpège tirés de `seed`), écho + réverbération légère, filtre106 * passe-bas, fondus d'entrée (1,5 s) et de sortie (3 s), niveau normalisé à `MUSIC_BED_LUFS`.107 */108export async function renderMusicBed(o: { seconds: number; mood: MusicMood; output: string; seed?: number;109  /** Instants (s) des changements de scène et temps forts : la nappe y fait une légère enflure (elle suit le montage). */110  accents?: number[] }): Promise<void> {111  if (!(o.seconds > 0)) throw new Error("renderMusicBed : durée invalide");112  const mood: MusicMood = o.mood in MOODS ? o.mood : "neutre";113  const m = MOODS[mood];114  const seed = Math.floor(o.seed ?? 1);115  const L = bedExpression({ mood, seed, side: 1 }), R = bedExpression({ mood, seed, side: -1 });116  const P = L.period;117  const raw = `${o.output}.raw.wav`;118  const gen = Math.min(o.seconds + 0.5, P);119  // boucle : on ne synthétise qu'une période (périodique par construction), FFmpeg la répète ; échos et fondus sont appliqués APRÈS120  const loop = o.seconds + 0.5 > P ? `aloop=loop=-1:size=${Math.round(P * SR)},` : "";121  const fin = Math.min(1.5, o.seconds / 4), fout = Math.min(3, o.seconds / 3);122  const d1 = Math.round(L.beat * 750), d2 = Math.round(L.beat * 1500);      // échos calés sur le tempo (croche pointée, blanche pointée)123  const chain = `${loop}atrim=duration=${(o.seconds + 0.2).toFixed(4)},highpass=f=45,lowpass=f=${m.lowpass},aecho=0.85:0.8:${d1}|${d2}:0.26|0.16,aecho=0.9:0.7:47|83|131|197:0.22|0.18|0.14|0.1,atrim=duration=${o.seconds.toFixed(4)},` +124    `afade=t=in:st=0:d=${fin.toFixed(3)},afade=t=out:st=${(o.seconds - fout).toFixed(3)}:d=${fout.toFixed(3)}`;125  // Enflures : +2,3 dB en cloche (≈ 0,9 s) centrée 0,15 s après chaque accent — sensible sans être un effet.126  const acc = (o.accents ?? []).filter((t) => t > 0.8 && t < o.seconds - 1).slice(0, 60);127  const swell = acc.length ? `,volume='1+0.3*(${acc.map((t) => `exp(-pow((t-${(t + 0.15).toFixed(2)})/0.45\\,2))`).join("+")})':eval=frame` : "";128  try {129    await ff(["-f", "lavfi", "-i", `aevalsrc='${L.expr}|${R.expr}':s=${SR}:d=${gen.toFixed(4)}`, "-af", chain + swell, "-c:a", "pcm_s24le", "-ar", String(SR), "-ac", "2", raw], 900_000);130    const lufs = await integratedLufs(raw);131    const gain = Number.isFinite(lufs) ? MUSIC_BED_LUFS - lufs : 0;132    await ff(["-i", raw, "-af", `volume=${gain.toFixed(2)}dB,alimiter=limit=0.7:attack=5:release=80:level=false`, "-c:a", "pcm_s16le", "-ar", String(SR), "-ac", "2", o.output]);133  } finally {134    await rm(raw, { force: true });135  }136}137138export type SfxKind = "whoosh" | "tick";139140/**141 * Petit effet sonore original (WAV 48 kHz stéréo).142 *  - `whoosh` (≈ 0,7 s) : souffle de transition — trois bandes de bruit rose dont les enveloppes se succèdent (grave → aigu), ce qui143 *    donne l'impression d'un balayage ; point fort à 0,34 s (à caler sur la coupe) ;144 *  - `tick` (≈ 0,18 s) : tic d'apparition, deux partiels très brefs.145 */146export async function renderSfx(o: { kind: SfxKind; output: string; seed?: number }): Promise<void> {147  const seed = Math.floor(o.seed ?? 1);148  if (o.kind === "tick") {149    const e = "exp(-t*42)*(1-exp(-t*2500))";150    await ff(["-f", "lavfi", "-i", `aevalsrc='0.22*${e}*(sin(2*PI*1320*t)+0.5*sin(2*PI*1980*t))|0.22*${e}*(sin(2*PI*1324*t)+0.5*sin(2*PI*1975*t))':s=${SR}:d=0.18`,151      "-af", "afade=t=out:st=0.12:d=0.06", "-c:a", "pcm_s16le", "-ar", String(SR), "-ac", "2", o.output]);152    return;153  }154  const band = (i: number, f: number, at: number, w: number, g: number) => `[n${i}]bandpass=f=${f}:width_type=q:w=0.9,volume='${g}*exp(-((t-${at})/${w})*((t-${at})/${w}))':eval=frame[b${i}]`;155  const graph = [156    `anoisesrc=c=pink:r=${SR}:a=0.9:seed=${1000 + seed}:d=0.7,aformat=channel_layouts=mono,asplit=3[n0][n1][n2]`,157    band(0, 420, 0.22, 0.13, 1.0), band(1, 1300, 0.31, 0.11, 0.8), band(2, 3600, 0.38, 0.09, 0.42),158    `[b0][b1][b2]amix=inputs=3:normalize=0,asplit=2[l][r]`,159    // largeur stéréo : le canal droit est légèrement retardé160    `[r]adelay=7:all=1[rd]`, `[l][rd]join=inputs=2:channel_layout=stereo,afade=t=in:st=0:d=0.05,afade=t=out:st=0.55:d=0.15,alimiter=limit=0.6:level=false[a]`,161  ];162  await ff(["-filter_complex", graph.join(";"), "-map", "[a]", "-t", "0.7", "-c:a", "pcm_s16le", "-ar", String(SR), "-ac", "2", o.output]);163}164165/**166 * Signature sonore du carton de fin (WAV 48 kHz stéréo, `seconds` s) : un accord de ré majeur 9 qui s'ouvre voix par voix, une note167 * de cloche, puis l'extinction. Original, synthétisé (voir l'en-tête du fichier).168 */169export async function renderSting(o: { seconds: number; output: string }): Promise<void> {170  const d = Math.max(0.6, o.seconds);171  const notes = [50, 57, 62, 66, 69, 76];172  const voice = (side: number) => notes.map((mid, i) => {173    const f = hz(mid) * (1 + side * 0.0012 * (i % 2 ? 1 : -1));174    const at = 0.06 + i * 0.07;175    return `${n4(0.13 - i * 0.012)}*gt(t,${n4(at)})*(1-exp(-(t-${n4(at)})*9))*exp(-(t-${n4(at)})*${n4(1.1 + i * 0.12)})*(sin(2*PI*${n4(f)}*t)+0.22*sin(2*PI*${n4(2 * f)}*t))`;176  }).join("+") + `+0.07*gt(t,0.5)*exp(-(t-0.5)*3.2)*(1-exp(-(t-0.5)*300))*sin(2*PI*${n4(hz(86) * (1 + side * 0.001))}*t)`;177  const fo = Math.min(0.8, d / 3);178  await ff(["-f", "lavfi", "-i", `aevalsrc='${voice(1)}|${voice(-1)}':s=${SR}:d=${d.toFixed(4)}`,179    "-af", `lowpass=f=6000,aecho=0.9:0.7:61|113|187:0.24|0.18|0.12,volume=5dB,afade=t=in:st=0:d=0.03,afade=t=out:st=${(d - fo).toFixed(3)}:d=${fo.toFixed(3)},apad=whole_dur=${d.toFixed(4)},atrim=duration=${d.toFixed(4)}`,180    "-c:a", "pcm_s16le", "-ar", String(SR), "-ac", "2", o.output]);181}182
Files main
Menu

Theme