feat: consolidate on the shadcn frontend and harden playback

Frontend
- Replace the Ant Design app with the shadcn/ui app as the single frontend,
  keeping the portfolio side-by-side revertible in this commit.
- Drop the abandoned mdui experiment and the AntD tree so there is one app,
  one router and one design system to maintain.

Live playback
- Stop racing the encoder. lowLatencyMode + liveSyncDurationCount:1 targeted a
  single 4s segment, so playback ran at up to 1.10x and the forward buffer
  bottomed out at 0.1s, re-buffering every segment. Measured over 40s:
  buffer min 0.1s -> 8.9s, rate 1.00 constant, 0 stalls.
- Remove the 落后 labels and the page-level edge-snapping timer that fought
  hls.js over two different definitions of "latency".
- Live can no longer be paused: the control is not rendered while it plays, so
  the icon can never misreport state.
- Fix autoplay: muted autoplay started silently and never unmuted, and the
  gesture that restored sound also toggled playback off. One owner now.

Source ("原画") rendition
- Publish the publisher's stream remuxed losslessly via -c:v copy alongside the
  transcoded ones, so a source option exists even when every ladder entry
  downsizes.
- Give renditions an ASCII path slug: the HLS path is part of the URL and
  MediaMTX rejects non-alphanumeric paths, so 原画 could never be served.

Backend
- Supervise MediaMTX from the backend: start it at boot and restart it on exit,
  never killing an origin it did not start.
- Clear stale HLS output before restarting an encoder; an ENDLIST-less playlist
  left by a dead encoder hangs hls.js forever.
- Mark JSON timestamps as UTC. utcnow().isoformat() emitted a naive string that
  JS read as local time, so every viewer heartbeat looked 8 hours old in UTC+8
  and the live board's active-viewer count was permanently zero.
- Rebind a viewer session when it arrives on another stream instead of failing,
  and survive the StrictMode double-heartbeat race on first insert.
- Replace the Linux-only /proc and os.getloadavg metrics with psutil.
- Complete MediaMTX's cookieCheck redirect inside /hls proxying, and hold the
  httpx client open for the streamed body.

Housekeeping
- Ignore RainOSS (it stores accessKeySecret), runtime output, TLS keys and
  .venv; remove generated screenshots, load test scripts and stray files.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 4.8 committed 2026-09-22 18:07:56 +08:00
1 parent 186e32caf1
commit 996e3fea39
70 files changed
+4844 -3070

No files matched your search

+188 -109
View File
@@ -1,24 +1,41 @@
import { useEffect, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { Alert, Button, Input, InputNumber, Segmented, Select, Space, Spin, Typography, message } from 'antd'
import { ArrowDownOutlined, ArrowLeftOutlined, ArrowUpOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons'
import { fetchMediaFiles, getStream, updateStream, type Chapter, type StreamInfo } from '../../api/streams'
const { Title, Text } = Typography
import { ArrowLeft, ArrowDown, ArrowUp, Trash2, Plus } from 'lucide-react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import {
fetchMediaFiles,
getStream,
updateStream,
type Chapter,
type StreamInfo,
} from '@/api/streams'
import VideoPlayer, { VideoPlayerHandle } from '@/viewer/components/VideoPlayer'
import { PageHeader } from '@/components/page-header'
export default function ReplayEditor() {
const { id } = useParams<{ id: string }>()
const navigate = useNavigate()
const videoRef = useRef<HTMLVideoElement>(null)
const playerRef = useRef<VideoPlayerHandle>(null)
const [stream, setStream] = useState<StreamInfo | null>(null)
const [mediaFiles, setMediaFiles] = useState<string[]>([])
const [replaySource, setReplaySource] = useState<'local' | 'remote'>('local')
const [replayFile, setReplayFile] = useState<string>()
const [replayUrl, setReplayUrl] = useState('')
const [previewUrl, setPreviewUrl] = useState<string>()
const [previewLoading, setPreviewLoading] = useState(false)
const [previewError, setPreviewError] = useState('')
const previewObjectUrlRef = useRef<string>()
const [chapters, setChapters] = useState<Chapter[]>([])
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
@@ -35,66 +52,27 @@ export default function ReplayEditor() {
setChapters(program.chapters || [])
setMediaFiles(files)
})
.catch(() => message.error('无法载入节目回放配置'))
.catch(() => toast.error('无法载入节目回放配置'))
.finally(() => setLoading(false))
}, [id])
useEffect(() => {
if (previewObjectUrlRef.current) {
URL.revokeObjectURL(previewObjectUrlRef.current)
previewObjectUrlRef.current = undefined
}
setPreviewUrl(undefined)
setPreviewError('')
if (replaySource === 'local') {
setPreviewLoading(false)
if (stream && replayFile) {
setPreviewUrl(`/api/streams/${stream.id}/replay?preview=${encodeURIComponent(replayFile)}`)
}
if (!stream) {
setPreviewUrl(undefined)
return
}
const remoteUrl = replayUrl.trim()
if (!remoteUrl) {
setPreviewLoading(false)
return
}
const controller = new AbortController()
let disposed = false
setPreviewLoading(true)
void fetch(remoteUrl, { signal: controller.signal })
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`)
return response.blob()
})
.then(blob => {
if (disposed) return
const objectUrl = URL.createObjectURL(blob)
previewObjectUrlRef.current = objectUrl
setPreviewUrl(objectUrl)
})
.catch(error => {
if (error instanceof DOMException && error.name === 'AbortError') return
if (!disposed) setPreviewError('远端回放拉取失败,请检查地址及其 CORS 配置')
})
.finally(() => {
if (!disposed) setPreviewLoading(false)
})
return () => {
disposed = true
controller.abort()
if (previewObjectUrlRef.current) {
URL.revokeObjectURL(previewObjectUrlRef.current)
previewObjectUrlRef.current = undefined
}
if (replaySource === 'local' && replayFile) {
setPreviewUrl(`/api/streams/${stream.id}/replay?preview=${encodeURIComponent(replayFile)}`)
} else if (replaySource === 'remote' && replayUrl.trim()) {
setPreviewUrl(replayUrl.trim())
} else {
setPreviewUrl(undefined)
}
}, [replaySource, replayFile, replayUrl, stream])
const move = (index: number, offset: number) => {
setChapters(current => {
setChapters((current) => {
const target = index + offset
if (target < 0 || target >= current.length) return current
const next = [...current]
@@ -104,74 +82,175 @@ export default function ReplayEditor() {
}
const addChapter = () => {
const time = Math.max(0, Math.round((videoRef.current?.currentTime || 0) * 10) / 10)
setChapters(current => [...current, { title: `章节 ${current.length + 1}`, time }])
const video = playerRef.current?.getVideo()
const time = Math.max(0, Math.round((video?.currentTime || 0) * 10) / 10)
setChapters((current) => [...current, { title: `章节 ${current.length + 1}`, time }])
}
const save = async () => {
if (!stream || !replayFile) return message.warning('请先选择回放文件')
if (!stream) return
const remoteUrl = replayUrl.trim()
if (replaySource === 'local' && !replayFile) return toast.warning('请先选择回放文件')
if (replaySource === 'remote' && !remoteUrl) return toast.warning('请输入外部回放 URL')
if (replaySource === 'remote' && !/^https?:\/\//i.test(remoteUrl)) {
return toast.warning('外部回放 URL 必须以 http:// 或 https:// 开头')
}
setSaving(true)
try {
await updateStream(stream.id, { replay_file: replayFile, chapters })
message.success('回放和章节已保存')
await updateStream(stream.id, {
replay_file: replaySource === 'local' ? replayFile : null,
replay_url: replaySource === 'remote' ? remoteUrl : null,
chapters,
})
toast.success('回放和章节已保存')
} catch {
message.error('保存失败,请检查章节标题、时间和媒体文件')
toast.error('保存失败,请检查回放来源、URL 和章节内容')
} finally {
setSaving(false)
}
}
if (loading) return <div style={{ padding: 48, textAlign: 'center' }}><Spin /></div>
if (!stream) return <Alert type="error" message="节目不存在" />
if (loading) {
return (
<div className="flex justify-center py-24">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-primary border-t-transparent" />
</div>
)
}
if (!stream) return <Alert variant="destructive"><AlertTitle>节目不存在</AlertTitle></Alert>
const isEditable = stream.status === 'ended'
return (
<div className="replay-editor" style={{ maxWidth: 980, margin: '0 auto', padding: '8px 0 48px', minWidth: 0 }}>
<Button type="text" icon={<ArrowLeftOutlined />} onClick={() => navigate('/admin/streams')} style={{ marginBottom: 20 }}>返回节目列表</Button>
<Title level={2} style={{ marginBottom: 4 }}>回放与章节</Title>
<Text type="secondary">{stream.title}</Text>
{stream.status !== 'ended' ? (
<Alert style={{ marginTop: 24 }} type="warning" showIcon message="节目结束后才能配置回放和章节" />
<div className="mx-auto max-w-4xl">
<Button variant="ghost" className="mb-5" onClick={() => navigate('/admin/streams')}>
<ArrowLeft className="h-4 w-4" />
返回节目列表
</Button>
<PageHeader title="回放与章节" kicker="Replay" description={stream.title} />
{!isEditable ? (
<Alert className="mt-6" variant="default">
<AlertTitle>不可编辑</AlertTitle>
<AlertDescription>节目结束后才能配置回放和章节</AlertDescription>
</Alert>
) : (
<Space direction="vertical" size={24} style={{ width: '100%', marginTop: 24 }}>
<Select
showSearch
value={replayFile}
placeholder="选择媒体目录中的回放文件"
options={mediaFiles.map(file => ({ value: file, label: file }))}
onChange={setReplayFile}
style={{ width: '100%' }}
/>
<video
ref={videoRef}
controls
src={replayFile ? `/api/streams/${stream.id}/replay?preview=${encodeURIComponent(replayFile)}` : undefined}
style={{ width: '100%', maxHeight: 520, borderRadius: 12, background: '#111' }}
/>
<Button icon={<PlusOutlined />} onClick={addChapter} disabled={!replayFile}>按当前播放时间添加章节</Button>
<Space direction="vertical" style={{ width: '100%' }}>
{chapters.map((chapter, index) => (
<Space key={index} wrap className="replay-chapter-row" style={{ width: '100%', minWidth: 0 }}>
<div className="mt-6 space-y-6">
<Card>
<CardHeader>
<CardTitle className="text-base">回放来源</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<Tabs value={replaySource} onValueChange={(v) => setReplaySource(v as 'local' | 'remote')}>
<TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="local">媒体目录文件</TabsTrigger>
<TabsTrigger value="remote">外部回放 URL</TabsTrigger>
</TabsList>
</Tabs>
{replaySource === 'local' ? (
<Select value={replayFile} onValueChange={setReplayFile}>
<SelectTrigger>
<SelectValue placeholder="选择媒体目录中的回放文件" />
</SelectTrigger>
<SelectContent>
{mediaFiles.length === 0 && (
<div className="px-2 py-1.5 text-sm text-muted-foreground">媒体目录中暂无可用视频文件</div>
)}
{mediaFiles.map((file) => (
<SelectItem key={file} value={file}>
{file}
</SelectItem>
))}
</SelectContent>
</Select>
) : (
<Input
value={chapter.title}
placeholder="章节标题"
onChange={event => setChapters(current => current.map((item, i) => i === index ? { ...item, title: event.target.value } : item))}
style={{ width: 320, maxWidth: '100%', flex: '1 1 220px' }}
value={replayUrl}
placeholder="https://example.com/path/replay.mp4"
onChange={(e) => setReplayUrl(e.target.value)}
/>
<InputNumber
min={0}
step={0.1}
value={chapter.time}
addonAfter="秒"
onChange={value => setChapters(current => current.map((item, i) => i === index ? { ...item, time: Number(value || 0) } : item))}
/>
<Button icon={<ArrowUpOutlined />} disabled={index === 0} onClick={() => move(index, -1)} />
<Button icon={<ArrowDownOutlined />} disabled={index === chapters.length - 1} onClick={() => move(index, 1)} />
<Button danger icon={<DeleteOutlined />} onClick={() => setChapters(current => current.filter((_, i) => i !== index))} />
</Space>
))}
</Space>
<Button type="primary" loading={saving} onClick={save}>保存回放与章节</Button>
</Space>
)}
{replaySource === 'remote' && (
<Alert variant="default">
<AlertTitle>跨域提示</AlertTitle>
<AlertDescription>外部地址需允许浏览器跨域访问(CORS),播放器将直接流式加载。</AlertDescription>
</Alert>
)}
{previewError && (
<Alert variant="destructive">
<AlertTitle>播放出错</AlertTitle>
<AlertDescription>{previewError}</AlertDescription>
</Alert>
)}
<VideoPlayer
ref={playerRef}
live={false}
replayUrl={previewUrl}
lines={[]}
qualities={[]}
activeLine=""
activeQuality=""
onLineChange={() => {}}
onQualityChange={() => {}}
onError={setPreviewError}
/>
<Button variant="outline" onClick={addChapter} disabled={!previewUrl}>
<Plus className="h-4 w-4" />
按当前播放时间添加章节
</Button>
</CardContent>
</Card>
{chapters.length > 0 && (
<Card>
<CardHeader>
<CardTitle className="text-base">章节列表</CardTitle>
</CardHeader>
<CardContent className="space-y-2">
{chapters.map((chapter, index) => (
<div key={index} className="flex items-center gap-2">
<Input
value={chapter.title}
placeholder="章节标题"
onChange={(e) =>
setChapters((cur) => cur.map((item, i) => (i === index ? { ...item, title: e.target.value } : item)))
}
className="flex-1"
/>
<Input
type="number"
min={0}
step={0.1}
value={chapter.time}
onChange={(e) =>
setChapters((cur) => cur.map((item, i) => (i === index ? { ...item, time: Number(e.target.value || 0) } : item)))
}
className="w-28"
/>
<Button variant="ghost" size="icon" disabled={index === 0} onClick={() => move(index, -1)}>
<ArrowUp className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" disabled={index === chapters.length - 1} onClick={() => move(index, 1)}>
<ArrowDown className="h-4 w-4" />
</Button>
<Button variant="ghost" size="icon" onClick={() => setChapters((cur) => cur.filter((_, i) => i !== index))}>
<Trash2 className="h-4 w-4 text-destructive" />
</Button>
</div>
))}
</CardContent>
</Card>
)}
<Button onClick={save} disabled={saving}>
{saving ? '保存中…' : '保存回放与章节'}
</Button>
</div>
)}
</div>
)