Commit 57741c3208

57741c3208984144b960041b2a319cb183ae6038

parent: 0a7afdf3e3

Unsigned

Wraient <wraient.911@gmail.com> · 2026-08-02 23:32 UTC

fix: reliable mpv playlist episode resolution and symmetric sub/dub toggle

Resolve clicked playlist rows from the frozen index + row title instead of
the lavfi filename (which decoded to arbitrary episodes like 300). Recompute
the alternate translation mode on every switch so the dub/sub toggle row
appears in both directions, and tag the alternate row ("(SUB)"/"(DUB)")
against the currently playing mode. Document playlist menu access.

Layout: unified · split

README.md +1 −1
@@ -381,7 +381,7 @@ If the browser reaches the localhost callback page but curd does not continue au
381| `AddMissingOptions` | Boolean | `true`, `false` | When `true`, on a **version upgrade** only options registered as new for that release are **appended** to `curd.conf` (not every historical default). Set `false` to opt out. Defaults still apply in memory always. | 381| `AddMissingOptions` | Boolean | `true`, `false` | When `true`, on a **version upgrade** only options registered as new for that release are **appended** to `curd.conf` (not every historical default). Set `false` to opt out. Defaults still apply in memory always. |
382| `VimKeys` | Boolean | `true`, `false` | When `true`, selection menus use vim motions: `j`/`k`/`h`/`l` (and arrows) to move, `/` or `?` to search. Default: `false` (type-to-filter immediately). Add `VimKeys=true` to `~/.config/curd/curd.conf` to enable. | 382| `VimKeys` | Boolean | `true`, `false` | When `true`, selection menus use vim motions: `j`/`k`/`h`/`l` (and arrows) to move, `/` or `?` to search. Default: `false` (type-to-filter immediately). Add `VimKeys=true` to `~/.config/curd/curd.conf` to enable. |
383| `CheckUpdates` | Boolean | `true`, `false` | When `true` (default), checks GitHub for a newer release **while idle** (does not delay startup). If an update is found, the next launch shows notes and options: update now / skip / remind later / turn off. | 383| `CheckUpdates` | Boolean | `true`, `false` | When `true` (default), checks GitHub for a newer release **while idle** (does not delay startup). If an update is found, the next launch shows notes and options: update now / skip / remind later / turn off. |
384| `MpvEpisodePlaylist` | Boolean | `true`, `false` | When `true` (default), after playback is stable curd fills the MPV playlist with episodes (and dub/sub when available) so you can pick from MPV's playlist UI. Built only while idle — does not delay start. Selecting an entry loads that stream and keeps tracking in sync. | 384| `MpvEpisodePlaylist` | Boolean | `true`, `false` | When `true` (default), after playback is stable curd fills the MPV playlist with episodes (and dub/sub when available) so you can pick from MPV's playlist UI. Access: `MPV` → right-click the prev/next OSC button (or `Ctrl+P`). Selecting a row loads that stream and keeps tracking in sync. |
385| `AlternateScreen` | Boolean | `true`, `false` | Toggles the use of an alternate screen buffer for cleaner UI. | 385| `AlternateScreen` | Boolean | `true`, `false` | Toggles the use of an alternate screen buffer for cleaner UI. |
386| `RofiSelection` | Boolean | `true`, `false` | Enables or disables anime selection via Rofi. | 386| `RofiSelection` | Boolean | `true`, `false` | Enables or disables anime selection via Rofi. |
387| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. | 387| `PercentageToMarkComplete`| Integer | `0` to `100` | Sets the percentage of an episode watched to consider it as completed. |
internal/mpv_playlist.go +96 −64
@@ -285,12 +285,11 @@ func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string {
285 base += " [Filler]" 285 base += " [Filler]"
286 } 286 }
287 mode = normalizeTranslationType(mode) 287 mode = normalizeTranslationType(mode)
288 if mode != "" && mode != c.preferredMode { 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 {
289 base += " (" + strings.ToUpper(mode) + ")" 292 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 } 293 }
295 if ep == c.currentPlaying && mode == c.currentMode { 294 if ep == c.currentPlaying && mode == c.currentMode {
296 base += " ◀" 295 base += " ◀"
@@ -582,14 +581,23 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
582 // missed jumps (logs showed time-pos drop with no "pos changed"). 581 // missed jumps (logs showed time-pos drop with no "pos changed").
583 Log("MPV playlist: watching path + playlist-pos for episode picks") 582 Log("MPV playlist: watching path + playlist-pos for episode picks")
584 poll := 150 * time.Millisecond 583 poll := 150 * time.Millisecond
585 var lastSeenPath string 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{}
586 590
587 for { 591 for {
588 if c.closed() { 592 if c.closed() {
589 return 593 return
590 } 594 }
591 if !IsMPVRunning(c.socket) { 595 if !IsMPVRunning(c.socket) {
592 return 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
593 } 601 }
594 if c.suppress.Load() || MPVPlaylistIsSwitching() { 602 if c.suppress.Load() || MPVPlaylistIsSwitching() {
595 time.Sleep(poll) 603 time.Sleep(poll)
@@ -599,44 +607,64 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
599 path := mpvStringProperty(c.socket, "path") 607 path := mpvStringProperty(c.socket, "path")
600 pos, posErr := c.playlistPos() 608 pos, posErr := c.playlistPos()
601 609
602 // --- Primary: path became a placeholder for episode N --- 610 // Heartbeat ~once a second: captures mpv's real reported state over time
603 if ep, ok := parseEpisodeFromPlaceholder(path); ok { 611 // even when nothing changes, so we can prove what mpv does on a click.
604 // Debounce: confirm path still that placeholder briefly (scrub). 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).
605 time.Sleep(80 * time.Millisecond) 639 time.Sleep(80 * time.Millisecond)
606 path2 := mpvStringProperty(c.socket, "path") 640 if !isPlaceholderPath(mpvStringProperty(c.socket, "path")) {
607 ep2, ok2 := parseEpisodeFromPlaceholder(path2)
608 if !ok2 {
609 continue 641 continue
610 } 642 }
611 ep = ep2 643
612 path = path2 644 targetPos := pos
613 645 if posErr != nil || pos < 0 {
614 mode := c.preferredMode 646 targetPos, _ = c.playlistPos()
615 if posErr == nil && pos >= 0 { 647 }
616 if _, title := c.playlistEntryMeta(pos); title != "" { 648 slot, slotErr := c.resolveSlotAt(targetPos)
617 if _, m, ok3 := parsePlaylistEpisodeTitle(title, c.preferredMode); ok3 { 649 if slotErr != nil {
618 mode = m 650 Log(fmt.Sprintf("MPV playlist: placeholder pick unresolvable at pos %d: %v", targetPos, slotErr))
619 } 651 c.lastPos = targetPos
620 } 652 continue
621 } 653 }
622 654
623 c.mu.Lock() 655 c.mu.Lock()
624 curEp := c.currentPlaying 656 curEp := c.currentPlaying
625 c.mu.Unlock() 657 c.mu.Unlock()
626 658
627 Log(fmt.Sprintf("MPV playlist: DETECT path placeholder ep=%d mode=%s (was ep=%d prevPath=%s)", 659 Log(fmt.Sprintf("MPV playlist: DETECT placeholder row pos=%d → ep %d (%s) (was ep=%d)",
628 ep, mode, curEp, truncateForLog(lastSeenPath, 50))) 660 targetPos, slot.Episode, slot.Mode, curEp))
629 661
630 beginMPVPlaylistSwitch() 662 beginMPVPlaylistSwitch()
631 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true}) 663 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
632 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", ep), 5000}) 664 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000})
633 665
634 if posErr == nil && pos >= 0 { 666 c.lastPos = targetPos
635 c.lastPos = pos
636 }
637 slot := playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)}
638 c.handlePlaylistJumpSlot(slot, curEp) 667 c.handlePlaylistJumpSlot(slot, curEp)
639 lastSeenPath = mpvStringProperty(c.socket, "path")
640 continue 668 continue
641 } 669 }
642 670
@@ -659,8 +687,7 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
659 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true}) 687 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
660 c.lastPos = targetPos 688 c.lastPos = targetPos
661 c.handlePlaylistJump(targetPos) 689 c.handlePlaylistJump(targetPos)
662 lastSeenPath = mpvStringProperty(c.socket, "path") 690 continue
663 continue
664 } 691 }
665 692
666 c.mu.Lock() 693 c.mu.Lock()
@@ -679,8 +706,7 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
679 beginMPVPlaylistSwitch() 706 beginMPVPlaylistSwitch()
680 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true}) 707 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
681 c.handlePlaylistJumpSlot(slot, curEp) 708 c.handlePlaylistJumpSlot(slot, curEp)
682 lastSeenPath = mpvStringProperty(c.socket, "path") 709 }
683 }
684 time.Sleep(poll) 710 time.Sleep(poll)
685 continue 711 continue
686 } 712 }
@@ -690,12 +716,11 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
690 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000}) 716 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000})
691 c.lastPos = targetPos 717 c.lastPos = targetPos
692 c.handlePlaylistJumpSlot(slot, curEp) 718 c.handlePlaylistJumpSlot(slot, curEp)
693 lastSeenPath = mpvStringProperty(c.socket, "path")
694 continue 719 continue
695 } 720 }
696 721
697 if path != "" { 722 if path != "" {
698 lastSeenPath = path 723
699 } 724 }
700 time.Sleep(poll) 725 time.Sleep(poll)
701 } 726 }
@@ -721,22 +746,15 @@ func (c *MPVPlaylistController) handlePlaylistJumpSlot(slot playlistSlot, curEp
721 if c.config != nil && c.config.PercentageToMarkComplete > 0 { 746 if c.config != nil && c.config.PercentageToMarkComplete > 0 {
722 threshold = c.config.PercentageToMarkComplete 747 threshold = c.config.PercentageToMarkComplete
723 } 748 }
724 action, pErr := promptPlaylistEpisodeLeave(curEp, slot.Episode, pct, threshold) 749 // Never interrupt playback with a terminal menu while the user is in
725 if pErr != nil { 750 // (possibly fullscreen) MPV. Resolve the remote action silently: backward
726 Log(fmt.Sprintf("MPV playlist leave prompt: %v (playing target anyway)", pErr)) 751 // jumps never regress upstream progress, +1 follows the standard "next"
727 action = playlistLeaveNone 752 // auto-mark behavior, other forward skips leave progress untouched.
728 } 753 leaveAction = resolvePlaylistLeaveDefault(curEp, slot.Episode, pct, threshold)
729 if action == playlistLeaveCancel { 754 Log(fmt.Sprintf("MPV playlist: SWITCH %d → %d (%s) leave=%s (silent, no session menu)",
730 Log("MPV playlist: user cancelled — reloading current ep real stream") 755 curEp, slot.Episode, slot.Mode, leaveAction))
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 { 756 } else {
757 leaveAction = playlistLeaveNone
740 Log(fmt.Sprintf("MPV playlist: reloading real stream for ep %d (was on placeholder)", curEp)) 758 Log(fmt.Sprintf("MPV playlist: reloading real stream for ep %d (was on placeholder)", curEp))
741 } 759 }
742 760
@@ -851,6 +869,28 @@ func maxInt(a, b int) int {
851 return b 869 return b
852} 870}
853 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
854// resolveSlotAt figures out which episode the user selected at playlist index pos. 894// resolveSlotAt figures out which episode the user selected at playlist index pos.
855// Order: placeholder filename encode → title → our slots map. 895// Order: placeholder filename encode → title → our slots map.
856// Never re-query playlist-pos here — caller freezes the index. 896// Never re-query playlist-pos here — caller freezes the index.
@@ -858,18 +898,6 @@ func (c *MPVPlaylistController) resolveSlotAt(pos int) (playlistSlot, error) {
858 filename, title := c.playlistEntryMeta(pos) 898 filename, title := c.playlistEntryMeta(pos)
859 Log(fmt.Sprintf("MPV playlist: resolve pos=%d filename=%q title=%q", pos, truncateForLog(filename, 60), title)) 899 Log(fmt.Sprintf("MPV playlist: resolve pos=%d filename=%q title=%q", pos, truncateForLog(filename, 60), title))
860 900
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 != "" { 901 if title != "" {
874 if ep, mode, ok := parsePlaylistEpisodeTitle(title, c.preferredMode); ok { 902 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)) 903 Log(fmt.Sprintf("MPV playlist: pos %d title %q → ep %d (%s)", pos, title, ep, mode))
@@ -1257,6 +1285,10 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
1257 c.mu.Lock() 1285 c.mu.Lock()
1258 c.currentPlaying = targetEp 1286 c.currentPlaying = targetEp
1259 c.currentMode = mode 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)
1260 alreadyAlt := normalizeTranslationType(slot.Mode) == c.alternateMode 1292 alreadyAlt := normalizeTranslationType(slot.Mode) == c.alternateMode
1261 // After loadfile replace the playlist is a single entry at index 0. 1293 // After loadfile replace the playlist is a single entry at index 0.
1262 c.lastPos = 0 1294 c.lastPos = 0
internal/mpv_playlist_test.go +31
@@ -268,6 +268,37 @@ func TestPromptPlaylistJumpOffersUpstreamOptions(t *testing.T) {
268 } 268 }
269} 269}
270 270
271func TestResolvePlaylistLeaveDefaultNeverRegressesOnRewind(t *testing.T) {
272 // Backward jump → never touch AniList/MAL, regardless of watch percentage.
273 if action := resolvePlaylistLeaveDefault(40, 39, 11, 85); action != playlistLeaveNone {
274 t.Fatalf("backward 11%% → %s want none", action)
275 }
276 if action := resolvePlaylistLeaveDefault(40, 39, 90, 85); action != playlistLeaveNone {
277 t.Fatalf("backward 90%% → %s want none", action)
278 }
279 if action := resolvePlaylistLeaveDefault(40, 1, 0, 85); action != playlistLeaveNone {
280 t.Fatalf("backward 0%% → %s want none", action)
281 }
282}
283
284func TestResolvePlaylistLeaveDefaultNeverPrompts(t *testing.T) {
285 // Same episode (mode toggle) → none.
286 if action := resolvePlaylistLeaveDefault(40, 40, 90, 85); action != playlistLeaveNone {
287 t.Fatalf("same ep → %s want none", action)
288 }
289 // Next +1 follows standard auto-mark behavior.
290 if action := resolvePlaylistLeaveDefault(40, 41, 11, 85); action != playlistLeaveNone {
291 t.Fatalf("forward early → %s want none", action)
292 }
293 if action := resolvePlaylistLeaveDefault(40, 41, 90, 85); action != playlistLeaveMarkLeft {
294 t.Fatalf("forward nearly-done → %s want mark", action)
295 }
296 // Forward skip (>+1) → none (deferred to session end).
297 if action := resolvePlaylistLeaveDefault(40, 45, 90, 85); action != playlistLeaveNone {
298 t.Fatalf("forward skip → %s want none", action)
299 }
300}
301
271func TestPromptPlaylistJumpCancelAndPromptError(t *testing.T) { 302func TestPromptPlaylistJumpCancelAndPromptError(t *testing.T) {
272 prev := promptSelectOrdered 303 prev := promptSelectOrdered
273 t.Cleanup(func() { promptSelectOrdered = prev }) 304 t.Cleanup(func() { promptSelectOrdered = prev })