internal/mpv_playlist.go
1495 lines · 47608 bytes
1package internal
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "regexp"
8 "sort"
9 "strconv"
10 "strings"
11 "sync"
12 "sync/atomic"
13 "time"
14)
15
16// Matches "Episode 12" / "Ep 12" in MPV playlist titles we set.
17var playlistEpisodeTitleRE = regexp.MustCompile(`(?i)\b(?:episode|ep)\s*(\d+)\b`)
18
19// Matches s=WWxHH inside our placeholder URLs (episode encoded in size).
20var placeholderSizeRE = regexp.MustCompile(`s=(\d+)x(\d+)`)
21
22const mpvPlaceholderDuration = 86400
23
24// placeholderURL returns a playable dummy path unique for episode ep.
25// Episode is encoded into lavfi size (fragments break lavfi in mpv).
26func placeholderURL(ep int) string {
27 if ep < 0 {
28 ep = 0
29 }
30 // ep = (h-16)*200 + (w-16); w,h >= 16
31 w := 16 + (ep % 200)
32 h := 16 + (ep / 200)
33 return fmt.Sprintf("av://lavfi:color=c=0x101010:s=%dx%d:d=%d", w, h, mpvPlaceholderDuration)
34}
35
36func parseEpisodeFromPlaceholder(path string) (int, bool) {
37 m := placeholderSizeRE.FindStringSubmatch(path)
38 if len(m) < 3 {
39 return 0, false
40 }
41 w, err1 := strconv.Atoi(m[1])
42 h, err2 := strconv.Atoi(m[2])
43 if err1 != nil || err2 != nil || w < 16 || h < 16 {
44 return 0, false
45 }
46 ep := (h-16)*200 + (w - 16)
47 if ep <= 0 {
48 return 0, false
49 }
50 return ep, true
51}
52
53const (
54 mpvPlaylistIdleDelay = 3 * time.Second
55 mpvPlaylistPollInterval = 400 * time.Millisecond
56 mpvPlaylistStableSamples = 3
57)
58
59// mpvPlaylistSwitching is set while a playlist-driven episode switch is in
60// progress. The main playback monitor must not treat transient time-pos loss
61// (placeholder EOF / loadfile gap) as "user quit".
62var mpvPlaylistSwitching atomic.Bool
63
64// MPVPlaylistIsSwitching reports whether a playlist episode switch is underway.
65func MPVPlaylistIsSwitching() bool {
66 return mpvPlaylistSwitching.Load()
67}
68
69func beginMPVPlaylistSwitch() {
70 mpvPlaylistSwitching.Store(true)
71}
72
73func endMPVPlaylistSwitch() {
74 mpvPlaylistSwitching.Store(false)
75}
76
77// playlistSlot maps an MPV playlist index to curd episode + audio mode.
78type playlistSlot struct {
79 Episode int
80 Mode string // "sub" or "dub"
81 Label string
82}
83
84// MPVPlaylistController maintains a seamless MPV playlist of episodes (and
85// optional alternate audio entry) without interrupting active playback while
86// it is being built. Population happens only after playback is idle/stable.
87//
88// Episode numbers come from a single provider EpisodesList call (not per-episode
89// stream probes). Placeholder rows use a temp M3U so MPV shows clean titles.
90type MPVPlaylistController struct {
91 config *CurdConfig
92 anime *Anime
93 socket string
94 done <-chan struct{}
95
96 mu sync.Mutex
97 slots []playlistSlot
98 suppress atomic.Bool // ignore playlist-pos churn we cause ourselves
99 lastPos int
100 built bool
101 preferredMode string
102 hasAlternate bool
103 alternateMode string
104 currentPlaying int // episode number currently intended
105 currentMode string
106 episodeNums []int // provider episode list (sorted), preferred mode
107}
108
109// StartMPVPlaylistController waits until playback is stable, then builds the
110// episode playlist and watches for user selections. Safe to call in a goroutine.
111// Does nothing for android-intent / empty sockets or when disabled in config.
112func StartMPVPlaylistController(config *CurdConfig, anime *Anime, socket string, done <-chan struct{}) {
113 if config == nil || anime == nil || !config.MpvEpisodePlaylist {
114 return
115 }
116 if socket == "" || socket == "android-intent" {
117 return
118 }
119
120 c := &MPVPlaylistController{
121 config: config,
122 anime: anime,
123 socket: socket,
124 done: done,
125 lastPos: -1,
126 preferredMode: normalizeTranslationType(config.SubOrDub),
127 currentPlaying: anime.Ep.Number,
128 currentMode: normalizeTranslationType(config.SubOrDub),
129 }
130 if c.preferredMode == "" {
131 c.preferredMode = "sub"
132 }
133 c.currentMode = c.preferredMode
134 c.alternateMode = alternateTranslationType(c.preferredMode)
135
136 go c.run()
137}
138
139func (c *MPVPlaylistController) closed() bool {
140 select {
141 case <-c.done:
142 return true
143 default:
144 return false
145 }
146}
147
148func (c *MPVPlaylistController) run() {
149 if !c.waitUntilIdleStable() {
150 return
151 }
152 if c.closed() {
153 return
154 }
155
156 // Build episode rows without touching the currently playing demuxer path
157 // beyond append/insert of titled placeholders (one EpisodesList fetch).
158 if err := c.buildEpisodePlaylist(); err != nil {
159 Log(fmt.Sprintf("MPV playlist build failed: %v", err))
160 // Still watch in case a partial list exists.
161 } else {
162 c.built = true
163 Log(fmt.Sprintf("MPV episode playlist ready (%d episodes)", len(c.episodeNums)))
164 }
165
166 if c.closed() {
167 return
168 }
169
170 // Probe alternate audio only for the *current* episode — never blocks first frame.
171 c.probeAndAttachAlternateAudio()
172
173 c.watchPlaylistSelection()
174}
175
176// waitUntilIdleStable waits until MPV reports a real time-pos a few times in a
177// row so we do not mutate the playlist during initial buffering.
178func (c *MPVPlaylistController) waitUntilIdleStable() bool {
179 deadline := time.Now().Add(45 * time.Second)
180 stable := 0
181 // Initial grace so loadfile/subs settle.
182 timer := time.NewTimer(mpvPlaylistIdleDelay)
183 defer timer.Stop()
184 select {
185 case <-c.done:
186 return false
187 case <-timer.C:
188 }
189
190 for time.Now().Before(deadline) {
191 if c.closed() {
192 return false
193 }
194 pos, err := MPVSendCommand(c.socket, []interface{}{"get_property", "time-pos"})
195 if err == nil && pos != nil {
196 if mpvNumber(pos) >= 0 {
197 stable++
198 if stable >= mpvPlaylistStableSamples {
199 return true
200 }
201 time.Sleep(mpvPlaylistPollInterval)
202 continue
203 }
204 }
205 stable = 0
206 time.Sleep(mpvPlaylistPollInterval)
207 }
208 Log("MPV playlist: playback never became stable; skipping playlist build")
209 return false
210}
211
212// fetchEpisodeNumbers loads the full episode number list from the provider in one
213// shot via EpisodesList. Never resolves per-episode streams (avoids 429s).
214func (c *MPVPlaylistController) fetchEpisodeNumbers() []int {
215 providerName, providerID := AnimeProviderID(c.anime)
216 if providerID != "" {
217 qualified := QualifyProviderID(providerName, providerID)
218 // Preferred mode only — one list request. Do not also hit alternate mode
219 // (GetProviderTotalEpisodes does that; we deliberately do not).
220 list, err := EpisodesList(qualified, c.preferredMode)
221 if err != nil {
222 Log(fmt.Sprintf("MPV playlist: EpisodesList(%s) failed: %v — falling back", providerName, err))
223 } else if nums := parseEpisodeNumberList(list); len(nums) > 0 {
224 return nums
225 }
226 }
227
228 // Fallback: contiguous 1..N from AniList / known total (still no stream probes).
229 total := c.anime.TotalEpisodes
230 if total <= 0 && providerID != "" {
231 if n, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), c.preferredMode); err == nil {
232 total = n
233 c.anime.TotalEpisodes = n
234 }
235 }
236 if total <= 0 {
237 return nil
238 }
239 nums := make([]int, 0, total)
240 for ep := 1; ep <= total; ep++ {
241 nums = append(nums, ep)
242 }
243 return nums
244}
245
246func parseEpisodeNumberList(list []string) []int {
247 seen := make(map[int]struct{}, len(list))
248 for _, raw := range list {
249 raw = strings.TrimSpace(raw)
250 if raw == "" {
251 continue
252 }
253 // Accept "12" or "12.0"
254 f, err := strconv.ParseFloat(raw, 64)
255 if err != nil || f <= 0 {
256 continue
257 }
258 ep := int(f)
259 if float64(ep) != f {
260 // Fractional episode markers (specials) — keep as floor if whole part > 0
261 if ep <= 0 {
262 continue
263 }
264 }
265 seen[ep] = struct{}{}
266 }
267 if len(seen) == 0 {
268 return nil
269 }
270 nums := make([]int, 0, len(seen))
271 for ep := range seen {
272 nums = append(nums, ep)
273 }
274 sort.Ints(nums)
275 return nums
276}
277
278func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string {
279 name := strings.TrimSpace(GetAnimeName(*c.anime))
280 base := fmt.Sprintf("Episode %d", ep)
281 if name != "" {
282 base = fmt.Sprintf("%s - Episode %d", name, ep)
283 }
284 if c.anime.FillerEpisodes != nil && IsEpisodeFiller(c.anime.FillerEpisodes, ep) {
285 base += " [Filler]"
286 }
287 mode = normalizeTranslationType(mode)
288 if mode != "" && mode != c.preferredMode {
289 base += " (" + strings.ToUpper(mode) + ")"
290 } else if mode == "dub" && c.preferredMode == "dub" {
291 // Preferred is dub — no extra tag on every row
292 } else if mode == "dub" {
293 base += " (DUB)"
294 }
295 if ep == c.currentPlaying && mode == c.currentMode {
296 base += " ◀"
297 }
298 return base
299}
300
301func (c *MPVPlaylistController) buildEpisodePlaylist() error {
302 episodes := c.fetchEpisodeNumbers()
303 if len(episodes) == 0 {
304 return fmt.Errorf("no episode list from provider")
305 }
306 c.episodeNums = episodes
307 if max := episodes[len(episodes)-1]; max > c.anime.TotalEpisodes {
308 c.anime.TotalEpisodes = max
309 }
310
311 currentEp := c.anime.Ep.Number
312 if currentEp < 1 {
313 currentEp = episodes[0]
314 }
315 // Ensure current episode is in the list (AniList progress may point at an ep
316 // the provider still lists under a different numbering — keep a slot).
317 if !containsInt(episodes, currentEp) {
318 episodes = append(episodes, currentEp)
319 sort.Ints(episodes)
320 c.episodeNums = episodes
321 }
322
323 c.suppress.Store(true)
324 defer c.suppress.Store(false)
325
326 // Prefer title display in the playlist OSD when mpv supports it.
327 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "osd-playlist-entry", "title"})
328
329 // Title the currently playing item (force-media-title sticks for the active entry).
330 curLabel := c.episodeLabel(currentEp, c.currentMode)
331 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", curLabel})
332 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", curLabel})
333
334 var before, after []playlistSlot
335 for _, ep := range episodes {
336 if ep < currentEp {
337 before = append(before, playlistSlot{
338 Episode: ep,
339 Mode: c.preferredMode,
340 Label: c.episodeLabel(ep, c.preferredMode),
341 })
342 } else if ep > currentEp {
343 after = append(after, playlistSlot{
344 Episode: ep,
345 Mode: c.preferredMode,
346 Label: c.episodeLabel(ep, c.preferredMode),
347 })
348 }
349 }
350
351 // Future episodes: one M3U loadlist append (titled placeholders, no stream probes).
352 if len(after) > 0 {
353 if err := c.loadTitledPlaceholders(after, false); err != nil {
354 Log(fmt.Sprintf("playlist append future: %v", err))
355 }
356 }
357
358 // Previous episodes: append via M3U then playlist-move to the front.
359 if len(before) > 0 {
360 if err := c.loadTitledPlaceholders(before, true); err != nil {
361 Log(fmt.Sprintf("playlist insert previous: %v", err))
362 }
363 }
364
365 // Rebuild slot map: before + current + after (preferred mode).
366 slots := make([]playlistSlot, 0, len(episodes))
367 slots = append(slots, before...)
368 slots = append(slots, playlistSlot{
369 Episode: currentEp,
370 Mode: c.preferredMode,
371 Label: curLabel,
372 })
373 slots = append(slots, after...)
374
375 c.mu.Lock()
376 c.slots = slots
377 c.currentPlaying = currentEp
378 c.mu.Unlock()
379
380 wantPos := len(before)
381 c.lastPos = wantPos
382 if pos, err := c.playlistPos(); err == nil {
383 c.lastPos = pos
384 if pos != wantPos {
385 Log(fmt.Sprintf("MPV playlist-pos=%d want=%d (leaving as-is to avoid stutter)", pos, wantPos))
386 }
387 }
388 return nil
389}
390
391// loadTitledPlaceholders writes a temp M3U with #EXTINF titles and loadlists it.
392// If moveToFront is true, entries are moved to the start of the playlist (preserving order).
393func (c *MPVPlaylistController) loadTitledPlaceholders(slots []playlistSlot, moveToFront bool) error {
394 if len(slots) == 0 {
395 return nil
396 }
397 path, err := c.writePlaceholderM3U(slots)
398 if err != nil {
399 return err
400 }
401 defer func() { _ = os.Remove(path) }()
402
403 beforeCount, _ := c.playlistCount()
404
405 if _, err := MPVSendCommand(c.socket, []interface{}{"loadlist", path, "append"}); err != nil {
406 return fmt.Errorf("loadlist: %w", err)
407 }
408
409 afterCount, err := c.playlistCount()
410 if err != nil {
411 return err
412 }
413 added := afterCount - beforeCount
414 if added <= 0 {
415 return fmt.Errorf("loadlist added 0 entries")
416 }
417
418 if !moveToFront {
419 return nil
420 }
421
422 // Move the newly appended block to the front, preserving relative order.
423 // Start: [current, ..., NEW0, NEW1, ...] → [NEW0, NEW1, ..., current, ...]
424 for i := 0; i < added; i++ {
425 from := beforeCount + i // shifts as we insert earlier
426 to := i
427 if _, err := MPVSendCommand(c.socket, []interface{}{"playlist-move", from, to}); err != nil {
428 Log(fmt.Sprintf("playlist-move %d→%d: %v", from, to, err))
429 }
430 }
431 return nil
432}
433
434func (c *MPVPlaylistController) writePlaceholderM3U(slots []playlistSlot) (string, error) {
435 dir := os.TempDir()
436 if c.config != nil && strings.TrimSpace(c.config.StoragePath) != "" {
437 dir = os.ExpandEnv(c.config.StoragePath)
438 _ = os.MkdirAll(dir, 0o755)
439 }
440 f, err := os.CreateTemp(dir, "curd-playlist-*.m3u")
441 if err != nil {
442 return "", err
443 }
444 path := f.Name()
445
446 var b strings.Builder
447 b.WriteString("#EXTM3U\n")
448 for _, s := range slots {
449 title := sanitizeM3UTitle(s.Label)
450 b.WriteString("#EXTINF:-1,")
451 b.WriteString(title)
452 b.WriteByte('\n')
453 // Unique URL per episode so mpv actually changes playlist-pos on select.
454 b.WriteString(placeholderURL(s.Episode))
455 b.WriteByte('\n')
456 }
457 if _, err := f.WriteString(b.String()); err != nil {
458 f.Close()
459 _ = os.Remove(path)
460 return "", err
461 }
462 if err := f.Close(); err != nil {
463 _ = os.Remove(path)
464 return "", err
465 }
466 return path, nil
467}
468
469// sanitizeM3UTitle keeps #EXTINF titles single-line and free of control chars.
470func sanitizeM3UTitle(title string) string {
471 title = strings.ReplaceAll(title, "\r", " ")
472 title = strings.ReplaceAll(title, "\n", " ")
473 title = strings.TrimSpace(title)
474 if title == "" {
475 return "Episode"
476 }
477 return title
478}
479
480func containsInt(nums []int, want int) bool {
481 for _, n := range nums {
482 if n == want {
483 return true
484 }
485 }
486 return false
487}
488
489func (c *MPVPlaylistController) playlistPos() (int, error) {
490 v, err := MPVSendCommand(c.socket, []interface{}{"get_property", "playlist-pos"})
491 if err != nil {
492 return -1, err
493 }
494 return int(mpvNumber(v) + 0.5), nil
495}
496
497func (c *MPVPlaylistController) playlistCount() (int, error) {
498 v, err := MPVSendCommand(c.socket, []interface{}{"get_property", "playlist-count"})
499 if err != nil {
500 return 0, err
501 }
502 return int(mpvNumber(v) + 0.5), nil
503}
504
505// probeAndAttachAlternateAudio checks whether the opposite sub/dub mode has a
506// stream for the *current* episode only (one resolve — not every episode).
507func (c *MPVPlaylistController) probeAndAttachAlternateAudio() {
508 if c.closed() || c.anime == nil {
509 return
510 }
511 alt := c.alternateMode
512 cfg := *c.config
513 cfg.SubOrDub = alt
514
515 // Background resolve — does not touch MPV until we know a stream exists.
516 result, err := ResolveEpisodeURL(cfg, c.anime, c.currentPlaying)
517 if err != nil || len(result.Links) == 0 {
518 Log(fmt.Sprintf("MPV playlist: no %s stream for ep %d (%v)", alt, c.currentPlaying, err))
519 c.hasAlternate = false
520 return
521 }
522 c.hasAlternate = true
523
524 c.suppress.Store(true)
525 defer c.suppress.Store(false)
526
527 c.mu.Lock()
528 curIdx := c.episodeIndexLocked(c.currentPlaying, c.currentMode)
529 if curIdx < 0 {
530 curIdx = 0
531 }
532 label := c.episodeLabel(c.currentPlaying, alt)
533 insertAt := curIdx + 1
534 c.mu.Unlock()
535
536 slot := playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label}
537 if err := c.insertTitledPlaceholderAt(insertAt, slot); err != nil {
538 Log(fmt.Sprintf("MPV playlist: failed to add %s entry: %v", alt, err))
539 return
540 }
541
542 c.mu.Lock()
543 if insertAt >= len(c.slots) {
544 c.slots = append(c.slots, slot)
545 } else {
546 c.slots = append(c.slots[:insertAt], append([]playlistSlot{slot}, c.slots[insertAt:]...)...)
547 }
548 c.mu.Unlock()
549 Log(fmt.Sprintf("MPV playlist: added %s option for ep %d", alt, c.currentPlaying))
550}
551
552// insertTitledPlaceholderAt appends a single titled M3U entry then moves it to index.
553func (c *MPVPlaylistController) insertTitledPlaceholderAt(index int, slot playlistSlot) error {
554 countBefore, _ := c.playlistCount()
555 if err := c.loadTitledPlaceholders([]playlistSlot{slot}, false); err != nil {
556 return err
557 }
558 countAfter, err := c.playlistCount()
559 if err != nil {
560 return err
561 }
562 if countAfter <= countBefore {
563 return fmt.Errorf("placeholder not added")
564 }
565 from := countAfter - 1
566 if from == index {
567 return nil
568 }
569 if index < 0 {
570 index = 0
571 }
572 if index > from {
573 index = from
574 }
575 _, err = MPVSendCommand(c.socket, []interface{}{"playlist-move", from, index})
576 return err
577}
578
579func (c *MPVPlaylistController) watchPlaylistSelection() {
580 // Detect selection primarily via path: when the user picks another playlist
581 // row, mpv loads our unique lavfi placeholder. Polling playlist-pos alone
582 // missed jumps (logs showed time-pos drop with no "pos changed").
583 Log("MPV playlist: watching path + playlist-pos for episode picks")
584 poll := 150 * time.Millisecond
585 var lastSeenPath string
586
587 for {
588 if c.closed() {
589 return
590 }
591 if !IsMPVRunning(c.socket) {
592 return
593 }
594 if c.suppress.Load() || MPVPlaylistIsSwitching() {
595 time.Sleep(poll)
596 continue
597 }
598
599 path := mpvStringProperty(c.socket, "path")
600 pos, posErr := c.playlistPos()
601
602 // --- Primary: path became a placeholder for episode N ---
603 if ep, ok := parseEpisodeFromPlaceholder(path); ok {
604 // Debounce: confirm path still that placeholder briefly (scrub).
605 time.Sleep(80 * time.Millisecond)
606 path2 := mpvStringProperty(c.socket, "path")
607 ep2, ok2 := parseEpisodeFromPlaceholder(path2)
608 if !ok2 {
609 continue
610 }
611 ep = ep2
612 path = path2
613
614 mode := c.preferredMode
615 if posErr == nil && pos >= 0 {
616 if _, title := c.playlistEntryMeta(pos); title != "" {
617 if _, m, ok3 := parsePlaylistEpisodeTitle(title, c.preferredMode); ok3 {
618 mode = m
619 }
620 }
621 }
622
623 c.mu.Lock()
624 curEp := c.currentPlaying
625 c.mu.Unlock()
626
627 Log(fmt.Sprintf("MPV playlist: DETECT path placeholder ep=%d mode=%s (was ep=%d prevPath=%s)",
628 ep, mode, curEp, truncateForLog(lastSeenPath, 50)))
629
630 beginMPVPlaylistSwitch()
631 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
632 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", ep), 5000})
633
634 if posErr == nil && pos >= 0 {
635 c.lastPos = pos
636 }
637 slot := playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)}
638 c.handlePlaylistJumpSlot(slot, curEp)
639 lastSeenPath = mpvStringProperty(c.socket, "path")
640 continue
641 }
642
643 // --- Secondary: playlist-pos moved ---
644 // IMPORTANT: freeze the *first* new index and resolve that entry immediately.
645 // Re-reading pos after a sleep was overwriting 38→39 (current) so we always
646 // reloaded ep 40 when the user clicked 39 (see debug: DETECT 39→38 then
647 // "pos 39 title Episode 40").
648 if posErr == nil && pos >= 0 && pos != c.lastPos {
649 targetPos := pos
650 fromPos := c.lastPos
651 Log(fmt.Sprintf("MPV playlist: DETECT pos %d → %d (path=%s)", fromPos, targetPos, truncateForLog(path, 50)))
652
653 // Resolve the entry the user landed on *now*, before mpv can snap back.
654 slot, slotErr := c.resolveSlotAt(targetPos)
655 if slotErr != nil {
656 Log(fmt.Sprintf("MPV playlist: resolve pos %d failed: %v", targetPos, slotErr))
657 // Still try path / slots fallback inside handlePlaylistJump.
658 beginMPVPlaylistSwitch()
659 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
660 c.lastPos = targetPos
661 c.handlePlaylistJump(targetPos)
662 lastSeenPath = mpvStringProperty(c.socket, "path")
663 continue
664 }
665
666 c.mu.Lock()
667 curEp := c.currentPlaying
668 c.mu.Unlock()
669
670 Log(fmt.Sprintf("MPV playlist: frozen target pos=%d → ep %d (cur ep %d)", targetPos, slot.Episode, curEp))
671
672 // If resolve says same episode as current and path is still the live stream,
673 // this was a false pos blip — ignore.
674 if slot.Episode == curEp && !isPlaceholderPath(path) {
675 Log(fmt.Sprintf("MPV playlist: ignore pos blip %d→%d (still ep %d, live path)", fromPos, targetPos, curEp))
676 c.lastPos = targetPos
677 // If pos really moved within same ep (dub row), still switch mode.
678 if normalizeTranslationType(slot.Mode) != normalizeTranslationType(c.currentMode) {
679 beginMPVPlaylistSwitch()
680 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
681 c.handlePlaylistJumpSlot(slot, curEp)
682 lastSeenPath = mpvStringProperty(c.socket, "path")
683 }
684 time.Sleep(poll)
685 continue
686 }
687
688 beginMPVPlaylistSwitch()
689 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
690 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000})
691 c.lastPos = targetPos
692 c.handlePlaylistJumpSlot(slot, curEp)
693 lastSeenPath = mpvStringProperty(c.socket, "path")
694 continue
695 }
696
697 if path != "" {
698 lastSeenPath = path
699 }
700 time.Sleep(poll)
701 }
702}
703
704func isPlaceholderPath(path string) bool {
705 return strings.HasPrefix(path, "av://lavfi:") || strings.Contains(path, "lavfi:color=")
706}
707
708// handlePlaylistJumpSlot switches to a known target slot (from path or pos detection).
709func (c *MPVPlaylistController) handlePlaylistJumpSlot(slot playlistSlot, curEp int) {
710 curMode := c.currentMode
711 if curMode == "" {
712 curMode = c.preferredMode
713 }
714 beginMPVPlaylistSwitch()
715 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
716
717 leaveAction := playlistLeaveNone
718 if slot.Episode != curEp {
719 pct := PercentageWatched(c.anime.Ep.Player.PlaybackTime, c.anime.Ep.Duration)
720 threshold := 85
721 if c.config != nil && c.config.PercentageToMarkComplete > 0 {
722 threshold = c.config.PercentageToMarkComplete
723 }
724 action, pErr := promptPlaylistEpisodeLeave(curEp, slot.Episode, pct, threshold)
725 if pErr != nil {
726 Log(fmt.Sprintf("MPV playlist leave prompt: %v (playing target anyway)", pErr))
727 action = playlistLeaveNone
728 }
729 if action == playlistLeaveCancel {
730 Log("MPV playlist: user cancelled — reloading current ep real stream")
731 // We're sitting on a dummy placeholder; put real current ep back.
732 if err := c.playSlot(playlistSlot{Episode: curEp, Mode: curMode, Label: c.episodeLabel(curEp, curMode)}); err != nil {
733 Log(fmt.Sprintf("MPV playlist: reload current failed: %v", err))
734 endMPVPlaylistSwitch()
735 }
736 return
737 }
738 leaveAction = action
739 } else {
740 Log(fmt.Sprintf("MPV playlist: reloading real stream for ep %d (was on placeholder)", curEp))
741 }
742
743 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 8000})
744 Log(fmt.Sprintf("MPV playlist: SWITCH ep %d → %d (%s) leave=%s", curEp, slot.Episode, slot.Mode, leaveAction))
745 CurdOut(fmt.Sprintf("Loading episode %d…", slot.Episode))
746
747 leftEp := curEp
748 if err := c.playSlot(slot); err != nil {
749 Log(fmt.Sprintf("MPV playlist: failed to play ep %d: %v", slot.Episode, err))
750 CurdOut(fmt.Sprintf("Could not play episode %d: %v", slot.Episode, err))
751 if err2 := c.playSlot(playlistSlot{Episode: curEp, Mode: curMode, Label: c.episodeLabel(curEp, curMode)}); err2 != nil {
752 Log(fmt.Sprintf("MPV playlist: recovery play failed: %v", err2))
753 endMPVPlaylistSwitch()
754 }
755 return
756 }
757
758 c.finalizePlaylistEpisodeChange(leftEp, slot.Episode, slot.Mode, leaveAction)
759
760 go func() {
761 time.Sleep(mpvPlaylistIdleDelay)
762 if c.closed() {
763 return
764 }
765 if err := c.rebuildPlaylistAroundCurrent(); err != nil {
766 Log(fmt.Sprintf("MPV playlist rebuild after switch: %v", err))
767 }
768 }()
769}
770
771// playlistLeaveAction is the user's choice when leaving an episode via playlist.
772type playlistLeaveAction string
773
774const (
775 playlistLeaveNone playlistLeaveAction = "none" // play target; last-played only (no remote)
776 playlistLeaveMarkLeft playlistLeaveAction = "mark" // mark left episode watched remotely
777 playlistLeaveSetWatch playlistLeaveAction = "setwatch" // set remote progress to toEp-1
778 playlistLeaveCancel playlistLeaveAction = "cancel" // stay on current episode
779)
780
781// promptPlaylistEpisodeLeave asks how to handle progress when changing episodes.
782// Overridable in tests. +1 (next) is auto; other jumps prompt.
783var promptPlaylistEpisodeLeave = defaultPromptPlaylistEpisodeLeave
784
785func defaultPromptPlaylistEpisodeLeave(fromEp, toEp int, percentageWatched float64, threshold int) (playlistLeaveAction, error) {
786 // Same episode (mode toggle only) — nothing to ask.
787 if toEp == fromEp {
788 return playlistLeaveNone, nil
789 }
790
791 nearlyDone := int(percentageWatched) >= threshold && percentageWatched > 0
792 pctLabel := fmt.Sprintf("%.0f%%", percentageWatched)
793 if percentageWatched <= 0 {
794 pctLabel = "just started"
795 }
796
797 // Sequential next episode (+1): no menu — same spirit as normal "next ep".
798 if toEp == fromEp+1 {
799 if nearlyDone {
800 CurdOut(fmt.Sprintf("Next episode %d · marking %d watched (was %s)", toEp, fromEp, pctLabel))
801 return playlistLeaveMarkLeft, nil
802 }
803 CurdOut(fmt.Sprintf("Next episode %d · last played updated", toEp))
804 return playlistLeaveNone, nil
805 }
806
807 // Non-linear jump — ask what to do with upstream progress.
808 CurdOut(fmt.Sprintf("Jump: episode %d (%s) → episode %d", fromEp, pctLabel, toEp))
809
810 options := []SelectionOption{
811 {Key: "none", Label: fmt.Sprintf("▶ Play episode %d only (don’t change AniList/MAL)", toEp)},
812 {Key: "mark", Label: fmt.Sprintf("✓ Mark episode %d watched, then play %d", fromEp, toEp)},
813 {Key: "setwatch", Label: fmt.Sprintf("📌 Set progress to %d (watching %d), play %d", maxInt(0, toEp-1), toEp, toEp)},
814 {Key: "cancel", Label: fmt.Sprintf("↩ Cancel — stay on episode %d", fromEp)},
815 }
816 // If they were almost done, put "mark left" first.
817 if nearlyDone {
818 options = []SelectionOption{
819 {Key: "mark", Label: fmt.Sprintf("✓ Mark episode %d watched (you were %s), play %d", fromEp, pctLabel, toEp)},
820 {Key: "none", Label: fmt.Sprintf("▶ Play episode %d only (don’t change AniList/MAL)", toEp)},
821 {Key: "setwatch", Label: fmt.Sprintf("📌 Set progress to %d (watching %d), play %d", maxInt(0, toEp-1), toEp, toEp)},
822 {Key: "cancel", Label: fmt.Sprintf("↩ Cancel — stay on episode %d", fromEp)},
823 }
824 }
825
826 selected, err := promptSelectOrdered(options)
827 if err != nil {
828 // User already picked a row in MPV — never cancel back to the old episode.
829 Log(fmt.Sprintf("playlist jump prompt failed (%v); playing %d without remote update", err, toEp))
830 return playlistLeaveNone, nil
831 }
832 if selected.Key == "cancel" || SelectionMeansQuit(selected) || SelectionMeansBack(selected) {
833 return playlistLeaveCancel, nil
834 }
835 switch selected.Key {
836 case "mark":
837 return playlistLeaveMarkLeft, nil
838 case "setwatch":
839 return playlistLeaveSetWatch, nil
840 case "none", "switch":
841 return playlistLeaveNone, nil
842 default:
843 return playlistLeaveNone, nil
844 }
845}
846
847func maxInt(a, b int) int {
848 if a > b {
849 return a
850 }
851 return b
852}
853
854// resolveSlotAt figures out which episode the user selected at playlist index pos.
855// Order: placeholder filename encode → title → our slots map.
856// Never re-query playlist-pos here — caller freezes the index.
857func (c *MPVPlaylistController) resolveSlotAt(pos int) (playlistSlot, error) {
858 filename, title := c.playlistEntryMeta(pos)
859 Log(fmt.Sprintf("MPV playlist: resolve pos=%d filename=%q title=%q", pos, truncateForLog(filename, 60), title))
860
861 if ep, ok := parseEpisodeFromPlaceholder(filename); ok {
862 mode := c.preferredMode
863 if _, m, ok2 := parsePlaylistEpisodeTitle(title, c.preferredMode); ok2 {
864 mode = m
865 }
866 Log(fmt.Sprintf("MPV playlist: pos %d filename → ep %d (title=%q)", pos, ep, title))
867 label := title
868 if label == "" {
869 label = c.episodeLabel(ep, mode)
870 }
871 return playlistSlot{Episode: ep, Mode: mode, Label: label}, nil
872 }
873 if title != "" {
874 if ep, mode, ok := parsePlaylistEpisodeTitle(title, c.preferredMode); ok {
875 Log(fmt.Sprintf("MPV playlist: pos %d title %q → ep %d (%s)", pos, title, ep, mode))
876 return playlistSlot{Episode: ep, Mode: mode, Label: title}, nil
877 }
878 Log(fmt.Sprintf("MPV playlist: pos %d title %q (unparsed) file=%q", pos, title, truncateForLog(filename, 40)))
879 }
880
881 c.mu.Lock()
882 defer c.mu.Unlock()
883 if pos < 0 || pos >= len(c.slots) {
884 return playlistSlot{}, fmt.Errorf("playlist pos %d out of range (slots=%d)", pos, len(c.slots))
885 }
886 slot := c.slots[pos]
887 Log(fmt.Sprintf("MPV playlist: pos %d slots fallback → ep %d", pos, slot.Episode))
888 return slot, nil
889}
890
891func (c *MPVPlaylistController) playlistEntryMeta(pos int) (filename, title string) {
892 v, err := MPVSendCommand(c.socket, []interface{}{"get_property", "playlist"})
893 if err != nil || v == nil {
894 return "", ""
895 }
896 entries, ok := v.([]interface{})
897 if !ok || pos < 0 || pos >= len(entries) {
898 return "", ""
899 }
900 entry, ok := entries[pos].(map[string]interface{})
901 if !ok {
902 return "", ""
903 }
904 if f, ok := entry["filename"].(string); ok {
905 filename = f
906 }
907 if t, ok := entry["title"].(string); ok {
908 title = strings.TrimSpace(t)
909 }
910 return filename, title
911}
912
913func parsePlaylistEpisodeTitle(title, preferredMode string) (ep int, mode string, ok bool) {
914 mode = normalizeTranslationType(preferredMode)
915 if mode == "" {
916 mode = "sub"
917 }
918 upper := strings.ToUpper(title)
919 if strings.Contains(upper, "(DUB)") || strings.Contains(upper, "· DUB") || strings.HasSuffix(strings.TrimSpace(upper), "DUB") {
920 mode = "dub"
921 } else if strings.Contains(upper, "(SUB)") {
922 mode = "sub"
923 }
924 m := playlistEpisodeTitleRE.FindStringSubmatch(title)
925 if len(m) < 2 {
926 return 0, mode, false
927 }
928 n, err := strconv.Atoi(m[1])
929 if err != nil || n <= 0 {
930 return 0, mode, false
931 }
932 return n, mode, true
933}
934
935func (c *MPVPlaylistController) handlePlaylistJump(pos int) {
936 curEp := c.currentPlaying
937
938 slot, err := c.resolveSlotAt(pos)
939 if err != nil {
940 Log(fmt.Sprintf("MPV playlist: resolve slot at %d: %v", pos, err))
941 // Path may still be a placeholder — try path-based parse of active media.
942 if ep, ok := parseEpisodeFromPlaceholder(mpvStringProperty(c.socket, "path")); ok {
943 slot = playlistSlot{Episode: ep, Mode: c.preferredMode, Label: c.episodeLabel(ep, c.preferredMode)}
944 c.handlePlaylistJumpSlot(slot, curEp)
945 return
946 }
947 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", false})
948 endMPVPlaylistSwitch()
949 return
950 }
951
952 c.handlePlaylistJumpSlot(slot, curEp)
953}
954
955// finalizePlaylistEpisodeChange updates local history, last-played id, episode
956// metadata, optional remote progress, and prefetches the next episode.
957func (c *MPVPlaylistController) finalizePlaylistEpisodeChange(fromEp, toEp int, mode string, leave playlistLeaveAction) {
958 if c.anime == nil || c.config == nil {
959 return
960 }
961 anime := c.anime
962 mode = normalizeTranslationType(mode)
963 if mode == "" {
964 mode = c.preferredMode
965 }
966
967 // Keep config + controller mode in sync (sub/dub playlist entries).
968 if mode != "" {
969 c.config.SubOrDub = mode
970 c.currentMode = mode
971 }
972
973 // Clear stale next-episode prefetch from the previous number.
974 anime.Ep.NextEpisode = NextEpisode{}
975 anime.Ep.IsCompleted = false
976 anime.Ep.LastWasSkipped = false
977 anime.Ep.Resume = false
978 anime.Ep.Number = toEp
979 anime.Ep.Player.PlaybackTime = 0
980 anime.Ep.IsFiller = IsEpisodeFiller(anime.FillerEpisodes, toEp)
981
982 // Episode titles / filler / recap from Jikan (non-fatal). Don't trust its duration.
983 if anime.MalId > 0 {
984 if err := GetEpisodeData(anime.MalId, toEp, anime); err != nil {
985 Log(fmt.Sprintf("MPV playlist: GetEpisodeData ep %d: %v", toEp, err))
986 }
987 // Playback duration comes from MPV, not Jikan.
988 anime.Ep.Duration = 0
989 }
990 // Filler list is authoritative when present.
991 if len(anime.FillerEpisodes) > 0 {
992 anime.Ep.IsFiller = IsEpisodeFiller(anime.FillerEpisodes, toEp)
993 }
994
995 // Last-played anime id (Continue Last Session).
996 writeLastPlayedAnimeID(c.config.StoragePath, anime.AnilistId)
997
998 // Local history: current episode is now toEp at position 0.
999 dbPath := localHistoryPath(c.config.StoragePath)
1000 if dbPath != "" {
1001 if err := LocalUpdateAnime(
1002 dbPath,
1003 anime.AnilistId,
1004 anime.ProviderId,
1005 toEp,
1006 0,
1007 0,
1008 GetAnimeName(*anime),
1009 CurrentAnimeProviderName(anime),
1010 ); err != nil {
1011 Log(fmt.Sprintf("MPV playlist: LocalUpdateAnime: %v", err))
1012 } else {
1013 Log(fmt.Sprintf("MPV playlist: last played → ep %d", toEp))
1014 }
1015 }
1016
1017 // Remote progress according to leave action.
1018 remoteProgress := 0
1019 switch leave {
1020 case playlistLeaveMarkLeft:
1021 if fromEp > 0 {
1022 remoteProgress = fromEp
1023 }
1024 case playlistLeaveSetWatch:
1025 if toEp > 1 {
1026 remoteProgress = toEp - 1
1027 }
1028 }
1029
1030 if remoteProgress > 0 {
1031 token := ""
1032 if u := GetGlobalUser(); u != nil {
1033 token = u.Token
1034 }
1035 if !anime.Rewatching && token != "" {
1036 go func(ep int) {
1037 if err := UpdateAnimeProgress(token, anime.AnilistId, ep); err != nil {
1038 Log(fmt.Sprintf("MPV playlist: UpdateAnimeProgress(%d): %v", ep, err))
1039 } else {
1040 CurdOut(fmt.Sprintf("Upstream progress → episode %d", ep))
1041 }
1042 }(remoteProgress)
1043 } else if anime.Rewatching {
1044 Log("MPV playlist: rewatching — skipped remote progress update")
1045 }
1046 CurdOut(fmt.Sprintf("Playing episode %d · upstream progress set to %d", toEp, remoteProgress))
1047 } else {
1048 CurdOut(fmt.Sprintf("Playing episode %d · last played updated (no upstream change)", toEp))
1049 }
1050
1051 // Prefetch next episode links in preferred mode (no audio prompts).
1052 go c.prefetchAfterPlaylistSwitch(toEp)
1053
1054 // Discord will pick up the new title/position on the next presence tick once
1055 // duration is known; force a soft title refresh for the window.
1056 title := fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), toEp)
1057 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", title})
1058 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", title})
1059}
1060
1061func localHistoryPath(storagePath string) string {
1062 storagePath = strings.TrimSpace(os.ExpandEnv(storagePath))
1063 if storagePath == "" {
1064 return ""
1065 }
1066 return filepath.Join(storagePath, "curd_history.txt")
1067}
1068
1069func writeLastPlayedAnimeID(storagePath string, anilistID int) {
1070 if anilistID <= 0 {
1071 return
1072 }
1073 storagePath = strings.TrimSpace(os.ExpandEnv(storagePath))
1074 if storagePath == "" {
1075 return
1076 }
1077 idPath := filepath.Join(storagePath, "curd_id")
1078 if err := os.MkdirAll(filepath.Dir(idPath), 0o755); err != nil {
1079 Log(fmt.Sprintf("MPV playlist: mkdir for curd_id: %v", err))
1080 return
1081 }
1082 if err := os.WriteFile(idPath, []byte(strconv.Itoa(anilistID)), 0o644); err != nil {
1083 Log(fmt.Sprintf("MPV playlist: write curd_id: %v", err))
1084 }
1085}
1086
1087func (c *MPVPlaylistController) prefetchAfterPlaylistSwitch(currentEp int) {
1088 if c == nil || c.config == nil || c.anime == nil {
1089 return
1090 }
1091 nextEp := currentEp + 1
1092 if c.anime.TotalEpisodes > 0 && nextEp > c.anime.TotalEpisodes {
1093 return
1094 }
1095 cfg := *c.config
1096 cfg.SubOrDub = c.preferredMode
1097 next := *c.anime
1098 result, err := ResolveEpisodeURL(cfg, &next, nextEp)
1099 if err != nil || len(result.Links) == 0 {
1100 Log(fmt.Sprintf("MPV playlist: prefetch ep %d: %v", nextEp, err))
1101 return
1102 }
1103 c.anime.Ep.NextEpisode = NextEpisode{
1104 Number: nextEp,
1105 Links: result.Links,
1106 ProviderName: result.ProviderName,
1107 ProviderId: result.ProviderID,
1108 Mode: result.Mode,
1109 }
1110 Log(fmt.Sprintf("MPV playlist: prefetched episode %d", nextEp))
1111}
1112
1113func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int {
1114 c.mu.Lock()
1115 defer c.mu.Unlock()
1116 return c.episodeIndexLocked(ep, mode)
1117}
1118
1119func (c *MPVPlaylistController) episodeIndexLocked(ep int, mode string) int {
1120 mode = normalizeTranslationType(mode)
1121 for i, s := range c.slots {
1122 if s.Episode == ep && normalizeTranslationType(s.Mode) == mode {
1123 return i
1124 }
1125 }
1126 // Fallback: first slot with that episode number.
1127 for i, s := range c.slots {
1128 if s.Episode == ep {
1129 return i
1130 }
1131 }
1132 if ep > 0 {
1133 return ep - 1
1134 }
1135 return 0
1136}
1137
1138func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
1139 // Caller (handlePlaylistJump) already called beginMPVPlaylistSwitch.
1140 // We clear it only after the new stream is stably playing (or on error paths
1141 // that return before that — handlePlaylistJump clears on failure).
1142 c.suppress.Store(true)
1143 defer c.suppress.Store(false)
1144
1145 mode := normalizeTranslationType(slot.Mode)
1146 if mode == "" {
1147 mode = c.preferredMode
1148 }
1149
1150 cfg := *c.config
1151 cfg.SubOrDub = mode
1152
1153 anime := c.anime
1154 prevEp := anime.Ep.Number
1155 targetEp := slot.Episode
1156
1157 // Clear ALL previous-episode playback state before resolve/load so the main
1158 // loop cannot seek/resume the old episode into the new stream.
1159 anime.Ep.Resume = false
1160 anime.Ep.Player.PlaybackTime = 0
1161 anime.Ep.Duration = 0
1162 anime.Ep.IsCompleted = false
1163 anime.Ep.Number = targetEp
1164 anime.Ep.Links = nil
1165 anime.Ep.NextEpisode = NextEpisode{}
1166 anime.Ep.StreamReferrer = ""
1167 anime.Ep.SubtitleURL = ""
1168 anime.Ep.SkipTimes = SkipTimes{}
1169
1170 Log(fmt.Sprintf("MPV playlist: resolving stream for episode %d (%s) [was %d]", targetEp, mode, prevEp))
1171
1172 // Snapshot current path so we can detect a real media change after loadfile.
1173 oldPath := mpvStringProperty(c.socket, "path")
1174
1175 // Preferred mode only — no nested DynamicSelect prompts from this goroutine.
1176 result, err := ResolveEpisodeURL(cfg, anime, targetEp)
1177 if err != nil || len(result.Links) == 0 {
1178 anime.Ep.Number = prevEp
1179 if err == nil {
1180 err = fmt.Errorf("no streams for episode %d", targetEp)
1181 }
1182 return err
1183 }
1184
1185 anime.Ep.Links = result.Links
1186 applyStreamPlaybackHints(anime, result.Links, result.LinkHints)
1187 link := PrioritizeLink(result.Links)
1188 if link == "" {
1189 anime.Ep.Number = prevEp
1190 return fmt.Errorf("empty stream link for episode %d", targetEp)
1191 }
1192
1193 // Refuse to "switch" to the exact same URL — that reloads the same episode.
1194 if oldPath != "" && (link == oldPath || strings.Contains(oldPath, link) || strings.Contains(link, oldPath)) {
1195 Log(fmt.Sprintf("MPV playlist: WARNING resolved link equals current path for ep %d; still forcing reload", targetEp))
1196 }
1197
1198 title := fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), targetEp)
1199 if mode != "" && mode != c.preferredMode {
1200 title += " (" + strings.ToUpper(mode) + ")"
1201 }
1202 Log(fmt.Sprintf("MPV playlist: loading ep %d in running mpv (was path %s): %s",
1203 targetEp, truncateForLog(oldPath, 60), truncateForLog(link, 80)))
1204
1205 anime.Ep.Player.SocketPath = c.socket
1206 if err := loadEpisodeInRunningMPV(c.socket, link, title, anime); err != nil {
1207 anime.Ep.Number = prevEp
1208 return err
1209 }
1210
1211 // Wait until path actually changes away from the old media (not just time-pos).
1212 // WaitForMPVPlaybackStart alone is wrong — old episode still has time-pos.
1213 if !waitForMPVMediaChange(c.socket, oldPath, link, 30*time.Second) {
1214 anime.Ep.Number = prevEp
1215 return fmt.Errorf("episode %d did not become the active media (still on previous file?)", targetEp)
1216 }
1217 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "time-pos", 0})
1218 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", false})
1219 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", title})
1220 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", title})
1221
1222 anime.Ep.Number = targetEp
1223 // Keep Started=true so the main monitor stays in "watching" mode continuously.
1224 anime.Ep.Started = true
1225 anime.Ep.IsCompleted = false
1226 anime.Ep.Player.PlaybackTime = 0
1227 anime.Ep.Duration = 0
1228 anime.Ep.SkipTimes = SkipTimes{}
1229 anime.Ep.Resume = false
1230 // Apply provider identity from the resolve result when present.
1231 if result.ProviderName != "" {
1232 anime.ProviderName = result.ProviderName
1233 }
1234 if result.ProviderID != "" {
1235 anime.ProviderId = result.ProviderID
1236 }
1237
1238 // Re-read duration for the new file (one-shot background).
1239 go func(socket string) {
1240 deadline := time.Now().Add(15 * time.Second)
1241 for time.Now().Before(deadline) {
1242 if c.closed() {
1243 return
1244 }
1245 durationPos, err := MPVSendCommand(socket, []interface{}{"get_property", "duration"})
1246 if err == nil && durationPos != nil {
1247 if duration, ok := durationPos.(float64); ok && duration > 1 {
1248 c.anime.Ep.Duration = int(duration + 0.5)
1249 Log(fmt.Sprintf("MPV playlist: episode %d duration %ds", targetEp, c.anime.Ep.Duration))
1250 return
1251 }
1252 }
1253 time.Sleep(300 * time.Millisecond)
1254 }
1255 }(c.socket)
1256
1257 c.mu.Lock()
1258 c.currentPlaying = targetEp
1259 c.currentMode = mode
1260 alreadyAlt := normalizeTranslationType(slot.Mode) == c.alternateMode
1261 // After loadfile replace the playlist is a single entry at index 0.
1262 c.lastPos = 0
1263 c.slots = []playlistSlot{{Episode: targetEp, Mode: mode, Label: title}}
1264 c.hasAlternate = false
1265 c.mu.Unlock()
1266
1267 // Stream is live — safe for the main loop again.
1268 endMPVPlaylistSwitch()
1269
1270 // Refresh skip times in background (non-blocking for playback).
1271 go func(ep int) {
1272 if c.anime.MalId > 0 {
1273 if err := GetAndParseAniSkipData(c.anime.MalId, ep, 0, c.anime); err != nil {
1274 Log(fmt.Sprintf("AniSkip for ep %d: %v", ep, err))
1275 }
1276 if c.anime.Ep.SkipTimes.Op.Start != c.anime.Ep.SkipTimes.Op.End ||
1277 c.anime.Ep.SkipTimes.Ed.Start != c.anime.Ep.SkipTimes.Ed.End {
1278 _ = SendSkipTimesToMPV(c.anime)
1279 }
1280 }
1281 }(targetEp)
1282
1283 // Re-probe alternate for the new episode only after placeholders are rebuilt.
1284 go func() {
1285 time.Sleep(mpvPlaylistIdleDelay + time.Second)
1286 if c.closed() || alreadyAlt {
1287 return
1288 }
1289 c.hasAlternate = false
1290 c.probeAndAttachAlternateAudio()
1291 }()
1292
1293 CurdOut(fmt.Sprintf("Playing episode %d (%s)", targetEp, mode))
1294 return nil
1295}
1296
1297// loadEpisodeInRunningMPV replaces the currently playing file with link.
1298// Note: mpv's loadfile-replace clears other playlist entries (we rebuild after).
1299func loadEpisodeInRunningMPV(socket, link, title string, anime *Anime) error {
1300 if socket == "" || link == "" {
1301 return fmt.Errorf("missing socket or link")
1302 }
1303 // Referrer / headers for the new stream.
1304 referrer := ""
1305 if anime != nil {
1306 referrer = strings.TrimSpace(anime.Ep.StreamReferrer)
1307 if referrer == "" {
1308 referrer = streamReferrerForLink(link, CurrentAnimeProviderName(anime))
1309 }
1310 }
1311 if referrer != "" {
1312 _, _ = MPVSendCommand(socket, []interface{}{"set_property", "referrer", referrer})
1313 }
1314
1315 opts := "force-media-title=" + escapeMPVOptionValue(title)
1316 // Explicit replace so we never append a second "current" by accident.
1317 if _, err := MPVSendCommand(socket, []interface{}{"loadfile", link, "replace", 0, opts}); err != nil {
1318 // Fallback without options (older mpv / option parse issues).
1319 if _, err2 := MPVSendCommand(socket, []interface{}{"loadfile", link, "replace"}); err2 != nil {
1320 return fmt.Errorf("loadfile: %w", err2)
1321 }
1322 _, _ = MPVSendCommand(socket, []interface{}{"set_property", "force-media-title", title})
1323 }
1324 // Stop at start of the new file; caller unpauses after path confirms.
1325 _, _ = MPVSendCommand(socket, []interface{}{"set_property", "pause", true})
1326 _, _ = MPVSendCommand(socket, []interface{}{"set_property", "time-pos", 0})
1327
1328 if anime != nil {
1329 sub := strings.TrimSpace(anime.Ep.SubtitleURL)
1330 if sub != "" {
1331 go func() {
1332 _ = waitForMPVFileReady(socket, link, 12*time.Second)
1333 _, _ = MPVSendCommand(socket, []interface{}{"sub-add", sub, "select"})
1334 }()
1335 }
1336 }
1337 return nil
1338}
1339
1340func mpvStringProperty(socket, name string) string {
1341 v, err := MPVSendCommand(socket, []interface{}{"get_property", name})
1342 if err != nil || v == nil {
1343 return ""
1344 }
1345 if s, ok := v.(string); ok {
1346 return s
1347 }
1348 return fmt.Sprint(v)
1349}
1350
1351// waitForMPVMediaChange waits until MPV's path is no longer oldPath and looks like
1352// the new link (or at least not the previous file / lavfi placeholder).
1353func waitForMPVMediaChange(socket, oldPath, newLink string, timeout time.Duration) bool {
1354 deadline := time.Now().Add(timeout)
1355 newKey := mediaURLKey(newLink)
1356 oldKey := mediaURLKey(oldPath)
1357 Log(fmt.Sprintf("MPV playlist: waiting for media change oldKey=%q newKey=%q", truncateForLog(oldKey, 40), truncateForLog(newKey, 40)))
1358
1359 for time.Now().Before(deadline) {
1360 path := mpvStringProperty(socket, "path")
1361 if path == "" {
1362 time.Sleep(150 * time.Millisecond)
1363 continue
1364 }
1365 // Still on placeholder or previous file.
1366 if strings.HasPrefix(path, "av://") {
1367 time.Sleep(150 * time.Millisecond)
1368 continue
1369 }
1370 if oldPath != "" && path == oldPath {
1371 time.Sleep(150 * time.Millisecond)
1372 continue
1373 }
1374 if oldKey != "" && mediaURLKey(path) == oldKey && newKey != oldKey {
1375 time.Sleep(150 * time.Millisecond)
1376 continue
1377 }
1378 // Prefer a positive match on the new URL when possible.
1379 if newKey != "" && (strings.Contains(path, newKey) || mediaURLKey(path) == newKey || strings.Contains(newLink, path) || strings.Contains(path, newLink)) {
1380 // Need a real time-pos too.
1381 if tpos, err := MPVSendCommand(socket, []interface{}{"get_property", "time-pos"}); err == nil && tpos != nil {
1382 Log(fmt.Sprintf("MPV playlist: media changed to %s", truncateForLog(path, 80)))
1383 return true
1384 }
1385 }
1386 // Path changed away from old and is not lavfi — accept.
1387 if oldPath != "" && path != oldPath && !strings.HasPrefix(path, "av://") {
1388 if tpos, err := MPVSendCommand(socket, []interface{}{"get_property", "time-pos"}); err == nil && tpos != nil {
1389 Log(fmt.Sprintf("MPV playlist: media path changed to %s", truncateForLog(path, 80)))
1390 return true
1391 }
1392 }
1393 time.Sleep(150 * time.Millisecond)
1394 }
1395 Log(fmt.Sprintf("MPV playlist: media change timed out; path now %q", truncateForLog(mpvStringProperty(socket, "path"), 80)))
1396 return false
1397}
1398
1399// mediaURLKey extracts a stable identity from a stream URL (host + path without query).
1400func mediaURLKey(raw string) string {
1401 raw = strings.TrimSpace(raw)
1402 if raw == "" {
1403 return ""
1404 }
1405 // Strip query/fragment so expiring tokens don't break comparison.
1406 if i := strings.IndexAny(raw, "?#"); i >= 0 {
1407 raw = raw[:i]
1408 }
1409 return raw
1410}
1411
1412func escapeMPVOptionValue(s string) string {
1413 // loadfile options: quote and escape embedded quotes/backslashes.
1414 s = strings.ReplaceAll(s, `\`, `\\`)
1415 s = strings.ReplaceAll(s, `"`, `\"`)
1416 s = strings.ReplaceAll(s, `,`, `\,`)
1417 s = strings.ReplaceAll(s, `=`, `\=`)
1418 return `"` + s + `"`
1419}
1420
1421func truncateForLog(s string, n int) string {
1422 if len(s) <= n {
1423 return s
1424 }
1425 return s[:n] + "…"
1426}
1427
1428// rebuildPlaylistAroundCurrent re-adds titled placeholders after loadfile replace
1429// wiped the playlist. Current playing entry stays index 0 until we insert before it.
1430func (c *MPVPlaylistController) rebuildPlaylistAroundCurrent() error {
1431 if c.closed() || c.anime == nil {
1432 return nil
1433 }
1434 episodes := c.episodeNums
1435 if len(episodes) == 0 {
1436 episodes = c.fetchEpisodeNumbers()
1437 c.episodeNums = episodes
1438 }
1439 if len(episodes) == 0 {
1440 return fmt.Errorf("no episodes for rebuild")
1441 }
1442
1443 currentEp := c.currentPlaying
1444 if currentEp < 1 {
1445 currentEp = c.anime.Ep.Number
1446 }
1447 mode := c.currentMode
1448 if mode == "" {
1449 mode = c.preferredMode
1450 }
1451
1452 c.suppress.Store(true)
1453 defer c.suppress.Store(false)
1454 beginMPVPlaylistSwitch()
1455 defer endMPVPlaylistSwitch()
1456
1457 var before, after []playlistSlot
1458 for _, ep := range episodes {
1459 if ep < currentEp {
1460 before = append(before, playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)})
1461 } else if ep > currentEp {
1462 after = append(after, playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)})
1463 }
1464 }
1465
1466 // Title the live entry (index 0 after replace).
1467 curLabel := c.episodeLabel(currentEp, mode)
1468 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", curLabel})
1469 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", curLabel})
1470
1471 if len(after) > 0 {
1472 if err := c.loadTitledPlaceholders(after, false); err != nil {
1473 Log(fmt.Sprintf("rebuild append future: %v", err))
1474 }
1475 }
1476 if len(before) > 0 {
1477 if err := c.loadTitledPlaceholders(before, true); err != nil {
1478 Log(fmt.Sprintf("rebuild insert previous: %v", err))
1479 }
1480 }
1481
1482 slots := make([]playlistSlot, 0, len(before)+1+len(after))
1483 slots = append(slots, before...)
1484 slots = append(slots, playlistSlot{Episode: currentEp, Mode: mode, Label: curLabel})
1485 slots = append(slots, after...)
1486
1487 c.mu.Lock()
1488 c.slots = slots
1489 c.lastPos = len(before)
1490 c.mu.Unlock()
1491
1492 Log(fmt.Sprintf("MPV playlist rebuilt around ep %d (%d entries)", currentEp, len(slots)))
1493 return nil
1494}
1495