Files
piik/scripts/network-lab/page.ts
T
AAA 42588f3a8b fix(media): stabilize reconnects and quality recovery
This maintenance phase corrects connection and media recovery after startup deadlines, congestion and packet loss. Route selection remains a bounded operation; Pion and LiveKit continue to own congestion control, adaptation and retransmission.

Changes stay within existing owners:

- Preserve an untried SFU fallback when a connected P2P candidate produces no first frame before its deadline. Retire expired native preparations using the current edge identity.
- Correct paced output, probe accounting and partial-recovery demand. Negotiate RTX consistently for native forwarding and SFU publication, including repaired stream identifiers for simulcast.
- Return working IPv4 mappings without waiting for optional IPv6 work, and separate NAT observations by the local socket/address that produced them.
- Keep optional App availability separate from basic source selection; stabilize nickname/chat layouts and restore volume from zero correctly.
- Retry complete Gitee reads, including response bodies and hash verification. Ambiguous uploads remain single attempts and are reconciled against the remote inventory before rerunning.

Related: #468, #464, #471. The repairs affect paths discussed in these reports; incomplete field diagnostics do not establish that each report has the same cause, so this PR does not automatically close them.

## Validation

- Web type checks, production build and 1,624 tests passed. Go core, formatting, vet and local target builds passed.
- Delayed RTX recovery reproduced the defect before the fix; the repaired-SSRC mutation also fails the focused regression. Real Windows H.264 and VP8 capture passed the SFU gates, including settings, reload recovery and retirement.
- The media lifecycle gate passed all 14 trials across Browser/App pairings and P2P/SFU handoffs. Native connectivity, paced forwarding and negative-control checks passed.
- Responsive UI and current website architecture links were checked; Gitee's current release was independently downloaded and matched against the GitHub originals.
- [Platform candidate](https://github.com/TNTcraftHIM/Piik/actions/runs/38669095115): all five Apps, both Server architectures and container checks passed at `c534573b`. Subsequent tracked changes only update documentation, the complete-matrix CI budget and race-test coverage.
- [Full network comparison](https://github.com/TNTcraftHIM/Piik/actions/runs/38667624364) completed 70 trials before the batch's 45-minute limit. The [remaining scenario](https://github.com/TNTcraftHIM/Piik/actions/runs/38672805155) passed three paired repetitions; all 71 scenario/setting variants are covered, with 58 media and 13 expected/observed unavailable outcomes. Six negative controls passed, and owned resources were cleaned up. These are controlled observations, not a public success rate.
- The final validation also includes the shared forwarder under the Go race detector. The separate sole-active-output publication experiment still shows inconsistent recovery: two of four current-code repeats did not pass its recovery observation, so the limitation below remains open.

The native SFU allocator still has a measured recovery limitation when only its lowest rate-controlled encoding is active. Fixing that requires a supported upstream demand input; no second controller or allocator fork is introduced. Unmatched capture-failure reports and physical-platform coverage retain their documented evidence limits.

## Release notes

### 中文

这是一次连接与播放稳定性更新,重点改善重连、弱网后的画质恢复和下载镜像可靠性。与 Piik 2.0.0 保持兼容。

- 修复连接等待超时后过早跳过备用线路的问题,保留尚未尝试的媒体服务器兜底机会。
- 改善原生分享在网络拥塞后的画质恢复,并修复转发和媒体服务器发布链路上的视频重传协商遗漏。
- 修复原生观看准备超时后的清理与重试,以及音量从零恢复时的异常。
- 避免可选的 IPv6 端口映射拖慢 IPv4 准备,并修正多网卡环境下的 NAT 预测观测归属。
- 修复昵称编辑、聊天字数变化引起的布局移动;保持 App 提示简洁,并为更新提示补充官网备用下载入口。
- 修复 Gitee 镜像同步在传输中途断开时未重试的问题,校验通过后才完成镜像发布。

仍在跟进:部分原生媒体服务器链路的弱网后恢复仍可能偏慢;尚缺匹配诊断的采集失败反馈不能确认已解决。

### English

This maintenance update improves connection and playback recovery after interruptions and congestion, along with download-mirror reliability. It remains compatible with Piik 2.0.0.

- Preserve untried media-server fallback routes when a connection reaches its waiting deadline.
- Improve native sharing quality recovery after congestion and fix missing video retransmission negotiation in forwarding and media-server publication paths.
- Correct cleanup and retry after native viewing preparation expires, and restore playback volume correctly from zero.
- Prevent optional IPv6 port mapping from delaying IPv4 preparation, and associate NAT-prediction observations with the correct local interface.
- Stabilize nickname editing and chat counters, keep App guidance unobtrusive, and add the website's alternate downloads to update notices.
- Retry interrupted Gitee mirror transfers and complete publication only after verification succeeds.

Still under investigation: recovery after congestion can remain slow on some native media-server paths. Capture-failure reports without matching diagnostics are not claimed as resolved.
2026-10-14 22:57:17 -04:00

159 lines
10 KiB
TypeScript

// Synthetic capture is the only media substitution. PeerConnection, signaling,
// candidate selection and readiness remain the production implementation.
export const pageProbe = String.raw`(() => {
localStorage.setItem('piik:ui-lang','en'); localStorage.setItem('piik:ui-mode','text');
const peers=[], sockets=[], events=[], errors=[], controls=[];
let route=null,natPrediction=null,freezeCapture=()=>{},resumeCapture=()=>{},peerSignalDelay=0,peerSignalReleaseAt=0;
let observedVideo=null,frameCallback=0,renderedFrames=0,lastFrameAt=0,maxFrameGapMs=0;
const observeVideo=video=>{
if(video===observedVideo)return;
observedVideo?.cancelVideoFrameCallback(frameCallback);observedVideo=video;
if(!video)return;
const frame=now=>{
if(video!==observedVideo)return;
if(lastFrameAt)maxFrameGapMs=Math.max(maxFrameGapMs,now-lastFrameAt);
lastFrameAt=now;renderedFrames++;frameCallback=video.requestVideoFrameCallback(frame);
};frameCallback=video.requestVideoFrameCallback(frame);
};
const PC=RTCPeerConnection, WS=WebSocket;
const picture=document.createElement('canvas');picture.width=64;picture.height=36;
const pictureContext=picture.getContext('2d',{willReadFrequently:true});
const record=(list,value)=>{ list.push(value); if(list.length>240)list.shift(); };
window.addEventListener('unhandledrejection', e=>record(errors,String(e.reason)));
window.RTCPeerConnection=class extends PC { constructor(...args){super(...args);const peerId=peers.push(this)-1;
this.addEventListener('icecandidate',e=>record(events,{at:performance.now(),type:'ice-candidate',peerId,candidate:e.candidate?.candidate}));
this.addEventListener('icecandidateerror',e=>record(events,{at:performance.now(),type:'ice-error',peerId,code:e.errorCode,reason:e.errorText,url:e.url}));
} };
window.WebSocket=class extends WS {
constructor(...args){ super(...args); sockets.push(this);
const scope=this.url.includes('/control')?'app':'room';
for(const type of ['open','close','error'])this.addEventListener(type,()=>record(events,{at:performance.now(),type:'ws-'+type,scope}));
this.addEventListener('message', event=>{
let message; try{message=JSON.parse(event.data);}catch{return;}
if(typeof message.routePolicy?.natPrediction==='boolean')natPrediction=message.routePolicy.natPrediction;
if(message.type==='route-update'&&message.phase==='active')route=message.assignment.upstream.kind;
const value={at:performance.now(),type:message.type,state:message.state,reason:message.reason,scope,
phase:message.phase,route:message.assignment?.upstream?.kind,connectionId:message.connectionId};
if(message.type==='punch-prepared')value.predictionStep=message.prediction?.step;
if(message.type==='punch-complete')value.connected=message.connected;
for(const key of ['localType','remoteType','natTraversalPath','sampleWindowMs','intervalFramesEncoded',
'framesPerSecond','bitrateKbps','availableOutgoingKbps','width','height'])if(message[key]!==undefined)value[key]=message[key];
record(events,value);
});
}
send(raw){
let m;try{m=JSON.parse(raw);}catch{}
if(this.url.includes('/control')){
if(m)record(controls,{type:m.type,connectionId:m.connectionId,punched:m.punched});
}else if(m?.type==='signal'&&peerSignalDelay>0){
// Delay real signaling once; never invent SDP, route state or readiness.
if(!peerSignalReleaseAt)peerSignalReleaseAt=performance.now()+peerSignalDelay;
const remaining=peerSignalReleaseAt-performance.now();
if(remaining>0){
record(events,{at:performance.now(),type:'test-signal-delayed',connectionId:m.connectionId});
setTimeout(()=>{if(this.readyState===WS.OPEN)super.send(raw);},remaining);return;
}
}
super.send(raw);
}
};
navigator.mediaDevices.getDisplayMedia=async()=>{
const canvas=document.createElement('canvas'); canvas.width=1280; canvas.height=720;
const ctx=canvas.getContext('2d');let frame=0;
const draw=()=>{ctx.fillStyle='#19292f';ctx.fillRect(0,0,1280,720);
// Deterministic moving detail puts real pressure on a constrained encoder.
for(let y=0;y<12;y++)for(let x=0;x<20;x++){
ctx.fillStyle='hsl('+((x*37+y*19+frame*3)%360)+' 65% 55%)';
ctx.fillRect((x*64+frame*7)%1280,y*60,45,42);
}
ctx.fillStyle='#fff';ctx.font='70px sans-serif';ctx.fillText(String(frame++),80,540);};
draw();let timer=setInterval(draw,1000/30);const stream=canvas.captureStream(30);
freezeCapture=()=>{clearInterval(timer);timer=null;};
resumeCapture=()=>{if(!timer)timer=setInterval(draw,1000/30);};
const video=stream.getVideoTracks()[0],stop=video.stop.bind(video);
video.stop=()=>{clearInterval(timer);stop();};
const ac=new AudioContext(),osc=ac.createOscillator(),dest=ac.createMediaStreamDestination();
osc.frequency.value=440;osc.connect(dest);osc.start();await ac.resume();
const sound=dest.stream.getAudioTracks()[0],stopSound=sound.stop.bind(sound);let stopped=false;
sound.stop=()=>{if(stopped)return;stopped=true;osc.stop();void ac.close();stopSound();};
stream.addTrack(sound);return stream;
};
window.networkLab={freezeCapture:()=>freezeCapture(),resumeCapture:()=>resumeCapture(),delayPeerSignals:ms=>{peerSignalDelay=ms;peerSignalReleaseAt=0;},
resetPlaybackProgress:()=>{renderedFrames=0;lastFrameAt=performance.now();maxFrameGapMs=0;},async signalProbe(){
const socket=sockets.findLast(s=>!s.url.includes('/control')&&s.readyState===WS.OPEN);
if(!socket)return false;
return new Promise(resolve=>{
const finish=value=>{clearTimeout(timer);socket.removeEventListener('message',receive);resolve(value);};
const receive=event=>{try{if(JSON.parse(event.data).type==='route-diagnostic-snapshot')finish(true);}catch{}};
const timer=setTimeout(()=>finish(false),1800);socket.addEventListener('message',receive);
socket.send(JSON.stringify({type:'request-route-diagnostic'}));
});
},async sample(){
const stats=[];
for(const [peerId,peer] of peers.entries()){if(peer.connectionState==='closed')continue;
const report=await peer.getStats();
for(const row of report.values()){
if(row.type==='candidate-pair')stats.push({type:'pair-state',peerId,state:row.state,
requestsSent:row.requestsSent,responsesReceived:row.responsesReceived,localCandidateId:row.localCandidateId,remoteCandidateId:row.remoteCandidateId});
if(row.type==='local-candidate'||row.type==='remote-candidate')stats.push({type:row.type,id:row.id,peerId,
address:row.address,port:row.port,protocol:row.protocol,candidateType:row.candidateType});
if(row.type==='inbound-rtp'||row.type==='outbound-rtp'||row.type==='remote-inbound-rtp'){
const selected={type:row.type,kind:row.kind,id:row.id,peerId};
for(const key of ['framesDecoded','framesReceived','framesEncoded','framesDropped','framesPerSecond',
'frameWidth','frameHeight','bytesReceived','bytesSent','packetsLost','packetsReceived','nackCount','qpSum',
'retransmittedPacketsReceived','retransmittedPacketsSent','freezeCount','totalFreezesDuration',
'pliCount','totalDecodeTime','jitterBufferDelay','jitterBufferEmittedCount','totalAudioEnergy',
'totalSamplesDuration','roundTripTime','reportsReceived','qualityLimitationReason','targetBitrate']){
if(row[key]!==undefined)selected[key]=row[key];
}stats.push(selected);
}
if(row.type==='candidate-pair'&&row.nominated&&row.state==='succeeded'){
const local=report.get(row.localCandidateId),remote=report.get(row.remoteCandidateId);
stats.push({type:'selected-pair',peerId,rtt:row.currentRoundTripTime,bwe:row.availableOutgoingBitrate,
localType:local?.candidateType,remoteType:remote?.candidateType,protocol:remote?.protocol,
localAddress:local?.address,remoteAddress:remote?.address,localPort:local?.port,remotePort:remote?.port});
}
}
}
const video=document.querySelector('video');
observeVideo(video);
const playbackTrack=video?.srcObject?.getVideoTracks?.()[0];
const playbackPeerId=playbackTrack?peers.findIndex(peer=>peer.getReceivers().some(receiver=>receiver.track===playbackTrack)):-1;
let pictureHash=null;
if(video?.videoWidth&&video.readyState>=2){
pictureContext.drawImage(video,0,0,64,36);let hash=2166136261;
for(const byte of pictureContext.getImageData(0,0,64,36).data)hash=Math.imul(hash^byte,16777619);
pictureHash=hash>>>0;
}
return{at:performance.now(),width:video?.videoWidth||0,height:video?.videoHeight||0,
frames:video?.getVideoPlaybackQuality().totalVideoFrames||0,pictureHash,playbackPeerId,route,natPrediction,stats,events:[...events],errors:[...errors],controls:[...controls],
playbackProgress:{renderedFrames,lastFrameAt,maxFrameGapMs:Math.max(maxFrameGapMs,lastFrameAt?performance.now()-lastFrameAt:0)},
sharing:!!document.querySelector('button[aria-label="Stop sharing"]'),
controlOpen:sockets.some(s=>s.url.includes('/control')&&s.readyState===WS.OPEN),
controlOrigins:sockets.filter(s=>s.url.includes('/control')&&s.readyState===WS.OPEN).map(s=>new URL(s.url).origin),
peerStates:peers.map(p=>p.connectionState),text:document.body.innerText.slice(-2000)};
}};
})();`;
export interface MediaSample {
at: number;
width: number;
height: number;
frames: number;
pictureHash: number | null;
playbackPeerId: number;
route: string | null;
natPrediction: boolean | null;
stats: Array<Record<string, string | number>>;
events: Array<{ at: number; type: string; scope?: string; state?: string; reason?: string; phase?: string; route?: string;
connectionId?: string; [key: string]: string | number | undefined }>;
errors: string[];
controls: Array<{ type: string; connectionId?: string }>;
sharing: boolean;
controlOpen: boolean;
controlOrigins: string[];
playbackProgress: { renderedFrames: number; lastFrameAt: number; maxFrameGapMs: number };
peerStates: string[];
text: string;
}