// Text-to-speech: engines (Piper, espeak-ng) via the Python worker in tools/tts/worker.py, then ffmpeg for // pitch/speed per layer, mixing up to 3 layers, effects and loudness. Output: cached mp3 in public/tts/. // // A voice config (stored in tts_voices.config, edited on the /tts page): // { layers: [ { engine: 'piper'|'espeak', voice, speaker, speed, pitch, volume, delay } ... up to 3 ], // effects: { stadium: 0..1, echo: 0..1, crush: 0..1, radio: 0..1, robot: 0..1, chorus: 0..1, flanger: 0..1, tremolo: 0..1 } } // pitch is in semitones (changes the voice's character, like the "deep demon"), speed 1 = normal. // // Env: TTS_PYTHON (python with piper-tts, default tools/tts/venv/bin/python), TTS_VOICES_DIR (Piper models, // default tools/tts/voices). See tools/tts/setup.sh. const { spawn, execFile } = require('child_process'); const crypto = require('crypto'); const fs = require('fs'); const path = require('path'); const ROOT = path.join(__dirname, '..'); const PY = process.env.TTS_PYTHON || path.join(ROOT, 'tools/tts/venv/bin/python'); const WORKER = path.join(ROOT, 'tools/tts/worker.py'); const VOICES_DIR = process.env.TTS_VOICES_DIR || path.join(ROOT, 'tools/tts/voices'); const OUT_DIR = path.join(ROOT, 'public/tts'); const TMP_DIR = path.join(OUT_DIR, 'tmp'); const KEEP_FILES = 300; // cached mp3s kept in public/tts (oldest deleted first) const MAX_CHARS = 300; const SR = 44100; const LIMITS = { layers: 3, speed: [0.5, 2], pitch: [-12, 12], volume: [0, 1.5], delay: [0, 1000], }; // effect key -> label, hint and the ffmpeg filter for amount a (0 < a <= 1) const EFFECTS = { stadium: { label: 'Stadium', hint: 'big hall: long double echo', f: a => `aecho=0.8:0.9:${r(60 + 60 * a)}|${r(120 + 120 * a)}:${n(0.25 + 0.25 * a)}|${n(0.15 + 0.2 * a)}` }, echo: { label: 'Echo', hint: 'short cave echo (the demon uses this)', f: a => `aecho=0.8:0.85:${r(40 + 60 * a)}:${n(0.15 + 0.35 * a)}` }, crush: { label: '8-bit', hint: 'bit-crushed, glitchy', f: a => `acrusher=bits=${r(8 - 5 * a)}:samples=${r(1 + 6 * a)}:mix=${n(0.4 + 0.5 * a)}` }, radio: { label: 'Radio', hint: 'thin, crackly walkie-talkie', f: a => `highpass=f=${r(300 + 300 * a)},lowpass=f=${r(3500 - 1200 * a)},acrusher=bits=8:mix=${n(0.1 + 0.3 * a)},volume=1.5` }, robot: { label: 'Robot', hint: 'metallic ring modulation', f: a => `aeval='val(0)*(${n(1 - a)}+${n(a)}*sin(2*PI*${r(30 + 30 * a)}*t))':c=same` }, chorus: { label: 'Choir', hint: 'several voices at once', f: a => `chorus=0.6:0.9:50|60|40:${n(0.4 * a)}|${n(0.32 * a)}|${n(0.3 * a)}:0.25|0.4|0.3:2|2.3|1.3` }, flanger: { label: 'Warp', hint: 'swooshy jet flanger', f: a => `flanger=delay=${n(2 * a)}:depth=${n(2 + 6 * a)}` }, tremolo: { label: 'Shaky', hint: 'wobbling volume', f: a => `tremolo=f=${n(4 + 6 * a)}:d=${n(0.2 + 0.6 * a)}` }, }; function r(x) { return Math.round(x); } function n(x) { return Number(x.toFixed(3)); } const DEFAULT_CONFIG = { layers: [{ engine: 'piper', voice: 'en_GB-alan-medium', speaker: '', speed: 1, pitch: 0, volume: 1, delay: 0 }], effects: {}, }; // ---------- validation ---------- const SAFE_NAME = /^[A-Za-z0-9_+-][A-Za-z0-9_.+-]{0,119}$/; const clamp = (v, [lo, hi], d) => { const x = parseFloat(v); return isNaN(x) ? d : Math.max(lo, Math.min(hi, x)); }; function normalize(input) { const c = typeof input === 'string' ? JSON.parse(input) : (input || {}); const layers = (Array.isArray(c.layers) ? c.layers : []).slice(0, LIMITS.layers).map(l => ({ engine: l.engine === 'espeak' ? 'espeak' : 'piper', voice: SAFE_NAME.test(l.voice || '') ? l.voice : '', // plain names only: no paths speaker: SAFE_NAME.test(l.speaker ?? '') ? String(l.speaker) : '', speed: clamp(l.speed, LIMITS.speed, 1), pitch: clamp(l.pitch, LIMITS.pitch, 0), volume: clamp(l.volume, LIMITS.volume, 1), delay: Math.round(clamp(l.delay, LIMITS.delay, 0)), })).filter(l => l.voice); if (!layers.length) throw new Error('a voice needs at least one layer'); const effects = {}; for (const k of Object.keys(EFFECTS)) { const a = clamp(c.effects?.[k], [0, 1], 0); if (a > 0) effects[k] = n(a); } return { layers, effects }; } function cleanText(text) { return String(text || '').replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, MAX_CHARS); } // ---------- viewer text (redeems) ---------- // Returns { text, blocked }. blocked = a blocklist word was found: do not read anything. const LEET = { 0: 'o', 1: 'i', 3: 'e', 4: 'a', 5: 's', 7: 't', '@': 'a', $: 's', '!': 'i' }; function parseBlocklist(list) { return String(list || '').split(/[\n,]/).map(w => w.trim().toLowerCase()).filter(Boolean); } function prepareViewerText(input, { maxChars = 200, blocklist = '' } = {}) { let t = cleanText(input) .replace(/\b(?:https?:\/\/|www\.)\S+/gi, ' ') // links .replace(/\b[\w-]+(?:\.[\w-]+)*\.(?:com|net|org|gg|tv|io|ru|xyz|ly|me|co|app|link|sk|ro|de|uk|info|site|shop)\b\S*/gi, ' ') .replace(/(\S)\1{3,}/g, '$1$1$1') // aaaaaaa -> aaa .replace(/\b(\w+)(?:\s+\1\b){2,}/gi, '$1 $1') // lol lol lol lol -> lol lol .replace(/\s+/g, ' ').trim(); const max = Math.max(20, Math.min(MAX_CHARS, maxChars | 0 || 200)); if (t.length > max) t = t.slice(0, max).replace(/\s+\S*$/, '') + '…'; const plain = t.toLowerCase().replace(/[013457@$!]/g, c => LEET[c] || c); const words = ' ' + plain.replace(/[^a-z0-9\u00c0-\u024f]+/g, ' ') + ' '; const squashed = plain.replace(/[^a-z\u00c0-\u024f]+/g, ''); const blocked = parseBlocklist(blocklist).some(w => { const ww = w.replace(/[013457@$!]/g, c => LEET[c] || c); return ww.length >= 4 ? squashed.includes(ww.replace(/[^a-z\u00c0-\u024f]+/g, '')) // longer words: also when spaced out : words.includes(' ' + ww.replace(/[^a-z0-9\u00c0-\u024f]+/g, ' ').trim() + ' '); }); return { text: t, blocked }; } // ---------- worker ---------- let proc = null, outBuf = '', nextId = 1; const pending = new Map(); function failAll(err) { for (const p of pending.values()) { clearTimeout(p.timer); p.reject(err); } pending.clear(); } function worker() { if (proc) return proc; proc = spawn(PY, [WORKER], { env: { ...process.env, TTS_VOICES_DIR: VOICES_DIR }, stdio: ['pipe', 'pipe', 'pipe'] }); outBuf = ''; proc.stdout.on('data', d => { outBuf += d; let i; while ((i = outBuf.indexOf('\n')) >= 0) { const line = outBuf.slice(0, i); outBuf = outBuf.slice(i + 1); let msg; try { msg = JSON.parse(line); } catch { continue; } // ignore stray library output const p = pending.get(msg.id); if (!p) continue; pending.delete(msg.id); clearTimeout(p.timer); msg.ok ? p.resolve(msg) : p.reject(new Error(msg.error || 'TTS failed')); } }); proc.stderr.on('data', d => { const s = String(d).trim(); if (s) console.log('[tts-worker]', s.slice(0, 500)); }); proc.on('error', e => { console.error('[tts] worker failed to start:', e.message, `(TTS_PYTHON=${PY})`); proc = null; failAll(e); }); proc.on('exit', code => { if (proc) console.log(`[tts] worker exited (${code})`); proc = null; failAll(new Error('TTS worker exited')); }); return proc; } function call(req, timeoutMs = 30000) { return new Promise((resolve, reject) => { const id = nextId++; const timer = setTimeout(() => { pending.delete(id); reject(new Error('TTS worker timed out')); }, timeoutMs); pending.set(id, { resolve, reject, timer }); try { worker().stdin.write(JSON.stringify({ ...req, id }) + '\n'); } catch (e) { pending.delete(id); clearTimeout(timer); reject(e); } }); } let voiceCache = null, voiceCacheAt = 0; async function voices() { if (voiceCache && Date.now() - voiceCacheAt < 60000) return voiceCache; const v = await call({ op: 'voices' }, 60000); voiceCache = { piper: v.piper || [], espeak: v.espeak || [] }; voiceCacheAt = Date.now(); return voiceCache; } // ---------- synthesis ---------- function ffmpeg(args) { return new Promise((resolve, reject) => execFile('ffmpeg', args, { timeout: 60000 }, (err, _o, stderr) => err ? reject(new Error('ffmpeg: ' + String(stderr || err.message).trim().split('\n').slice(-3).join(' '))) : resolve())); } function layerFilter(l, i) { const f = [`aresample=${SR}`]; if (l.pitch) { const k = Math.pow(2, l.pitch / 12); // shift pitch + formants, keep the length f.push(`asetrate=${r(SR * k)}`, `aresample=${SR}`, `atempo=${n(1 / k)}`); } if (l.volume !== 1) f.push(`volume=${l.volume}`); if (l.delay) f.push(`adelay=${l.delay}|${l.delay}`); return `[${i}:a]${f.join(',')}[l${i}]`; } function durationMs(file) { return new Promise(resolve => execFile('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'csv=p=0', file], { timeout: 10000 }, (err, out) => resolve(err ? 0 : Math.round(parseFloat(out) * 1000) || 0))); } // Loudness curve: one value 0..1 per 40 ms (peak = 1). The overlay uses it to time the words of the // envelope letter (ink in as they are spoken). ~25 numbers per second of speech. const ENV_STEP_MS = 40; function loudness(file) { return new Promise(resolve => execFile('ffmpeg', ['-loglevel', 'error', '-i', file, '-ac', '1', '-ar', '8000', '-f', 's16le', '-'], { encoding: 'buffer', maxBuffer: 16 * 1024 * 1024, timeout: 15000 }, (err, out) => { if (err || !out.length) return resolve([]); const step = 8 * ENV_STEP_MS, env = []; for (let i = 0; i + 1 < out.length / 2; i += step) { let sum = 0, n = 0; for (let j = i; j < Math.min(i + step, out.length / 2); j++) { const v = out.readInt16LE(j * 2) / 32768; sum += v * v; n++; } env.push(Math.sqrt(sum / n)); } const max = Math.max(...env) || 1; resolve(env.map(v => Math.round(100 * v / max) / 100)); })); } function prune() { try { const files = fs.readdirSync(OUT_DIR).filter(f => f.endsWith('.mp3')) .map(f => ({ f, t: fs.statSync(path.join(OUT_DIR, f)).mtimeMs })).sort((a, b) => b.t - a.t); for (const x of files.slice(KEEP_FILES)) fs.unlinkSync(path.join(OUT_DIR, x.f)); } catch (e) { console.warn('[tts] prune:', e.message); } } // Returns { url, file, cached, ms, durationMs }. Same config + text = same file (cached). async function synth(configIn, textIn) { const config = normalize(configIn); const text = cleanText(textIn); if (!text) throw new Error('nothing to say'); const hash = crypto.createHash('sha1').update(JSON.stringify([config, text])).digest('hex').slice(0, 20); const file = path.join(OUT_DIR, `${hash}.mp3`); const url = `/tts/${hash}.mp3`; if (fs.existsSync(file)) return { url, file, cached: true, ms: 0, durationMs: await durationMs(file) }; const t0 = Date.now(); fs.mkdirSync(TMP_DIR, { recursive: true }); const wavs = config.layers.map((_, i) => path.join(TMP_DIR, `${hash}-${i}.wav`)); try { await Promise.all(config.layers.map((l, i) => call(l.engine === 'piper' ? { op: 'say', engine: 'piper', voice: l.voice, speaker: l.speaker || null, length_scale: n(1 / l.speed), text, out: wavs[i] } : { op: 'say', engine: 'espeak', voice: l.voice, rate: r(160 * l.speed), text, out: wavs[i] }))); const parts = config.layers.map(layerFilter); const mixIn = config.layers.map((_, i) => `[l${i}]`).join(''); const fx = Object.entries(config.effects).map(([k, a]) => EFFECTS[k].f(a)); const chain = [ config.layers.length > 1 ? `${mixIn}amix=inputs=${config.layers.length}:duration=longest:normalize=0` : `[l0]anull`, ...fx, 'loudnorm=I=-16:TP=-1.5', ].join(','); await ffmpeg(['-loglevel', 'error', '-y', ...wavs.flatMap(w => ['-i', w]), '-filter_complex', `${parts.join(';')};${chain}[out]`, '-map', '[out]', '-ac', '1', '-ar', String(SR), '-codec:a', 'libmp3lame', '-q:a', '3', file]); } finally { for (const w of wavs) fs.rm(w, { force: true }, () => {}); } prune(); return { url, file, cached: false, ms: Date.now() - t0, durationMs: await durationMs(file) }; } module.exports = { voices, synth, loudness, ENV_STEP_MS, normalize, cleanText, prepareViewerText, parseBlocklist, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };