internal/mpv_playlist.go

1527 lines · 49540 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	// Tag the row when its translation mode differs from what is currently
 289	// playing, so the alternate track is always obvious (in dub, a plain sub row
 290	// still shows "(SUB)"; in sub, the dub row shows "(DUB)").
 291	if c.currentMode != "" && mode != c.currentMode {
 292		base += " (" + strings.ToUpper(mode) + ")"
 293	}
 294	if ep == c.currentPlaying && mode == c.currentMode {
 295		base += "  ◀"
 296	}
 297	return base
 298}
 299
 300func (c *MPVPlaylistController) buildEpisodePlaylist() error {
 301	episodes := c.fetchEpisodeNumbers()
 302	if len(episodes) == 0 {
 303		return fmt.Errorf("no episode list from provider")
 304	}
 305	c.episodeNums = episodes
 306	if max := episodes[len(episodes)-1]; max > c.anime.TotalEpisodes {
 307		c.anime.TotalEpisodes = max
 308	}
 309
 310	currentEp := c.anime.Ep.Number
 311	if currentEp < 1 {
 312		currentEp = episodes[0]
 313	}
 314	// Ensure current episode is in the list (AniList progress may point at an ep
 315	// the provider still lists under a different numbering — keep a slot).
 316	if !containsInt(episodes, currentEp) {
 317		episodes = append(episodes, currentEp)
 318		sort.Ints(episodes)
 319		c.episodeNums = episodes
 320	}
 321
 322	c.suppress.Store(true)
 323	defer c.suppress.Store(false)
 324
 325	// Prefer title display in the playlist OSD when mpv supports it.
 326	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "osd-playlist-entry", "title"})
 327
 328	// Title the currently playing item (force-media-title sticks for the active entry).
 329	curLabel := c.episodeLabel(currentEp, c.currentMode)
 330	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", curLabel})
 331	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", curLabel})
 332
 333	var before, after []playlistSlot
 334	for _, ep := range episodes {
 335		if ep < currentEp {
 336			before = append(before, playlistSlot{
 337				Episode: ep,
 338				Mode:    c.preferredMode,
 339				Label:   c.episodeLabel(ep, c.preferredMode),
 340			})
 341		} else if ep > currentEp {
 342			after = append(after, playlistSlot{
 343				Episode: ep,
 344				Mode:    c.preferredMode,
 345				Label:   c.episodeLabel(ep, c.preferredMode),
 346			})
 347		}
 348	}
 349
 350	// Future episodes: one M3U loadlist append (titled placeholders, no stream probes).
 351	if len(after) > 0 {
 352		if err := c.loadTitledPlaceholders(after, false); err != nil {
 353			Log(fmt.Sprintf("playlist append future: %v", err))
 354		}
 355	}
 356
 357	// Previous episodes: append via M3U then playlist-move to the front.
 358	if len(before) > 0 {
 359		if err := c.loadTitledPlaceholders(before, true); err != nil {
 360			Log(fmt.Sprintf("playlist insert previous: %v", err))
 361		}
 362	}
 363
 364	// Rebuild slot map: before + current + after (preferred mode).
 365	slots := make([]playlistSlot, 0, len(episodes))
 366	slots = append(slots, before...)
 367	slots = append(slots, playlistSlot{
 368		Episode: currentEp,
 369		Mode:    c.preferredMode,
 370		Label:   curLabel,
 371	})
 372	slots = append(slots, after...)
 373
 374	c.mu.Lock()
 375	c.slots = slots
 376	c.currentPlaying = currentEp
 377	c.mu.Unlock()
 378
 379	wantPos := len(before)
 380	c.lastPos = wantPos
 381	if pos, err := c.playlistPos(); err == nil {
 382		c.lastPos = pos
 383		if pos != wantPos {
 384			Log(fmt.Sprintf("MPV playlist-pos=%d want=%d (leaving as-is to avoid stutter)", pos, wantPos))
 385		}
 386	}
 387	return nil
 388}
 389
 390// loadTitledPlaceholders writes a temp M3U with #EXTINF titles and loadlists it.
 391// If moveToFront is true, entries are moved to the start of the playlist (preserving order).
 392func (c *MPVPlaylistController) loadTitledPlaceholders(slots []playlistSlot, moveToFront bool) error {
 393	if len(slots) == 0 {
 394		return nil
 395	}
 396	path, err := c.writePlaceholderM3U(slots)
 397	if err != nil {
 398		return err
 399	}
 400	defer func() { _ = os.Remove(path) }()
 401
 402	beforeCount, _ := c.playlistCount()
 403
 404	if _, err := MPVSendCommand(c.socket, []interface{}{"loadlist", path, "append"}); err != nil {
 405		return fmt.Errorf("loadlist: %w", err)
 406	}
 407
 408	afterCount, err := c.playlistCount()
 409	if err != nil {
 410		return err
 411	}
 412	added := afterCount - beforeCount
 413	if added <= 0 {
 414		return fmt.Errorf("loadlist added 0 entries")
 415	}
 416
 417	if !moveToFront {
 418		return nil
 419	}
 420
 421	// Move the newly appended block to the front, preserving relative order.
 422	// Start: [current, ..., NEW0, NEW1, ...] → [NEW0, NEW1, ..., current, ...]
 423	for i := 0; i < added; i++ {
 424		from := beforeCount + i // shifts as we insert earlier
 425		to := i
 426		if _, err := MPVSendCommand(c.socket, []interface{}{"playlist-move", from, to}); err != nil {
 427			Log(fmt.Sprintf("playlist-move %d→%d: %v", from, to, err))
 428		}
 429	}
 430	return nil
 431}
 432
 433func (c *MPVPlaylistController) writePlaceholderM3U(slots []playlistSlot) (string, error) {
 434	dir := os.TempDir()
 435	if c.config != nil && strings.TrimSpace(c.config.StoragePath) != "" {
 436		dir = os.ExpandEnv(c.config.StoragePath)
 437		_ = os.MkdirAll(dir, 0o755)
 438	}
 439	f, err := os.CreateTemp(dir, "curd-playlist-*.m3u")
 440	if err != nil {
 441		return "", err
 442	}
 443	path := f.Name()
 444
 445	var b strings.Builder
 446	b.WriteString("#EXTM3U\n")
 447	for _, s := range slots {
 448		title := sanitizeM3UTitle(s.Label)
 449		b.WriteString("#EXTINF:-1,")
 450		b.WriteString(title)
 451		b.WriteByte('\n')
 452		// Unique URL per episode so mpv actually changes playlist-pos on select.
 453		b.WriteString(placeholderURL(s.Episode))
 454		b.WriteByte('\n')
 455	}
 456	if _, err := f.WriteString(b.String()); err != nil {
 457		f.Close()
 458		_ = os.Remove(path)
 459		return "", err
 460	}
 461	if err := f.Close(); err != nil {
 462		_ = os.Remove(path)
 463		return "", err
 464	}
 465	return path, nil
 466}
 467
 468// sanitizeM3UTitle keeps #EXTINF titles single-line and free of control chars.
 469func sanitizeM3UTitle(title string) string {
 470	title = strings.ReplaceAll(title, "\r", " ")
 471	title = strings.ReplaceAll(title, "\n", " ")
 472	title = strings.TrimSpace(title)
 473	if title == "" {
 474		return "Episode"
 475	}
 476	return title
 477}
 478
 479func containsInt(nums []int, want int) bool {
 480	for _, n := range nums {
 481		if n == want {
 482			return true
 483		}
 484	}
 485	return false
 486}
 487
 488func (c *MPVPlaylistController) playlistPos() (int, error) {
 489	v, err := MPVSendCommand(c.socket, []interface{}{"get_property", "playlist-pos"})
 490	if err != nil {
 491		return -1, err
 492	}
 493	return int(mpvNumber(v) + 0.5), nil
 494}
 495
 496func (c *MPVPlaylistController) playlistCount() (int, error) {
 497	v, err := MPVSendCommand(c.socket, []interface{}{"get_property", "playlist-count"})
 498	if err != nil {
 499		return 0, err
 500	}
 501	return int(mpvNumber(v) + 0.5), nil
 502}
 503
 504// probeAndAttachAlternateAudio checks whether the opposite sub/dub mode has a
 505// stream for the *current* episode only (one resolve — not every episode).
 506func (c *MPVPlaylistController) probeAndAttachAlternateAudio() {
 507	if c.closed() || c.anime == nil {
 508		return
 509	}
 510	alt := c.alternateMode
 511	cfg := *c.config
 512	cfg.SubOrDub = alt
 513
 514	// Background resolve — does not touch MPV until we know a stream exists.
 515	result, err := ResolveEpisodeURL(cfg, c.anime, c.currentPlaying)
 516	if err != nil || len(result.Links) == 0 {
 517		Log(fmt.Sprintf("MPV playlist: no %s stream for ep %d (%v)", alt, c.currentPlaying, err))
 518		c.hasAlternate = false
 519		return
 520	}
 521	c.hasAlternate = true
 522
 523	c.suppress.Store(true)
 524	defer c.suppress.Store(false)
 525
 526	c.mu.Lock()
 527	curIdx := c.episodeIndexLocked(c.currentPlaying, c.currentMode)
 528	if curIdx < 0 {
 529		curIdx = 0
 530	}
 531	label := c.episodeLabel(c.currentPlaying, alt)
 532	insertAt := curIdx + 1
 533	c.mu.Unlock()
 534
 535	slot := playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label}
 536	if err := c.insertTitledPlaceholderAt(insertAt, slot); err != nil {
 537		Log(fmt.Sprintf("MPV playlist: failed to add %s entry: %v", alt, err))
 538		return
 539	}
 540
 541	c.mu.Lock()
 542	if insertAt >= len(c.slots) {
 543		c.slots = append(c.slots, slot)
 544	} else {
 545		c.slots = append(c.slots[:insertAt], append([]playlistSlot{slot}, c.slots[insertAt:]...)...)
 546	}
 547	c.mu.Unlock()
 548	Log(fmt.Sprintf("MPV playlist: added %s option for ep %d", alt, c.currentPlaying))
 549}
 550
 551// insertTitledPlaceholderAt appends a single titled M3U entry then moves it to index.
 552func (c *MPVPlaylistController) insertTitledPlaceholderAt(index int, slot playlistSlot) error {
 553	countBefore, _ := c.playlistCount()
 554	if err := c.loadTitledPlaceholders([]playlistSlot{slot}, false); err != nil {
 555		return err
 556	}
 557	countAfter, err := c.playlistCount()
 558	if err != nil {
 559		return err
 560	}
 561	if countAfter <= countBefore {
 562		return fmt.Errorf("placeholder not added")
 563	}
 564	from := countAfter - 1
 565	if from == index {
 566		return nil
 567	}
 568	if index < 0 {
 569		index = 0
 570	}
 571	if index > from {
 572		index = from
 573	}
 574	_, err = MPVSendCommand(c.socket, []interface{}{"playlist-move", from, index})
 575	return err
 576}
 577
 578func (c *MPVPlaylistController) watchPlaylistSelection() {
 579	// Detect selection primarily via path: when the user picks another playlist
 580	// row, mpv loads our unique lavfi placeholder. Polling playlist-pos alone
 581	// missed jumps (logs showed time-pos drop with no "pos changed").
 582	Log("MPV playlist: watching path + playlist-pos for episode picks")
 583	poll := 150 * time.Millisecond
 584	// Sample tracking independent of the (possibly stale) cached lastPos so we
 585	// never silently miss an mpv path/pos transition.
 586	var samplePath string
 587	var samplePos int
 588	haveSample := false
 589	lastHeartbeat := time.Time{}
 590
 591	for {
 592		if c.closed() {
 593			return
 594		}
 595		if !IsMPVRunning(c.socket) {
 596			// A transient IPC blip (mpv can briefly refuse the unix socket while
 597			// alive) must NOT kill the only episode-selection watcher. Retry on
 598			// the next tick; true termination is signalled via the done channel.
 599			time.Sleep(poll)
 600			continue
 601		}
 602		if c.suppress.Load() || MPVPlaylistIsSwitching() {
 603			time.Sleep(poll)
 604			continue
 605		}
 606
 607		path := mpvStringProperty(c.socket, "path")
 608		pos, posErr := c.playlistPos()
 609
 610		// Heartbeat ~once a second: captures mpv's real reported state over time
 611		// even when nothing changes, so we can prove what mpv does on a click.
 612		if time.Since(lastHeartbeat) >= time.Second {
 613			lastHeartbeat = time.Now()
 614			count, _ := c.playlistCount()
 615			Log(fmt.Sprintf("MPV playlist: HB pos=%d count=%d path=%s", pos, count, truncateForLog(path, 45)))
 616		}
 617
 618		if !haveSample || path != samplePath || (posErr == nil && pos != samplePos) {
 619			samplePath = path
 620			samplePos = pos
 621			haveSample = true
 622			if isPlaceholderPath(path) {
 623				if ep, ok := parseEpisodeFromPlaceholder(path); ok {
 624					Log(fmt.Sprintf("MPV playlist: SAMPLE placeholder ep=%d path=%s", ep, truncateForLog(path, 60)))
 625				} else {
 626					Log(fmt.Sprintf("MPV playlist: SAMPLE placeholder path=%s", truncateForLog(path, 60)))
 627				}
 628			} else if posErr == nil {
 629				Log(fmt.Sprintf("MPV playlist: SAMPLE pos=%d path=%s", pos, truncateForLog(path, 50)))
 630			}
 631		}
 632
 633		// --- Primary: path became a placeholder (a row was picked) ---
 634		// Resolve the episode from the frozen index + row title ONLY. The lavfi
 635		// filename's WxH encoding is unreliable (decodes to random episodes like
 636		// 192/300) and must never drive which episode we load.
 637		if isPlaceholderPath(path) {
 638			// Debounce: confirm the placeholder is still the active path (scrub).
 639			time.Sleep(80 * time.Millisecond)
 640			if !isPlaceholderPath(mpvStringProperty(c.socket, "path")) {
 641				continue
 642			}
 643
 644			targetPos := pos
 645			if posErr != nil || pos < 0 {
 646				targetPos, _ = c.playlistPos()
 647			}
 648			slot, slotErr := c.resolveSlotAt(targetPos)
 649			if slotErr != nil {
 650				Log(fmt.Sprintf("MPV playlist: placeholder pick unresolvable at pos %d: %v", targetPos, slotErr))
 651				c.lastPos = targetPos
 652				continue
 653			}
 654
 655			c.mu.Lock()
 656			curEp := c.currentPlaying
 657			c.mu.Unlock()
 658
 659			Log(fmt.Sprintf("MPV playlist: DETECT placeholder row pos=%d → ep %d (%s) (was ep=%d)",
 660				targetPos, slot.Episode, slot.Mode, curEp))
 661
 662			beginMPVPlaylistSwitch()
 663			_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
 664			_, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000})
 665
 666			c.lastPos = targetPos
 667			c.handlePlaylistJumpSlot(slot, curEp)
 668			continue
 669		}
 670
 671		// --- Secondary: playlist-pos moved ---
 672		// IMPORTANT: freeze the *first* new index and resolve that entry immediately.
 673		// Re-reading pos after a sleep was overwriting 38→39 (current) so we always
 674		// reloaded ep 40 when the user clicked 39 (see debug: DETECT 39→38 then
 675		// "pos 39 title Episode 40").
 676		if posErr == nil && pos >= 0 && pos != c.lastPos {
 677			targetPos := pos
 678			fromPos := c.lastPos
 679			Log(fmt.Sprintf("MPV playlist: DETECT pos %d → %d (path=%s)", fromPos, targetPos, truncateForLog(path, 50)))
 680
 681			// Resolve the entry the user landed on *now*, before mpv can snap back.
 682			slot, slotErr := c.resolveSlotAt(targetPos)
 683			if slotErr != nil {
 684				Log(fmt.Sprintf("MPV playlist: resolve pos %d failed: %v", targetPos, slotErr))
 685				// Still try path / slots fallback inside handlePlaylistJump.
 686				beginMPVPlaylistSwitch()
 687				_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
 688				c.lastPos = targetPos
 689				c.handlePlaylistJump(targetPos)
 690					continue
 691			}
 692
 693			c.mu.Lock()
 694			curEp := c.currentPlaying
 695			c.mu.Unlock()
 696
 697			Log(fmt.Sprintf("MPV playlist: frozen target pos=%d → ep %d (cur ep %d)", targetPos, slot.Episode, curEp))
 698
 699			// If resolve says same episode as current and path is still the live stream,
 700			// this was a false pos blip — ignore.
 701			if slot.Episode == curEp && !isPlaceholderPath(path) {
 702				Log(fmt.Sprintf("MPV playlist: ignore pos blip %d→%d (still ep %d, live path)", fromPos, targetPos, curEp))
 703				c.lastPos = targetPos
 704				// If pos really moved within same ep (dub row), still switch mode.
 705				if normalizeTranslationType(slot.Mode) != normalizeTranslationType(c.currentMode) {
 706					beginMPVPlaylistSwitch()
 707					_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
 708					c.handlePlaylistJumpSlot(slot, curEp)
 709						}
 710				time.Sleep(poll)
 711				continue
 712			}
 713
 714			beginMPVPlaylistSwitch()
 715			_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
 716			_, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000})
 717			c.lastPos = targetPos
 718			c.handlePlaylistJumpSlot(slot, curEp)
 719			continue
 720		}
 721
 722		if path != "" {
 723
 724		}
 725		time.Sleep(poll)
 726	}
 727}
 728
 729func isPlaceholderPath(path string) bool {
 730	return strings.HasPrefix(path, "av://lavfi:") || strings.Contains(path, "lavfi:color=")
 731}
 732
 733// handlePlaylistJumpSlot switches to a known target slot (from path or pos detection).
 734func (c *MPVPlaylistController) handlePlaylistJumpSlot(slot playlistSlot, curEp int) {
 735	curMode := c.currentMode
 736	if curMode == "" {
 737		curMode = c.preferredMode
 738	}
 739	beginMPVPlaylistSwitch()
 740	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
 741
 742	leaveAction := playlistLeaveNone
 743	if slot.Episode != curEp {
 744		pct := PercentageWatched(c.anime.Ep.Player.PlaybackTime, c.anime.Ep.Duration)
 745		threshold := 85
 746		if c.config != nil && c.config.PercentageToMarkComplete > 0 {
 747			threshold = c.config.PercentageToMarkComplete
 748		}
 749		// Never interrupt playback with a terminal menu while the user is in
 750		// (possibly fullscreen) MPV. Resolve the remote action silently: backward
 751		// jumps never regress upstream progress, +1 follows the standard "next"
 752		// auto-mark behavior, other forward skips leave progress untouched.
 753		leaveAction = resolvePlaylistLeaveDefault(curEp, slot.Episode, pct, threshold)
 754		Log(fmt.Sprintf("MPV playlist: SWITCH %d → %d (%s) leave=%s (silent, no session menu)",
 755			curEp, slot.Episode, slot.Mode, leaveAction))
 756	} else {
 757		leaveAction = playlistLeaveNone
 758		Log(fmt.Sprintf("MPV playlist: reloading real stream for ep %d (was on placeholder)", curEp))
 759	}
 760
 761	_, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 8000})
 762	Log(fmt.Sprintf("MPV playlist: SWITCH ep %d → %d (%s) leave=%s", curEp, slot.Episode, slot.Mode, leaveAction))
 763	CurdOut(fmt.Sprintf("Loading episode %d…", slot.Episode))
 764
 765	leftEp := curEp
 766	if err := c.playSlot(slot); err != nil {
 767		Log(fmt.Sprintf("MPV playlist: failed to play ep %d: %v", slot.Episode, err))
 768		CurdOut(fmt.Sprintf("Could not play episode %d: %v", slot.Episode, err))
 769		if err2 := c.playSlot(playlistSlot{Episode: curEp, Mode: curMode, Label: c.episodeLabel(curEp, curMode)}); err2 != nil {
 770			Log(fmt.Sprintf("MPV playlist: recovery play failed: %v", err2))
 771			endMPVPlaylistSwitch()
 772		}
 773		return
 774	}
 775
 776	c.finalizePlaylistEpisodeChange(leftEp, slot.Episode, slot.Mode, leaveAction)
 777
 778	go func() {
 779		time.Sleep(mpvPlaylistIdleDelay)
 780		if c.closed() {
 781			return
 782		}
 783		if err := c.rebuildPlaylistAroundCurrent(); err != nil {
 784			Log(fmt.Sprintf("MPV playlist rebuild after switch: %v", err))
 785		}
 786	}()
 787}
 788
 789// playlistLeaveAction is the user's choice when leaving an episode via playlist.
 790type playlistLeaveAction string
 791
 792const (
 793	playlistLeaveNone     playlistLeaveAction = "none"     // play target; last-played only (no remote)
 794	playlistLeaveMarkLeft playlistLeaveAction = "mark"     // mark left episode watched remotely
 795	playlistLeaveSetWatch playlistLeaveAction = "setwatch" // set remote progress to toEp-1
 796	playlistLeaveCancel   playlistLeaveAction = "cancel"   // stay on current episode
 797)
 798
 799// promptPlaylistEpisodeLeave asks how to handle progress when changing episodes.
 800// Overridable in tests. +1 (next) is auto; other jumps prompt.
 801var promptPlaylistEpisodeLeave = defaultPromptPlaylistEpisodeLeave
 802
 803func defaultPromptPlaylistEpisodeLeave(fromEp, toEp int, percentageWatched float64, threshold int) (playlistLeaveAction, error) {
 804	// Same episode (mode toggle only) — nothing to ask.
 805	if toEp == fromEp {
 806		return playlistLeaveNone, nil
 807	}
 808
 809	nearlyDone := int(percentageWatched) >= threshold && percentageWatched > 0
 810	pctLabel := fmt.Sprintf("%.0f%%", percentageWatched)
 811	if percentageWatched <= 0 {
 812		pctLabel = "just started"
 813	}
 814
 815	// Sequential next episode (+1): no menu — same spirit as normal "next ep".
 816	if toEp == fromEp+1 {
 817		if nearlyDone {
 818			CurdOut(fmt.Sprintf("Next episode %d · marking %d watched (was %s)", toEp, fromEp, pctLabel))
 819			return playlistLeaveMarkLeft, nil
 820		}
 821		CurdOut(fmt.Sprintf("Next episode %d · last played updated", toEp))
 822		return playlistLeaveNone, nil
 823	}
 824
 825	// Non-linear jump — ask what to do with upstream progress.
 826	CurdOut(fmt.Sprintf("Jump: episode %d (%s) → episode %d", fromEp, pctLabel, toEp))
 827
 828	options := []SelectionOption{
 829		{Key: "none", Label: fmt.Sprintf("▶ Play episode %d only (don’t change AniList/MAL)", toEp)},
 830		{Key: "mark", Label: fmt.Sprintf("✓ Mark episode %d watched, then play %d", fromEp, toEp)},
 831		{Key: "setwatch", Label: fmt.Sprintf("📌 Set progress to %d (watching %d), play %d", maxInt(0, toEp-1), toEp, toEp)},
 832		{Key: "cancel", Label: fmt.Sprintf("↩ Cancel — stay on episode %d", fromEp)},
 833	}
 834	// If they were almost done, put "mark left" first.
 835	if nearlyDone {
 836		options = []SelectionOption{
 837			{Key: "mark", Label: fmt.Sprintf("✓ Mark episode %d watched (you were %s), play %d", fromEp, pctLabel, toEp)},
 838			{Key: "none", Label: fmt.Sprintf("▶ Play episode %d only (don’t change AniList/MAL)", toEp)},
 839			{Key: "setwatch", Label: fmt.Sprintf("📌 Set progress to %d (watching %d), play %d", maxInt(0, toEp-1), toEp, toEp)},
 840			{Key: "cancel", Label: fmt.Sprintf("↩ Cancel — stay on episode %d", fromEp)},
 841		}
 842	}
 843
 844	selected, err := promptSelectOrdered(options)
 845	if err != nil {
 846		// User already picked a row in MPV — never cancel back to the old episode.
 847		Log(fmt.Sprintf("playlist jump prompt failed (%v); playing %d without remote update", err, toEp))
 848		return playlistLeaveNone, nil
 849	}
 850	if selected.Key == "cancel" || SelectionMeansQuit(selected) || SelectionMeansBack(selected) {
 851		return playlistLeaveCancel, nil
 852	}
 853	switch selected.Key {
 854	case "mark":
 855		return playlistLeaveMarkLeft, nil
 856	case "setwatch":
 857		return playlistLeaveSetWatch, nil
 858	case "none", "switch":
 859		return playlistLeaveNone, nil
 860	default:
 861		return playlistLeaveNone, nil
 862	}
 863}
 864
 865func maxInt(a, b int) int {
 866	if a > b {
 867		return a
 868	}
 869	return b
 870}
 871
 872// resolvePlaylistLeaveDefault decides what to do with upstream progress after an
 873// MPV-playlist episode pick WITHOUT prompting mid-playback. Rules:
 874//   - same episode                       → nothing (mode toggle / reload)
 875//   - going backward (toEp < fromEp)     → nothing; never regress the tracker
 876//   - forward next (+1) nearly finished  → mark the left episode watched
 877//   - any other forward jump             → nothing (surfaced at session end)
 878func resolvePlaylistLeaveDefault(fromEp, toEp int, percentageWatched float64, threshold int) playlistLeaveAction {
 879	if toEp <= 0 || toEp == fromEp {
 880		return playlistLeaveNone
 881	}
 882	if toEp < fromEp {
 883		return playlistLeaveNone
 884	}
 885	if toEp == fromEp+1 {
 886		nearlyDone := int(percentageWatched) >= threshold && percentageWatched > 0
 887		if nearlyDone {
 888			return playlistLeaveMarkLeft
 889		}
 890	}
 891	return playlistLeaveNone
 892}
 893
 894// resolveSlotAt figures out which episode the user selected at playlist index pos.
 895// Order: placeholder filename encode → title → our slots map.
 896// Never re-query playlist-pos here — caller freezes the index.
 897func (c *MPVPlaylistController) resolveSlotAt(pos int) (playlistSlot, error) {
 898	filename, title := c.playlistEntryMeta(pos)
 899	Log(fmt.Sprintf("MPV playlist: resolve pos=%d filename=%q title=%q", pos, truncateForLog(filename, 60), title))
 900
 901	if title != "" {
 902		if ep, mode, ok := parsePlaylistEpisodeTitle(title, c.preferredMode); ok {
 903			Log(fmt.Sprintf("MPV playlist: pos %d title %q → ep %d (%s)", pos, title, ep, mode))
 904			return playlistSlot{Episode: ep, Mode: mode, Label: title}, nil
 905		}
 906		Log(fmt.Sprintf("MPV playlist: pos %d title %q (unparsed) file=%q", pos, title, truncateForLog(filename, 40)))
 907	}
 908
 909	c.mu.Lock()
 910	defer c.mu.Unlock()
 911	if pos < 0 || pos >= len(c.slots) {
 912		return playlistSlot{}, fmt.Errorf("playlist pos %d out of range (slots=%d)", pos, len(c.slots))
 913	}
 914	slot := c.slots[pos]
 915	Log(fmt.Sprintf("MPV playlist: pos %d slots fallback → ep %d", pos, slot.Episode))
 916	return slot, nil
 917}
 918
 919func (c *MPVPlaylistController) playlistEntryMeta(pos int) (filename, title string) {
 920	v, err := MPVSendCommand(c.socket, []interface{}{"get_property", "playlist"})
 921	if err != nil || v == nil {
 922		return "", ""
 923	}
 924	entries, ok := v.([]interface{})
 925	if !ok || pos < 0 || pos >= len(entries) {
 926		return "", ""
 927	}
 928	entry, ok := entries[pos].(map[string]interface{})
 929	if !ok {
 930		return "", ""
 931	}
 932	if f, ok := entry["filename"].(string); ok {
 933		filename = f
 934	}
 935	if t, ok := entry["title"].(string); ok {
 936		title = strings.TrimSpace(t)
 937	}
 938	return filename, title
 939}
 940
 941func parsePlaylistEpisodeTitle(title, preferredMode string) (ep int, mode string, ok bool) {
 942	mode = normalizeTranslationType(preferredMode)
 943	if mode == "" {
 944		mode = "sub"
 945	}
 946	upper := strings.ToUpper(title)
 947	if strings.Contains(upper, "(DUB)") || strings.Contains(upper, "· DUB") || strings.HasSuffix(strings.TrimSpace(upper), "DUB") {
 948		mode = "dub"
 949	} else if strings.Contains(upper, "(SUB)") {
 950		mode = "sub"
 951	}
 952	m := playlistEpisodeTitleRE.FindStringSubmatch(title)
 953	if len(m) < 2 {
 954		return 0, mode, false
 955	}
 956	n, err := strconv.Atoi(m[1])
 957	if err != nil || n <= 0 {
 958		return 0, mode, false
 959	}
 960	return n, mode, true
 961}
 962
 963func (c *MPVPlaylistController) handlePlaylistJump(pos int) {
 964	curEp := c.currentPlaying
 965
 966	slot, err := c.resolveSlotAt(pos)
 967	if err != nil {
 968		Log(fmt.Sprintf("MPV playlist: resolve slot at %d: %v", pos, err))
 969		// Path may still be a placeholder — try path-based parse of active media.
 970		if ep, ok := parseEpisodeFromPlaceholder(mpvStringProperty(c.socket, "path")); ok {
 971			slot = playlistSlot{Episode: ep, Mode: c.preferredMode, Label: c.episodeLabel(ep, c.preferredMode)}
 972			c.handlePlaylistJumpSlot(slot, curEp)
 973			return
 974		}
 975		_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", false})
 976		endMPVPlaylistSwitch()
 977		return
 978	}
 979
 980	c.handlePlaylistJumpSlot(slot, curEp)
 981}
 982
 983// finalizePlaylistEpisodeChange updates local history, last-played id, episode
 984// metadata, optional remote progress, and prefetches the next episode.
 985func (c *MPVPlaylistController) finalizePlaylistEpisodeChange(fromEp, toEp int, mode string, leave playlistLeaveAction) {
 986	if c.anime == nil || c.config == nil {
 987		return
 988	}
 989	anime := c.anime
 990	mode = normalizeTranslationType(mode)
 991	if mode == "" {
 992		mode = c.preferredMode
 993	}
 994
 995	// Keep config + controller mode in sync (sub/dub playlist entries).
 996	if mode != "" {
 997		c.config.SubOrDub = mode
 998		c.currentMode = mode
 999	}
1000
1001	// Clear stale next-episode prefetch from the previous number.
1002	anime.Ep.NextEpisode = NextEpisode{}
1003	anime.Ep.IsCompleted = false
1004	anime.Ep.LastWasSkipped = false
1005	anime.Ep.Resume = false
1006	anime.Ep.Number = toEp
1007	anime.Ep.Player.PlaybackTime = 0
1008	anime.Ep.IsFiller = IsEpisodeFiller(anime.FillerEpisodes, toEp)
1009
1010	// Episode titles / filler / recap from Jikan (non-fatal). Don't trust its duration.
1011	if anime.MalId > 0 {
1012		if err := GetEpisodeData(anime.MalId, toEp, anime); err != nil {
1013			Log(fmt.Sprintf("MPV playlist: GetEpisodeData ep %d: %v", toEp, err))
1014		}
1015		// Playback duration comes from MPV, not Jikan.
1016		anime.Ep.Duration = 0
1017	}
1018	// Filler list is authoritative when present.
1019	if len(anime.FillerEpisodes) > 0 {
1020		anime.Ep.IsFiller = IsEpisodeFiller(anime.FillerEpisodes, toEp)
1021	}
1022
1023	// Last-played anime id (Continue Last Session).
1024	writeLastPlayedAnimeID(c.config.StoragePath, anime.AnilistId)
1025
1026	// Local history: current episode is now toEp at position 0.
1027	dbPath := localHistoryPath(c.config.StoragePath)
1028	if dbPath != "" {
1029		if err := LocalUpdateAnime(
1030			dbPath,
1031			anime.AnilistId,
1032			anime.ProviderId,
1033			toEp,
1034			0,
1035			0,
1036			GetAnimeName(*anime),
1037			CurrentAnimeProviderName(anime),
1038		); err != nil {
1039			Log(fmt.Sprintf("MPV playlist: LocalUpdateAnime: %v", err))
1040		} else {
1041			Log(fmt.Sprintf("MPV playlist: last played → ep %d", toEp))
1042		}
1043	}
1044
1045	// Remote progress according to leave action.
1046	remoteProgress := 0
1047	switch leave {
1048	case playlistLeaveMarkLeft:
1049		if fromEp > 0 {
1050			remoteProgress = fromEp
1051		}
1052	case playlistLeaveSetWatch:
1053		if toEp > 1 {
1054			remoteProgress = toEp - 1
1055		}
1056	}
1057
1058	if remoteProgress > 0 {
1059		token := ""
1060		if u := GetGlobalUser(); u != nil {
1061			token = u.Token
1062		}
1063		if !anime.Rewatching && token != "" {
1064			go func(ep int) {
1065				if err := UpdateAnimeProgress(token, anime.AnilistId, ep); err != nil {
1066					Log(fmt.Sprintf("MPV playlist: UpdateAnimeProgress(%d): %v", ep, err))
1067				} else {
1068					CurdOut(fmt.Sprintf("Upstream progress → episode %d", ep))
1069				}
1070			}(remoteProgress)
1071		} else if anime.Rewatching {
1072			Log("MPV playlist: rewatching — skipped remote progress update")
1073		}
1074		CurdOut(fmt.Sprintf("Playing episode %d · upstream progress set to %d", toEp, remoteProgress))
1075	} else {
1076		CurdOut(fmt.Sprintf("Playing episode %d · last played updated (no upstream change)", toEp))
1077	}
1078
1079	// Prefetch next episode links in preferred mode (no audio prompts).
1080	go c.prefetchAfterPlaylistSwitch(toEp)
1081
1082	// Discord will pick up the new title/position on the next presence tick once
1083	// duration is known; force a soft title refresh for the window.
1084	title := fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), toEp)
1085	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", title})
1086	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", title})
1087}
1088
1089func localHistoryPath(storagePath string) string {
1090	storagePath = strings.TrimSpace(os.ExpandEnv(storagePath))
1091	if storagePath == "" {
1092		return ""
1093	}
1094	return filepath.Join(storagePath, "curd_history.txt")
1095}
1096
1097func writeLastPlayedAnimeID(storagePath string, anilistID int) {
1098	if anilistID <= 0 {
1099		return
1100	}
1101	storagePath = strings.TrimSpace(os.ExpandEnv(storagePath))
1102	if storagePath == "" {
1103		return
1104	}
1105	idPath := filepath.Join(storagePath, "curd_id")
1106	if err := os.MkdirAll(filepath.Dir(idPath), 0o755); err != nil {
1107		Log(fmt.Sprintf("MPV playlist: mkdir for curd_id: %v", err))
1108		return
1109	}
1110	if err := os.WriteFile(idPath, []byte(strconv.Itoa(anilistID)), 0o644); err != nil {
1111		Log(fmt.Sprintf("MPV playlist: write curd_id: %v", err))
1112	}
1113}
1114
1115func (c *MPVPlaylistController) prefetchAfterPlaylistSwitch(currentEp int) {
1116	if c == nil || c.config == nil || c.anime == nil {
1117		return
1118	}
1119	nextEp := currentEp + 1
1120	if c.anime.TotalEpisodes > 0 && nextEp > c.anime.TotalEpisodes {
1121		return
1122	}
1123	cfg := *c.config
1124	cfg.SubOrDub = c.preferredMode
1125	next := *c.anime
1126	result, err := ResolveEpisodeURL(cfg, &next, nextEp)
1127	if err != nil || len(result.Links) == 0 {
1128		Log(fmt.Sprintf("MPV playlist: prefetch ep %d: %v", nextEp, err))
1129		return
1130	}
1131	c.anime.Ep.NextEpisode = NextEpisode{
1132		Number:       nextEp,
1133		Links:        result.Links,
1134		ProviderName: result.ProviderName,
1135		ProviderId:   result.ProviderID,
1136		Mode:         result.Mode,
1137	}
1138	Log(fmt.Sprintf("MPV playlist: prefetched episode %d", nextEp))
1139}
1140
1141func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int {
1142	c.mu.Lock()
1143	defer c.mu.Unlock()
1144	return c.episodeIndexLocked(ep, mode)
1145}
1146
1147func (c *MPVPlaylistController) episodeIndexLocked(ep int, mode string) int {
1148	mode = normalizeTranslationType(mode)
1149	for i, s := range c.slots {
1150		if s.Episode == ep && normalizeTranslationType(s.Mode) == mode {
1151			return i
1152		}
1153	}
1154	// Fallback: first slot with that episode number.
1155	for i, s := range c.slots {
1156		if s.Episode == ep {
1157			return i
1158		}
1159	}
1160	if ep > 0 {
1161		return ep - 1
1162	}
1163	return 0
1164}
1165
1166func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
1167	// Caller (handlePlaylistJump) already called beginMPVPlaylistSwitch.
1168	// We clear it only after the new stream is stably playing (or on error paths
1169	// that return before that — handlePlaylistJump clears on failure).
1170	c.suppress.Store(true)
1171	defer c.suppress.Store(false)
1172
1173	mode := normalizeTranslationType(slot.Mode)
1174	if mode == "" {
1175		mode = c.preferredMode
1176	}
1177
1178	cfg := *c.config
1179	cfg.SubOrDub = mode
1180
1181	anime := c.anime
1182	prevEp := anime.Ep.Number
1183	targetEp := slot.Episode
1184
1185	// Clear ALL previous-episode playback state before resolve/load so the main
1186	// loop cannot seek/resume the old episode into the new stream.
1187	anime.Ep.Resume = false
1188	anime.Ep.Player.PlaybackTime = 0
1189	anime.Ep.Duration = 0
1190	anime.Ep.IsCompleted = false
1191	anime.Ep.Number = targetEp
1192	anime.Ep.Links = nil
1193	anime.Ep.NextEpisode = NextEpisode{}
1194	anime.Ep.StreamReferrer = ""
1195	anime.Ep.SubtitleURL = ""
1196	anime.Ep.SkipTimes = SkipTimes{}
1197
1198	Log(fmt.Sprintf("MPV playlist: resolving stream for episode %d (%s) [was %d]", targetEp, mode, prevEp))
1199
1200	// Snapshot current path so we can detect a real media change after loadfile.
1201	oldPath := mpvStringProperty(c.socket, "path")
1202
1203	// Preferred mode only — no nested DynamicSelect prompts from this goroutine.
1204	result, err := ResolveEpisodeURL(cfg, anime, targetEp)
1205	if err != nil || len(result.Links) == 0 {
1206		anime.Ep.Number = prevEp
1207		if err == nil {
1208			err = fmt.Errorf("no streams for episode %d", targetEp)
1209		}
1210		return err
1211	}
1212
1213	anime.Ep.Links = result.Links
1214	applyStreamPlaybackHints(anime, result.Links, result.LinkHints)
1215	link := PrioritizeLink(result.Links)
1216	if link == "" {
1217		anime.Ep.Number = prevEp
1218		return fmt.Errorf("empty stream link for episode %d", targetEp)
1219	}
1220
1221	// Refuse to "switch" to the exact same URL — that reloads the same episode.
1222	if oldPath != "" && (link == oldPath || strings.Contains(oldPath, link) || strings.Contains(link, oldPath)) {
1223		Log(fmt.Sprintf("MPV playlist: WARNING resolved link equals current path for ep %d; still forcing reload", targetEp))
1224	}
1225
1226	title := fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), targetEp)
1227	if mode != "" && mode != c.preferredMode {
1228		title += " (" + strings.ToUpper(mode) + ")"
1229	}
1230	Log(fmt.Sprintf("MPV playlist: loading ep %d in running mpv (was path %s): %s",
1231		targetEp, truncateForLog(oldPath, 60), truncateForLog(link, 80)))
1232
1233	anime.Ep.Player.SocketPath = c.socket
1234	if err := loadEpisodeInRunningMPV(c.socket, link, title, anime); err != nil {
1235		anime.Ep.Number = prevEp
1236		return err
1237	}
1238
1239	// Wait until path actually changes away from the old media (not just time-pos).
1240	// WaitForMPVPlaybackStart alone is wrong — old episode still has time-pos.
1241	if !waitForMPVMediaChange(c.socket, oldPath, link, 30*time.Second) {
1242		anime.Ep.Number = prevEp
1243		return fmt.Errorf("episode %d did not become the active media (still on previous file?)", targetEp)
1244	}
1245	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "time-pos", 0})
1246	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", false})
1247	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", title})
1248	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", title})
1249
1250	anime.Ep.Number = targetEp
1251	// Keep Started=true so the main monitor stays in "watching" mode continuously.
1252	anime.Ep.Started = true
1253	anime.Ep.IsCompleted = false
1254	anime.Ep.Player.PlaybackTime = 0
1255	anime.Ep.Duration = 0
1256	anime.Ep.SkipTimes = SkipTimes{}
1257	anime.Ep.Resume = false
1258	// Apply provider identity from the resolve result when present.
1259	if result.ProviderName != "" {
1260		anime.ProviderName = result.ProviderName
1261	}
1262	if result.ProviderID != "" {
1263		anime.ProviderId = result.ProviderID
1264	}
1265
1266	// Re-read duration for the new file (one-shot background).
1267	go func(socket string) {
1268		deadline := time.Now().Add(15 * time.Second)
1269		for time.Now().Before(deadline) {
1270			if c.closed() {
1271				return
1272			}
1273			durationPos, err := MPVSendCommand(socket, []interface{}{"get_property", "duration"})
1274			if err == nil && durationPos != nil {
1275				if duration, ok := durationPos.(float64); ok && duration > 1 {
1276					c.anime.Ep.Duration = int(duration + 0.5)
1277					Log(fmt.Sprintf("MPV playlist: episode %d duration %ds", targetEp, c.anime.Ep.Duration))
1278					return
1279				}
1280			}
1281			time.Sleep(300 * time.Millisecond)
1282		}
1283	}(c.socket)
1284
1285	c.mu.Lock()
1286	c.currentPlaying = targetEp
1287	c.currentMode = mode
1288	// The alternate is always the *other* mode from what is now playing, so after
1289	// a sub→dub switch the offered extra row is sub (not dub again). Recompute
1290	// here so probeAndAttachAlternateAudio stays symmetric in both directions.
1291	c.alternateMode = alternateTranslationType(mode)
1292	alreadyAlt := normalizeTranslationType(slot.Mode) == c.alternateMode
1293	// After loadfile replace the playlist is a single entry at index 0.
1294	c.lastPos = 0
1295	c.slots = []playlistSlot{{Episode: targetEp, Mode: mode, Label: title}}
1296	c.hasAlternate = false
1297	c.mu.Unlock()
1298
1299	// Stream is live — safe for the main loop again.
1300	endMPVPlaylistSwitch()
1301
1302	// Refresh skip times in background (non-blocking for playback).
1303	go func(ep int) {
1304		if c.anime.MalId > 0 {
1305			if err := GetAndParseAniSkipData(c.anime.MalId, ep, 0, c.anime); err != nil {
1306				Log(fmt.Sprintf("AniSkip for ep %d: %v", ep, err))
1307			}
1308			if c.anime.Ep.SkipTimes.Op.Start != c.anime.Ep.SkipTimes.Op.End ||
1309				c.anime.Ep.SkipTimes.Ed.Start != c.anime.Ep.SkipTimes.Ed.End {
1310				_ = SendSkipTimesToMPV(c.anime)
1311			}
1312		}
1313	}(targetEp)
1314
1315	// Re-probe alternate for the new episode only after placeholders are rebuilt.
1316	go func() {
1317		time.Sleep(mpvPlaylistIdleDelay + time.Second)
1318		if c.closed() || alreadyAlt {
1319			return
1320		}
1321		c.hasAlternate = false
1322		c.probeAndAttachAlternateAudio()
1323	}()
1324
1325	CurdOut(fmt.Sprintf("Playing episode %d (%s)", targetEp, mode))
1326	return nil
1327}
1328
1329// loadEpisodeInRunningMPV replaces the currently playing file with link.
1330// Note: mpv's loadfile-replace clears other playlist entries (we rebuild after).
1331func loadEpisodeInRunningMPV(socket, link, title string, anime *Anime) error {
1332	if socket == "" || link == "" {
1333		return fmt.Errorf("missing socket or link")
1334	}
1335	// Referrer / headers for the new stream.
1336	referrer := ""
1337	if anime != nil {
1338		referrer = strings.TrimSpace(anime.Ep.StreamReferrer)
1339		if referrer == "" {
1340			referrer = streamReferrerForLink(link, CurrentAnimeProviderName(anime))
1341		}
1342	}
1343	if referrer != "" {
1344		_, _ = MPVSendCommand(socket, []interface{}{"set_property", "referrer", referrer})
1345	}
1346
1347	opts := "force-media-title=" + escapeMPVOptionValue(title)
1348	// Explicit replace so we never append a second "current" by accident.
1349	if _, err := MPVSendCommand(socket, []interface{}{"loadfile", link, "replace", 0, opts}); err != nil {
1350		// Fallback without options (older mpv / option parse issues).
1351		if _, err2 := MPVSendCommand(socket, []interface{}{"loadfile", link, "replace"}); err2 != nil {
1352			return fmt.Errorf("loadfile: %w", err2)
1353		}
1354		_, _ = MPVSendCommand(socket, []interface{}{"set_property", "force-media-title", title})
1355	}
1356	// Stop at start of the new file; caller unpauses after path confirms.
1357	_, _ = MPVSendCommand(socket, []interface{}{"set_property", "pause", true})
1358	_, _ = MPVSendCommand(socket, []interface{}{"set_property", "time-pos", 0})
1359
1360	if anime != nil {
1361		sub := strings.TrimSpace(anime.Ep.SubtitleURL)
1362		if sub != "" {
1363			go func() {
1364				_ = waitForMPVFileReady(socket, link, 12*time.Second)
1365				_, _ = MPVSendCommand(socket, []interface{}{"sub-add", sub, "select"})
1366			}()
1367		}
1368	}
1369	return nil
1370}
1371
1372func mpvStringProperty(socket, name string) string {
1373	v, err := MPVSendCommand(socket, []interface{}{"get_property", name})
1374	if err != nil || v == nil {
1375		return ""
1376	}
1377	if s, ok := v.(string); ok {
1378		return s
1379	}
1380	return fmt.Sprint(v)
1381}
1382
1383// waitForMPVMediaChange waits until MPV's path is no longer oldPath and looks like
1384// the new link (or at least not the previous file / lavfi placeholder).
1385func waitForMPVMediaChange(socket, oldPath, newLink string, timeout time.Duration) bool {
1386	deadline := time.Now().Add(timeout)
1387	newKey := mediaURLKey(newLink)
1388	oldKey := mediaURLKey(oldPath)
1389	Log(fmt.Sprintf("MPV playlist: waiting for media change oldKey=%q newKey=%q", truncateForLog(oldKey, 40), truncateForLog(newKey, 40)))
1390
1391	for time.Now().Before(deadline) {
1392		path := mpvStringProperty(socket, "path")
1393		if path == "" {
1394			time.Sleep(150 * time.Millisecond)
1395			continue
1396		}
1397		// Still on placeholder or previous file.
1398		if strings.HasPrefix(path, "av://") {
1399			time.Sleep(150 * time.Millisecond)
1400			continue
1401		}
1402		if oldPath != "" && path == oldPath {
1403			time.Sleep(150 * time.Millisecond)
1404			continue
1405		}
1406		if oldKey != "" && mediaURLKey(path) == oldKey && newKey != oldKey {
1407			time.Sleep(150 * time.Millisecond)
1408			continue
1409		}
1410		// Prefer a positive match on the new URL when possible.
1411		if newKey != "" && (strings.Contains(path, newKey) || mediaURLKey(path) == newKey || strings.Contains(newLink, path) || strings.Contains(path, newLink)) {
1412			// Need a real time-pos too.
1413			if tpos, err := MPVSendCommand(socket, []interface{}{"get_property", "time-pos"}); err == nil && tpos != nil {
1414				Log(fmt.Sprintf("MPV playlist: media changed to %s", truncateForLog(path, 80)))
1415				return true
1416			}
1417		}
1418		// Path changed away from old and is not lavfi — accept.
1419		if oldPath != "" && path != oldPath && !strings.HasPrefix(path, "av://") {
1420			if tpos, err := MPVSendCommand(socket, []interface{}{"get_property", "time-pos"}); err == nil && tpos != nil {
1421				Log(fmt.Sprintf("MPV playlist: media path changed to %s", truncateForLog(path, 80)))
1422				return true
1423			}
1424		}
1425		time.Sleep(150 * time.Millisecond)
1426	}
1427	Log(fmt.Sprintf("MPV playlist: media change timed out; path now %q", truncateForLog(mpvStringProperty(socket, "path"), 80)))
1428	return false
1429}
1430
1431// mediaURLKey extracts a stable identity from a stream URL (host + path without query).
1432func mediaURLKey(raw string) string {
1433	raw = strings.TrimSpace(raw)
1434	if raw == "" {
1435		return ""
1436	}
1437	// Strip query/fragment so expiring tokens don't break comparison.
1438	if i := strings.IndexAny(raw, "?#"); i >= 0 {
1439		raw = raw[:i]
1440	}
1441	return raw
1442}
1443
1444func escapeMPVOptionValue(s string) string {
1445	// loadfile options: quote and escape embedded quotes/backslashes.
1446	s = strings.ReplaceAll(s, `\`, `\\`)
1447	s = strings.ReplaceAll(s, `"`, `\"`)
1448	s = strings.ReplaceAll(s, `,`, `\,`)
1449	s = strings.ReplaceAll(s, `=`, `\=`)
1450	return `"` + s + `"`
1451}
1452
1453func truncateForLog(s string, n int) string {
1454	if len(s) <= n {
1455		return s
1456	}
1457	return s[:n] + "…"
1458}
1459
1460// rebuildPlaylistAroundCurrent re-adds titled placeholders after loadfile replace
1461// wiped the playlist. Current playing entry stays index 0 until we insert before it.
1462func (c *MPVPlaylistController) rebuildPlaylistAroundCurrent() error {
1463	if c.closed() || c.anime == nil {
1464		return nil
1465	}
1466	episodes := c.episodeNums
1467	if len(episodes) == 0 {
1468		episodes = c.fetchEpisodeNumbers()
1469		c.episodeNums = episodes
1470	}
1471	if len(episodes) == 0 {
1472		return fmt.Errorf("no episodes for rebuild")
1473	}
1474
1475	currentEp := c.currentPlaying
1476	if currentEp < 1 {
1477		currentEp = c.anime.Ep.Number
1478	}
1479	mode := c.currentMode
1480	if mode == "" {
1481		mode = c.preferredMode
1482	}
1483
1484	c.suppress.Store(true)
1485	defer c.suppress.Store(false)
1486	beginMPVPlaylistSwitch()
1487	defer endMPVPlaylistSwitch()
1488
1489	var before, after []playlistSlot
1490	for _, ep := range episodes {
1491		if ep < currentEp {
1492			before = append(before, playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)})
1493		} else if ep > currentEp {
1494			after = append(after, playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)})
1495		}
1496	}
1497
1498	// Title the live entry (index 0 after replace).
1499	curLabel := c.episodeLabel(currentEp, mode)
1500	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", curLabel})
1501	_, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", curLabel})
1502
1503	if len(after) > 0 {
1504		if err := c.loadTitledPlaceholders(after, false); err != nil {
1505			Log(fmt.Sprintf("rebuild append future: %v", err))
1506		}
1507	}
1508	if len(before) > 0 {
1509		if err := c.loadTitledPlaceholders(before, true); err != nil {
1510			Log(fmt.Sprintf("rebuild insert previous: %v", err))
1511		}
1512	}
1513
1514	slots := make([]playlistSlot, 0, len(before)+1+len(after))
1515	slots = append(slots, before...)
1516	slots = append(slots, playlistSlot{Episode: currentEp, Mode: mode, Label: curLabel})
1517	slots = append(slots, after...)
1518
1519	c.mu.Lock()
1520	c.slots = slots
1521	c.lastPos = len(before)
1522	c.mu.Unlock()
1523
1524	Log(fmt.Sprintf("MPV playlist rebuilt around ep %d (%d entries)", currentEp, len(slots)))
1525	return nil
1526}
1527