Skip to content

Text to vertical video in 100+ styles: AI codes each scene (HTML/SVG/WebGL), renders a 9:16 MP4 with music and English/Vietnamese voice. MCP, CLI and REST for AI agents.

9.7 KB
Raw Blame
// DSP thuần JS dùng chung cho sfx + nhạc: dao động, nhiễu, lọc biquad, reverb, ghi/đọc WAV.
// Mọi thứ tất định: ngẫu nhiên lấy từ rng(seed), không dùng Math.random.
import fs from 'node:fs';

export const SR = 48000;
export const TAU = Math.PI * 2;

export const ns = (sec) => Math.max(1, Math.round(sec * SR));
export const dbToGain = (db) => Math.pow(10, db / 20);
export const midiHz = (m) => 440 * Math.pow(2, (m - 69) / 12);
export const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));

/** mulberry32: rng(seed) → hàm r() trong [0,1). */
export function rng(seed) {
  let a = (seed >>> 0) || 1;
  return () => {
    a = (a + 0x6d2b79f5) | 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
export function hashStr(s) {
  let h = 2166136261;
  for (const c of String(s)) { h ^= c.codePointAt(0); h = Math.imul(h, 16777619); }
  return h >>> 0;
}

// ---------- dạng sóng (phase 0..1) ----------
export const WAVES = {
  sine: (p) => Math.sin(TAU * p),
  tri: (p) => 1 - 4 * Math.abs(((p + 0.25) % 1) - 0.5),
  saw: (p) => 2 * (p % 1) - 1,
  square: (p) => ((p % 1) < 0.5 ? 1 : -1),
  pulse25: (p) => ((p % 1) < 0.25 ? 1 : -1),
  soft: (p) => Math.tanh(2.5 * Math.sin(TAU * p)) / Math.tanh(2.5), // vuông mềm, ít chói
};

/** Dao động có tần số thay theo thời gian: f(t) Hz, amp(t). Trả Float32Array. */
export function osc(dur, f, { wave = 'sine', amp = () => 1, phase = 0 } = {}) {
  const n = ns(dur), out = new Float32Array(n), w = WAVES[wave] || wave;
  const fF = typeof f === 'function' ? f : () => f;
  let p = phase;
  for (let i = 0; i < n; i++) {
    const t = i / SR;
    out[i] = w(p) * amp(t);
    p += fF(t) / SR;
    if (p > 1e6) p -= Math.floor(p);
  }
  return out;
}

/** FM 2 toán tử: sóng mang fc, sóng điều chế fc*ratio, chỉ số index(t). */
export function fm(dur, fc, ratio, index, amp = () => 1) {
  const n = ns(dur), out = new Float32Array(n);
  const fF = typeof fc === 'function' ? fc : () => fc;
  const iF = typeof index === 'function' ? index : () => index;
  let pc = 0, pm = 0;
  for (let i = 0; i < n; i++) {
    const t = i / SR, f = fF(t);
    out[i] = Math.sin(TAU * pc + iF(t) * Math.sin(TAU * pm)) * amp(t);
    pc += f / SR; pm += (f * ratio) / SR;
  }
  return out;
}

export function noise(dur, r, amp = () => 1) {
  const n = ns(dur), out = new Float32Array(n);
  for (let i = 0; i < n; i++) out[i] = (r() * 2 - 1) * amp(i / SR);
  return out;
}

// ---------- đường bao ----------
/** Tấn công tuyến tính `a` giây rồi tắt dần mũ với hằng số tau. */
export const envAD = (a, tau) => (t) => (t < a ? t / a : Math.exp(-(t - a) / tau));
/** Hình chuông (sin^p) dài dur, đỉnh ở peak (0..1). */
export const envBell = (dur, peak = 0.5, pw = 2) => (t) => {
  const x = t / dur; if (x <= 0 || x >= 1) return 0;
  const k = x < peak ? x / peak : (1 - x) / (1 - peak);
  return Math.pow(Math.sin((k * Math.PI) / 2), pw);
};
/** ADSR theo giây, gate = thời gian giữ phím. */
export const envADSR = (a, d, s, r, gate) => (t) => {
  if (t < a) return t / a;
  if (t < a + d) return 1 - (1 - s) * ((t - a) / d);
  if (t < gate) return s;
  return s * Math.max(0, 1 - (t - gate) / r);
};

// ---------- lọc ----------
export class Biquad {
  constructor(type, f, q = 0.707) { this.type = type; this.x1 = this.x2 = this.y1 = this.y2 = 0; this.set(f, q); }
  set(f, q = this.q) {
    this.q = q;
    f = clamp(f, 10, SR * 0.45);
    const w = (TAU * f) / SR, c = Math.cos(w), s = Math.sin(w), al = s / (2 * q);
    let b0, b1, b2;
    if (this.type === 'lp') { b0 = (1 - c) / 2; b1 = 1 - c; b2 = (1 - c) / 2; }
    else if (this.type === 'hp') { b0 = (1 + c) / 2; b1 = -(1 + c); b2 = (1 + c) / 2; }
    else { b0 = al; b1 = 0; b2 = -al; } // bp, đỉnh 0 dB
    const a0 = 1 + al;
    this.b0 = b0 / a0; this.b1 = b1 / a0; this.b2 = b2 / a0; this.a1 = (-2 * c) / a0; this.a2 = (1 - al) / a0;
  }
  tick(x) {
    const y = this.b0 * x + this.b1 * this.x1 + this.b2 * this.x2 - this.a1 * this.y1 - this.a2 * this.y2;
    this.x2 = this.x1; this.x1 = x; this.y2 = this.y1; this.y1 = y;
    return y;
  }
}
/** Lọc cả buffer; f có thể là hàm của t (cập nhật mỗi 16 mẫu). */
export function filt(buf, type, f, q = 0.707) {
  const fF = typeof f === 'function' ? f : null;
  const bq = new Biquad(type, fF ? fF(0) : f, q);
  const out = new Float32Array(buf.length);
  for (let i = 0; i < buf.length; i++) {
    if (fF && (i & 15) === 0) bq.set(fF(i / SR), q);
    out[i] = bq.tick(buf[i]);
  }
  return out;
}

// ---------- tiện ích buffer ----------
export function mixInto(dst, src, at = 0, gain = 1) {
  const s = Math.round(at * SR);
  for (let i = 0; i < src.length; i++) { const j = s + i; if (j >= 0 && j < dst.length) dst[j] += src[i] * gain; }
  return dst;
}
export function sum(dur, parts) {
  const out = new Float32Array(ns(dur));
  for (const [buf, at = 0, g = 1] of parts) mixInto(out, buf, at, g);
  return out;
}
export const mul = (buf, f) => { for (let i = 0; i < buf.length; i++) buf[i] *= f(i / SR); return buf; };
export const softclip = (buf, drive = 1) => { const k = Math.tanh(drive); for (let i = 0; i < buf.length; i++) buf[i] = Math.tanh(buf[i] * drive) / k; return buf; };
export function peak(...bufs) { let p = 0; for (const b of bufs) for (let i = 0; i < b.length; i++) p = Math.max(p, Math.abs(b[i])); return p; }
export function rms(...bufs) { let s = 0, n = 0; for (const b of bufs) { for (let i = 0; i < b.length; i++) s += b[i] * b[i]; n += b.length; } return Math.sqrt(s / Math.max(1, n)); }
export function normalizePeak(bufs, db = -1) {
  const p = peak(...bufs); if (p < 1e-9) return bufs;
  const g = dbToGain(db) / p; for (const b of bufs) for (let i = 0; i < b.length; i++) b[i] *= g;
  return bufs;
}
/** Đưa RMS về `db`, đỉnh vượt `ceilDb` thì nén mềm bằng tanh. */
export function normalizeRms(bufs, db = -16, ceilDb = -1) {
  const r = rms(...bufs); if (r < 1e-9) return bufs;
  const g = dbToGain(db) / r, c = dbToGain(ceilDb);
  for (const b of bufs) for (let i = 0; i < b.length; i++) { const x = b[i] * g; b[i] = Math.abs(x) > 0.6 * c ? Math.sign(x) * (0.6 * c + 0.4 * c * Math.tanh((Math.abs(x) - 0.6 * c) / (0.4 * c))) : x; }
  return bufs;
}
export function fade(bufs, fin = 0.005, fout = 0.01) {
  for (const b of bufs) {
    const a = ns(fin), z = ns(fout), n = b.length;
    for (let i = 0; i < Math.min(a, n); i++) b[i] *= i / a;
    for (let i = 0; i < Math.min(z, n); i++) b[n - 1 - i] *= i / z;
  }
  return bufs;
}
/** Pan hằng công suất: p -1 (trái) .. 1 (phải), có thể là hàm của t. */
export function pan(mono, p = 0) {
  const pF = typeof p === 'function' ? p : () => p;
  const L = new Float32Array(mono.length), R = new Float32Array(mono.length);
  for (let i = 0; i < mono.length; i++) {
    const a = ((clamp(pF(i / SR), -1, 1) + 1) * Math.PI) / 4;
    L[i] = mono[i] * Math.cos(a) * Math.SQRT2; R[i] = mono[i] * Math.sin(a) * Math.SQRT2;
  }
  return [L, R];
}

/** Reverb Schroeder (4 comb + 2 allpass), trả [L,R] đuôi ướt (không gồm tín hiệu khô). */
export function reverb(mono, { room = 0.82, damp = 0.35, tail = 1.2 } = {}) {
  const n = mono.length + ns(tail), k = SR / 44100;
  const run = (off) => {
    const out = new Float32Array(n);
    for (const d0 of [1557, 1617, 1491, 1422, 1277, 1356]) {
      const d = Math.round((d0 + off) * k), line = new Float32Array(d); let idx = 0, lp = 0;
      for (let i = 0; i < n; i++) {
        const y = line[idx];
        lp = y * (1 - damp) + lp * damp;
        line[idx] = (i < mono.length ? mono[i] : 0) + lp * room;
        idx = (idx + 1) % d; out[i] += y / 6;
      }
    }
    for (const d0 of [556, 441, 341]) {
      const d = Math.round((d0 + off) * k), line = new Float32Array(d); let idx = 0;
      for (let i = 0; i < n; i++) { const b = line[idx], x = out[i]; line[idx] = x + b * 0.5; out[i] = b - x * 0.5; idx = (idx + 1) % d; }
    }
    return out;
  };
  return [run(0), run(23)];
}

// ---------- WAV ----------
/** Ghi WAV PCM 16-bit; chans = [L] hoặc [L,R]. */
export function writeWav(file, chans, sr = SR) {
  const nc = chans.length, n = Math.max(...chans.map((c) => c.length));
  const buf = Buffer.alloc(44 + n * nc * 2);
  buf.write('RIFF', 0); buf.writeUInt32LE(36 + n * nc * 2, 4); buf.write('WAVE', 8);
  buf.write('fmt ', 12); buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(nc, 22);
  buf.writeUInt32LE(sr, 24); buf.writeUInt32LE(sr * nc * 2, 28); buf.writeUInt16LE(nc * 2, 32); buf.writeUInt16LE(16, 34);
  buf.write('data', 36); buf.writeUInt32LE(n * nc * 2, 40);
  let o = 44;
  for (let i = 0; i < n; i++) for (let c = 0; c < nc; c++) {
    const v = clamp(chans[c][i] || 0, -1, 1); buf.writeInt16LE(Math.round(v * 32767), o); o += 2;
  }
  fs.writeFileSync(file, buf);
}
/** Đọc WAV PCM 16-bit → { sr, chans: Float32Array[] }. */
export function readWav(file) {
  const b = fs.readFileSync(file);
  let p = 12, fmt = null;
  while (p + 8 <= b.length) {
    const id = b.toString('ascii', p, p + 4), size = b.readUInt32LE(p + 4);
    if (id === 'fmt ') fmt = { nc: b.readUInt16LE(p + 10), sr: b.readUInt32LE(p + 12), bits: b.readUInt16LE(p + 22) };
    if (id === 'data') {
      if (!fmt || fmt.bits !== 16) throw new Error('readWav: chỉ đọc PCM 16-bit: ' + file);
      const n = Math.floor(Math.min(size, b.length - p - 8) / (2 * fmt.nc));
      const chans = Array.from({ length: fmt.nc }, () => new Float32Array(n));
      for (let i = 0; i < n; i++) for (let c = 0; c < fmt.nc; c++) chans[c][i] = b.readInt16LE(p + 8 + (i * fmt.nc + c) * 2) / 32768;
      return { sr: fmt.sr, chans };
    }
    p += 8 + size + (size & 1);
  }
  throw new Error('readWav: không thấy data chunk: ' + file);
}