chore: archive recoverable gateway source baseline
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
export class Resampler {
|
||||
constructor(inputRate, outputRate) { this.step=inputRate/outputRate; this.samples=[]; this.position=0; }
|
||||
push(input) {
|
||||
this.samples.push(...input);
|
||||
const output=[];
|
||||
while(this.position+1<this.samples.length) {
|
||||
const i=Math.floor(this.position), f=this.position-i;
|
||||
output.push(this.samples[i]*(1-f)+this.samples[i+1]*f); this.position+=this.step;
|
||||
}
|
||||
const used=Math.min(Math.floor(this.position),this.samples.length);
|
||||
if(used){this.samples.splice(0,used);this.position-=used;}
|
||||
return output;
|
||||
}
|
||||
}
|
||||
export function pcmFrame(direction,turn,seq,pcm) {
|
||||
const buffer=new ArrayBuffer(12+pcm.length*2), view=new DataView(buffer);
|
||||
view.setUint8(0,76);view.setUint8(1,86);view.setUint8(2,1);view.setUint8(3,direction);
|
||||
view.setUint32(4,turn);view.setUint32(8,seq);
|
||||
for(let i=0;i<pcm.length;i++)view.setInt16(12+i*2,pcm[i],true);
|
||||
return buffer;
|
||||
}
|
||||
export function readFrame(buffer) {
|
||||
const v=new DataView(buffer);
|
||||
if(v.byteLength<14 || v.getUint8(0)!==76 || v.getUint8(1)!==86 || v.getUint8(2)!==1 || v.getUint8(3)!==2 || (v.byteLength-12)%2)throw Error('Invalid audio header');
|
||||
const pcm=new Float32Array((v.byteLength-12)/2);
|
||||
for(let i=0;i<pcm.length;i++)pcm[i]=v.getInt16(12+2*i,true)/32768;
|
||||
return {turn:v.getUint32(4),seq:v.getUint32(8),pcm};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import {Resampler} from './audio-core.js';
|
||||
class Capture extends AudioWorkletProcessor {
|
||||
constructor(){super();this.resampler=new Resampler(sampleRate,16000);this.pending=[];this.enabled=false;this.total=0;
|
||||
this.port.onmessage=({data})=>{this.enabled=data.enabled;this.pending=[];this.resampler=new Resampler(sampleRate,16000);this.total=0;};
|
||||
}
|
||||
process(inputs,outputs){
|
||||
const audio=inputs[0]?.[0];
|
||||
if(audio){let energy=0;for(const x of audio)energy+=x*x;
|
||||
if(this.enabled){
|
||||
this.pending.push(...this.resampler.push(audio));
|
||||
while(this.pending.length>=320){const frame=new Int16Array(320);for(let i=0;i<320;i++)frame[i]=Math.round(Math.max(-1,Math.min(1,this.pending[i]))*32767);this.pending.splice(0,320);this.total+=320;this.port.postMessage({type:'frame',pcm:frame.buffer,endSample:this.total,rms:Math.sqrt(energy/audio.length),captureContextTime:currentTime},[frame.buffer]);}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('capture',Capture);
|
||||
@@ -0,0 +1,121 @@
|
||||
import {pcmFrame,readFrame} from './audio-core.js';
|
||||
const $=id=>document.getElementById(id);
|
||||
let ws,ctx,mic,stream,capture,play,turn=0,upSeq=0,downSeq=0,listening=false,auto=false,ready=false;
|
||||
let connectionGeneration=0,closingSocket=Promise.resolve(),connecting=false,selectionTimer=null;
|
||||
let events=[],captureTimes=[],lastEnd=null,latestMetrics={},rendered={},capturing=false,localAbortAt=null;
|
||||
let conversationId=null,historyRows=[],liveMessages=new Map(),sentSamples=0,sessionSecret='',debugItems=[],debugUrl=null;
|
||||
try{conversationId=localStorage.getItem('lanVoiceConversationId');}catch{}
|
||||
function renderHistory(){const root=$('history');root.replaceChildren();for(const row of [...historyRows,...liveMessages.values()]){const p=document.createElement('p');p.textContent=`${row.role}: ${row.text} [${row.status}; 播放:${row.playback??'未确认'}]`;root.append(p);}$('conversation').textContent='会话 '+(conversationId??'尚未建立')+';转录/回答将持久化到测试SQLite,无音频。';}
|
||||
function rememberConversation(id){conversationId=id;try{localStorage.setItem('lanVoiceConversationId',id);}catch{}renderHistory();}
|
||||
function status(text){$('status').textContent=text;}
|
||||
function control(data){if(ws?.readyState===WebSocket.OPEN)ws.send(JSON.stringify(data));}
|
||||
function clearAudio(){play?.port.postMessage({type:'clear',turn,mode:$('synthesisMode').value});}
|
||||
function haltCapture(){capturing=false;capture?.port.postMessage({enabled:false});}
|
||||
async function audio(){
|
||||
if(ctx){await ctx.resume();return;}
|
||||
if(!window.isSecureContext)throw Error('录音必须HTTPS或安全localhost;HTTP LAN IP不能录音');
|
||||
ctx=new AudioContext();await ctx.resume();
|
||||
await ctx.audioWorklet.addModule('/static/capture-worklet.js');await ctx.audioWorklet.addModule('/static/play-worklet.js');
|
||||
play=new AudioWorkletNode(ctx,'playback');play.connect(ctx.destination);clearAudio();
|
||||
play.port.onmessage=({data})=>{
|
||||
if(data.turn!==turn)return;
|
||||
if(data.type==='overflow'){abort();status('播放缓冲超限,已取消');return;}
|
||||
if(data.type==='drained'){setTimeout(()=>{if(data.turn===turn)control({type:'playback.drained',turn_id:turn});},200);status(auto?'播放队列已排空,200ms尾音保护后继续监听':'播放队列已排空');}
|
||||
if(data.type==='playback.metrics'||data.type==='drained'){rendered.playback=data.values??data.metrics;events.push({type:'browser.playback.metrics',turn_id:turn,values:rendered.playback});if(events.length>300)events.shift();showMetrics();}
|
||||
const observed=performance.now();
|
||||
if(data.type==='rendered'||data.type==='voiced'){rendered[data.type]={contextTime:data.contextTime,observedAtMs:observed,captureEndToRenderObservedMs:lastEnd===null?null:observed-lastEnd};events.push({type:'browser.'+data.type,turn_id:turn,...rendered[data.type]});showMetrics();}
|
||||
if(data.type==='cleared'&&localAbortAt!==null){events.push({type:'browser.abort_clear',turn_id:turn,ms:observed-localAbortAt});localAbortAt=null;showMetrics();}
|
||||
};
|
||||
stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:true,noiseSuppression:true,autoGainControl:true}});
|
||||
$('settings').textContent=JSON.stringify(stream.getAudioTracks()[0].getSettings(),null,2)+'\n这是实际返回设置,不是AEC效果保证;推荐耳机。AudioContext rate='+ctx.sampleRate;
|
||||
mic=ctx.createMediaStreamSource(stream);capture=new AudioWorkletNode(ctx,'capture');mic.connect(capture);capture.connect(ctx.destination);
|
||||
capture.port.onmessage=({data})=>{
|
||||
if(data.type!=='frame'||!capturing||!ready)return;
|
||||
$('level').textContent='麦克风 RMS '+data.rms.toFixed(4);
|
||||
const now=performance.now();sentSamples+=320;captureTimes.push({sample:sentSamples,time:now});if(captureTimes.length>1600)captureTimes.shift();
|
||||
draw(new Int16Array(data.pcm));
|
||||
if(ws.bufferedAmount>128000){abort();status('上行缓冲超限');return;}
|
||||
ws.send(pcmFrame(1,turn,++upSeq,new Int16Array(data.pcm)));
|
||||
};
|
||||
}
|
||||
function draw(pcm){const c=$('wave'),g=c.getContext('2d');g.clearRect(0,0,c.width,c.height);g.strokeStyle='#34d399';g.beginPath();for(let i=0;i<pcm.length;i++){const x=i*c.width/pcm.length,y=35-pcm[i]/32768*34;i?g.lineTo(x,y):g.moveTo(x,y);}g.stroke();}
|
||||
function showMetrics(){$('metrics').textContent=JSON.stringify({server:latestMetrics,browser:rendered,recent:events.slice(-6)},null,2);}
|
||||
function abort(){localAbortAt=performance.now();clearAudio();control({type:'abort',turn_id:turn});status('本地已停播,取消上游;持续采集保持');}
|
||||
async function begin(mode){if(!ready)throw Error('请先连接认证');await audio();haltCapture();clearAudio();auto=mode==='auto';listening=true;captureTimes=[];lastEnd=null;control({type:'listen',mode,state:'start',barge_in:$('barge').checked,start_windows:Number($('debounce').value)});}
|
||||
function disconnect(){connectionGeneration++;connecting=false;const old=ws;ws=null;if(old&&old.readyState!==WebSocket.CLOSED){closingSocket=new Promise(resolve=>{old.addEventListener('close',resolve,{once:true});setTimeout(resolve,800);});old.close();}clearAudio();haltCapture();ready=false;listening=false;stream?.getTracks().forEach(t=>t.stop());mic?.disconnect();ctx?.close();ctx=null;capture=null;play=null;stream=null;if($('mainVoice'))$('mainVoice').textContent='开始语音对话';status('已断开');}
|
||||
$('connect').onclick=async()=>{
|
||||
if(connecting||ws?.readyState===WebSocket.OPEN)return;
|
||||
connecting=true;const generation=++connectionGeneration;await closingSocket;if(generation!==connectionGeneration)return;
|
||||
const secret=$('token').value;sessionSecret=secret;$('token').value='';
|
||||
if(!secret&&document.body.dataset.friendly){try{const r=await fetch('/session/bootstrap',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});if(!r.ok)throw Error('访客连接不可用:仅指定LAN网段;高级设置可用管理员token');if(!sessionStorage.getItem('lanVoiceGuestBootstrapped')){conversationId=null;sessionStorage.setItem('lanVoiceGuestBootstrapped','1');}}catch(e){if(generation===connectionGeneration){connecting=false;status(e.message);}return;}}
|
||||
if(secret||!document.body.dataset.friendly)await fetch('/session/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});
|
||||
if(generation!==connectionGeneration)return;
|
||||
const socket=new WebSocket('wss://'+location.host+'/ws/dialogue');ws=socket;socket.binaryType='arraybuffer';
|
||||
const current=()=>ws===socket&&generation===connectionGeneration;
|
||||
socket.onopen=()=>{if(!current()){socket.close();return;}if(secret||!document.body.dataset.friendly)socket.send(JSON.stringify({type:'auth',token:secret}));};
|
||||
socket.onclose=()=>{if(!current())return;connecting=false;ready=false;sessionSecret='';clearAudio();haltCapture();status('连接已关闭(认证/Origin/单会话限制或断开),点击连接可重试');};
|
||||
socket.onerror=()=>{if(current()){connecting=false;status('WSS失败:检查证书信任、服务和Origin');}};
|
||||
socket.onmessage=({data})=>{
|
||||
if(!current())return;
|
||||
if(typeof data!=='string'){
|
||||
try{const frame=readFrame(data);if(frame.turn!==turn)return;if(frame.seq!==downSeq+1)throw Error('下行序号不连续');downSeq=frame.seq;play?.port.postMessage({type:'pcm',turn,pcm:frame.pcm},[frame.pcm.buffer]);}catch(e){abort();status(e.message);}return;
|
||||
}
|
||||
const event=JSON.parse(data);
|
||||
if(event.type==='auth'){control({type:'hello',codec:'pcm16',sample_rate:16000,channels:1,frame_duration:20,synthesis_mode:$('synthesisMode').value,voice_mode:$('voiceMode').value,persona:$('persona').value,tts_debug:$('ttsDebug').checked,...(conversationId?{conversation_id:conversationId}:{})});return;}
|
||||
if(event.type==='hello'){connecting=false;ready=true;document.body.dataset.connected='true';turn=event.turn_id;rememberConversation(event.conversation_id);$('voiceId').replaceChildren();for(const voice of event.voices){const option=document.createElement('option');option.value=voice.id;option.textContent=voice.id+' ['+(voice.default?'default / ':'')+voice.source+']';$('voiceId').append(option);}$('voiceId').value=event.voice_id;$('voiceId').disabled=$('persona').value!=='default';$('voiceInfo').textContent='固定登记reference:'+event.voice_id+';模式 '+event.voice_mode+',开始后锁定。';status('已认证;PCM16双工握手完成');return;}
|
||||
if(event.type==='abort'){
|
||||
turn=event.turn_id;upSeq=0;downSeq=0;clearAudio();rendered={};latestMetrics={};
|
||||
if(Number.isFinite(event.accepted_input_samples)){captureTimes=captureTimes.filter(p=>p.sample<=event.accepted_input_samples);sentSamples=event.accepted_input_samples;}
|
||||
for(const row of liveMessages.values())if(row.status==='generating')row.status='interrupted';
|
||||
renderHistory();
|
||||
if(event.reason.startsWith('history_')){listening=false;haltCapture();}
|
||||
return;
|
||||
}
|
||||
if(event.turn_id!==turn)return;
|
||||
if(event.type==='debug.saved'){control({type:'debug',action:'list'});return;}
|
||||
if(event.type==='debug.list'){debugItems=event.items;$('debugInfo').textContent='本会话已保存 '+debugItems.length+' 轮;最近状态 '+(debugItems[0]?.status??'无')+';marked='+(debugItems[0]?.marked_abnormal??false);return;}
|
||||
if(event.type==='history'){rememberConversation(event.conversation_id);historyRows=event.messages;liveMessages.clear();renderHistory();return;}
|
||||
if(event.type==='listen'&&event.state==='start'){if(!capturing){sentSamples=0;captureTimes=[];capturing=true;capture?.port.postMessage({enabled:true});}status('监听 '+event.mode+',双工='+$('barge').checked);}
|
||||
if(event.type==='capture.end'){
|
||||
const target=captureTimes.find(p=>p.sample>=event.end_sample);lastEnd=target?.time??performance.now();
|
||||
$('llm').textContent='';$('sentence').textContent='';status('STT → LLM → TTS');
|
||||
}
|
||||
if(event.type==='stt')$('stt').textContent=event.text;
|
||||
if(event.type==='llm'){$('llm').textContent+=event.text;const row=liveMessages.get(turn)??{role:'assistant',text:'',status:'generating'};row.text+=event.text;liveMessages.set(turn,row);renderHistory();}
|
||||
if(event.type==='tts'&&event.state==='sentence_start')$('sentence').textContent=event.text;
|
||||
if(event.type==='listen'&&event.state==='resumed'){status('播放确认收到;采集持续(耳机)');}
|
||||
if(event.type==='tts'&&event.state==='stop'){play?.port.postMessage({type:'end',turn});status('服务端音频已发完,等待浏览器播放队列排空');}
|
||||
if(event.type==='voice'){$('voiceId').value=event.voice_id;$('voiceId').disabled=event.locked;$('voiceInfo').textContent='固定reference '+event.voice_id+';锁定='+event.locked;}
|
||||
if(event.type==='llm.finished'){latestMetrics.llm_finished_ms=event.llm_finished_ms;latestMetrics.voice_mode=event.voice_mode;showMetrics();}
|
||||
if(event.type==='voice.metrics'){latestMetrics.voice_mode=event.voice_mode;latestMetrics.voice_id=event.voice_id;latestMetrics.tts_request_count=event.tts_request_count;showMetrics();}
|
||||
if(event.type==='metrics'){latestMetrics=event.values;showMetrics();}
|
||||
if(event.type==='error')status(event.message);
|
||||
const safe={type:event.type,turn_id:event.turn_id,seq:event.seq,server_ms:event.server_ms};
|
||||
if(event.type==='tts.metrics'){latestMetrics.lastSegment=event.values;showMetrics();}
|
||||
if(event.type==='metrics'||event.type==='tts.metrics')safe.values=event.values;
|
||||
events.push(safe);if(events.length>300)events.shift();
|
||||
};
|
||||
};
|
||||
$('auto').onclick=()=>begin('auto').catch(e=>status(e.message));
|
||||
$('manual').onpointerdown=event=>{event.currentTarget.setPointerCapture(event.pointerId);begin('manual').catch(e=>status(e.message));};
|
||||
function finishManual(){if(listening&&!auto){lastEnd=performance.now();haltCapture();control({type:'listen',mode:'manual',state:'stop'});listening=false;}}
|
||||
$('manual').onpointerup=finishManual;$('manual').onpointercancel=finishManual;
|
||||
$('abort').onclick=abort;$('disconnect').onclick=disconnect;
|
||||
$('newConversation').onclick=()=>{if(!ready)return;clearAudio();haltCapture();control({type:'history',action:'new',conversation_id:conversationId});};
|
||||
$('clearHistory').onclick=()=>{if(!ready)return;clearAudio();haltCapture();control({type:'history',action:'clear',conversation_id:conversationId});};
|
||||
$('export').onclick=()=>{const blob=new Blob([JSON.stringify({version:'0.7.1',events,server:latestMetrics,browser:rendered},null,2)],{type:'application/json'});const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='lan-voice-timing.json';a.click();URL.revokeObjectURL(url);};
|
||||
$('voiceId').onchange=()=>{if(ready)control({type:'voice',voice_id:$('voiceId').value});};
|
||||
$('ttsDebug').onchange=()=>{if(ready)control({type:'debug',action:'set',enabled:$('ttsDebug').checked});};
|
||||
$('markDebug').onclick=()=>{if(debugItems[0])control({type:'debug',action:'mark',debug_id:debugItems[0].debug_id});else status('尚无保存轮,无法恢复旧音频');};
|
||||
async function fetchDebug(kind){if(!debugItems[0])throw Error('无保存轮');const r=await fetch('/debug/download',{method:'POST',headers:{'Authorization':'Bearer '+sessionSecret,'Content-Type':'application/json'},body:JSON.stringify({debug_id:debugItems[0].debug_id,conversation_id:conversationId,kind})});if(!r.ok)throw Error('debug download '+r.status);return r.blob();}
|
||||
$('replayDebug').onclick=async()=>{try{abort();const blob=await fetchDebug('wav');if(debugUrl)URL.revokeObjectURL(debugUrl);debugUrl=URL.createObjectURL(blob);$('debugPlayer').src=debugUrl;await $('debugPlayer').play();}catch(e){status(e.message);}};
|
||||
$('metadataDebug').onclick=async()=>{try{const blob=await fetchDebug('metadata'),url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download='tts-metadata.json';a.click();URL.revokeObjectURL(url);}catch(e){status(e.message);}};
|
||||
if(document.body.dataset.friendly){
|
||||
function selectRole(role){clearTimeout(selectionTimer);control({type:'abort',turn_id:turn});disconnect();conversationId=null;historyRows=[];liveMessages.clear();debugItems=[];renderHistory();$('persona').disabled=false;$('persona').value=role;document.body.dataset.connected='false';document.querySelectorAll('[data-persona]').forEach(c=>{const selected=c.dataset.persona===role;c.classList.toggle('selected',selected);c.setAttribute('aria-pressed',String(selected));});status('已停止旧监听,正在为所选角色建立新会话');selectionTimer=setTimeout(()=>$('connect').onclick(),100);}
|
||||
document.querySelectorAll('[data-persona]').forEach(card=>{card.setAttribute('aria-pressed',String(card.classList.contains('selected')));card.onclick=()=>selectRole(card.dataset.persona);});
|
||||
$('persona').onchange=()=>selectRole($('persona').value);
|
||||
$('mainVoice').onclick=async()=>{if(capturing){control({type:'listen',mode:'auto',state:'stop'});abort();haltCapture();$('mainVoice').textContent='开始语音对话';status('已停止麦克风');return;}if(!ready){await $('connect').onclick();status('正在连接,请连接完成后再次点击开始;如失败请检查证书');return;}try{await begin('auto');$('mainVoice').textContent='停止语音对话';}catch(e){status('麦克风失败:'+e.message+'。请检查HTTPS证书与浏览器麦权限。');}};
|
||||
$('logoutGuest').onclick=async()=>{disconnect();await fetch('/session/logout',{method:'POST',headers:{'Content-Type':'application/json'},body:'{}'});conversationId=null;sessionStorage.removeItem('lanVoiceGuestBootstrapped');localStorage.removeItem('lanVoiceConversationId');status('访客会话已撤销');};
|
||||
$('connect').onclick();
|
||||
}
|
||||
window.addEventListener('beforeunload',()=>{clearAudio();ws?.close();});
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>LAN Voice 硬件模拟器</title><style>body{font:16px system-ui;max-width:1000px;margin:24px auto;padding:16px;background:#111827;color:#e5e7eb}button,input,select{padding:10px;margin:5px;border-radius:6px}section{background:#1f2937;padding:15px;margin:12px 0;border-radius:8px}pre{white-space:pre-wrap;overflow-wrap:anywhere}canvas{width:100%;height:70px}#status{color:#93c5fd}label{display:inline-block}button:disabled{opacity:.4}</style></head><body><h1>LAN Voice 浏览器硬件模拟器</h1><p>自定义 PCM 协议,不是完全小智兼容。请用耳机。自动模式使用 batch SenseVoice;服务端VAD不消回声。</p><section><label>共享 token <input id="token" type="password" autocomplete="off" placeholder="仅内存,不保存"></label><select id="codec"><option value="pcm16">PCM16</option><option disabled>Opus:浏览器真实编码链路未实现</option></select><label>合成策略(重连生效)<select id="synthesisMode"><option value="balanced">平衡默认:240ms音频缓冲,少碎句</option><option value="low_latency">低延迟:100ms缓冲,欠供风险较高</option></select></label><label>声音生成(重连生效)<select id="voiceMode"><option value="continuous_voice">默认每轮单generator:等全文</option><option value="fragment">实验分片:音色/韵律跳变风险</option></select></label><label>已登记固定音色<select id="voiceId" disabled></select></label><p id="voiceInfo">默认登记reference;开始前选择,开始后锁定。</p><label>角色(重连;角色强制新会话)<select id="persona"><option value="default">普通助手</option><option value="lvbu">吕布:固定clone+lore</option><option value="yangmi_fiction">杨密(原创测试角色)</option></select></label><p>杨密为原创角色:已使用用户确认许可的普通女生前7秒参考clone,非杨幂仿声;仅本地非商用测试,听感相似未验证。</p><label><input type="checkbox" id="ttsDebug" checked>下一轮记录TTS debug(保存合成台词与音频,限额本地测试)</label><button id="markDebug">标记上一轮异常</button><button id="replayDebug">回放上一轮debug WAV</button><button id="metadataDebug">下载上一轮metadata</button><audio id="debugPlayer" controls></audio><p id="debugInfo">旧轮未保存不能恢复。debug不保存麦克风/token/reference。</p><button id="connect">连接</button><button id="auto">开始持续对话(耳机)</button><button id="manual">按住说话(调试)</button><button id="abort">打断</button><button id="disconnect">断开</button><label><input type="checkbox" id="barge" checked>双工语音打断(默认;关闭仅半双工调试)</label><label>起声debounce<select id="debounce"><option value="3">96ms默认</option><option value="2">64ms</option></select></label><p>默认计算/播放期间持续收音。全双工存在播放自回声自激风险;实际AEC/NS设置不是效果证明,请用耳机。</p><button id="newConversation">新会话</button><button id="clearHistory">清空当前会话历史</button><p id="conversation"></p><div id="history"></div><p id="status">未连接</p></section><section><canvas id="wave" width="900" height="70"></canvas><p id="level">麦克风音量:0</p><pre id="settings">麦克风未请求;HTTPS或安全localhost需要录音权限。AEC设置不保证实际效果。</pre></section><section><h3>ASR</h3><p id="stt"></p><h3>LLM正文</h3><p id="llm"></p><h3>当前句字幕</h3><p id="sentence"></p></section><section><p>平衡缓冲会增加首音等待(不是免费优化),240ms是累计音频量不是固定墙钟等待;模型持续供给慢仍可能卡顿。</p><h3>延迟(不同机器时钟不相减)</h3><pre id="metrics"></pre><button id="export">导出计时(无音频/token)</button><p>rendered=AudioWorklet首次呈现样本,不是硬件实际听到;voiced只是−40dBFS近似,不保证语义有效。</p></section><script type="module" src="/static/client.js"></script></body></html>
|
||||
@@ -0,0 +1 @@
|
||||
:root{color-scheme:dark;--bg:#171a1c;--panel:#23272a;--muted:#bac2c6;--accent:#eac6a2}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:#f6f2ed;font:16px/1.6 system-ui,sans-serif}main{max-width:980px;margin:auto;padding:30px 24px}header{display:flex;align-items:center;gap:20px;color:var(--muted);font-size:13px}.brand{font-size:25px;color:var(--accent);margin-right:auto}a{color:var(--accent)}.hero{padding:48px 0 25px}.hero small{color:var(--accent);letter-spacing:2px}h1{font-size:clamp(32px,5vw,52px);line-height:1.2;font-weight:600;margin:18px 0}p{color:var(--muted)}.cards{display:grid;grid-template-columns:repeat(3,1fr);gap:15px}.card{display:flex;flex-direction:column;text-align:left;padding:22px;min-height:170px;background:var(--panel);border:1px solid #454b4f}.card span{font-size:35px;color:var(--accent)}.card b{font-size:20px}.card small{color:var(--muted)}.card.selected{border-color:var(--accent);background:#37332f}button,input,select{font:inherit;border-radius:12px;padding:10px 16px;border:1px solid #555e64;background:#30363a;color:#f6f2ed;margin:5px 4px 5px 0}button{cursor:pointer;transition:background .15s}button:hover{background:#414a50}button:focus-visible,summary:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid var(--accent);outline-offset:3px}.voice-panel,.chat,.privacy,details{margin-top:24px;padding:24px;border-radius:20px;background:var(--panel)}.voice-panel{text-align:center}.primary{background:var(--accent);color:#251e18;border:0;font-weight:700;min-width:240px;padding:16px 28px}.primary:hover{background:#f5d9bb}.status{display:flex;justify-content:center;gap:10px;align-items:center}.status i{width:8px;height:8px;border-radius:50%;background:#a4c9b2}.status p{margin:0}canvas{width:100%;height:70px}.hint,footer,.privacy p,details p{font-size:13px;color:var(--muted)}h2{font-size:21px}#history p{background:#303639;padding:14px 18px;border-radius:12px;white-space:pre-wrap;overflow-wrap:anywhere}.subtitle{color:var(--accent)}.current small{color:var(--accent)}audio{display:block;width:100%;margin-top:12px}summary{cursor:pointer;color:var(--accent)}pre{white-space:pre-wrap;overflow-wrap:anywhere;background:#181d20;padding:12px;border-radius:10px;font-size:12px}footer{padding:24px 4px}label{display:inline-block}input[type=password]{max-width:100%}@media(max-width:620px){main{padding:20px 14px}header{flex-wrap:wrap;gap:12px}.hero{padding-top:30px}.cards{grid-template-columns:1fr}.card{min-height:auto;display:grid;grid-template-columns:45px 1fr;padding:16px}.card small{grid-column:2}.voice-panel,.chat,.privacy,details{padding:18px}.primary{width:100%;min-width:0}}@media(prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important}}
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>声伴 · LAN Voice</title><link rel="stylesheet" href="/static/home.css"></head><body data-friendly="true"><main><header><span class="brand">◌ 声伴</span><span>仅在你的局域网 · v0.7</span><a href="/debug">开发调试页</a></header><section class="hero"><small>让对话,自然发生</small><h1>选一位伙伴,<br>说说今天的事。</h1><p>点击才会开启麦克风。建议戴耳机,声音打断默认开启。</p></section><section class="cards" aria-label="选择角色"><button class="card selected" data-persona="default"><span>◎</span><b>普通助手</b><small>清晰、实用,陪你理顺思路</small></button><button class="card" data-persona="yangmi_fiction"><span>✧</span><b>杨密</b><small>原创测试角色 · 机敏温暖<br>普通女生授权参考,非真人仿声</small></button><button class="card" data-persona="lvbu"><span>◇</span><b>吕布</b><small>威武而简短 · 本地角色测试</small></button></section><section class="voice-panel"><div class="status"><i></i><p id="status" role="status" aria-live="polite">准备好了,点击开始</p></div><canvas id="wave" width="900" height="70" aria-label="麦克风波形"></canvas><button id="mainVoice" class="primary">开始语音对话</button><button id="abort">打断回答</button><p id="level">麦克风尚未开启</p><p class="hint">浏览器AEC设置不保证实际消回声。角色切换会建立新会话。</p></section><section class="chat"><h2>这段对话</h2><p id="conversation"></p><div id="history" aria-live="polite"></div><div class="current"><small>你刚刚说</small><p id="stt"></p><small>回答正在形成</small><p id="llm"></p><p id="sentence" class="subtitle"></p></div></section><section class="privacy"><label><input type="checkbox" id="ttsDebug" checked>记录合成音频用于排查异常</label><p>默认记录TTS台词和合成WAV;不记录麦克风或token。最多20轮/200MiB,72小时在操作时清理。聊天文字存于本机测试数据库。</p><button id="markDebug">标记上一轮异常</button><button id="replayDebug">回放上一轮</button><button id="metadataDebug">下载记录</button><audio id="debugPlayer" controls></audio><p id="debugInfo">尚无合成记录</p><button id="newConversation">新会话</button><button id="clearHistory">清空当前历史</button><button id="logoutGuest">退出访客会话</button></section><details><summary>高级设置与计时</summary><label>管理员手动token<input id="token" type="password" autocomplete="off" placeholder="访客无需填写;仅内存"></label><button id="connect">连接 / 管理员连接</button><button id="disconnect">断开</button><button id="auto">持续监听</button><button id="manual">按住说话调试</button><select id="persona" aria-label="角色"><option value="default">普通助手</option><option value="yangmi_fiction">杨密(原创测试角色)</option><option value="lvbu">吕布</option></select><select id="codec" aria-label="编码"><option>pcm16</option><option disabled>Opus未实现</option></select><select id="synthesisMode" aria-label="缓冲模式"><option value="balanced">240ms平衡缓冲</option><option value="low_latency">100ms低延迟实验</option></select><select id="voiceMode" aria-label="声音连续性"><option value="continuous_voice">每轮单generator</option><option value="fragment">分片质量风险实验</option></select><select id="voiceId" disabled aria-label="固定音色"></select><p id="voiceInfo"></p><label><input id="barge" type="checkbox" checked>双工语音打断</label><select id="debounce" aria-label="起声确认"><option value="3">96ms</option><option value="2">64ms</option></select><pre id="settings">等待麦克风授权</pre><pre id="metrics"></pre><button id="export">导出计时(无正文/音频/token)</button><p>软件render/drain不是硬件实际听到;不同机器时钟不相减。HTTPS证书必须可信,HTTP LAN IP不能录音。</p></details><footer>Cookie访客鉴权,不是账号。仅允许指定LAN网段与loopback;同网段用户可调用模型,不应视为可信网络。</footer></main><script type="module" src="/static/client.js"></script></body></html>
|
||||
@@ -0,0 +1,21 @@
|
||||
import {Resampler} from './audio-core.js';
|
||||
import {PlaybackBuffer} from './playback-core.js';
|
||||
class Playback extends AudioWorkletProcessor {
|
||||
constructor(){
|
||||
super();this.first=false;this.voiced=false;this.blocks=0;this.resampler=new Resampler(48000,sampleRate);
|
||||
this.queue=new PlaybackBuffer(sampleRate,event=>this.port.postMessage({...event,contextTime:currentTime}));
|
||||
this.port.onmessage=({data})=>{
|
||||
if(data.type==='clear'){if(data.mode)this.queue.configure(data.mode);this.queue.clear(data.turn);this.first=false;this.voiced=false;this.blocks=0;this.resampler=new Resampler(48000,sampleRate);this.port.postMessage({type:'cleared',turn:data.turn,contextTime:currentTime});}
|
||||
if(data.type==='end')this.queue.end(data.turn);
|
||||
if(data.type==='pcm'&&data.turn===this.queue.turn)this.queue.push(data.turn,this.resampler.push(data.pcm),currentTime*1000);
|
||||
};
|
||||
}
|
||||
process(inputs,outputs){
|
||||
const out=outputs[0][0],used=this.queue.render(out,currentTime*1000)||0;
|
||||
if(used&&!this.first){this.first=true;this.port.postMessage({type:'rendered',turn:this.queue.turn,contextTime:currentTime});}
|
||||
if(!this.voiced){for(let i=0;i<used;i++)if(Math.abs(out[i])>.01){this.voiced=true;this.port.postMessage({type:'voiced',turn:this.queue.turn,contextTime:currentTime+i/sampleRate});break;}}
|
||||
if(++this.blocks%32===0&&!this.queue.done)this.port.postMessage({type:'playback.metrics',turn:this.queue.turn,values:this.queue.snapshot()});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('playback',Playback);
|
||||
@@ -0,0 +1,31 @@
|
||||
export class PlaybackBuffer {
|
||||
constructor(rate, emit=()=>{},mode='balanced') {this.rate=rate;this.emit=emit;this.buffer=new Float32Array(rate*2);this.configure(mode);this.clear(0);}
|
||||
configure(mode){this.mode=mode==='low_latency'?'low_latency':'balanced';this.startupMs=this.mode==='balanced'?240:100;this.baseRecoveryMs=this.mode==='balanced'?240:150;this.recoveryCapMs=this.mode==='balanced'?400:250;}
|
||||
clear(turn){this.turn=turn;this.read=0;this.length=0;this.ending=false;this.started=false;this.rebuffer=false;this.done=false;this.firstInput=null;this.waitAt=null;this.lastArrival=null;this.recoveryMs=this.baseRecoveryMs;this.metrics={underruns:0,underSupplyMs:0,rebufferMs:0,startBufferDelayMs:0,minQueueMs:null,chunkCount:0,lastChunkMs:null,lastInterarrivalMs:null,maxInterarrivalMs:0};}
|
||||
push(turn,samples,now){if(turn!==this.turn||this.done)return;if(this.firstInput===null)this.firstInput=now;if(this.length+samples.length>this.buffer.length){this.emit({type:'overflow',turn});return;}if(this.lastArrival!==null){const gap=Math.max(0,now-this.lastArrival);this.metrics.lastInterarrivalMs=gap;this.metrics.maxInterarrivalMs=Math.max(this.metrics.maxInterarrivalMs,gap);}this.lastArrival=now;this.metrics.chunkCount++;this.metrics.lastChunkMs=samples.length*1000/this.rate;for(const x of samples){this.buffer[(this.read+this.length)%this.buffer.length]=x;this.length++;}}
|
||||
end(turn){if(turn===this.turn)this.ending=true;}
|
||||
snapshot(){return {mode:this.mode,effectiveStartupMs:this.startupMs,queueMs:this.length*1000/this.rate,recoveryTargetMs:this.recoveryMs,recoveryCapMs:this.recoveryCapMs,...this.metrics};}
|
||||
render(out,now){
|
||||
out.fill(0);
|
||||
if(this.done)return;
|
||||
const enough=this.length>=Math.ceil(this.rate*(this.rebuffer?this.recoveryMs:this.startupMs)/1000);
|
||||
if(!this.started||this.rebuffer){
|
||||
if(!enough&&!this.ending){if(this.rebuffer)this.metrics.underSupplyMs+=out.length*1000/this.rate;return;}
|
||||
if(this.length){
|
||||
if(!this.started){this.metrics.startBufferDelayMs=Math.max(0,now-this.firstInput);this.started=true;}
|
||||
if(this.rebuffer){this.metrics.rebufferMs+=Math.max(0,now-this.waitAt);this.rebuffer=false;}
|
||||
}
|
||||
}
|
||||
let used=0;
|
||||
while(used<out.length&&this.length){out[used++]=this.buffer[this.read];this.read=(this.read+1)%this.buffer.length;this.length--;}
|
||||
if(this.started&&!this.ending){const ms=this.length*1000/this.rate;this.metrics.minQueueMs=this.metrics.minQueueMs===null?ms:Math.min(this.metrics.minQueueMs,ms);}
|
||||
if(used<out.length&&this.started&&!this.ending&&!this.rebuffer){
|
||||
this.rebuffer=true;this.metrics.underruns++;this.recoveryMs=Math.min(this.recoveryCapMs,this.baseRecoveryMs+(this.metrics.underruns-1)*80);this.waitAt=now+used*1000/this.rate;this.metrics.underSupplyMs+=(out.length-used)*1000/this.rate;
|
||||
}
|
||||
if(this.ending&&!this.length){
|
||||
if(this.rebuffer){this.metrics.rebufferMs+=Math.max(0,now-this.waitAt);this.rebuffer=false;}
|
||||
this.done=true;this.emit({type:'drained',turn:this.turn,metrics:this.snapshot()});
|
||||
}
|
||||
return used;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import {PlaybackBuffer} from './playback-core.js';
|
||||
export function runPlaybackTests(){
|
||||
const assert=(value,name)=>{if(!value)throw Error(name);};const results=[];
|
||||
const q=new PlaybackBuffer(1000,e=>results.push(e.type),'low_latency');q.clear(1);
|
||||
q.push(1,new Float32Array(80).fill(.2),0);q.render(new Float32Array(20),20);assert(!q.started&&q.metrics.underruns===0,'startup no underrun');
|
||||
q.push(1,new Float32Array(40).fill(.2),30);const out=new Float32Array(20);q.render(out,30);assert(q.started&&out[0]>.1,'100ms buffered start');
|
||||
for(let t=50;t<=150;t+=20)q.render(out,t);
|
||||
assert(q.metrics.underruns===1&&q.rebuffer,'single underrun');
|
||||
q.push(1,new Float32Array(80).fill(.3),180);q.render(out,180);assert(q.rebuffer,'wait recovery threshold');
|
||||
q.push(1,new Float32Array(80).fill(.3),200);q.render(out,200);assert(!q.rebuffer&&out[0]>.2,'recovery');
|
||||
q.clear(2);q.push(1,new Float32Array(100),210);q.render(out,220);assert(q.length===0&&q.metrics.underruns===0&&!q.ending,'clear immediate old turn rejected');
|
||||
q.push(2,new Float32Array(10).fill(.5),230);q.end(2);q.render(out,240);assert(q.done&&out[0]>.4&&q.metrics.underruns===0,'short final drains');
|
||||
q.clear(3);q.push(3,new Float32Array(2001),250);assert(results.includes('overflow')&&q.length===0,'max two seconds');
|
||||
q.clear(4);q.end(4);q.render(out,260);assert(q.done&&q.metrics.underruns===0,'empty end');
|
||||
function simulate(mode,gap){const p=new PlaybackBuffer(1000,()=>{},mode);p.clear(1);const block=new Float32Array(10);for(let t=0;t<gap*8+400;t+=10){if(t%gap===0&&t/gap<8)p.push(1,new Float32Array(160).fill(.2),t);if(t===gap*7)p.end(1);p.render(block,t);}return p.snapshot();}
|
||||
const cadence=[];
|
||||
for(const gap of [170,180,190]){const low=simulate('low_latency',gap),balanced=simulate('balanced',gap);assert(balanced.underruns<low.underruns,'balanced cadence reduces underruns '+gap);assert(balanced.startBufferDelayMs>=gap,'explicit startup cost');assert(balanced.maxInterarrivalMs===gap,'interarrival metric');cadence.push({gap,low,balanced});}
|
||||
return {status:'passed',cases:['jitter/startup','underrun_recovery','clear_old_turn','short_tail_end','max_buffer','empty_end','160ms chunks 170/180/190ms cadence'],cadence,events:results};
|
||||
}
|
||||
Reference in New Issue
Block a user