Files
client/app/renderer/js/watch.js
T
omar 7287fdb63e
ci / linux-x64 (push) Failing after 1m26s
ci / linux-arm64-cross (push) Failing after 2m20s
TeamsPeach desktop client: Electron UI, Rust core bridge, TS6 stream viewer, CI
2026-10-24 03:31:54 +03:00

405 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// TS6 screenshare: discovery (stream_list + notifications), one viewing session, the viewer panel.
import { $, setIcon, setText } from './dom.js';
import { S, isConnected, clientById } from './state.js';
import { call, log } from './core.js';
import { StreamDirectory } from './stream/directory.js';
import { StreamViewerSession } from './stream/session.js';
import { toast } from './toast.js';
import { errorText } from './text.js';
// Same public STUN endpoints the official TS6 client ships with (see docs/evidence/ts6-official-client.md).
const ICE_SERVERS = [{ urls: ['stun:turn.teamspeak.com:3478', 'stun:turn2.teamspeak.com:3478'] }];
export const directory = new StreamDirectory();
let session = null;
let current = null; // { id, clientId, name, nickname }
let media = null;
let statsTimer = null;
let attachTimer = null;
let lastCodecLogged = '';
let sfuToastShown = false;
let hooks = { onChange: () => {}, savePrefs: () => {} };
let listTimer = null;
let listFull = false;
const listClients = new Set();
let knownChannelPeers = new Set();
let knownOwnChannel = null;
function emptyStats() {
return {
codec: '', fmtp: '', decoder: '', powerEfficientDecoder: null, width: 0, height: 0, fps: 0,
framesDecoded: 0, videoPackets: 0, videoBytes: 0, packetsLost: 0, keyFrames: 0,
audioTrackPresent: false, streamAdvertisesAudio: null, audioCodec: '', inboundAudioPackets: 0, inboundAudioBytes: 0,
remoteCandidatesAdded: 0, staleCandidates: 0, candidateErrors: 0, offersApplied: 0, answersSent: 0, pair: '',
sinkId: '', sinkError: '',
};
}
export const watchStats = { state: 'idle', ...emptyStats() };
export function initWatch(h0) {
hooks = { ...hooks, ...h0 };
const video = $('#stream-video');
const volume = $('#stream-volume');
volume.addEventListener('input', () => applyVolume());
volume.addEventListener('change', () => hooks.savePrefs({ streamVolume: Number(volume.value) }));
$('#stream-mute').addEventListener('click', () => {
const btn = $('#stream-mute');
btn.setAttribute('aria-pressed', String(btn.getAttribute('aria-pressed') !== 'true'));
applyVolume();
});
$('#stream-fullscreen').addEventListener('click', () => {
const view = $('#stream-view');
if (document.fullscreenElement) document.exitFullscreen();
else view.requestFullscreen().catch((err) => toast(`Полноэкранный режим недоступен: ${err.message}`, 'error'));
});
$('#stream-stop').addEventListener('click', () => stopWatching());
video.addEventListener('resize', () => updateStatsLine());
// The output device is applied to a running player only; an element without media has nothing to route.
video.addEventListener('playing', () => applySink());
}
export function streamOf(clientId) {
return directory.byClient(clientId);
}
export function watchingId() {
return session && !session.closed ? current.id : null;
}
export function toggleWatch(stream) {
if (session && !session.closed && current && current.id === stream.id) {
stopWatching();
return;
}
startWatching(stream);
}
// ---------- discovery ----------
/** Called for every snapshot: asks newly seen channel members whether they stream. */
export function onSnapshot() {
const snap = S.snap;
const present = new Set(snap.clients.map((c) => c.id));
let changed = directory.prune(present);
const peers = new Set(snap.clients.filter((c) => c.channel_id === snap.own_channel_id && !c.is_self && c.client_type !== 'query').map((c) => c.id));
if (knownOwnChannel !== snap.own_channel_id) {
knownOwnChannel = snap.own_channel_id;
scheduleList(null);
} else {
for (const id of peers) if (!knownChannelPeers.has(id)) scheduleList(id);
}
knownChannelPeers = peers;
if (session && !session.closed && current && !present.has(current.clientId)) {
session.terminate('streamer_left');
changed = true;
}
if (changed) hooks.onChange();
}
function scheduleList(clientId) {
if (clientId === null) listFull = true;
else listClients.add(clientId);
if (listTimer) return;
listTimer = setTimeout(runList, 300);
}
async function runList() {
listTimer = null;
if (!isConnected()) return;
const full = listFull;
const ids = Array.from(listClients);
listFull = false;
listClients.clear();
const requests = full ? [undefined] : ids.map((id) => ({ client_id: id }));
for (const args of requests) {
try {
const result = await call('stream_list', args);
let changed = false;
for (const r of result.results ?? []) {
// A client that is not streaming answers requeststreaminfo with an error only.
if (!r.ok && directory.byClient(r.client_id)) {
changed = directory.handle('notifystreamstopped', [{ clid: String(r.client_id) }]) || changed;
}
}
if (changed) hooks.onChange();
} catch (err) {
log('warn', `stream_list failed: ${err.code}`);
}
}
}
/** `stream` event from the core (bridge §5). */
export function onStreamEvent(evt) {
const name = evt.name;
const items = Array.isArray(evt.items) ? evt.items : [];
log('info', `stream event ${name} items=${items.length} keys=${items[0] ? Object.keys(items[0]).sort().join(',') : '-'}`);
if (session && !session.closed) {
for (const item of items) session.handle(name, item);
}
if (name === 'notifysfuaccessinfo' && !sfuToastShown) {
sfuToastShown = true;
toast('Сервер передаёт трансляции через SFU. TeamsPeach поддерживает только прямые (P2P) трансляции TeamSpeak 6.', 'error');
}
if (directory.handle(name, items)) hooks.onChange();
}
export function onDisconnected() {
if (session && !session.closed) session.terminate('disconnected');
directory.clear();
knownChannelPeers = new Set();
knownOwnChannel = null;
sfuToastShown = false;
}
// ---------- viewing ----------
/** Core-backed signaling for a session (bridge §4.12–4.14). */
const coreTransport = {
join: (id, clid, msg) => call('stream_join', { stream_id: id, client_id: clid, message: msg }),
send: (id, clid, json) => call('stream_signal', { stream_id: id, client_id: clid, json }),
leave: (id, clid) => call('stream_leave', { stream_id: id, client_id: clid }),
};
/**
* Starts viewing `stream`. `transport` is the signaling path; production always uses the core.
* Every async continuation below checks that its session is still the current one.
*/
export function startWatching(stream, transport = coreTransport) {
stopWatching();
const streamer = clientById(stream.clientId);
current = { id: stream.id, clientId: stream.clientId, name: stream.name, nickname: streamer?.nickname ?? stream.nickname ?? '?' };
const sessionMedia = new MediaStream();
media = sessionMedia;
const video = $('#stream-video');
applyVolume();
lastCodecLogged = '';
Object.assign(watchStats, emptyStats());
watchStats.streamAdvertisesAudio = stream.fields?.audio === '1' ? true : stream.fields?.audio === '0' ? false : null;
$('#stream-view').hidden = false;
setText($('#stream-title'), current.name ? `${current.nickname} — ${current.name}` : `Трансляция ${current.nickname}`);
setText($('#stream-stats'), '');
const own = new StreamViewerSession({
streamId: stream.id,
clientId: stream.clientId,
ownClientId: S.snap?.own_client_id ?? 0,
message: S.profile?.nickname ?? '',
signal: transport,
createPeerConnection: (config) => new RTCPeerConnection(config),
iceServers: ICE_SERVERS,
onState: (state, detail) => {
if (session === own) onSessionState(state, detail);
},
onTrack: (track) => {
if (session !== own) return;
sessionMedia.addTrack(track);
if (track.kind === 'audio') watchStats.audioTrackPresent = true;
track.addEventListener('ended', () => sessionMedia.removeTrack(track));
// Both tracks of an offer arrive in one setRemoteDescription; attach the stream once after them.
// Later tracks are picked up by the element from the same MediaStream.
if (attachTimer === null && video.srcObject !== sessionMedia) {
attachTimer = setTimeout(() => {
attachTimer = null;
if (session !== own || own.closed || media !== sessionMedia) return;
video.srcObject = sessionMedia;
video.play().catch((err) => log('warn', `watch: play() rejected: ${err.name}`));
}, 0);
}
},
log,
});
session = own;
hooks.onChange();
own.start();
statsTimer = setInterval(pollStats, 1500);
}
export function stopWatching() {
if (session && !session.closed) session.stop();
session = null;
current = null;
teardownMedia();
$('#stream-view').hidden = true;
watchStats.state = 'idle';
hooks.onChange();
}
function teardownMedia() {
clearInterval(statsTimer);
statsTimer = null;
clearTimeout(attachTimer);
attachTimer = null;
const video = $('#stream-video');
video.srcObject = null;
if (media) for (const t of media.getTracks()) t.stop();
media = null;
if (document.fullscreenElement) document.exitFullscreen().catch(() => {});
}
const STATE_TEXT = {
requesting: 'Запрос отправлен. Ждём ответа стримера…',
connecting: 'Соединение со стримером…',
live: '',
unstable: 'Связь со стримером прервалась, ждём восстановления…',
declined: 'Стример отклонил запрос на просмотр.',
removed: 'Стример убрал вас из зрителей.',
stopped: '',
};
function failureText(detail) {
switch (detail) {
case 'no_response': return 'Стример не ответил на запрос за 90 секунд.';
case 'ice_failed': return 'Не удалось установить прямое соединение со стримером. Для просмотра нужен прямой сетевой доступ к его компьютеру (через STUN, без TURN).';
default: return `Ошибка трансляции: ${detail}`;
}
}
function endedText(detail) {
switch (detail) {
case 'stream_stopped': return 'Трансляция завершена.';
case 'streamer_left': return 'Стример покинул сервер.';
case 'disconnected': return 'Соединение с сервером потеряно.';
default: return 'Трансляция завершена.';
}
}
function onSessionState(state, detail) {
watchStats.state = state;
log('info', `watch: state ${state}${detail ? ` (${detail})` : ''}`);
if (state === 'stopped') return;
let text = STATE_TEXT[state];
if (state === 'failed') text = failureText(detail);
else if (state === 'ended') text = endedText(detail);
else if (state === 'unsupported') text = 'Эта трансляция идёт через SFU-сервер TeamSpeak. TeamsPeach поддерживает только прямые (P2P) трансляции.';
else if (state === 'declined' && detail) text = `${STATE_TEXT.declined} ${detail}`;
if (state === 'live' && watchStats.framesDecoded === 0) text = 'Соединение установлено, ждём первый кадр…';
setText($('#stream-overlay'), text ?? '');
const terminal = ['declined', 'ended', 'removed', 'failed', 'unsupported'].includes(state);
setText($('#stream-stop'), terminal ? 'Закрыть' : state === 'requesting' ? 'Отменить' : 'Прекратить просмотр');
if (terminal) {
teardownMedia();
if (state !== 'ended' || detail !== 'disconnected') toast(text, state === 'ended' ? 'info' : 'error');
}
hooks.onChange();
}
async function pollStats() {
const own = session;
const pc = own?.pc;
if (!own || !pc || own.closed) return;
let report;
try {
report = await pc.getStats();
} catch {
return;
}
// The user may have stopped or switched streams while getStats() was pending.
if (session !== own || own.closed) return;
let inbound = null;
let audioIn = null;
let pair = null;
const codecs = new Map();
report.forEach((s) => {
if (s.type === 'inbound-rtp' && s.kind === 'video') inbound = s;
if (s.type === 'inbound-rtp' && s.kind === 'audio') audioIn = s;
if (s.type === 'candidate-pair' && s.nominated && s.state === 'succeeded') pair = s;
if (s.type === 'codec') codecs.set(s.id, s);
});
watchStats.remoteCandidatesAdded = own.remoteCandidatesAdded;
watchStats.staleCandidates = own.staleCandidates;
watchStats.candidateErrors = own.candidateErrors;
watchStats.offersApplied = own.offersApplied;
watchStats.answersSent = own.answersSent;
if (pair) {
const local = report.get(pair.localCandidateId);
const remote = report.get(pair.remoteCandidateId);
watchStats.pair = `${local?.candidateType ?? '?'}/${local?.protocol ?? '?'} → ${remote?.candidateType ?? '?'}`;
}
if (audioIn) {
const ac = codecs.get(audioIn.codecId);
watchStats.audioCodec = ac ? ac.mimeType : '';
watchStats.inboundAudioPackets = audioIn.packetsReceived ?? 0;
watchStats.inboundAudioBytes = audioIn.bytesReceived ?? 0;
}
if (!inbound) return;
watchStats.videoPackets = inbound.packetsReceived ?? 0;
watchStats.videoBytes = inbound.bytesReceived ?? 0;
watchStats.packetsLost = inbound.packetsLost ?? 0;
watchStats.keyFrames = inbound.keyFramesDecoded ?? 0;
const codec = codecs.get(inbound.codecId);
watchStats.codec = codec ? codec.mimeType.replace(/^video\//, '') : '';
watchStats.fmtp = codec?.sdpFmtpLine ?? '';
watchStats.width = inbound.frameWidth ?? 0;
watchStats.height = inbound.frameHeight ?? 0;
watchStats.fps = Math.round(inbound.framesPerSecond ?? 0);
const firstFrame = watchStats.framesDecoded === 0 && (inbound.framesDecoded ?? 0) > 0;
watchStats.framesDecoded = inbound.framesDecoded ?? 0;
watchStats.decoder = inbound.decoderImplementation ?? '';
watchStats.powerEfficientDecoder = typeof inbound.powerEfficientDecoder === 'boolean' ? inbound.powerEfficientDecoder : null;
if (firstFrame && own.state === 'live') setText($('#stream-overlay'), '');
const sig = `${watchStats.codec} ${watchStats.fmtp}`;
if (codec && sig !== lastCodecLogged) {
lastCodecLogged = sig;
log('info', `watch: negotiated ${codec.mimeType} fmtp="${codec.sdpFmtpLine ?? ''}" decoder=${watchStats.decoder}`);
}
updateStatsLine();
}
function updateStatsLine() {
if (!session) return;
const parts = [];
if (watchStats.codec) parts.push(watchStats.codec);
if (watchStats.width) parts.push(`${watchStats.width}×${watchStats.height}`);
if (watchStats.fps) parts.push(`${watchStats.fps} к/с`);
if (session.state === 'live') {
if (watchStats.streamAdvertisesAudio === false) parts.push('стример не передаёт звук');
else if (watchStats.inboundAudioPackets > 0) parts.push('со звуком');
}
setText($('#stream-stats'), parts.join(' · '));
}
export function applyVolume() {
const video = $('#stream-video');
const volume = $('#stream-volume');
const muted = $('#stream-mute').getAttribute('aria-pressed') === 'true';
video.volume = Number(volume.value) / 100;
video.muted = muted || S.audio.output_muted;
setText($('#stream-volume-value'), `${volume.value}%`);
setIcon($('#stream-mute').firstElementChild, muted ? 'speaker-off' : 'speaker');
$('#stream-mute').title = muted ? 'Включить звук трансляции' : 'Выключить звук трансляции';
}
let sinkChain = Promise.resolve();
/**
* Routes stream audio to the selected output device. Calls are serialized and only issued for a
* playing element whose current sink differs; a failure is reported with the device name and the
* element keeps playing on its current device.
*/
export function applySink() {
const video = $('#stream-video');
if (typeof video.setSinkId !== 'function' || !S.prefs) return;
sinkChain = sinkChain.then(async () => {
const own = session;
const target = S.prefs.outputDeviceId || '';
if (!own || !video.srcObject || video.sinkId === target) {
watchStats.sinkId = video.sinkId;
return;
}
try {
await video.setSinkId(target);
if (session !== own) return;
watchStats.sinkId = video.sinkId;
watchStats.sinkError = '';
log('info', `watch: audio output set (${target ? 'selected device' : 'system default'})`);
} catch (err) {
log('warn', `watch: setSinkId failed ${err.name}: ${err.message}`);
if (session !== own) return;
watchStats.sinkError = `${err.name}: ${err.message}`;
const label = Array.from($('#output-device').options).find((o) => o.value === target)?.textContent || 'выбранное устройство';
toast(`Звук трансляции не удалось направить на «${label}» (${err.name}). Он продолжает играть через текущее устройство; выберите другое в Настройки → Звук.`, 'error');
}
});
}