Add TTS voice builder (/tts): Piper + espeak, layers, effects
- src/tts.js: synth(config, text) -> cached mp3 in public/tts; up to 3 layers (engine, voice, speaker, speed, pitch, volume, delay) mixed with ffmpeg, 8 effects (stadium, echo, 8-bit, radio, robot, choir, warp, shaky), loudnorm; config is clamped and voice/speaker names are restricted to plain names - tools/tts/worker.py: long-running Python worker (JSON lines), Piper models kept loaded (LRU of 4), espeak-ng via libespeak-ng + ctypes - tools/tts/setup.sh: venv + piper-tts + default voice set - /tts page: presets, layers, effects, test playback, save/load/delete named voices (tts_voices table); TTS link in the nav - public/tts, tools/tts/venv and tools/tts/voices are gitignored Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
463c6580f4
commit
b5a81bdb15
10 changed files with 780 additions and 0 deletions
197
src/tts.js
Normal file
197
src/tts.js
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
// 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);
|
||||
}
|
||||
|
||||
// ---------- 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 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 }. 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 };
|
||||
|
||||
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 };
|
||||
}
|
||||
|
||||
module.exports = { voices, synth, normalize, cleanText, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };
|
||||
Loading…
Add table
Add a link
Reference in a new issue