Compare commits

...

5 Commits

Author SHA1 Message Date
truewhile 4d698d2757 优化播放 2026-09-08 09:24:29 +08:00
truewhile fdfb2ee987 bug处理 2026-09-08 08:41:01 +08:00
truewhile b23b1d728e bug处理 2026-09-08 00:36:56 +08:00
truewhile ad427fc0d2 bug处理 2026-09-08 00:10:25 +08:00
truewhile c489374b61 bug处理 2026-09-07 23:45:59 +08:00
18 changed files with 803 additions and 162 deletions
+16
View File
@@ -0,0 +1,16 @@
{
"mcpServers": {
"ssh": {
"command": "cmd.exe",
"args": [
"/c",
"npx",
"-y",
"@aiondadotcom/mcp-ssh"
],
"env": {
"ProgramData": "C:\\ProgramData"
}
}
}
}
+1
View File
@@ -124,6 +124,7 @@ func (b *serviceContainerBuilder) initContentServices() {
// STRM 直连失败后的 HLS 转码:把 .strm 解析成 ffmpeg 可读取的本地路径或 HTTP 直链。
b.c.Transcoder.SetStrmPlayTargetResolver(b.c.Strm.ResolvePlayTarget)
b.c.Transcoder.SetProbe(b.c.FFprobe)
b.c.Subtitle.SetStrmPlayTargetResolver(b.c.Strm.ResolvePlayTarget)
// 弹幕识别需要把远程 Emby 条目解析为 Media 元数据及可拉取前 16MB 的直链 URL。
if b.c.EmbyRemote != nil {
b.c.Danmaku.SetRemoteMediaResolver(func(ctx context.Context, encodedID string) (*model.Media, string, error) {
+42 -5
View File
@@ -24,11 +24,18 @@ func (s *StreamService) ServeHLSPlaylist(w http.ResponseWriter, r *http.Request,
return ErrTranscodeDisabled
}
startSec := parseHLSStartSec(r)
if _, err := s.transcoder.EnsureJobFrom(r.Context(), mediaID, startSec); err != nil {
seekGen := parseHLSSeekGen(r)
subtitleStream := parseHLSSubtitleStream(r)
if _, err := s.transcoder.EnsureJobFromSubtitle(r.Context(), mediaID, startSec, seekGen, subtitleStream); err != nil {
return err
}
s.transcoder.TouchJob(mediaID)
if !s.transcoder.WaitReady(r.Context(), mediaID, 30*time.Second) {
readyTimeout := 45 * time.Second
if startSec > 0.05 {
// Mid-file HTTP seeks (esp. WMV) need longer before the first segment appears.
readyTimeout = 120 * time.Second
}
if !s.transcoder.WaitReady(r.Context(), mediaID, readyTimeout) {
return errors.New("hls playlist not ready")
}
playlist := s.transcoder.PlaylistPath(mediaID)
@@ -54,6 +61,21 @@ func (s *StreamService) ServeHLSPlaylist(w http.ResponseWriter, r *http.Request,
return nil
}
func parseHLSSubtitleStream(r *http.Request) int {
if r == nil {
return -1
}
raw := strings.TrimSpace(r.URL.Query().Get("subtitle"))
if raw == "" {
return -1
}
v, err := strconv.Atoi(raw)
if err != nil || v < 0 {
return -1
}
return v
}
func parseHLSStartSec(r *http.Request) float64 {
if r == nil {
return 0
@@ -69,12 +91,27 @@ func parseHLSStartSec(r *http.Request) float64 {
return v
}
func parseHLSSeekGen(r *http.Request) int64 {
if r == nil {
return 0
}
raw := strings.TrimSpace(r.URL.Query().Get("_seek"))
if raw == "" {
return 0
}
v, err := strconv.ParseInt(raw, 10, 64)
if err != nil || v < 0 {
return 0
}
return v
}
func appendQueryToHLSSegments(playlist, rawQuery string) string {
if strings.TrimSpace(rawQuery) == "" {
return playlist
}
// Segment fetches only need auth/profile tokens; drop start= so a seek
// restart does not keep forcing EnsureJobFrom on every .ts hit.
// Segment fetches do not need start=, but must keep _seek as a cache-busting
// generation because every transcode restart reuses seg_00000.ts names.
q := filterHLSSegmentQuery(rawQuery)
if q == "" {
return playlist
@@ -110,7 +147,7 @@ func filterHLSSegmentQuery(rawQuery string) string {
key = part[:i]
}
switch strings.ToLower(key) {
case "start", "_seek":
case "start":
continue
}
kept = append(kept, part)
+6 -3
View File
@@ -302,9 +302,12 @@ func TestRequestTokenFromMediaBrowserAuthorizationHeader(t *testing.T) {
func TestAppendQueryToHLSSegments(t *testing.T) {
in := "#EXTM3U\n#EXTINF:4.0,\nseg_00000.ts\n#EXTINF:4.0,\nseg_00001.ts?old=1\n"
got := appendQueryToHLSSegments(in, "token=abc")
if !strings.Contains(got, "seg_00000.ts?token=abc") {
t.Fatalf("missing tokenized segment: %q", got)
got := appendQueryToHLSSegments(in, "token=abc&start=120.5&_seek=1001")
if !strings.Contains(got, "seg_00000.ts?token=abc&_seek=1001") {
t.Fatalf("missing token or seek generation on segment: %q", got)
}
if strings.Contains(got, "start=120.5") {
t.Fatalf("segment URL must not contain transcode start: %q", got)
}
if !strings.Contains(got, "seg_00001.ts?old=1") {
t.Fatalf("existing query should be preserved: %q", got)
+197 -13
View File
@@ -16,12 +16,15 @@ package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
@@ -29,14 +32,16 @@ import (
"go.uber.org/zap"
"github.com/truewhile/MeBox/internal/config"
"github.com/truewhile/MeBox/internal/model"
"github.com/truewhile/MeBox/internal/repository"
)
// SubtitleService is the discovery + conversion entry point.
type SubtitleService struct {
log *zap.Logger
repo *repository.Container
cfg *config.Config
log *zap.Logger
repo *repository.Container
cfg *config.Config
strmResolve func(ctx context.Context, raw string) (*StrmPlayResult, error)
// 目录发现是 Emby 条目列表的热路径(每个媒体源一次 DB 查询 + 最多 5 次
// os.ReadDir),而字幕文件极少变化:按 media_id 做短 TTL 缓存。
@@ -61,11 +66,14 @@ func NewSubtitleService(cfg *config.Config, log *zap.Logger, repo *repository.Co
// SubtitleTrack describes one external subtitle file.
type SubtitleTrack struct {
Lang string `json:"lang"`
Label string `json:"label"`
Path string `json:"path"`
URL string `json:"url"`
Codec string `json:"codec"`
Lang string `json:"lang"`
Label string `json:"label"`
Path string `json:"path"`
URL string `json:"url"`
Codec string `json:"codec"`
Source string `json:"source"`
Delivery string `json:"delivery"`
StreamIndex int `json:"stream_index,omitempty"`
}
// extToCodec maps the file extension to the inner codec name.
@@ -86,7 +94,17 @@ func (s *SubtitleService) Discover(ctx context.Context, mediaID string) ([]Subti
// DiscoverExternalOnly 只返回媒体旁边的外挂字幕文件,不含容器内嵌字幕轨。
// Emby 字幕接口(/Videos/:id/Subtitles/...)用。
func (s *SubtitleService) DiscoverExternalOnly(ctx context.Context, mediaID string) ([]SubtitleTrack, error) {
return s.discover(ctx, mediaID)
tracks, err := s.discover(ctx, mediaID)
if err != nil {
return nil, err
}
out := make([]SubtitleTrack, 0, len(tracks))
for _, track := range tracks {
if track.Source != "embedded" {
out = append(out, track)
}
}
return out, nil
}
func (s *SubtitleService) discover(ctx context.Context, mediaID string) ([]SubtitleTrack, error) {
@@ -187,16 +205,153 @@ func (s *SubtitleService) discoverUncached(ctx context.Context, mediaID string)
}
lang := detectLang(fullName, matchedBase)
tracks = append(tracks, SubtitleTrack{
Lang: lang,
Label: lang,
Path: filepath.Join(c, e.Name()),
Codec: codec,
Lang: lang,
Label: lang,
Path: filepath.Join(c, e.Name()),
Codec: codec,
Source: "external",
Delivery: "webvtt",
})
}
}
embedded, err := s.discoverEmbedded(ctx, m)
if err != nil {
if s.log != nil {
s.log.Debug("discover embedded subtitles failed", zap.String("media_id", mediaID), zap.Error(err))
}
} else {
tracks = append(tracks, embedded...)
}
return tracks, nil
}
type embeddedSubtitleProbe struct {
Streams []struct {
Index int `json:"index"`
CodecName string `json:"codec_name"`
Tags struct {
Language string `json:"language"`
Title string `json:"title"`
} `json:"tags"`
Disposition struct {
Default int `json:"default"`
Forced int `json:"forced"`
} `json:"disposition"`
} `json:"streams"`
}
var imageSubtitleCodecs = map[string]bool{
"hdmv_pgs_subtitle": true,
"dvd_subtitle": true,
"dvb_subtitle": true,
"xsub": true,
}
func (s *SubtitleService) discoverEmbedded(ctx context.Context, media *model.Media) ([]SubtitleTrack, error) {
if s == nil || s.cfg == nil {
return nil, errors.New("subtitle probe unavailable")
}
input, err := s.resolveInput(ctx, media)
if err != nil {
return nil, err
}
bin, err := resolveLocalExecutable(s.cfg.App.FFprobePath, "ffprobe")
if err != nil {
return nil, err
}
probeCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
args := []string{"-v", "error"}
if headers := ffmpegHeaderText(input.Headers); headers != "" {
args = append(args, "-headers", headers)
}
args = append(args,
"-select_streams", "s",
"-show_entries", "stream=index,codec_name:stream_tags=language,title:stream_disposition=default,forced",
"-of", "json", input.Source,
)
out, err := exec.CommandContext(probeCtx, bin, args...).Output() // #nosec G204 -- executable is resolved locally and arguments do not use a shell.
if err != nil {
return nil, err
}
var probe embeddedSubtitleProbe
if err := json.Unmarshal(out, &probe); err != nil {
return nil, err
}
return subtitleTracksFromProbe(probe), nil
}
func subtitleTracksFromProbe(probe embeddedSubtitleProbe) []SubtitleTrack {
tracks := make([]SubtitleTrack, 0, len(probe.Streams))
for _, stream := range probe.Streams {
codec := strings.ToLower(strings.TrimSpace(stream.CodecName))
lang := strings.ToLower(strings.TrimSpace(stream.Tags.Language))
if lang == "" {
lang = "und"
}
label := strings.TrimSpace(stream.Tags.Title)
if label == "" {
label = lang
}
if stream.Disposition.Forced != 0 {
label += "(强制)"
} else if stream.Disposition.Default != 0 {
label += "(默认)"
}
delivery := "webvtt"
if imageSubtitleCodecs[codec] {
delivery = "burn"
}
sourceLabel := "(内嵌)"
if delivery == "burn" {
sourceLabel = "(内嵌·图片)"
}
tracks = append(tracks, SubtitleTrack{
Lang: lang,
Label: label + sourceLabel,
Path: "embedded:" + strconv.Itoa(stream.Index),
Codec: codec,
Source: "embedded",
Delivery: delivery,
StreamIndex: stream.Index,
})
}
return tracks
}
func (s *SubtitleService) SetStrmPlayTargetResolver(resolve func(context.Context, string) (*StrmPlayResult, error)) {
if s != nil {
s.strmResolve = resolve
}
}
func (s *SubtitleService) resolveInput(ctx context.Context, media *model.Media) (transcodeInput, error) {
if media == nil {
return transcodeInput{}, ErrMediaNotFound
}
if !isStrmMediaRow(media) {
if _, err := os.Stat(media.Path); err != nil {
return transcodeInput{}, ErrMediaNotFound
}
return transcodeInput{Source: media.Path}, nil
}
raw := strings.TrimSpace(media.STRMURL)
if raw == "" && strings.HasSuffix(strings.ToLower(media.Path), ".strm") {
raw, _ = readLocalSTRMTarget(media.Path)
}
if s.strmResolve != nil {
resolved, err := s.strmResolve(ctx, raw)
if err != nil {
return transcodeInput{}, err
}
return transcodeInputFromPlayResult(resolved)
}
if isHTTPPlaybackTarget(raw) {
return transcodeInput{Source: raw}, nil
}
return transcodeInput{}, errors.New("subtitle source unavailable")
}
// langTag matches the .zh / .zh-cn / .chs language sub-extensions.
var langTag = regexp.MustCompile(`(?i)\.([a-z]{2,3}(?:[-_][a-z]{2,4})?)$`)
@@ -220,6 +375,13 @@ func (s *SubtitleService) Serve(ctx context.Context, mediaID, sub string, w io.W
if err != nil || m == nil {
return errors.New("media not found")
}
if strings.HasPrefix(sub, "embedded:") {
index, err := strconv.Atoi(strings.TrimPrefix(sub, "embedded:"))
if err != nil || index < 0 {
return errors.New("invalid embedded subtitle")
}
return s.serveEmbedded(ctx, m, index, w)
}
abs, err := filepath.Abs(sub)
if err != nil {
return err
@@ -252,6 +414,28 @@ func (s *SubtitleService) Serve(ctx context.Context, mediaID, sub string, w io.W
return err
}
func (s *SubtitleService) serveEmbedded(ctx context.Context, media *model.Media, streamIndex int, w io.Writer) error {
input, err := s.resolveInput(ctx, media)
if err != nil {
return err
}
bin, err := resolveLocalExecutable(s.cfg.App.FFmpegPath, "ffmpeg")
if err != nil {
return err
}
args := []string{"-hide_banner", "-loglevel", "error"}
args = append(args, ffmpegHTTPInputArgs(input)...)
args = append(args, "-i", input.Source, "-map", "0:"+strconv.Itoa(streamIndex), "-f", "webvtt", "-")
cmd := exec.CommandContext(ctx, bin, args...) // #nosec G204 -- executable is resolved locally and arguments do not use a shell.
cmd.Stdout = w
var stderr strings.Builder
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("extract embedded subtitle: %w: %s", err, strings.TrimSpace(stderr.String()))
}
return nil
}
// ServeRaw writes the subtitle file in its original format without any
// WebVTT conversion. Emby/Jellyfin clients advertise the source codec (ASS,
// subrip, etc.) in MediaStreams, then fetch the subtitle bytes via the
+22
View File
@@ -2,6 +2,7 @@ package service
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"testing"
@@ -46,6 +47,27 @@ func TestSubtitleDiscoverNoTracksReturnsEmptySlice(t *testing.T) {
}
}
func TestEmbeddedSubtitleProbeClassifiesTextAndBitmapTracks(t *testing.T) {
var probe embeddedSubtitleProbe
raw := []byte(`{"streams":[
{"index":2,"codec_name":"ass","tags":{"language":"chi","title":"中文"},"disposition":{"default":1}},
{"index":4,"codec_name":"hdmv_pgs_subtitle","tags":{"language":"eng"},"disposition":{"forced":1}}
]}`)
if err := json.Unmarshal(raw, &probe); err != nil {
t.Fatal(err)
}
tracks := subtitleTracksFromProbe(probe)
if len(tracks) != 2 {
t.Fatalf("len(tracks) = %d, want 2", len(tracks))
}
if tracks[0].Delivery != "webvtt" || tracks[0].Path != "embedded:2" {
t.Fatalf("text track = %#v", tracks[0])
}
if tracks[1].Delivery != "burn" || tracks[1].StreamIndex != 4 {
t.Fatalf("bitmap track = %#v", tracks[1])
}
}
func TestNormaliseTimecode(t *testing.T) {
cases := map[string]string{
"0:00:01": "00:00:01",
+139 -17
View File
@@ -49,6 +49,9 @@ type TranscoderService struct {
mu sync.Mutex
jobs map[string]*hlsJob
// startGates serializes EnsureJobFrom / StopJob per media so concurrent
// playlist hits cannot spawn multiple ffmpeg writers into one HLS dir.
startGates sync.Map // mediaID -> *sync.Mutex
strmResolve func(ctx context.Context, raw string) (*StrmPlayResult, error)
probe *FFprobeService
}
@@ -65,6 +68,14 @@ type hlsJob struct {
// startSec is the source seek offset fed to ffmpeg (-ss). The HLS
// playlist itself always starts at t=0 for that session.
startSec float64
// seekGen is the client `_seek` token for this job. Newer gens win;
// older/missing gens must not cancel a mid-file restart.
seekGen int64
// subtitleStream is an absolute ffmpeg stream index to burn into the
// picture, or -1 when no bitmap subtitle is selected.
subtitleStream int
// done is closed when the ffmpeg goroutine fully exits (after process death).
done chan struct{}
}
var (
@@ -99,7 +110,7 @@ func (t *TranscoderService) PlaylistPath(mediaID string) string {
// EnsureJob makes sure a transcode is running for mediaID from the start of
// the source. Prefer EnsureJobFrom when the player seeks into the middle.
func (t *TranscoderService) EnsureJob(ctx context.Context, mediaID string) (string, error) {
return t.EnsureJobFrom(ctx, mediaID, 0)
return t.EnsureJobFrom(ctx, mediaID, 0, 0)
}
// EnsureJobFrom starts (or reuses) an HLS job that seeks the source to
@@ -107,7 +118,18 @@ func (t *TranscoderService) EnsureJob(ctx context.Context, mediaID string) (stri
// matches that offset; otherwise the previous job is cancelled and the HLS
// cache dir is wiped so the player can jump without waiting for a full
// head-to-tail transcode.
func (t *TranscoderService) EnsureJobFrom(ctx context.Context, mediaID string, startSec float64) (string, error) {
//
// seekGen is the client `_seek` query (unix ms). A newer gen replaces an older
// job; an older or missing gen must not clobber a mid-file restart — hls.js
// in-flight playlist refreshes from a destroyed player commonly arrive as
// start=0 right after a scrub and would otherwise reset playback to the head.
func (t *TranscoderService) EnsureJobFrom(ctx context.Context, mediaID string, startSec float64, seekGen int64) (string, error) {
return t.EnsureJobFromSubtitle(ctx, mediaID, startSec, seekGen, -1)
}
// EnsureJobFromSubtitle is EnsureJobFrom with an optional bitmap subtitle
// stream. Selecting or closing a burned subtitle creates a new HLS generation.
func (t *TranscoderService) EnsureJobFromSubtitle(ctx context.Context, mediaID string, startSec float64, seekGen int64, subtitleStream int) (string, error) {
if !t.cfg.Transcoder.Enabled {
return "", ErrTranscodeDisabled
}
@@ -122,23 +144,37 @@ func (t *TranscoderService) EnsureJobFrom(ctx context.Context, mediaID string, s
return "", ErrMediaNotFound
}
gate := t.mediaStartGate(mediaID)
gate.Lock()
defer gate.Unlock()
t.mu.Lock()
if existing, ok := t.jobs[mediaID]; ok {
if sameHLSStart(existing.startSec, startSec) {
if sameHLSConfiguration(existing, startSec, subtitleStream) {
t.touchJobLocked(mediaID)
t.mu.Unlock()
return t.PlaylistPath(mediaID), nil
}
existing.cancel()
delete(t.jobs, mediaID)
if !shouldReplaceHLSJobConfiguration(existing, startSec, seekGen, subtitleStream) {
t.touchJobLocked(mediaID)
t.mu.Unlock()
return t.PlaylistPath(mediaID), nil
}
prev := t.detachJobLocked(mediaID)
t.mu.Unlock()
waitJobExit(prev, 12*time.Second)
} else {
t.mu.Unlock()
}
t.mu.Unlock()
input, err := t.resolveTranscodeInput(ctx, m)
if err != nil {
return "", err
}
input.StartSec = startSec
if subtitleStream >= 0 {
input.SubtitleStream = &subtitleStream
}
t.maybeFillDuration(ctx, m, input)
if _, err := t.resolveFFmpegPath(); err != nil {
return "", err
@@ -146,19 +182,27 @@ func (t *TranscoderService) EnsureJobFrom(ctx context.Context, mediaID string, s
outDir := t.HLSDir(mediaID)
// Wipe prior segments so a mid-file restart cannot serve stale early chunks.
// Only safe after the previous ffmpeg has exited (waited above / via gate).
if err := resetHLSDir(outDir); err != nil {
return "", err
}
t.mu.Lock()
if existing, ok := t.jobs[mediaID]; ok {
if sameHLSStart(existing.startSec, startSec) {
if sameHLSConfiguration(existing, startSec, subtitleStream) {
t.touchJobLocked(mediaID)
t.mu.Unlock()
return t.PlaylistPath(mediaID), nil
}
existing.cancel()
delete(t.jobs, mediaID)
if !shouldReplaceHLSJobConfiguration(existing, startSec, seekGen, subtitleStream) {
t.touchJobLocked(mediaID)
t.mu.Unlock()
return t.PlaylistPath(mediaID), nil
}
prev := t.detachJobLocked(mediaID)
t.mu.Unlock()
waitJobExit(prev, 12*time.Second)
t.mu.Lock()
}
if max := t.maxConcurrent(); max > 0 && len(t.jobs) >= max {
t.mu.Unlock()
@@ -166,23 +210,101 @@ func (t *TranscoderService) EnsureJobFrom(ctx context.Context, mediaID string, s
}
jobCtx, cancel := context.WithCancel(context.Background())
jobEncoder := t.effectiveEncoder()
if subtitleStream >= 0 {
jobEncoder = "software (subtitle burn-in)"
}
job := &hlsJob{
mediaID: mediaID,
outputDir: outDir,
cancel: cancel,
startedAt: time.Now(),
lastAccess: time.Now(),
encoder: t.effectiveEncoder(),
startSec: startSec,
mediaID: mediaID,
outputDir: outDir,
cancel: cancel,
startedAt: time.Now(),
lastAccess: time.Now(),
encoder: jobEncoder,
startSec: startSec,
seekGen: seekGen,
subtitleStream: subtitleStream,
done: make(chan struct{}),
}
t.jobs[mediaID] = job
t.mu.Unlock()
helper.Go(t.log, "transcoder.monitorIdle", func() { t.monitorIdle(jobCtx, job) })
helper.Go(t.log, "transcoder.ffmpeg", func() { t.runFFmpeg(jobCtx, job, input) })
helper.Go(t.log, "transcoder.ffmpeg", func() {
defer close(job.done)
t.runFFmpeg(jobCtx, job, input)
})
return t.PlaylistPath(mediaID), nil
}
// shouldReplaceHLSJob reports whether an incoming playlist request may cancel
// the running job. Stale hls.js refreshes (older/missing `_seek`) must not win.
func shouldReplaceHLSJob(existing *hlsJob, startSec float64, seekGen int64) bool {
if existing == nil {
return true
}
if sameHLSStart(existing.startSec, startSec) {
return false
}
return newerHLSGenerationMayReplace(existing, seekGen)
}
func shouldReplaceHLSJobConfiguration(existing *hlsJob, startSec float64, seekGen int64, subtitleStream int) bool {
if existing == nil {
return true
}
if sameHLSConfiguration(existing, startSec, subtitleStream) {
return false
}
return newerHLSGenerationMayReplace(existing, seekGen)
}
func newerHLSGenerationMayReplace(existing *hlsJob, seekGen int64) bool {
if seekGen > 0 && existing.seekGen > 0 && seekGen < existing.seekGen {
return false
}
// Untagged request while a seek-tagged job is active: treat as stale.
if seekGen == 0 && existing.seekGen > 0 {
return false
}
return true
}
func sameHLSConfiguration(existing *hlsJob, startSec float64, subtitleStream int) bool {
return existing != nil &&
existing.subtitleStream == subtitleStream &&
sameHLSStart(existing.startSec, startSec)
}
func (t *TranscoderService) mediaStartGate(mediaID string) *sync.Mutex {
v, _ := t.startGates.LoadOrStore(mediaID, &sync.Mutex{})
return v.(*sync.Mutex)
}
// detachJobLocked cancels and removes a job from the map without waiting.
// Caller must hold t.mu and must waitJobExit afterwards before wiping the HLS dir.
func (t *TranscoderService) detachJobLocked(mediaID string) *hlsJob {
j, ok := t.jobs[mediaID]
if !ok {
return nil
}
j.cancel()
delete(t.jobs, mediaID)
return j
}
func waitJobExit(job *hlsJob, timeout time.Duration) {
if job == nil || job.done == nil {
return
}
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-job.done:
case <-timer.C:
}
}
func sameHLSStart(a, b float64) bool {
const tol = 0.75
if a < b {
+14
View File
@@ -0,0 +1,14 @@
//go:build unix
package service
import (
"os/exec"
"syscall"
)
// setFFmpegSysProcAttr puts ffmpeg in its own process group so cancel can
// tear down the whole group (and any helpers) reliably on Linux/macOS.
func setFFmpegSysProcAttr(cmd *exec.Cmd) {
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
}
@@ -0,0 +1,9 @@
//go:build windows
package service
import "os/exec"
func setFFmpegSysProcAttr(cmd *exec.Cmd) {
// Windows: CommandContext cancel is enough for the single ffmpeg process.
}
+24 -10
View File
@@ -11,9 +11,10 @@ import (
)
type transcodeInput struct {
Source string
Headers map[string]string
StartSec float64
Source string
Headers map[string]string
StartSec float64
SubtitleStream *int
}
type ffmpegArgSettings struct {
@@ -46,6 +47,13 @@ func buildFFmpegArgs(cfg *config.Config, source, playlist, segments string) []st
func buildFFmpegArgsForInput(cfg *config.Config, input transcodeInput, playlist, segments string) []string {
settings := ffmpegArgSettingsFromConfig(cfg)
video := ffmpegVideoPlanForSettings(settings)
if input.SubtitleStream != nil {
// Bitmap subtitles must be composited in software. Keeping CUDA/QSV/
// VAAPI frames here would require a download/upload filter chain that
// differs by driver and is considerably less portable.
settings.encoder = ""
video = ffmpegVideoPlanForSettings(settings)
}
// Mid-file restarts must not use -re: output -ss would otherwise crawl to the
// seek point at 1x wall-clock before emitting the first HLS segment.
@@ -133,17 +141,23 @@ func appendInputAndVideoArgs(args []string, input transcodeInput, settings ffmpe
if input.StartSec > 0.05 {
ss = strconv.FormatFloat(input.StartSec, 'f', 3, 64)
}
// Local files: input -ss (byte/keyframe seek). HTTP/STRM: output -ss after
// -i — several cloud/WMV demuxers ignore input seeks and would otherwise
// restart from t=0. Realtime (-re) is already disabled for StartSec > 0.
if ss != "" && !isHTTPSource(input.Source) {
// Always use input -ss (before -i). Output -ss on HTTP/WMV decodes from
// byte 0 up to the offset and cannot meet playlist WaitReady for deep
// scrubbing; CDNs with Range support jump via demuxer seek instead.
if ss != "" {
args = append(args, "-ss", ss)
}
args = append(args, "-i", input.Source)
if ss != "" && isHTTPSource(input.Source) {
args = append(args, "-ss", ss)
if input.SubtitleStream != nil {
filter := fmt.Sprintf(
"[0:v:0][0:%d]overlay=0:0:eof_action=pass,scale=-2:min(%d\\,ih)[v]",
*input.SubtitleStream,
settings.height,
)
args = append(args, "-filter_complex", filter, "-map", "[v]", "-map", "0:a:0?", "-c:v", video.codec)
} else {
args = append(args, "-map", "0:v:0?", "-map", "0:a:0?", "-vf", video.filter, "-c:v", video.codec)
}
args = append(args, "-map", "0:v:0?", "-map", "0:a:0?", "-vf", video.filter, "-c:v", video.codec)
if settings.threads > 0 && video.codec == "libx264" {
args = append(args, "-threads", strconv.Itoa(settings.threads))
}
+10 -4
View File
@@ -34,6 +34,7 @@ func (t *TranscoderService) runFFmpeg(ctx context.Context, job *hlsJob, input tr
args := buildFFmpegArgsForInput(t.cfg, input, playlist, segments)
cmd := exec.CommandContext(ctx, bin, args...) // #nosec G204 -- bin is resolved by resolveFFmpegPath and args are passed without a shell.
setFFmpegSysProcAttr(cmd)
cmd.Stderr = os.Stderr
t.log.Info("transcode started",
@@ -43,20 +44,25 @@ func (t *TranscoderService) runFFmpeg(ctx context.Context, job *hlsJob, input tr
zap.Float64("start_sec", input.StartSec),
)
t.hub.Publish("transcode", map[string]any{
"media_id": job.mediaID,
"encoder": job.encoder,
"status": "started",
"media_id": job.mediaID,
"encoder": job.encoder,
"status": "started",
"start_sec": input.StartSec,
})
if err := cmd.Run(); err != nil && !errors.Is(ctx.Err(), context.Canceled) {
t.log.Warn("ffmpeg exited",
zap.String("media_id", job.mediaID),
zap.Float64("start_sec", input.StartSec),
zap.Error(err),
)
}
t.mu.Lock()
delete(t.jobs, job.mediaID)
// Only drop the map entry if we are still the registered generation.
if cur, ok := t.jobs[job.mediaID]; ok && cur == job {
delete(t.jobs, job.mediaID)
}
t.mu.Unlock()
t.hub.Publish("transcode", map[string]any{
+17 -10
View File
@@ -45,14 +45,18 @@ func (t *TranscoderService) WaitReady(ctx context.Context, mediaID string, timeo
}
}
// StopJob cancels a running ffmpeg process for mediaID, if any.
// StopJob cancels a running ffmpeg process for mediaID, if any, and waits
// briefly for it to exit so a subsequent EnsureJobFrom cannot race-write the
// same HLS directory.
func (t *TranscoderService) StopJob(mediaID string) {
gate := t.mediaStartGate(mediaID)
gate.Lock()
defer gate.Unlock()
t.mu.Lock()
defer t.mu.Unlock()
if j, ok := t.jobs[mediaID]; ok {
j.cancel()
delete(t.jobs, mediaID)
}
prev := t.detachJobLocked(mediaID)
t.mu.Unlock()
waitJobExit(prev, 12*time.Second)
}
// TouchJob records client activity for the HLS playlist or segment. The idle
@@ -73,10 +77,13 @@ func (t *TranscoderService) touchJobLocked(mediaID string) {
// StopAll terminates every running transcode (called on graceful shutdown).
func (t *TranscoderService) StopAll() {
t.mu.Lock()
defer t.mu.Unlock()
for id, j := range t.jobs {
j.cancel()
delete(t.jobs, id)
pending := make([]*hlsJob, 0, len(t.jobs))
for id := range t.jobs {
pending = append(pending, t.detachJobLocked(id))
}
t.mu.Unlock()
for _, j := range pending {
waitJobExit(j, 5*time.Second)
}
}
+69 -5
View File
@@ -232,23 +232,52 @@ func TestBuildFFmpegArgsHTTPSeekAfterDashI(t *testing.T) {
if strings.Contains(joined, " -re ") {
t.Fatalf("seek restart must disable -re, got: %s", joined)
}
idxSS, idxI := -1, -1
idxSS, idxI, ssCount := -1, -1, 0
for i, arg := range args {
if arg == "-ss" {
idxSS = i
ssCount++
if idxSS < 0 {
idxSS = i
}
}
if arg == "-i" && idxI < 0 {
idxI = i
}
}
if idxSS < 0 || idxI < 0 || idxSS < idxI {
t.Fatalf("expected http -ss after -i, args=%v", args)
if idxSS < 0 || idxI < 0 || idxSS > idxI {
t.Fatalf("expected http -ss before -i, args=%v", args)
}
if ssCount != 1 {
t.Fatalf("expected a single -ss, got %d in %v", ssCount, args)
}
if args[idxSS+1] != "90.000" {
t.Fatalf("start = %q", args[idxSS+1])
}
}
func TestBuildFFmpegArgsBurnsBitmapSubtitleInSoftware(t *testing.T) {
cfg := &config.Config{}
cfg.Transcoder.HardwareAccel = true
cfg.Transcoder.Encoder = "nvenc"
cfg.Transcoder.MaxHeight = 720
cfg.Transcoder.SegmentSeconds = 4
stream := 3
args := buildFFmpegArgsForInput(cfg, transcodeInput{
Source: "/x.mkv",
SubtitleStream: &stream,
}, "/o/x.m3u8", "/o/seg_%05d.ts")
joined := strings.Join(args, " ")
if !strings.Contains(joined, "[0:v:0][0:3]overlay=0:0:eof_action=pass") {
t.Fatalf("bitmap subtitle overlay missing: %s", joined)
}
if !strings.Contains(joined, "-map [v]") || !strings.Contains(joined, "-c:v libx264") {
t.Fatalf("burn-in should use the filtered software video stream: %s", joined)
}
if strings.Contains(joined, "cuda") || strings.Contains(joined, "h264_nvenc") {
t.Fatalf("burn-in must not retain hardware-only frames: %s", joined)
}
}
func TestSameHLSStart(t *testing.T) {
if !sameHLSStart(10, 10.2) {
t.Fatal("expected close starts to match")
@@ -258,12 +287,47 @@ func TestSameHLSStart(t *testing.T) {
}
}
func TestShouldReplaceHLSJob(t *testing.T) {
existing := &hlsJob{startSec: 120, seekGen: 1000}
if shouldReplaceHLSJob(existing, 0, 0) {
t.Fatal("untagged start=0 must not clobber seek-tagged job")
}
if shouldReplaceHLSJob(existing, 0, 900) {
t.Fatal("older _seek must not clobber newer job")
}
if !shouldReplaceHLSJob(existing, 200, 1001) {
t.Fatal("newer _seek should replace")
}
if !shouldReplaceHLSJob(&hlsJob{startSec: 0, seekGen: 0}, 120, 1000) {
t.Fatal("seek should replace untagged head job")
}
if shouldReplaceHLSJob(existing, 120.2, 1001) {
t.Fatal("same start should not replace")
}
}
func TestBitmapSubtitleChangeReplacesHLSJob(t *testing.T) {
existing := &hlsJob{startSec: 120, seekGen: 1000, subtitleStream: 2}
if !shouldReplaceHLSJobConfiguration(existing, 120, 1001, 3) {
t.Fatal("changing bitmap subtitle must replace the HLS generation")
}
if !shouldReplaceHLSJobConfiguration(existing, 120, 1001, -1) {
t.Fatal("closing bitmap subtitle must replace the HLS generation")
}
if shouldReplaceHLSJobConfiguration(existing, 120.2, 1001, 2) {
t.Fatal("same subtitle and nearby start should reuse the HLS generation")
}
}
func TestFilterHLSSegmentQueryDropsStart(t *testing.T) {
got := filterHLSSegmentQuery("token=abc&start=120.5&profile_id=1")
got := filterHLSSegmentQuery("token=abc&start=120.5&_seek=1001&profile_id=1")
if strings.Contains(got, "start=") {
t.Fatalf("start should be stripped, got %q", got)
}
if !strings.Contains(got, "token=abc") || !strings.Contains(got, "profile_id=1") {
t.Fatalf("auth/profile query should remain, got %q", got)
}
if !strings.Contains(got, "_seek=1001") {
t.Fatalf("_seek must remain to isolate cached segment generations, got %q", got)
}
}
+25 -6
View File
@@ -147,12 +147,31 @@ export function streamURL(mediaId: string): string {
// hlsURL returns the m3u8 playlist URL fed into hls.js.
// startSec > 0 asks the server to (re)start ffmpeg from that source offset.
export function hlsURL(mediaId: string, startSec = 0): string {
const start =
startSec > 0.05 ? `&start=${encodeURIComponent(String(Math.round(startSec * 1000) / 1000))}` : ''
// Cache-bust so a seek restart cannot reuse a stale start=0 playlist from disk/browser.
const bust = startSec > 0.05 ? `&_seek=${Date.now()}` : ''
return `/api/hls/${encodeURIComponent(mediaId)}/index.m3u8?${tokenQuery()}${profileQuery()}${start}${bust}`
export function hlsURL(mediaId: string, startSec = 0, subtitleStream?: number): string {
const safeStart = Math.max(0, Math.round(startSec * 1000) / 1000)
// Always send start= (including 0) so the server can tell an intentional
// restart-from-head apart from a missing query on a stale refresh.
const start = `&start=${encodeURIComponent(String(safeStart))}`
// Monotonic-ish client generation: newer seeks win; older in-flight playlist
// requests must not cancel the active ffmpeg job back to t=0.
const bust = `&_seek=${Date.now()}`
const subtitle =
subtitleStream !== undefined && subtitleStream >= 0
? `&subtitle=${encodeURIComponent(String(subtitleStream))}`
: ''
return `/api/hls/${encodeURIComponent(mediaId)}/index.m3u8?${tokenQuery()}${profileQuery()}${start}${subtitle}${bust}`
}
// Stop an on-demand HLS job. keepalive makes the request survive page
// navigation/tab close, where an axios promise can be discarded by browsers.
export function stopHLSJob(mediaId: string): void {
const url = `/api/hls/${encodeURIComponent(mediaId)}?${tokenQuery()}${profileQuery()}`
void fetch(url, {
method: 'DELETE',
credentials: 'same-origin',
keepalive: true,
cache: 'no-store',
}).catch(() => undefined)
}
// imageURL converts a remote poster URL into a same-origin proxy URL so it
+3
View File
@@ -7,6 +7,9 @@ export interface SubtitleTrack {
path: string
url: string
codec: string
source: 'external' | 'embedded'
delivery: 'webvtt' | 'burn'
stream_index?: number
}
export const subtitlesAPI = {
+31 -13
View File
@@ -30,6 +30,8 @@ function formatTime(s: number): string {
type PlayerControlsProps = {
videoRef: React.RefObject<HTMLVideoElement>
uiVisible: boolean
onUiVisibleChange: (visible: boolean) => void
subs: SubtitleTrack[]
/** 当前激活字幕轨道:-1=关闭,0..n-1=对应轨道。 */
subtitleIndex: number
@@ -56,6 +58,8 @@ type PlayerControlsProps = {
export function PlayerControls({
videoRef,
uiVisible,
onUiVisibleChange,
subs,
subtitleIndex,
onSelectSubtitle,
@@ -88,7 +92,6 @@ export function PlayerControls({
const [muted, setMuted] = useState(false)
const [fullscreen, setFullscreen] = useState(false)
const [pip, setPip] = useState(false)
const [uiVisible, setUiVisible] = useState(true)
const [controlsHovered, setControlsHovered] = useState(false)
const [isScrubbing, setIsScrubbing] = useState(false)
const [scrubValue, setScrubValue] = useState<number | null>(null)
@@ -100,6 +103,7 @@ export function PlayerControls({
const subtitleMenuOpenRef = useRef(false)
const danmakuOpenRef = useRef(false)
const playlistOpenRef = useRef(false)
const pendingSeekRef = useRef<number | null>(null)
useEffect(() => {
controlsHoveredRef.current = controlsHovered
@@ -158,14 +162,14 @@ export function PlayerControls({
!danmakuOpenRef.current &&
!playlistOpenRef.current
) {
setUiVisible(false)
onUiVisibleChange(false)
}
}, 3000)
}
}
const onMove = () => {
setUiVisible(true)
onUiVisibleChange(true)
resetTimer()
}
@@ -176,7 +180,7 @@ export function PlayerControls({
}
if (el.paused || controlsHoveredRef.current || isScrubbingRef.current || playlistOpenRef.current) return
if (hideTimerRef.current) clearTimeout(hideTimerRef.current)
setUiVisible(false)
onUiVisibleChange(false)
}
const syncPlay = () => {
@@ -184,16 +188,28 @@ export function PlayerControls({
onMove()
}
const syncTime = () => {
if (!isScrubbingRef.current) {
setCurrentTime(streamOffset + el.currentTime)
if (isScrubbingRef.current) return
if (pendingSeekRef.current !== null) {
const curAbs = streamOffset + el.currentTime
if (Math.abs(curAbs - pendingSeekRef.current) < 3 && el.currentTime > 0.1) {
pendingSeekRef.current = null
setCurrentTime(curAbs)
} else {
setCurrentTime(pendingSeekRef.current)
}
return
}
setCurrentTime(streamOffset + el.currentTime)
}
const syncMeta = () => {
const streamDur = Number.isFinite(el.duration) ? el.duration : 0
setDuration(Math.max(knownDuration || 0, streamOffset + streamDur))
if (!isScrubbingRef.current) {
setCurrentTime(streamOffset + el.currentTime)
if (isScrubbingRef.current) return
if (pendingSeekRef.current !== null) {
setCurrentTime(pendingSeekRef.current)
return
}
setCurrentTime(streamOffset + el.currentTime)
}
const syncVolume = () => {
setVolume(el.volume)
@@ -235,7 +251,7 @@ export function PlayerControls({
if (hideTimerRef.current) clearTimeout(hideTimerRef.current)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [videoRef, knownDuration, streamOffset])
}, [videoRef, knownDuration, streamOffset, onUiVisibleChange])
// Keep the scrubber max in sync when metadata duration arrives after mount.
useEffect(() => {
@@ -247,16 +263,16 @@ export function PlayerControls({
// 当悬停或菜单状态改变时,更新控制栏计时器
useEffect(() => {
if (controlsHovered || isScrubbing || subtitleMenuOpen || danmakuOpen || playlistOpen) {
setUiVisible(true)
onUiVisibleChange(true)
if (hideTimerRef.current) clearTimeout(hideTimerRef.current)
} else {
const el = video()
if (el && !el.paused) {
if (hideTimerRef.current) clearTimeout(hideTimerRef.current)
hideTimerRef.current = setTimeout(() => setUiVisible(false), 3000)
hideTimerRef.current = setTimeout(() => onUiVisibleChange(false), 3000)
}
}
}, [controlsHovered, isScrubbing, subtitleMenuOpen, danmakuOpen, playlistOpen])
}, [controlsHovered, isScrubbing, subtitleMenuOpen, danmakuOpen, playlistOpen, onUiVisibleChange])
const togglePlay = () => {
const el = video()
@@ -269,6 +285,7 @@ export function PlayerControls({
const el = video()
if (!el) return
if (onSeekAbsolute?.(absolute)) {
pendingSeekRef.current = absolute
setCurrentTime(absolute)
return
}
@@ -287,7 +304,7 @@ export function PlayerControls({
const handleSeekStart = () => {
setIsScrubbing(true)
setUiVisible(true)
onUiVisibleChange(true)
if (hideTimerRef.current) clearTimeout(hideTimerRef.current)
}
@@ -347,6 +364,7 @@ export function PlayerControls({
onMouseEnter={() => setControlsHovered(true)}
onMouseLeave={() => setControlsHovered(false)}
onClick={(e) => e.stopPropagation()}
onPointerUp={(e) => e.stopPropagation()}
>
<div className="flex flex-wrap items-center gap-2 text-white sm:flex-nowrap sm:gap-2.5">
{/* 上一集 */}
+129 -59
View File
@@ -4,7 +4,7 @@ import type Hls from 'hls.js'
import toast from 'react-hot-toast'
import { mediaAPI, libraryAPI } from '../api/library'
import { api, hlsURL, streamURL } from '../api/client'
import { hlsURL, stopHLSJob, streamURL } from '../api/client'
import { danmakuAPI, type DanmakuAnime, type DanmakuLoadedInfo } from '../api/danmaku'
import { playbackAPI } from '../api/playback'
import { subtitlesAPI, type SubtitleTrack } from '../api/subtitles'
@@ -33,23 +33,6 @@ import { mediaVersionsOf } from '../utils/mediaVersion'
//
// External subtitles next to the source file are auto-discovered and
// attached as <track> elements.
const SUBTITLE_STORAGE_KEY = 'mebox.subtitle'
// 初始字幕偏好:localStorage 记录上次选择的轨道(-1=关闭);没有偏好时
// 默认 0(自动加载第一条字幕)。
function initialSubtitleIndex(): number {
try {
const saved = localStorage.getItem(SUBTITLE_STORAGE_KEY)
if (saved !== null && saved !== '') {
const n = parseInt(saved, 10)
if (Number.isFinite(n)) return n
}
} catch {
// ignore
}
return 0
}
export function PlayerPage() {
const { id = '' } = useParams()
const [params, setParams] = useSearchParams()
@@ -63,13 +46,14 @@ export function PlayerPage() {
const [media, setMedia] = useState<Media | null>(null)
const [mode, setMode] = useState<PlayerMode>('direct')
const [subs, setSubs] = useState<SubtitleTrack[]>([])
const [subtitleIndex, setSubtitleIndex] = useState<number>(initialSubtitleIndex)
const [subtitleIndex, setSubtitleIndex] = useState<number>(0)
const [hlsUnavailable, setHlsUnavailable] = useState(false)
const [playerError, setPlayerError] = useState('')
// 媒体元数据加载失败(404 / 无权限等):舞台区直接展示错误而不是永远「加载中」
const [loadError, setLoadError] = useState('')
// 「客户端直连解码」模式:宿主机不转码,播放器强制 direct play、隐藏 HLS 切换。
const [directOnly, setDirectOnly] = useState(false)
const [directOnlyKnown, setDirectOnlyKnown] = useState(false)
const [resumePosition, setResumePosition] = useState(0)
const [initialSeekDone, setInitialSeekDone] = useState(false)
// HLS session source offset: playlist t=0 maps to this absolute second.
@@ -97,14 +81,11 @@ export function PlayerPage() {
const [playlistEpisodes, setPlaylistEpisodes] = useState<Media[]>([])
const [playlistOpen, setPlaylistOpen] = useState(false)
const teardownHls = useCallback((mediaId?: string, stopServer = false) => {
const teardownHls = useCallback(() => {
if (hlsRef.current) {
hlsRef.current.destroy()
hlsRef.current = null
}
if (stopServer && mediaId) {
api.delete(`/hls/${encodeURIComponent(mediaId)}`).catch(() => undefined)
}
}, [])
const backTarget = useCallback(() => {
@@ -124,6 +105,7 @@ export function PlayerPage() {
.info()
.then((info) => setDirectOnly(Boolean(info.direct_play_only)))
.catch(() => setDirectOnly(false))
.finally(() => setDirectOnlyKnown(true))
}, [])
// 读取宿主机已保存的弹幕参数作为面板初始值(无 admin 权限也可读)。
@@ -228,9 +210,8 @@ export function PlayerPage() {
if (cancelled) return
const list = tracks ?? []
setSubs(list)
// 记忆的轨道下标可能超出当前媒体的轨道数(不同媒体字幕数量不同),
// 越界时回退到第一条;无字幕则关闭。
setSubtitleIndex((cur) => (cur >= list.length ? (list.length > 0 ? 0 : -1) : cur))
// 服务端始终把外挂字幕排在内嵌字幕前面,因此第一条就是默认优先轨。
setSubtitleIndex(list.length > 0 ? 0 : -1)
})
.catch(() => {
if (cancelled) return
@@ -242,23 +223,42 @@ export function PlayerPage() {
}, [id, modeParam, directOnly])
// Wire up the actual <video> element when we know the mode.
// Depend on media.id (not the media object): refreshing duration after
// MANIFEST_PARSED must not remount HLS or it storms EnsureJob / DELETE.
const mediaId = media?.id
const selectedSubtitle = subtitleIndex >= 0 ? subs[subtitleIndex] : undefined
const burnedSubtitleStream =
selectedSubtitle?.delivery === 'burn' ? selectedSubtitle.stream_index : undefined
const mediaRef = useRef(media)
mediaRef.current = media
useEffect(() => {
if (!media || !ref.current) return
if (!mediaId || !ref.current) return
const currentMedia = mediaRef.current
if (!currentMedia) return
let cancelled = false
teardownHls()
const video = ref.current
const durationSec = currentMedia.duration_sec || 0
if (mode === 'hls') {
const url = hlsURL(media.id, hlsStartSec)
const url = hlsURL(mediaId, hlsStartSec, burnedSubtitleStream)
void import('hls.js').then(({ default: HlsCtor }) => {
if (cancelled || !ref.current) return
if (HlsCtor.isSupported()) {
const hls = new HlsCtor({ enableWorker: true, lowLatencyMode: false })
try {
video.currentTime = 0
} catch {
// ignore
}
hls.loadSource(url)
hls.attachMedia(video)
hls.on(HlsCtor.Events.MANIFEST_PARSED, () => {
void video.play().catch(() => undefined)
// .strm 入库时常缺 duration;转码启动时会补探测,这里刷新一次给进度条总时长。
if ((media.duration_sec || 0) > 0) return
if (durationSec > 0) return
mediaAPI
.get(media.id)
.get(mediaId)
.then((fresh) => {
if ((fresh.duration_sec || 0) > 0) setMedia(fresh)
})
@@ -274,39 +274,61 @@ export function PlayerPage() {
setParams(params, { replace: true })
}
})
if (cancelled) {
hls.destroy()
return
}
hlsRef.current = hls
} else if (video.canPlayType('application/vnd.apple.mpegurl')) {
try {
video.currentTime = 0
} catch {
// ignore
}
video.src = url
void video.play().catch(() => undefined)
} else {
setHlsUnavailable(true)
setPlayerError('当前浏览器不支持 HLS,正在尝试直接播放。')
toast.error('当前浏览器不支持 HLS,降级到直接播放')
setMode('direct')
}
void video.play().catch(() => undefined)
}).catch(() => {
if (cancelled) return
setHlsUnavailable(true)
setPlayerError('HLS 播放组件加载失败,正在尝试直接播放。')
setMode('direct')
})
} else {
video.src = streamURL(media.id)
if (hlsUnavailable && needsTranscodeForBrowser(media)) {
video.src = streamURL(mediaId)
if (hlsUnavailable && needsTranscodeForBrowser(currentMedia)) {
setPlayerError('当前正在直连播放原始文件;此封装或音轨浏览器兼容性有限,可能只有画面没有声音。请配置本机 ffmpeg 后切回 HLS 转码播放。')
}
void video.play().catch(() => undefined)
}
return () => teardownHls()
}, [hlsUnavailable, hlsStartSec, media, mode, params, setParams, teardownHls])
// Stop the host ffmpeg job only when leaving HLS for this media (not on mid-file seek restarts).
useEffect(() => {
if (!media || mode !== 'hls') return
const mediaId = media.id
return () => {
api.delete(`/hls/${encodeURIComponent(mediaId)}`).catch(() => undefined)
cancelled = true
teardownHls()
}
}, [media, mode])
}, [burnedSubtitleStream, hlsUnavailable, hlsStartSec, mediaId, mode, params, setParams, teardownHls])
// Stop host ffmpeg when leaving this HLS player. The keepalive request also
// survives route navigation while the component is being torn down.
useEffect(() => {
if (!mediaId || mode !== 'hls') return
return () => {
stopHLSJob(mediaId)
}
}, [mediaId, mode])
// React cleanup is not guaranteed when a tab/window closes. pagehide fires
// while the document can still dispatch a keepalive request.
useEffect(() => {
if (!mediaId || mode !== 'hls') return
const stopOnPageExit = () => stopHLSJob(mediaId)
window.addEventListener('pagehide', stopOnPageExit)
return () => window.removeEventListener('pagehide', stopOnPageExit)
}, [mediaId, mode])
// 自动拉取已有的播放进度并恢复播放位置
useEffect(() => {
@@ -357,22 +379,33 @@ export function PlayerPage() {
}
}, [resumePosition, initialSeekDone, mode, hlsStartSec])
// 使用 ref 实时同步进度计算所需的状态,避免每次 hlsStartSec 改变都触发 cleanup 并误上报旧进度
const hlsStartSecRef = useRef(hlsStartSec)
hlsStartSecRef.current = hlsStartSec
const modeRef = useRef(mode)
modeRef.current = mode
// Persist resume position every 10 seconds while playing, and immediately upon pause/unmount.
useEffect(() => {
if (!media || !ref.current) return
if (!id || !ref.current) return
const video = ref.current
const absolutePositionMs = () =>
Math.floor(((mode === 'hls' ? hlsStartSec : 0) + video.currentTime) * 1000)
const absoluteDurationMs = () =>
Math.floor(Math.max(media.duration_sec || 0, (mode === 'hls' ? hlsStartSec : 0) + (video.duration || 0)) * 1000)
const absolutePositionMs = () => {
const currentStartSec = modeRef.current === 'hls' ? hlsStartSecRef.current : 0
return Math.floor((currentStartSec + (video.currentTime || 0)) * 1000)
}
const absoluteDurationMs = () => {
const currentStartSec = modeRef.current === 'hls' ? hlsStartSecRef.current : 0
const mediaDur = mediaRef.current?.duration_sec || 0
return Math.floor(Math.max(mediaDur, currentStartSec + (video.duration || 0)) * 1000)
}
const handler = () => {
const now = Date.now()
if (now - lastSentRef.current < 10_000) return
lastSentRef.current = now
const positionMs = absolutePositionMs()
const durationMs = absoluteDurationMs()
if (positionMs > 0) {
playbackAPI.recordProgress(media.id, positionMs, durationMs).catch(() => undefined)
if (positionMs > 0 && mediaRef.current) {
playbackAPI.recordProgress(mediaRef.current.id, positionMs, durationMs).catch(() => undefined)
}
}
video.addEventListener('timeupdate', handler)
@@ -382,11 +415,11 @@ export function PlayerPage() {
video.removeEventListener('pause', handler)
const positionMs = absolutePositionMs()
const durationMs = absoluteDurationMs()
if (positionMs > 0 && media) {
playbackAPI.recordProgress(media.id, positionMs, durationMs).catch(() => undefined)
if (positionMs > 0 && mediaRef.current) {
playbackAPI.recordProgress(mediaRef.current.id, positionMs, durationMs).catch(() => undefined)
}
}
}, [media, mode, hlsStartSec])
}, [id])
// 加载剧集/播放列表
useEffect(() => {
@@ -554,6 +587,31 @@ export function PlayerPage() {
const isDirectStream = isDirectStreamMedia(media)
// 没有外挂字幕且第一条内嵌字幕是图片时,默认轨需要通过 HLS 烧录。
useEffect(() => {
if (
!directOnlyKnown ||
directOnly ||
isDirectStream ||
selectedSubtitle?.delivery !== 'burn' ||
mode === 'hls'
) {
return
}
setHlsStartSec(ref.current?.currentTime || 0)
setMode('hls')
params.set('mode', 'hls')
setParams(params, { replace: true })
}, [
directOnly,
directOnlyKnown,
isDirectStream,
mode,
params,
selectedSubtitle?.delivery,
setParams,
])
const toggleMode = useCallback(() => {
if (isDirectStream) {
toast('该媒体为直连播放,无需且不支持转码')
@@ -600,15 +658,27 @@ export function PlayerPage() {
[hlsStartSec, mode],
)
// 用户切换字幕轨道:-1=关闭;记忆偏好,下次播放默认沿用。
// 用户切换图片字幕时从当前位置创建新的 HLS 烧录任务;文本字幕只在网页层切换。
const selectSubtitle = useCallback((index: number) => {
setSubtitleIndex(index)
try {
localStorage.setItem(SUBTITLE_STORAGE_KEY, String(index))
} catch {
// ignore
const oldTrack = subtitleIndex >= 0 ? subs[subtitleIndex] : undefined
const nextTrack = index >= 0 ? subs[index] : undefined
if (nextTrack?.delivery === 'burn' && (directOnly || isDirectStream)) {
toast.error('图片字幕需要开启 HLS 转码后才能显示')
return
}
}, [])
const burnChanged =
oldTrack?.delivery === 'burn' || nextTrack?.delivery === 'burn'
if (burnChanged && mode === 'hls' && ref.current) {
setHlsStartSec(hlsStartSec + (ref.current.currentTime || 0))
}
setSubtitleIndex(index)
if (nextTrack?.delivery === 'burn' && mode !== 'hls' && !directOnly && !isDirectStream) {
setHlsStartSec(ref.current?.currentTime || 0)
setMode('hls')
params.set('mode', 'hls')
setParams(params, { replace: true })
}
}, [directOnly, hlsStartSec, isDirectStream, mode, params, setParams, subs, subtitleIndex])
const handleVideoError = useCallback(() => {
// 浏览器对 <video src> 的错误描述非常有限,把详细原因
+49 -17
View File
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react'
import type { ReactNode, RefObject } from 'react'
import type { PointerEvent, ReactNode, RefObject } from 'react'
import { subtitlesAPI, type SubtitleTrack } from '../api/subtitles'
import { type DanmakuAnime, type DanmakuLoadedInfo } from '../api/danmaku'
@@ -85,6 +85,8 @@ export function PlayerVideoStage({
const stageRef = useRef<HTMLDivElement>(null)
const [videoRatio, setVideoRatio] = useState<number | null>(null)
const [stageRect, setStageRect] = useState<{ width: number; height: number } | null>(null)
const [controlsVisible, setControlsVisible] = useState(true)
const revealControlsOnlyRef = useRef(false)
// 当前展示的字幕文本(由自定义字幕层渲染,100% 透明无黑框)
const [activeCueText, setActiveCueText] = useState<string>('')
@@ -123,13 +125,26 @@ export function PlayerVideoStage({
}
}, [videoRef, media])
// 点击视频切换播放/暂停;双击切换全屏(控制栏事件自行阻止冒泡)。
// 桌面端点击直接切换播放;移动端控制栏隐藏时首次轻触只唤出控制栏,
// 控制栏已显示时再次轻触才切换播放/暂停。
const togglePlay = () => {
const video = videoRef.current
if (!video) return
if (video.paused) void video.play()?.catch(() => undefined)
else video.pause()
}
const handleStagePointerDown = (event: PointerEvent<HTMLDivElement>) => {
revealControlsOnlyRef.current = event.pointerType === 'touch' && !controlsVisible
}
const handleStageClick = () => {
if (revealControlsOnlyRef.current) {
revealControlsOnlyRef.current = false
setControlsVisible(true)
return
}
revealControlsOnlyRef.current = false
togglePlay()
}
const toggleFullscreen = () => {
const stage = stageRef.current
if (!stage) return
@@ -142,15 +157,22 @@ export function PlayerVideoStage({
// 由下方的 React 自定义层输出 100% 纯透明背景、高清晰文字阴影的字幕。
useEffect(() => {
const video = videoRef.current
if (!video || subs.length === 0 || subtitleIndex < 0 || !subs[subtitleIndex]) {
const selectedTrack = subs[subtitleIndex]
if (
!video ||
subs.length === 0 ||
subtitleIndex < 0 ||
!selectedTrack ||
selectedTrack.delivery === 'burn'
) {
setActiveCueText('')
return
}
const trackIdx = subtitleIndex
const updateCue = () => {
const trackEls = Array.from(video.querySelectorAll('track'))
const selectedEl = trackEls[trackIdx]
const selectedEl = video.querySelector<HTMLTrackElement>(
`track[data-subtitle-index="${subtitleIndex}"]`,
)
const tt = selectedEl?.track
if (!tt) {
setActiveCueText('')
@@ -160,13 +182,13 @@ export function PlayerVideoStage({
// 优先从浏览器 activeCues 中取当前文本;若浏览器在 hidden 模式下延迟触发 cuechange,
// 则从 tt.cues 中根据 video.currentTime 实时匹配当前字幕,确保初次加载无感立即可见。
const texts: string[] = []
if (tt.activeCues && tt.activeCues.length > 0) {
if ((!streamOffset || streamOffset <= 0.05) && tt.activeCues && tt.activeCues.length > 0) {
for (let i = 0; i < tt.activeCues.length; i++) {
const cue = tt.activeCues[i] as VTTCue
if (cue && cue.text) texts.push(cue.text)
}
} else if (tt.cues && tt.cues.length > 0) {
const cur = video.currentTime
const cur = video.currentTime + (streamOffset ?? 0)
for (let i = 0; i < tt.cues.length; i++) {
const cue = tt.cues[i] as VTTCue
if (cue && cur >= cue.startTime && cur <= cue.endTime && cue.text) {
@@ -180,15 +202,18 @@ export function PlayerVideoStage({
const apply = () => {
const trackEls = Array.from(video.querySelectorAll('track'))
if (trackEls.length === 0) return
trackEls.forEach((el, i) => {
trackEls.forEach((el) => {
const tt = el.track
if (tt) {
// 'hidden' 模式:浏览器解析 WebVTT 并触发 cuechange,但隐藏原生黑底 UI
tt.mode = i === trackIdx ? 'hidden' : 'disabled'
tt.mode =
el.dataset.subtitleIndex === String(subtitleIndex) ? 'hidden' : 'disabled'
}
})
const selected = trackEls[trackIdx]
const selected = video.querySelector<HTMLTrackElement>(
`track[data-subtitle-index="${subtitleIndex}"]`,
)
if (!selected) return
const tt = selected.track
@@ -216,8 +241,9 @@ export function PlayerVideoStage({
video.removeEventListener('seeking', updateCue)
video.removeEventListener('seeked', updateCue)
video.removeEventListener('playing', updateCue)
const trackEls = Array.from(video.querySelectorAll('track'))
const selected = trackEls[trackIdx]
const selected = video.querySelector<HTMLTrackElement>(
`track[data-subtitle-index="${subtitleIndex}"]`,
)
if (selected) {
selected.removeEventListener('load', updateCue)
if (selected.track) {
@@ -225,7 +251,7 @@ export function PlayerVideoStage({
}
}
}
}, [subtitleIndex, subs, videoRef, media])
}, [subtitleIndex, subs, videoRef, media, streamOffset])
// 根据视频画面宽高比与舞台宽高比,确定视频在哪个轴向撑满 100%
const isWiderThanStage =
@@ -251,7 +277,8 @@ export function PlayerVideoStage({
ref={stageRef}
data-player-stage
className="relative flex h-full w-full flex-1 items-center justify-center overflow-hidden bg-black"
onClick={togglePlay}
onPointerDown={handleStagePointerDown}
onClick={handleStageClick}
onDoubleClick={toggleFullscreen}
>
{media ? (
@@ -267,16 +294,19 @@ export function PlayerVideoStage({
className="h-full w-full object-contain bg-black"
onError={onVideoError}
>
{subs.map((track, index) => (
{subs.map((track, index) =>
track.delivery === 'burn' ? null : (
<track
key={track.path}
data-subtitle-index={index}
kind="subtitles"
src={subtitlesAPI.url(media.id, track.path)}
srcLang={track.lang}
label={track.label || track.lang}
default={subtitleIndex === index}
/>
))}
),
)}
</video>
<DanmakuStage
key={media.id}
@@ -310,6 +340,8 @@ export function PlayerVideoStage({
</div>
<PlayerControls
videoRef={videoRef}
uiVisible={controlsVisible}
onUiVisibleChange={setControlsVisible}
subs={subs}
subtitleIndex={subtitleIndex}
onSelectSubtitle={onSelectSubtitle}