TTS redeems: envelope letter with words inked in as spoken

- TTS alerts use the new `tts` style: envelope opens, the letter rises out
  and settles in front near the top, words ink in as the voice says them
  (timed from a loudness curve the server sends: tts.loudness, tts_env,
  tts_prefix); if the voice fails, the full text shows
- Highlight my message keeps its taped note

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-21 14:42:36 +02:00
parent 4fda6060bf
commit 060b2351f7
6 changed files with 122 additions and 9 deletions

View file

@ -141,7 +141,10 @@ Builder page to make named TTS voices, used by redeem variations (Redeems page:
- Redeem with a TTS voice + viewer text: `redeems.addSpeech()` cleans the text (`tts.prepareViewerText`: links out,
repeats collapsed, cut to `settings.tts_max_chars` at a word, `settings.tts_blocklist` -> nothing read, note says
"(message removed)"), synthesizes "<user> says: <text>" (`tts_say_name`), and only then sends the alert with
`tts` (URL) + `tts_ms`. Shown as the big paper note (style `message`, caption "says:"). TTS on = the variation's
`tts` (URL), `tts_ms`, `tts_env` (loudness per 40 ms, `tts.loudness()`) and `tts_prefix` (words said before the message).
Shown as the envelope letter (style `tts`, `public/alerts/fx.js` envelope(), CSS in fx.css): flap opens, the letter rises
out and settles in front ~80px from the top, words ink in as spoken (timing estimated from tts_env; if the voice
does not start, the whole text shows). Design preview: `~/Desktop/Stream/tts-alerts/`. TTS on = the variation's
sound is not sent (the voice replaces it; the Redeems page greys the picker out). Synthesis errors: the note still shows, silent.
- Dashboard "Skip current alert" -> POST `/alerts/skip` -> WS `{type:'alert_skip'}` -> `PolaroidAlerts.skip()`.
- `tts_blocklist` never goes to overlay pages: they get `db.getOverlaySettings()` (render and settings_update).

View file

@ -31,3 +31,33 @@
#fx-alert .note .who .u { color:var(--red); }
#fx-alert .note .text { font:700 46px/52px 'Caveat', cursive; color:var(--ink); word-wrap:break-word;
overflow:hidden; display:-webkit-box; -webkit-line-clamp:9; -webkit-box-orient:vertical; }
/* TTS redeems: envelope letter (fx.js envelope()). The flap opens, the letter rises all the way out (its peak may
leave the screen), then comes down in front of the envelope and ends ~80px from the top; words ink in as spoken.
Coordinates are bottom-up inside .envl (360x560); the letter's slot is clipped at the envelope's bottom edge. */
#fx-alert .envl { position:absolute; left:90px; top:-146px; width:360px; height:560px; }
#fx-alert .envl .env { position:absolute; left:0; bottom:0; width:360px; height:216px; z-index:3; background:#e9d3b0; border-radius:6px;
box-shadow:0 10px 20px rgba(0,0,0,.45); }
#fx-alert .envl .env:before { content:''; position:absolute; inset:0; border-radius:6px; z-index:3;
background:linear-gradient(32deg, #dcc39b 50%, transparent 50%) left/50% 100% no-repeat,
linear-gradient(-32deg, #dcc39b 50%, transparent 50%) right/50% 100% no-repeat; }
#fx-alert .envl .flap { position:absolute; left:0; bottom:216px; width:360px; height:122px; transform-origin:bottom; z-index:1;
background:#d8bd93; clip-path:polygon(0 100%, 50% 0, 100% 100%); animation:fx-flap .6s .35s ease-out both; }
@keyframes fx-flap { from { transform:rotateX(180deg); z-index:4; } }
#fx-alert .envl .slot { position:absolute; left:-40px; right:-40px; bottom:0; top:-400px; overflow:hidden; z-index:2; animation:fx-zswap 1.6s .8s both; }
@keyframes fx-zswap { 0%, 54% { z-index:2; } 55%, 100% { z-index:6; } }
#fx-alert .envl .letter { position:absolute; left:62px; bottom:30px; width:316px; min-height:290px; background:#fffdf7; padding:18px 22px 22px;
box-shadow:0 4px 12px rgba(0,0,0,.3); animation:fx-rise 1.6s .8s both;
background-image:repeating-linear-gradient(transparent 0 29px, rgba(110,150,200,.3) 29px 30px); background-position:0 46px; }
@keyframes fx-rise {
0% { transform:translateY(110px); animation-timing-function:cubic-bezier(.3,.7,.4,1); }
45% { transform:translateY(-200px) rotate(-1deg); }
55% { transform:translateY(-200px) rotate(-1deg); animation-timing-function:cubic-bezier(.4,0,.3,1.2); }
100% { transform:translateY(-14px) rotate(-2deg); }
}
#fx-alert .envl .to { font:700 22px/1 Caveat, cursive; color:var(--red); margin-bottom:6px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#fx-alert .envl .tx { font:700 24px/30px Caveat, cursive; color:var(--ink); word-wrap:break-word; }
#fx-alert .envl .w { opacity:.12; transition:opacity .25s; }
#fx-alert .envl .w.on { opacity:1; }
#fx-alert .envl .seal { position:absolute; left:157px; bottom:86px; width:46px; height:46px; z-index:5; border-radius:50%; background:#b74347;
box-shadow:inset 0 -3px 0 rgba(0,0,0,.2), 0 3px 6px rgba(0,0,0,.35); color:#ffd9d4; font:22px/46px sans-serif; text-align:center; }

View file

@ -2,8 +2,10 @@
Special redeem visuals, called by polaroid.js (shared queue). Each returns a Promise that resolves when done.
FxAlert.giant(d, cur, snd) Gigantify Power-up: the viewer's emote grows huge, pulses while the sound plays
FxAlert.rain(d, cur, snd) On-Screen Celebration Power-up: copies of the emote bounce around the screen
FxAlert.message(d, cur, snd) Highlight my message / Message Effect / TTS redeems: big taped paper note with the message
(d.tts = spoken message URL, d.ttsMs = its length; TTS redeems come without a sound)
FxAlert.message(d, cur, snd) Highlight my message / Message Effect: big taped paper note with the message
FxAlert.envelope(d, cur, snd) TTS redeems: envelope opens, the letter rises out and settles in front, words ink in as
they are spoken (d.tts URL, d.ttsMs length, d.ttsEnv loudness per 40 ms, d.ttsPrefix
= words said before the message, e.g. "<name> says:")
d: { name (user), line, msg, emote (image URL or null) }; snd: { url, len, volume }
cur: { anims, timer, audio } so reset/skip can stop it (anything with cancel() can go in anims).
*/
@ -131,5 +133,63 @@
{ delay:exitAt, duration:500, easing:'ease-in' }));
}
window.FxAlert = { giant, rain, message, hide };
// ---- TTS redeems: envelope letter ----
const VOICE_AT = 1300; // ms: the voice starts while the letter comes back down
const ENV_STEP = 0.04; // s per loudness value (src/tts.js ENV_STEP_MS)
// when each shown word starts (s), spread over the voiced part of the clip, longer words and pauses after
// punctuation get more time. The first `prefix` spoken words ("<name> says:") are not on the letter.
function wordStarts(env, prefixWords, words) {
let s = 0, e = env.length - 1;
while (s < e && env[s] < .08) s++;
while (e > s && env[e] < .08) e--;
const all = [...prefixWords, ...words];
const weight = all.map(x => x.length + 2 + (/[.!?,:]$/.test(x) ? 5 : 0));
const total = weight.reduce((a, b) => a + b, 0) || 1;
let acc = 0;
const starts = all.map((_, i) => { const t = (s + (e - s + 1) * acc / total) * ENV_STEP; acc += weight[i]; return t; });
return starts.slice(prefixWords.length);
}
function envelope(d, cur, snd) {
const el = root();
const text = d.msg || '';
const words = text.split(/\s+/).filter(Boolean);
el.innerHTML = `<div class="envl"><div class="flap"></div>
<div class="slot"><div class="letter"><div class="to">from ${esc(d.name)} ♡</div>
<div class="tx">${words.map(w => `<span class="w">${esc(w)}</span>`).join(' ')}</div></div></div>
<div class="env"></div><div class="seal">♥</div></div>`;
el.style.visibility = 'visible';
const box = el.querySelector('.envl');
const spans = [...box.querySelectorAll('.w')];
A(cur, box, [{ transform:'translateY(-40px) scale(.92) rotate(-3deg)', opacity:0 }, { transform:'none', opacity:1 }],
{ duration:600, easing:'cubic-bezier(.2,1.25,.4,1)' });
let exitAt;
if (d.tts) {
const prefix = d.ttsPrefix ? [d.name, 'says:'].slice(0, d.ttsPrefix) : [];
const starts = d.ttsEnv && d.ttsEnv.length ? wordStarts(d.ttsEnv, prefix, words) : null;
const a = new Audio(d.tts); a.volume = snd.volume;
const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, VOICE_AT);
let raf = 0, failed = false;
const fail = () => { failed = true; }; // voice missing/blocked: show the whole text anyway
a.addEventListener('error', fail, { once:true });
const t2 = setTimeout(() => { if (!a.currentTime) fail(); }, VOICE_AT + 1500);
const tick = () => { // ink in each word as it is said
const now = a.ended ? Infinity : a.currentTime + .05;
spans.forEach((w, i) => w.classList.toggle('on', failed || a.ended || (!a.paused || a.currentTime > 0) && (!starts || now >= starts[i])));
raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
cur.anims.push({ cancel: () => { clearTimeout(t); clearTimeout(t2); cancelAnimationFrame(raf); a.pause(); } });
exitAt = VOICE_AT + (d.ttsMs || 4000) + 1400;
} else { // blocked or no voice: just show the letter
spans.forEach(w => w.classList.add('on'));
exitAt = 2400 + 2000 + 60 * text.length;
}
return done(cur, A(cur, box, [{ transform:'none', opacity:1 }, { transform:'translateY(40px) scale(.95) rotate(4deg)', opacity:0 }],
{ delay:exitAt, duration:500, easing:'ease-in' }));
}
window.FxAlert = { giant, rain, message, envelope, hide };
})();

View file

@ -129,7 +129,7 @@
name: e.user || 'Someone', line: fill(e.caption || 'redeemed it! ♡'), msg: e.input,
title: e.variation || e.reward, sub: e.reward, rarity: e.rarity,
sound: e.sound || null, volume: e.volume, soundOnly: e.polaroid === false && !e.tts,
tts: e.tts ? rebase(e.tts) : null, ttsMs: e.tts_ms || 0 };
tts: e.tts ? rebase(e.tts) : null, ttsMs: e.tts_ms || 0, ttsEnv: e.tts_env || [], ttsPrefix: e.tts_prefix || 0 };
}
case 'bits': {
if (!(e.bits >= BITS_MIN)) return null;
@ -255,7 +255,7 @@
const len = url ? await soundLength(url) : 0;
if (cur !== current) return; // skipped while measuring the sound
const fx = { emote: 'giant', emote_rain: 'rain', message: 'message' }[d.style];
const fx = { emote: 'giant', emote_rain: 'rain', message: 'message', tts: 'envelope' }[d.style];
if (fx && !d.soundOnly && window.FxAlert) {
return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? VOLUME })
.then(() => { if (current === cur) current = null; });

View file

@ -50,8 +50,8 @@ function pick(variations) {
}
function toAlert(v, { user, input, emote }) {
const spoken = !!(v.tts_voice_id && input); // TTS variations are shown as the big paper note
const style = spoken ? 'message' : (STYLE[`${v.kind}:${v.key}`] || 'cassette');
const spoken = !!(v.tts_voice_id && input); // TTS variations: envelope letter (fx.js envelope())
const style = spoken ? 'tts' : (STYLE[`${v.kind}:${v.key}`] || 'cassette');
const line = spoken ? LINE.tts : LINE[style];
return {
type: 'redeem', kind: v.kind, key: v.key, style,
@ -81,6 +81,8 @@ async function addSpeech(v, alert) {
const out = await tts.synth(voice.config, say);
alert.tts = out.url;
alert.tts_ms = out.durationMs;
alert.tts_env = await tts.loudness(out.file); // word timing on the overlay
alert.tts_prefix = say === text ? 0 : 2; // words spoken before the message ("<name> says:")
} catch (e) {
console.warn(`[tts] ${alert.user}: ${e.message}`);
}

View file

@ -181,6 +181,24 @@ function durationMs(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'))
@ -225,4 +243,4 @@ async function synth(configIn, textIn) {
return { url, file, cached: false, ms: Date.now() - t0, durationMs: await durationMs(file) };
}
module.exports = { voices, synth, normalize, cleanText, prepareViewerText, parseBlocklist, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };
module.exports = { voices, synth, loudness, ENV_STEP_MS, normalize, cleanText, prepareViewerText, parseBlocklist, EFFECTS, LIMITS, DEFAULT_CONFIG, MAX_CHARS };