Files
piik/tests/viewer-audio.test.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

210 lines
7.7 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ViewerAudio } from "../src/client/media/viewer-audio.ts";
class PlaybackVideo extends EventTarget {
volume = 1;
muted = false;
paused = false;
ended = false;
srcObject = {};
}
class AudioStream {
constructor(public tracks: MediaStreamTrack[]) {}
getAudioTracks(): MediaStreamTrack[] { return this.tracks; }
}
class PlaybackContext extends EventTarget {
static instances: PlaybackContext[] = [];
state: AudioContextState = "suspended";
destination = {};
gain = { gain: { value: 1 }, connect: vi.fn(), disconnect: vi.fn() };
sources: Array<{ stream: AudioStream; connect: ReturnType<typeof vi.fn>; disconnect: ReturnType<typeof vi.fn> }> = [];
resolveResume!: () => void;
rejectResume!: () => void;
pendingResume = new Promise<void>((resolve, reject) => {
this.resolveResume = resolve;
this.rejectResume = reject;
});
resume = vi.fn(() => this.pendingResume);
close = vi.fn(() => {
this.state = "closed";
return Promise.resolve();
});
constructor() {
super();
PlaybackContext.instances.push(this);
}
createGain() { return this.gain; }
createMediaStreamSource(stream: AudioStream) {
const source = { stream, connect: vi.fn(), disconnect: vi.fn() };
this.sources.push(source);
return source;
}
start() {
this.state = "running";
this.dispatchEvent(new Event("statechange"));
this.resolveResume();
}
}
function audioTrack() {
return { enabled: true, stop: vi.fn() } as unknown as MediaStreamTrack;
}
describe("Viewer local audio", () => {
beforeEach(() => {
PlaybackContext.instances = [];
vi.stubGlobal("AudioContext", PlaybackContext);
vi.stubGlobal("MediaStream", AudioStream);
});
afterEach(() => vi.unstubAllGlobals());
it("lazily adjusts current audio while pause, mute and track changes remain local", () => {
const video = new PlaybackVideo();
const srcObject = video.srcObject;
const onChange = vi.fn();
const audio = new ViewerAudio(video as unknown as HTMLVideoElement, onChange);
const firstTrack = audioTrack();
const stream = new AudioStream([firstTrack]);
audio.bind(stream as unknown as MediaStream);
expect(PlaybackContext.instances).toHaveLength(0);
audio.setLevel(0.5);
expect(video.volume).toBe(0.5);
const context = PlaybackContext.instances[0];
expect(video.muted).toBe(false);
expect(context.gain.gain.value).toBe(0);
audio.setLevel(0);
expect(video.muted).toBe(true);
audio.setLevel(0.5);
context.start();
expect(video.muted).toBe(true);
expect(context.gain.gain.value).toBe(0.5);
audio.setLevel(2);
expect(PlaybackContext.instances).toHaveLength(1);
expect(context.gain.gain.value).toBe(2);
expect(audio.snapshot).toEqual({ level: 2, muted: false, boostAvailable: true });
const nextTrack = audioTrack();
stream.tracks = [nextTrack];
audio.bind(stream as unknown as MediaStream);
expect(context.sources[0].disconnect).toHaveBeenCalledOnce();
expect(context.sources[1].stream.tracks).toEqual([nextTrack]);
audio.setMuted(true);
expect(context.gain.gain.value).toBe(0);
audio.setMuted(false);
expect(context.gain.gain.value).toBe(2);
video.paused = true;
video.dispatchEvent(new Event("pause"));
expect(context.gain.gain.value).toBe(0);
audio.bind(null);
expect(context.sources[1].disconnect).toHaveBeenCalledOnce();
audio.bind(stream as unknown as MediaStream);
expect(context.gain.gain.value).toBe(0);
video.paused = false;
video.dispatchEvent(new Event("play"));
expect(context.gain.gain.value).toBe(2);
video.ended = true;
video.dispatchEvent(new Event("ended"));
expect(context.gain.gain.value).toBe(0);
expect(video.srcObject).toBe(srcObject);
for (const track of [firstTrack, nextTrack]) {
expect(track.enabled).toBe(true);
expect(track.stop).not.toHaveBeenCalled();
}
audio.useNativeControls();
expect(audio.snapshot).toEqual({ level: 1, muted: false, boostAvailable: true });
expect(video.muted).toBe(false);
expect(context.sources[2].disconnect).toHaveBeenCalledOnce();
video.volume = 0.65;
video.muted = true;
video.dispatchEvent(new Event("volumechange"));
audio.resume();
expect(audio.snapshot).toEqual({ level: 0.65, muted: true, boostAvailable: true });
expect(PlaybackContext.instances).toHaveLength(1);
audio.dispose();
expect(context.close).toHaveBeenCalledOnce();
});
it("falls back to ordinary audio if starting the context fails", async () => {
const video = new PlaybackVideo();
const audio = new ViewerAudio(video as unknown as HTMLVideoElement, vi.fn());
audio.bind(new AudioStream([audioTrack()]) as unknown as MediaStream);
audio.setLevel(2);
const context = PlaybackContext.instances[0];
context.rejectResume();
await Promise.resolve();
expect(audio.snapshot).toEqual({ level: 1, muted: false, boostAvailable: false });
expect(video.muted).toBe(false);
expect(context.close).toHaveBeenCalledOnce();
audio.setLevel(2);
expect(PlaybackContext.instances).toHaveLength(1);
expect(audio.snapshot.level).toBe(1);
audio.setLevel(0);
expect(video.muted).toBe(true);
audio.setLevel(0.5);
expect(video.muted).toBe(false);
expect(audio.snapshot.level).toBe(0.5);
expect(PlaybackContext.instances).toHaveLength(1);
audio.dispose();
});
it("uses current preferences after resume and ignores completions after disposal", async () => {
const video = new PlaybackVideo();
const onChange = vi.fn();
const audio = new ViewerAudio(video as unknown as HTMLVideoElement, onChange);
audio.bind(new AudioStream([audioTrack()]) as unknown as MediaStream);
audio.setLevel(2);
const context = PlaybackContext.instances[0];
audio.setLevel(0.4);
audio.setMuted(true);
const currentTrack = audioTrack();
audio.bind(new AudioStream([currentTrack]) as unknown as MediaStream);
context.start();
await Promise.resolve();
expect(audio.snapshot).toEqual({ level: 0.4, muted: true, boostAvailable: true });
expect(context.gain.gain.value).toBe(0);
expect(context.sources[0].disconnect).toHaveBeenCalledOnce();
expect(context.sources[1].stream.tracks).toEqual([currentTrack]);
context.state = "suspended";
context.pendingResume = new Promise<void>((resolve) => { context.resolveResume = resolve; });
audio.resume();
audio.dispose();
video.volume = 0.75;
video.muted = false;
onChange.mockClear();
context.start();
await Promise.resolve();
expect(video.volume).toBe(0.75);
expect(video.muted).toBe(false);
expect(onChange).not.toHaveBeenCalled();
});
it.each(["absent", "failed"])("restores zero volume when the audio context is %s", (state) => {
vi.stubGlobal("AudioContext", state === "absent" ? undefined : class {
constructor() { throw new DOMException("Audio unavailable", "NotSupportedError"); }
});
const video = new PlaybackVideo();
const audio = new ViewerAudio(video as unknown as HTMLVideoElement, vi.fn());
audio.setLevel(0);
// HTMLMediaElement queues this for both volume and muted writes.
video.dispatchEvent(new Event("volumechange"));
audio.setLevel(0.5);
video.dispatchEvent(new Event("volumechange"));
expect(audio.snapshot).toEqual({ level: 0.5, muted: false, boostAvailable: false });
expect(video.muted).toBe(false);
audio.setMuted(true);
audio.setLevel(0);
video.dispatchEvent(new Event("volumechange"));
audio.setLevel(0.5);
video.dispatchEvent(new Event("volumechange"));
expect(audio.snapshot.muted).toBe(true);
expect(video.muted).toBe(true);
audio.dispose();
});
});