live/: every active stream opens as a dockable window (WHEP, HLS fallback), audio follows the focused window, per-window mute/volume, pinning. Caddy live.HOST block with forward-auth proxies /api /webrtc /hls to MediaMTX on loopback and serves /srv/live. WebRTC media on 8189 (firewall). configure.py asks the live hostname and an optional Discord webhook; MediaMTX -ffmpeg image runs the runOnReady hook. deployLive.sh builds and ships dist/. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
91 lines
4.6 KiB
JavaScript
91 lines
4.6 KiB
JavaScript
import React, { useEffect, useRef, useState } from 'react'
|
|
import Hls from 'hls.js'
|
|
import { whepUrl, hlsUrl } from './api.js'
|
|
import { audio, effectiveMuted } from './useAudio.js'
|
|
|
|
// WebRTC (WHEP) first, HLS fallback. Mute/volume come from the shared audio store.
|
|
export default function Player({ params, api }) {
|
|
const { id, user, title } = params
|
|
const videoRef = useRef(null)
|
|
const [status, setStatus] = useState('connecting…')
|
|
const [viewers, setViewers] = useState(params.viewers ?? 0)
|
|
const state = audio.use()
|
|
const muted = effectiveMuted(state, id)
|
|
const volume = state.streams[id]?.volume ?? 0.8
|
|
const override = state.streams[id]?.override
|
|
const focused = state.focused === id
|
|
|
|
useEffect(() => { audio.ensure(id) }, [id])
|
|
useEffect(() => { const d = api.onDidActiveChange?.(() => {}) ; return () => d?.dispose?.() }, [api])
|
|
useEffect(() => { const t = setInterval(() => setViewers(params.viewers ?? 0), 2000); return () => clearInterval(t) }, [params.viewers])
|
|
|
|
// apply audio state to the element
|
|
useEffect(() => {
|
|
const v = videoRef.current; if (!v) return
|
|
v.muted = muted; v.volume = volume
|
|
if (!muted && v.paused) v.play().catch(() => {})
|
|
}, [muted, volume])
|
|
|
|
// connect
|
|
useEffect(() => {
|
|
const v = videoRef.current; if (!v) return
|
|
let pc, hls, cancelled = false
|
|
const startHls = () => {
|
|
if (cancelled) return
|
|
setStatus('hls')
|
|
if (Hls.isSupported()) {
|
|
hls = new Hls({ lowLatencyMode: true, liveSyncDurationCount: 2, enableWorker: true })
|
|
hls.loadSource(hlsUrl(id)); hls.attachMedia(v)
|
|
hls.on(Hls.Events.MANIFEST_PARSED, () => v.play().catch(() => {}))
|
|
hls.on(Hls.Events.ERROR, (_, d) => { if (d.fatal) setStatus('hls error: ' + d.details) })
|
|
} else if (v.canPlayType('application/vnd.apple.mpegurl')) {
|
|
v.src = hlsUrl(id); v.play().catch(() => {})
|
|
} else setStatus('no playback method')
|
|
}
|
|
const startWhep = async () => {
|
|
try {
|
|
pc = new RTCPeerConnection({ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] })
|
|
pc.addTransceiver('video', { direction: 'recvonly' })
|
|
pc.addTransceiver('audio', { direction: 'recvonly' })
|
|
pc.ontrack = e => { if (v.srcObject !== e.streams[0]) { v.srcObject = e.streams[0]; v.play().catch(() => {}) } }
|
|
pc.onconnectionstatechange = () => {
|
|
if (pc.connectionState === 'connected') setStatus('')
|
|
if (['failed', 'disconnected', 'closed'].includes(pc.connectionState) && !cancelled) { pc.close(); startHls() }
|
|
}
|
|
const offer = await pc.createOffer()
|
|
await pc.setLocalDescription(offer)
|
|
await new Promise(res => { if (pc.iceGatheringState === 'complete') return res(); const t = setTimeout(res, 1500); pc.onicegatheringstatechange = () => { if (pc.iceGatheringState === 'complete') { clearTimeout(t); res() } } })
|
|
const r = await fetch(whepUrl(id), { method: 'POST', headers: { 'Content-Type': 'application/sdp' }, body: pc.localDescription.sdp, credentials: 'same-origin' })
|
|
if (!r.ok) throw new Error('whep ' + r.status)
|
|
await pc.setRemoteDescription({ type: 'answer', sdp: await r.text() })
|
|
setStatus('webrtc')
|
|
} catch (e) {
|
|
if (cancelled) return
|
|
try { pc?.close() } catch {}
|
|
startHls()
|
|
}
|
|
}
|
|
startWhep()
|
|
return () => { cancelled = true; try { pc?.close() } catch {}; try { hls?.destroy() } catch {}; v.srcObject = null; v.removeAttribute('src') }
|
|
}, [id])
|
|
|
|
const icon = muted ? '🔇' : volume === 0 ? '🔈' : volume < 0.5 ? '🔉' : '🔊'
|
|
return (
|
|
<div className={'player' + (focused ? ' focused' : '')} onMouseDown={() => api.setActive?.()}>
|
|
<video ref={videoRef} autoPlay playsInline muted />
|
|
{status && <div className="status">{status}</div>}
|
|
<div className="bar">
|
|
<span className="live">LIVE</span>
|
|
<span className="who">{user}</span>
|
|
<span className="title" title={title}>{title}</span>
|
|
<span className="viewers">👁 {viewers}</span>
|
|
<button className={'mute' + (!muted ? ' on' : '') + (override === 'unmuted' && !focused ? ' pinned' : '')}
|
|
title={override ? (override === 'unmuted' ? 'audio pinned on (click to mute)' : 'muted (click to unmute)') : (focused ? 'focused: audio on (click to mute)' : 'muted: click to pin audio on')}
|
|
onMouseDown={e => e.stopPropagation()} onClick={() => audio.toggleMute(id)}>{icon}</button>
|
|
<input type="range" min="0" max="1" step="0.02" value={volume} onMouseDown={e => e.stopPropagation()}
|
|
onChange={e => audio.setVolume(id, parseFloat(e.target.value))} />
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|