122 lines
15 KiB
JavaScript
122 lines
15 KiB
JavaScript
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();});
|