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
381381| `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. |
382382| `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. |
383383| `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. |
385385| `AlternateScreen` | Boolean | `true`, `false` | Toggles the use of an alternate screen buffer for cleaner UI. |
386386| `RofiSelection` | Boolean | `true`, `false` | Enables or disables anime selection via Rofi. |
387387| `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 {
285285 base += " [Filler]"
286286 }
287287 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 {
289292 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)"
294293 }
295294 if ep == c.currentPlaying && mode == c.currentMode {
296295 base += " ◀"
@@ -582,14 +581,23 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
582581 // missed jumps (logs showed time-pos drop with no "pos changed").
583582 Log("MPV playlist: watching path + playlist-pos for episode picks")
584583 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{}
586590
587591 for {
588592 if c.closed() {
589593 return
590594 }
591595 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
593601 }
594602 if c.suppress.Load() || MPVPlaylistIsSwitching() {
595603 time.Sleep(poll)
@@ -599,44 +607,64 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
599607 path := mpvStringProperty(c.socket, "path")
600608 pos, posErr := c.playlistPos()
601609
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).
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).
605639 time.Sleep(80 * time.Millisecond)
606 path2 := mpvStringProperty(c.socket, "path")
607 ep2, ok2 := parseEpisodeFromPlaceholder(path2)
608 if !ok2 {
640 if !isPlaceholderPath(mpvStringProperty(c.socket, "path")) {
609641 continue
610642 }
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 }
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
621653 }
622654
623655 c.mu.Lock()
624656 curEp := c.currentPlaying
625657 c.mu.Unlock()
626658
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)))
659 Log(fmt.Sprintf("MPV playlist: DETECT placeholder row pos=%d → ep %d (%s) (was ep=%d)",
660 targetPos, slot.Episode, slot.Mode, curEp))
629661
630662 beginMPVPlaylistSwitch()
631663 _, _ = 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})
633665
634 if posErr == nil && pos >= 0 {
635 c.lastPos = pos
636 }
637 slot := playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)}
666 c.lastPos = targetPos
638667 c.handlePlaylistJumpSlot(slot, curEp)
639 lastSeenPath = mpvStringProperty(c.socket, "path")
640668 continue
641669 }
642670
@@ -659,8 +687,7 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
659687 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
660688 c.lastPos = targetPos
661689 c.handlePlaylistJump(targetPos)
662 lastSeenPath = mpvStringProperty(c.socket, "path")
663 continue
690 continue
664691 }
665692
666693 c.mu.Lock()
@@ -679,8 +706,7 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
679706 beginMPVPlaylistSwitch()
680707 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
681708 c.handlePlaylistJumpSlot(slot, curEp)
682 lastSeenPath = mpvStringProperty(c.socket, "path")
683 }
709 }
684710 time.Sleep(poll)
685711 continue
686712 }
@@ -690,12 +716,11 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
690716 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000})
691717 c.lastPos = targetPos
692718 c.handlePlaylistJumpSlot(slot, curEp)
693 lastSeenPath = mpvStringProperty(c.socket, "path")
694719 continue
695720 }
696721
697722 if path != "" {
698 lastSeenPath = path
723
699724 }
700725 time.Sleep(poll)
701726 }
@@ -721,22 +746,15 @@ func (c *MPVPlaylistController) handlePlaylistJumpSlot(slot playlistSlot, curEp
721746 if c.config != nil && c.config.PercentageToMarkComplete > 0 {
722747 threshold = c.config.PercentageToMarkComplete
723748 }
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
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))
739756 } else {
757 leaveAction = playlistLeaveNone
740758 Log(fmt.Sprintf("MPV playlist: reloading real stream for ep %d (was on placeholder)", curEp))
741759 }
742760
@@ -851,6 +869,28 @@ func maxInt(a, b int) int {
851869 return b
852870}
853871
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
854894// resolveSlotAt figures out which episode the user selected at playlist index pos.
855895// Order: placeholder filename encode → title → our slots map.
856896// Never re-query playlist-pos here — caller freezes the index.
@@ -858,18 +898,6 @@ func (c *MPVPlaylistController) resolveSlotAt(pos int) (playlistSlot, error) {
858898 filename, title := c.playlistEntryMeta(pos)
859899 Log(fmt.Sprintf("MPV playlist: resolve pos=%d filename=%q title=%q", pos, truncateForLog(filename, 60), title))
860900
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 }
873901 if title != "" {
874902 if ep, mode, ok := parsePlaylistEpisodeTitle(title, c.preferredMode); ok {
875903 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 {
12571285 c.mu.Lock()
12581286 c.currentPlaying = targetEp
12591287 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)
12601292 alreadyAlt := normalizeTranslationType(slot.Mode) == c.alternateMode
12611293 // After loadfile replace the playlist is a single entry at index 0.
12621294 c.lastPos = 0
internal/mpv_playlist_test.go +31
@@ -268,6 +268,37 @@ func TestPromptPlaylistJumpOffersUpstreamOptions(t *testing.T) {
268268 }
269269}
270270
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
271302func TestPromptPlaylistJumpCancelAndPromptError(t *testing.T) {
272303 prev := promptSelectOrdered
273304 t.Cleanup(func() { promptSelectOrdered = prev })