/* Talk mode: a hands-free spoken conversation. * Listen (it hears when you start and stop talking) -> text -> answer -> speak -> listen again. * Talk over the answer to interrupt it. Say "stop" or "bye" to end. * Shared by the side panel and the phone page. */ "use strict"; (function (root) { const END_WORDS = /^\s*(stop|stop talking|goodbye|bye|bye bye|that'?s all|thanks,? that'?s all|end( the)? (talk|conversation)|exit)[.!]?\s*$/i; function rms(an, buf) { an.getFloatTimeDomainData(buf); let s = 0; for (let i = 0; i < buf.length; i++) s += buf[i] * buf[i]; return Math.sqrt(s / buf.length); } /* Splits what to say into small pieces: a short first piece so Welly starts talking almost at once, then a sentence or two at a time (the next piece is prepared while the current one plays). */ function splitChunks(text) { const sents = String(text).replace(/\s+/g, " ").trim().split(/(?<=[.!?])\s+/).filter(Boolean); const out = []; let cur = ""; for (const sn of sents) { const limit = out.length === 0 ? 110 : 220; if (cur && (cur + " " + sn).length > limit) { out.push(cur); cur = sn; } else cur = cur ? cur + " " + sn : sn; } if (cur) out.push(cur); return out.length ? out : [String(text)]; } /* Plays an answer and moves the mascot's mouth. fetchAudio(text, lang) returns a Blob (natural voice) or null. Every path has a time limit, so a stuck player can never freeze the conversation. */ function makeSpeaker(ctx, fetchAudio, onLevel, log, onChunk) { let audio = null, url = null, nodes = [], gen = 0, finish = null; function cleanup() { for (const n of nodes) { try { n.disconnect(); } catch (_) { /* gone */ } } nodes = []; if (url) { URL.revokeObjectURL(url); url = null; } audio = null; } function playBlob(blob, my, i, text) { return new Promise((resolve) => { url = URL.createObjectURL(blob); const a = audio = new Audio(url); const src = ctx.createMediaElementSource(a), an = ctx.createAnalyser(); an.fftSize = 512; src.connect(an); an.connect(ctx.destination); nodes = [src, an]; const buf = new Float32Array(an.fftSize); const tick = () => { if (audio !== a || a.paused || my !== gen) return; onLevel(Math.min(1, rms(an, buf) * 6)); requestAnimationFrame(tick); }; let done = false; const guard = setTimeout(() => { log && log("voice-timeout", {}); finish(); }, 45000); finish = () => { if (!done) { done = true; clearTimeout(guard); cleanup(); resolve(); } }; a.onloadedmetadata = () => { clearTimeout(guard); setTimeout(finish, (a.duration || 30) * 1000 + 3000); }; a.onended = a.onpause = a.onerror = finish; a.onplaying = () => { onChunk && onChunk(i, text, a.duration || text.split(/\s+/).length / 2.7); a.onplaying = null; }; a.play().then(tick).catch((e) => { log && log("voice-play-blocked", String(e && e.message || e)); finish(); }); }); } function speakBrowser(text, lang, i) { onChunk && onChunk(i, text, String(text).split(/\s+/).length / 2.7); // Last resort: the browser's own voice. Chrome sometimes never reports "done", so it gets a time limit too. return new Promise((resolve) => { speechSynthesis.cancel(); const u = new SpeechSynthesisUtterance(String(text)); u.lang = lang || "en"; let done = false; const t = setInterval(() => onLevel(0.25 + Math.random() * 0.6), 110); finish = () => { if (!done) { done = true; clearInterval(t); clearTimeout(guard); onLevel(0); resolve(); } }; const guard = setTimeout(finish, String(text).split(/\s+/).length * 450 + 3000); u.onend = u.onerror = finish; speechSynthesis.speak(u); }); } async function speak(text, lang) { stop(); const my = ++gen; const parts = splitChunks(String(text).replace(/\[[\d,\s]+\]/g, "")); const t0 = Date.now(); const get = (i) => fetchAudio(parts[i], lang).catch((e) => { log && log("voice-fetch-error", String(e && e.message || e)); return null; }); let next = get(0); for (let i = 0; i < parts.length; i++) { const blob = await next; if (my !== gen) return; if (i === 0) log && log("voice-ready", { ms: Date.now() - t0, natural: !!blob, pieces: parts.length }); next = i + 1 < parts.length ? get(i + 1) : null; if (ctx.state !== "running") { try { await ctx.resume(); } catch (_) { /* ignore */ } } if (blob) await playBlob(blob, my, i, parts[i]); else await speakBrowser(parts[i], lang, i); if (my !== gen) return; } onLevel(0); } function stop() { gen++; if (audio) { try { audio.pause(); } catch (_) { /* ignore */ } } speechSynthesis.cancel(); if (finish) finish(); cleanup(); } return { speak, stop }; } /* opts: { transcribe(blob) -> text, ask(text) -> {answer, language, found}, fetchAudio(text, lang) -> Blob|null, onState(state, detail), onLevel(v), onTurn({you, answer, res}), onError(msg) } */ function create(opts) { let stream = null, ctx = null, an = null, buf = null, rec = null, chunks = []; let running = false, state = "off", timer = null, speaker = null; let floor = 0.01, thr = 0.03, speechFrames = 0, silenceFrames = 0, heard = false, recStart = 0, bargeFrames = 0; let since = Date.now(), watch = null; const log = (type, detail) => { try { opts.log && opts.log(type, detail); } catch (_) { /* ignore */ } }; function setState(s, detail) { state = s; since = Date.now(); log("state", s); opts.onState && opts.onState(s, detail || ""); } async function start() { if (running) return; try { stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } }); } catch (e) { log("mic-error", String(e && e.name)); opts.onError && opts.onError("mic"); return false; } ctx = new (window.AudioContext || window.webkitAudioContext)(); await ctx.resume(); an = ctx.createAnalyser(); an.fftSize = 1024; ctx.createMediaStreamSource(stream).connect(an); buf = new Float32Array(an.fftSize); speaker = makeSpeaker(ctx, opts.fetchAudio, (v) => opts.onLevel && opts.onLevel(v), log, (i, t, d) => opts.onSpeakChunk && opts.onSpeakChunk(i, t, d)); running = true; // Measure the room's background noise for half a second, so "talking" means louder than that. setState("calibrating", "One moment…"); let sum = 0, n = 0; await new Promise((r) => { const t = setInterval(() => { sum += rms(an, buf); n++; if (n >= 10) { clearInterval(t); r(); } }, 50); }); floor = Math.max(0.004, sum / n); thr = Math.max(0.018, floor * 3.2); listen(); timer = setInterval(loop, 50); // Watchdog: nothing may hang. A stuck step is logged and the conversation goes back to listening. watch = setInterval(() => { if (!running) return; const age = Date.now() - since; if (state === "thinking" && age > 45000) { log("watchdog", "thinking " + age); opts.onError && opts.onError("That took too long. Ask again?"); if (opts.once) stop(); else listen(); } else if (state === "speaking" && age > 75000) { log("watchdog", "speaking " + age); speaker.stop(); if (opts.once) stop(); else listen(); } else if (state === "listening" && ctx && ctx.state !== "running") { log("resume-audio", ctx.state); ctx.resume().catch(() => {}); } }, 1000); return true; } function newRecorder() { chunks = []; rec = new MediaRecorder(stream); rec.ondataavailable = (e) => e.data.size && chunks.push(e.data); rec.start(); recStart = Date.now(); } function listen() { heard = false; speechFrames = 0; silenceFrames = 0; newRecorder(); setState("listening", "Listening… ask your question"); } async function finishUtterance() { const r = rec; if (!r) return; rec = null; setState("thinking", "Turning your voice into text…"); const blob = await new Promise((res) => { r.onstop = () => res(new Blob(chunks, { type: r.mimeType || "audio/webm" })); r.stop(); }); if (!running) return; setState("thinking", "Turning your voice into text…"); let text = ""; const tt = Date.now(); try { text = (await opts.transcribe(blob)) || ""; } catch (e) { log("transcribe-error", e.message); opts.onError && opts.onError(e.message); } log("heard", { ms: Date.now() - tt, bytes: blob.size, text: text.slice(0, 80) }); if (!running) return; text = text.trim(); if (!text || text.length < 2) { if (opts.once) { opts.onError && opts.onError("I didn't catch that. Tap the mic and try again."); stop(); } else listen(); return; } if (END_WORDS.test(text)) { setState("speaking", "Bye for now"); await speaker.speak("Okay. I'm here if you need me.", "en"); stop(); return; } setState("thinking", text); let res = null; const ta = Date.now(); try { res = await opts.ask(text); } catch (e) { log("ask-error", e.message); opts.onError && opts.onError(e.message); } log("answered", { ms: Date.now() - ta, ok: !!res }); if (!running) return; if (!res) { listen(); return; } opts.onTurn && opts.onTurn({ you: text, answer: res.answer, res }); setState("speaking", res.answer); bargeFrames = 0; const said = res.spoken || res.answer; try { opts.onSpeakStart && opts.onSpeakStart(said, splitChunks(String(said).replace(/\[[\d,\s]+\]/g, ""))); } catch (e) { log("caption-error", e.message); } await speaker.speak(said, res.language); if (running && state === "speaking") { if (opts.once) stop(); else listen(); } } function loop() { if (!running || !an) return; const v = rms(an, buf); if (state === "listening") { opts.onLevel && opts.onLevel(Math.min(1, (v - floor) / (thr * 3))); if (v > thr) { speechFrames++; silenceFrames = 0; if (speechFrames >= 3) heard = true; } else { speechFrames = 0; if (heard) silenceFrames++; } const long = Date.now() - recStart; if (heard && (silenceFrames >= 22 || long > 25000)) finishUtterance(); // ~1.1 s of quiet after speech else if (!heard && long > 15000) { // nothing said if (opts.once) { stop(); return; } rec.onstop = null; rec.stop(); newRecorder(); } } else if (state === "speaking") { // Talking over the answer interrupts it (echo cancellation keeps the helper's own voice out). if (v > thr * 2.6) bargeFrames++; else bargeFrames = Math.max(0, bargeFrames - 1); if (bargeFrames >= 6) { speaker.stop(); listen(); heard = true; } } } function stop() { running = false; clearInterval(timer); clearInterval(watch); try { rec && rec.state !== "inactive" && (rec.onstop = null, rec.stop()); } catch (_) { /* ignore */ } rec = null; speaker && speaker.stop(); stream && stream.getTracks().forEach((t) => t.stop()); ctx && ctx.close(); stream = ctx = an = null; setState("off", ""); } return { start, stop, get running() { return running; }, get state() { return state; } }; } root.Talk = { create, makeSpeaker, chunks: splitChunks }; })(typeof self !== "undefined" ? self : this);