Commit b0a92dd2a6

b0a92dd2a6c9a2c15e8fde67dfd3b75ee0a81cf8

parent: 4450a463dd

Unsigned

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

Fix MPV playlist episode switching and progress handling.

Detect picks via frozen playlist index and placeholder path (not a
re-sampled pos that snapped back to the current episode), load the
resolved stream only after the media path actually changes, harden
mpv IPC JSON reads, and update last-played/upstream progress with
clear +1 vs jump UX.

Layout: unified · split

cmd/curd/main.go +126 −102
@@ -643,68 +643,84 @@ func main() {
643 continue 643 continue
644 } 644 }
645 645
646 // Check if the error is due to invalid JSON
647 // User closed the video
648 if anime.Ep.Started { 646 if anime.Ep.Started {
649 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 647 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
650 // Episode is completed 648 action := internal.ClassifyPlaybackLoss(
649 anime.Ep.Player.SocketPath,
650 anime.Ep.Started,
651 percentageWatched,
652 userCurdConfig.PercentageToMarkComplete,
653 )
654 internal.Log(fmt.Sprintf("playback loss: pct=%.1f action=%d mpvRunning=%v switching=%v",
655 percentageWatched, action,
656 internal.IsMPVRunning(anime.Ep.Player.SocketPath),
657 internal.MPVPlaylistIsSwitching()))
658
659 switch action {
660 case internal.PlaybackLossWait:
661 // Playlist jump / demuxer reload / pause — MPV still open.
662 continue
663 case internal.PlaybackLossExit:
664 internal.Log("Episode is not completed, exiting")
665 internal.ExitCurd(nil)
666 return
667 case internal.PlaybackLossComplete:
668 // fall through to completion handling below
669 }
670
671 // Episode completed (threshold met, with or without MPV still idle).
651 internal.Log(fmt.Sprint(percentageWatched)) 672 internal.Log(fmt.Sprint(percentageWatched))
652 internal.Log(fmt.Sprint(anime.Ep.Player.Speed)) 673 internal.Log(fmt.Sprint(anime.Ep.Player.Speed))
653 internal.Log(fmt.Sprint(anime.Ep.Player.PlaybackTime)) 674 internal.Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
654 internal.Log(fmt.Sprint(anime.Ep.Duration)) 675 internal.Log(fmt.Sprint(anime.Ep.Duration))
655 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete)) 676 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
656 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { 677 anime.Ep.IsCompleted = true
657 anime.Ep.IsCompleted = true 678 if !userCurdConfig.NextEpisodePrompt {
658 if !userCurdConfig.NextEpisodePrompt { 679 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
659 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token) 680 } else {
660 } else { 681 // For Rofi mode, show prompt immediately after completion
661 // For Rofi mode, show prompt immediately after completion 682 if userCurdConfig.RofiSelection {
662 if userCurdConfig.RofiSelection { 683 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
663 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig) 684 if shouldContinue {
664 if shouldContinue { 685 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
665 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token) 686 } else {
666 } else { 687 // Episode was already marked as completed above
667 // Episode was already marked as completed above 688 // Handle completion if this was the last episode
668 // Handle completion if this was the last episode 689 if anime.Ep.Number == anime.TotalEpisodes {
669 if anime.Ep.Number == anime.TotalEpisodes { 690 internal.HandleLastEpisodeCompletion(&userCurdConfig, &anime, user.Token)
670 internal.HandleLastEpisodeCompletion(&userCurdConfig, &anime, user.Token) 691 }
671 } 692 // Update local database with completed episode
672 // Update local database with completed episode 693 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name())
673 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name()) 694 if err != nil {
674 if err != nil { 695 internal.Log("Error updating local database on quit: " + err.Error())
675 internal.Log("Error updating local database on quit: " + err.Error()) 696 }
676 }
677 697
678 // Update Anilist progress if not rewatching 698 // Update Anilist progress if not rewatching
679 if !anime.Rewatching { 699 if !anime.Rewatching {
680 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil { 700 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
681 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error()) 701 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error())
682 } else { 702 } else {
683 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) 703 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
684 }
685 } 704 }
686
687 internal.ExitCurd(nil)
688 } 705 }
689 } else { 706
690 // For CLI mode, let the continuous prompt handle it 707 internal.ExitCurd(nil)
691 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
692 } 708 }
693 // Exit the skip loop - only close if not already closed 709 } else {
694 select { 710 // For CLI mode, let the continuous prompt handle it
695 case isClosed := <-skipLoopClosed: 711 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
696 if !isClosed { 712 }
697 close(skipLoopDone) 713 // Exit the skip loop - only close if not already closed
698 skipLoopClosed <- true // Mark as closed 714 select {
699 } 715 case isClosed := <-skipLoopClosed:
700 default: 716 if !isClosed {
701 // Channel is busy, another goroutine is handling closure 717 close(skipLoopDone)
718 skipLoopClosed <- true // Mark as closed
702 } 719 }
703 return 720 default:
721 // Channel is busy, another goroutine is handling closure
704 } 722 }
705 } else { 723 return
706 internal.Log("Episode is not completed, exiting")
707 internal.ExitCurd(nil)
708 } 724 }
709 // Exit the skip loop - only close if not already closed 725 // Exit the skip loop - only close if not already closed
710 select { 726 select {
@@ -757,15 +773,14 @@ func main() {
757 } 773 }
758 } 774 }
759 775
760 // Check if anything is playing, if nothing is playing and episode was started, handle completion 776 // Check if anything is playing; if not and episode was started, classify the loss.
761 hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath) 777 hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath)
762 if err != nil { 778 if err != nil {
763 internal.Log("Error checking playback status: " + err.Error()) 779 internal.Log("Error checking playback status: " + err.Error())
764 } else if !hasPlayback && anime.Ep.Started { 780 } else if !hasPlayback && anime.Ep.Started {
765 // Wait for a moment to allow playback to start 781 // Wait for a moment to allow playback to start / playlist switch to settle
766 time.Sleep(2 * time.Second) // Wait for 2 seconds 782 time.Sleep(2 * time.Second)
767 783
768 // Check playback status again
769 hasPlayback, err = internal.HasActivePlayback(anime.Ep.Player.SocketPath) 784 hasPlayback, err = internal.HasActivePlayback(anime.Ep.Player.SocketPath)
770 if err != nil { 785 if err != nil {
771 internal.Log("Error checking playback status: " + err.Error()) 786 internal.Log("Error checking playback status: " + err.Error())
@@ -775,75 +790,84 @@ func main() {
775 continue 790 continue
776 } 791 }
777 792
778 // Nothing is playing, check percentage watched
779 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 793 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
780 // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n", 794 action := internal.ClassifyPlaybackLoss(
781 // int(percentageWatched), 795 anime.Ep.Player.SocketPath,
782 // userCurdConfig.PercentageToMarkComplete) 796 anime.Ep.Started,
783 797 percentageWatched,
784 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { 798 userCurdConfig.PercentageToMarkComplete,
785 anime.Ep.IsCompleted = true 799 )
786 if !userCurdConfig.NextEpisodePrompt { 800 internal.Log(fmt.Sprintf("no active playback: pct=%.1f action=%d", percentageWatched, action))
787 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token) 801
788 } else { 802 switch action {
789 // For Rofi mode, show prompt immediately after completion 803 case internal.PlaybackLossWait:
790 if userCurdConfig.RofiSelection { 804 continue
791 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig) 805 case internal.PlaybackLossExit:
792 if shouldContinue { 806 internal.Log("Episode is not completed, exiting")
793 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token) 807 internal.ExitCurd(nil)
794 } else { 808 return
795 // Episode was already marked as completed above 809 case internal.PlaybackLossComplete:
796 // Update local database with completed episode 810 // fall through
797 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name()) 811 }
798 if err != nil {
799 internal.Log("Error updating local database on quit: " + err.Error())
800 }
801
802 // Update Anilist progress if not rewatching
803 if !anime.Rewatching {
804 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
805 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error())
806 } else {
807 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
808 }
809 }
810 812
811 internal.ExitCurd(nil) 813 anime.Ep.IsCompleted = true
812 } 814 if !userCurdConfig.NextEpisodePrompt {
815 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
816 } else {
817 // For Rofi mode, show prompt immediately after completion
818 if userCurdConfig.RofiSelection {
819 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
820 if shouldContinue {
821 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
813 } else { 822 } else {
814 // For CLI mode, update progress immediately since episode is 85%+ complete 823 // Episode was already marked as completed above
815 // Update local database with completed episode 824 // Update local database with completed episode
816 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name()) 825 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name())
817 if err != nil { 826 if err != nil {
818 internal.Log("Error updating local database on completion: " + err.Error()) 827 internal.Log("Error updating local database on quit: " + err.Error())
819 } 828 }
820 829
821 // Update Anilist progress if not rewatching 830 // Update Anilist progress if not rewatching
822 if !anime.Rewatching { 831 if !anime.Rewatching {
823 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil { 832 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
824 internal.Log("Error updating Anilist progress on completion: " + progressErr.Error()) 833 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error())
825 } else { 834 } else {
826 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number)) 835 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
827 } 836 }
828 } 837 }
829 838
830 internal.Log("Episode completed, updated progress, exiting monitoring to let CLI prompt handle next episode") 839 internal.ExitCurd(nil)
840 }
841 } else {
842 // For CLI mode, update progress immediately since episode is 85%+ complete
843 // Update local database with completed episode
844 err := internal.LocalUpdateAnime(databaseFile, anime.AnilistId, anime.ProviderId, anime.Ep.Number, anime.Ep.Player.PlaybackTime, internal.ConvertSecondsToMinutes(anime.Ep.Duration), internal.GetAnimeName(anime), internal.GetProvider().Name())
845 if err != nil {
846 internal.Log("Error updating local database on completion: " + err.Error())
831 } 847 }
832 // Exit the skip loop - only close if not already closed 848
833 select { 849 // Update Anilist progress if not rewatching
834 case isClosed := <-skipLoopClosed: 850 if !anime.Rewatching {
835 if !isClosed { 851 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
836 close(skipLoopDone) 852 internal.Log("Error updating Anilist progress on completion: " + progressErr.Error())
837 skipLoopClosed <- true // Mark as closed 853 } else {
854 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
838 } 855 }
839 default:
840 // Channel is busy, another goroutine is handling closure
841 } 856 }
842 return 857
858 internal.Log("Episode completed, updated progress, exiting monitoring to let CLI prompt handle next episode")
843 } 859 }
844 } else { 860 // Exit the skip loop - only close if not already closed
845 internal.Log("Episode is not completed, exiting") 861 select {
846 internal.ExitCurd(nil) 862 case isClosed := <-skipLoopClosed:
863 if !isClosed {
864 close(skipLoopDone)
865 skipLoopClosed <- true // Mark as closed
866 }
867 default:
868 // Channel is busy, another goroutine is handling closure
869 }
870 return
847 } 871 }
848 // Exit the skip loop - only close if not already closed 872 // Exit the skip loop - only close if not already closed
849 select { 873 select {
internal/localTracking.go +16 −9
@@ -545,19 +545,25 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
545 545
546 if anime.Ep.Started { 546 if anime.Ep.Started {
547 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration) 547 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
548 Log(fmt.Sprint(percentageWatched)) 548 action := ClassifyPlaybackLoss(
549 Log(fmt.Sprint(anime.Ep.Player.PlaybackTime)) 549 anime.Ep.Player.SocketPath,
550 Log(fmt.Sprint(anime.Ep.Duration)) 550 anime.Ep.Started,
551 Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete)) 551 percentageWatched,
552 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete { 552 userCurdConfig.PercentageToMarkComplete,
553 )
554 Log(fmt.Sprintf("untracked playback loss: pct=%.1f action=%d", percentageWatched, action))
555 switch action {
556 case PlaybackLossWait:
557 time.Sleep(200 * time.Millisecond)
558 continue
559 case PlaybackLossComplete:
553 anime.Ep.Number++ 560 anime.Ep.Number++
554 anime.Ep.Started = false 561 anime.Ep.Started = false
555 Log("Completed episode, starting next.") 562 Log("Completed episode, starting next.")
556 anime.Ep.IsCompleted = true 563 anime.Ep.IsCompleted = true
557 break 564 // Break the playback monitor loop (not just the switch).
558 } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" { 565 goto nextUntrackedEpisode
559 Log("Received invalid JSON response, continuing...") 566 case PlaybackLossExit:
560 } else {
561 Log("Episode is not completed, exiting") 567 Log("Episode is not completed, exiting")
562 ExitCurd(nil) 568 ExitCurd(nil)
563 } 569 }
@@ -616,6 +622,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
616 } 622 }
617 time.Sleep(1 * time.Second) 623 time.Sleep(1 * time.Second)
618 } 624 }
625 nextUntrackedEpisode:
619 } 626 }
620 627
621} 628}
internal/mpv_playlist.go +1109 −161
@@ -2,15 +2,53 @@ package internal
2 2
3import ( 3import (
4 "fmt" 4 "fmt"
5 "os"
6 "path/filepath"
7 "regexp"
8 "sort"
9 "strconv"
5 "strings" 10 "strings"
6 "sync" 11 "sync"
7 "sync/atomic" 12 "sync/atomic"
8 "time" 13 "time"
9) 14)
10 15
11// Placeholder media for non-current playlist rows. Short black frame so idle 16// Matches "Episode 12" / "Ep 12" in MPV playlist titles we set.
12// playlist construction never pulls real streams; on select we replace immediately. 17var playlistEpisodeTitleRE = regexp.MustCompile(`(?i)\b(?:episode|ep)\s*(\d+)\b`)
13const mpvEpisodePlaceholder = "av://lavfi:color=c=0x101010:s=16x16:d=1" 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}
14 52
15const ( 53const (
16 mpvPlaylistIdleDelay = 3 * time.Second 54 mpvPlaylistIdleDelay = 3 * time.Second
@@ -18,6 +56,24 @@ const (
18 mpvPlaylistStableSamples = 3 56 mpvPlaylistStableSamples = 3
19) 57)
20 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
21// playlistSlot maps an MPV playlist index to curd episode + audio mode. 77// playlistSlot maps an MPV playlist index to curd episode + audio mode.
22type playlistSlot struct { 78type playlistSlot struct {
23 Episode int 79 Episode int
@@ -28,6 +84,9 @@ type playlistSlot struct {
28// MPVPlaylistController maintains a seamless MPV playlist of episodes (and 84// MPVPlaylistController maintains a seamless MPV playlist of episodes (and
29// optional alternate audio entry) without interrupting active playback while 85// optional alternate audio entry) without interrupting active playback while
30// it is being built. Population happens only after playback is idle/stable. 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.
31type MPVPlaylistController struct { 90type MPVPlaylistController struct {
32 config *CurdConfig 91 config *CurdConfig
33 anime *Anime 92 anime *Anime
@@ -44,6 +103,7 @@ type MPVPlaylistController struct {
44 alternateMode string 103 alternateMode string
45 currentPlaying int // episode number currently intended 104 currentPlaying int // episode number currently intended
46 currentMode string 105 currentMode string
106 episodeNums []int // provider episode list (sorted), preferred mode
47} 107}
48 108
49// StartMPVPlaylistController waits until playback is stable, then builds the 109// StartMPVPlaylistController waits until playback is stable, then builds the
@@ -94,20 +154,20 @@ func (c *MPVPlaylistController) run() {
94 } 154 }
95 155
96 // Build episode rows without touching the currently playing demuxer path 156 // Build episode rows without touching the currently playing demuxer path
97 // beyond append/insert of placeholders. 157 // beyond append/insert of titled placeholders (one EpisodesList fetch).
98 if err := c.buildEpisodePlaylist(); err != nil { 158 if err := c.buildEpisodePlaylist(); err != nil {
99 Log(fmt.Sprintf("MPV playlist build failed: %v", err)) 159 Log(fmt.Sprintf("MPV playlist build failed: %v", err))
100 // Still watch in case a partial list exists. 160 // Still watch in case a partial list exists.
101 } else { 161 } else {
102 c.built = true 162 c.built = true
103 Log("MPV episode playlist ready") 163 Log(fmt.Sprintf("MPV episode playlist ready (%d episodes)", len(c.episodeNums)))
104 } 164 }
105 165
106 if c.closed() { 166 if c.closed() {
107 return 167 return
108 } 168 }
109 169
110 // Probe alternate audio only after the list is up — never blocks first frame. 170 // Probe alternate audio only for the *current* episode — never blocks first frame.
111 c.probeAndAttachAlternateAudio() 171 c.probeAndAttachAlternateAudio()
112 172
113 c.watchPlaylistSelection() 173 c.watchPlaylistSelection()
@@ -149,36 +209,88 @@ func (c *MPVPlaylistController) waitUntilIdleStable() bool {
149 return false 209 return false
150} 210}
151 211
152func (c *MPVPlaylistController) totalEpisodes() int { 212// fetchEpisodeNumbers loads the full episode number list from the provider in one
153 if c.anime.TotalEpisodes > 0 { 213// shot via EpisodesList. Never resolves per-episode streams (avoids 429s).
154 return c.anime.TotalEpisodes 214func (c *MPVPlaylistController) fetchEpisodeNumbers() []int {
155 }
156 providerName, providerID := AnimeProviderID(c.anime) 215 providerName, providerID := AnimeProviderID(c.anime)
157 if providerID == "" { 216 if providerID != "" {
158 return 0 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 }
159 } 235 }
160 total, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), c.preferredMode) 236 if total <= 0 {
161 if err != nil || total <= 0 { 237 return nil
162 return 0 238 }
239 nums := make([]int, 0, total)
240 for ep := 1; ep <= total; ep++ {
241 nums = append(nums, ep)
163 } 242 }
164 c.anime.TotalEpisodes = total 243 return nums
165 return total 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
166} 276}
167 277
168func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string { 278func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string {
169 name := GetAnimeName(*c.anime) 279 name := strings.TrimSpace(GetAnimeName(*c.anime))
170 base := fmt.Sprintf("Ep %02d", ep) 280 base := fmt.Sprintf("Episode %d", ep)
171 if name != "" { 281 if name != "" {
172 base = fmt.Sprintf("%s · Ep %02d", name, ep) 282 base = fmt.Sprintf("%s - Episode %d", name, ep)
173 } 283 }
174 if c.anime.FillerEpisodes != nil && IsEpisodeFiller(c.anime.FillerEpisodes, ep) { 284 if c.anime.FillerEpisodes != nil && IsEpisodeFiller(c.anime.FillerEpisodes, ep) {
175 base += " [Filler]" 285 base += " [Filler]"
176 } 286 }
177 mode = normalizeTranslationType(mode) 287 mode = normalizeTranslationType(mode)
178 if mode != "" && mode != c.preferredMode { 288 if mode != "" && mode != c.preferredMode {
179 base += " · " + strings.ToUpper(mode) 289 base += " (" + strings.ToUpper(mode) + ")"
290 } else if mode == "dub" && c.preferredMode == "dub" {
291 // Preferred is dub — no extra tag on every row
180 } else if mode == "dub" { 292 } else if mode == "dub" {
181 base += " · DUB" 293 base += " (DUB)"
182 } 294 }
183 if ep == c.currentPlaying && mode == c.currentMode { 295 if ep == c.currentPlaying && mode == c.currentMode {
184 base += " ◀" 296 base += " ◀"
@@ -187,105 +299,191 @@ func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string {
187} 299}
188 300
189func (c *MPVPlaylistController) buildEpisodePlaylist() error { 301func (c *MPVPlaylistController) buildEpisodePlaylist() error {
190 total := c.totalEpisodes() 302 episodes := c.fetchEpisodeNumbers()
191 if total <= 0 { 303 if len(episodes) == 0 {
192 return fmt.Errorf("unknown total episode count") 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
193 } 309 }
310
194 currentEp := c.anime.Ep.Number 311 currentEp := c.anime.Ep.Number
195 if currentEp < 1 { 312 if currentEp < 1 {
196 currentEp = 1 313 currentEp = episodes[0]
197 } 314 }
198 if currentEp > total { 315 // Ensure current episode is in the list (AniList progress may point at an ep
199 currentEp = total 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
200 } 321 }
201 322
202 c.suppress.Store(true) 323 c.suppress.Store(true)
203 defer c.suppress.Store(false) 324 defer c.suppress.Store(false)
204 325
205 // Title the currently playing item (index 0). 326 // Prefer title display in the playlist OSD when mpv supports it.
206 _ = c.setPlaylistTitle(0, c.episodeLabel(currentEp, c.currentMode)) 327 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "osd-playlist-entry", "title"})
207 328
208 // Insert previous episodes at the front (shifts current down). 329 // Title the currently playing item (force-media-title sticks for the active entry).
209 for ep := currentEp - 1; ep >= 1; ep-- { 330 curLabel := c.episodeLabel(currentEp, c.currentMode)
210 if c.closed() { 331 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", curLabel})
211 return nil 332 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", curLabel})
212 } 333
213 if err := c.insertPlaceholderAt(0, ep, c.preferredMode); err != nil { 334 var before, after []playlistSlot
214 Log(fmt.Sprintf("playlist insert ep %d: %v", ep, err)) 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 })
215 } 348 }
216 // Tiny yield so IPC is not flooded mid-watch.
217 time.Sleep(30 * time.Millisecond)
218 } 349 }
219 350
220 // Append future episodes. 351 // Future episodes: one M3U loadlist append (titled placeholders, no stream probes).
221 for ep := currentEp + 1; ep <= total; ep++ { 352 if len(after) > 0 {
222 if c.closed() { 353 if err := c.loadTitledPlaceholders(after, false); err != nil {
223 return nil 354 Log(fmt.Sprintf("playlist append future: %v", err))
224 }
225 if err := c.appendPlaceholder(ep, c.preferredMode); err != nil {
226 Log(fmt.Sprintf("playlist append ep %d: %v", ep, err))
227 } 355 }
228 time.Sleep(30 * time.Millisecond)
229 } 356 }
230 357
231 // Rebuild slot map: index i => episode i+1 (preferred mode). 358 // Previous episodes: append via M3U then playlist-move to the front.
232 slots := make([]playlistSlot, 0, total) 359 if len(before) > 0 {
233 for ep := 1; ep <= total; ep++ { 360 if err := c.loadTitledPlaceholders(before, true); err != nil {
234 slots = append(slots, playlistSlot{ 361 Log(fmt.Sprintf("playlist insert previous: %v", err))
235 Episode: ep, 362 }
236 Mode: c.preferredMode,
237 Label: c.episodeLabel(ep, c.preferredMode),
238 })
239 } 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
240 c.mu.Lock() 375 c.mu.Lock()
241 c.slots = slots 376 c.slots = slots
242 c.currentPlaying = currentEp 377 c.currentPlaying = currentEp
243 c.mu.Unlock() 378 c.mu.Unlock()
244 379
245 // Ensure MPV is still on the current episode index without forcing a reload 380 wantPos := len(before)
246 // when already correct.
247 wantPos := currentEp - 1
248 if pos, err := c.playlistPos(); err == nil && pos != wantPos {
249 // Setting playlist-pos would reload — only do it if we drifted.
250 // After inserts, mpv usually keeps the playing entry selected.
251 Log(fmt.Sprintf("MPV playlist-pos=%d want=%d (leaving as-is to avoid stutter)", pos, wantPos))
252 }
253 c.lastPos = wantPos 381 c.lastPos = wantPos
254 if pos, err := c.playlistPos(); err == nil { 382 if pos, err := c.playlistPos(); err == nil {
255 c.lastPos = pos 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 }
256 } 387 }
257 return nil 388 return nil
258} 389}
259 390
260func (c *MPVPlaylistController) insertPlaceholderAt(index, ep int, mode string) error { 391// loadTitledPlaceholders writes a temp M3U with #EXTINF titles and loadlists it.
261 // loadfile <url> insert-at <index> 392// If moveToFront is true, entries are moved to the start of the playlist (preserving order).
262 _, err := MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "insert-at", index}) 393func (c *MPVPlaylistController) loadTitledPlaceholders(slots []playlistSlot, moveToFront bool) error {
394 if len(slots) == 0 {
395 return nil
396 }
397 path, err := c.writePlaceholderM3U(slots)
263 if err != nil { 398 if err != nil {
264 // Older mpv: fall back to append (order less perfect but non-fatal). 399 return err
265 _, err = MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "append"}) 400 }
266 if err != nil { 401 defer func() { _ = os.Remove(path) }()
267 return err 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))
268 } 429 }
269 } 430 }
270 return c.setPlaylistTitle(index, c.episodeLabel(ep, mode)) 431 return nil
271} 432}
272 433
273func (c *MPVPlaylistController) appendPlaceholder(ep int, mode string) error { 434func (c *MPVPlaylistController) writePlaceholderM3U(slots []playlistSlot) (string, error) {
274 _, err := MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "append"}) 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")
275 if err != nil { 441 if err != nil {
276 return err 442 return "", err
277 } 443 }
278 count, err := c.playlistCount() 444 path := f.Name()
279 if err != nil || count <= 0 { 445
280 return err 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')
281 } 456 }
282 return c.setPlaylistTitle(count-1, c.episodeLabel(ep, mode)) 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
283} 467}
284 468
285func (c *MPVPlaylistController) setPlaylistTitle(index int, title string) error { 469// sanitizeM3UTitle keeps #EXTINF titles single-line and free of control chars.
286 // mpv property: playlist/N/title 470func sanitizeM3UTitle(title string) string {
287 _, err := MPVSendCommand(c.socket, []interface{}{"set_property", fmt.Sprintf("playlist/%d/title", index), title}) 471 title = strings.ReplaceAll(title, "\r", " ")
288 return err 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
289} 487}
290 488
291func (c *MPVPlaylistController) playlistPos() (int, error) { 489func (c *MPVPlaylistController) playlistPos() (int, error) {
@@ -305,8 +503,7 @@ func (c *MPVPlaylistController) playlistCount() (int, error) {
305} 503}
306 504
307// probeAndAttachAlternateAudio checks whether the opposite sub/dub mode has a 505// probeAndAttachAlternateAudio checks whether the opposite sub/dub mode has a
308// stream for the *current* episode. If yes, inserts a playlist row so the user 506// stream for the *current* episode only (one resolve — not every episode).
309// can switch audio by selecting it (full stream reload — only when chosen).
310func (c *MPVPlaylistController) probeAndAttachAlternateAudio() { 507func (c *MPVPlaylistController) probeAndAttachAlternateAudio() {
311 if c.closed() || c.anime == nil { 508 if c.closed() || c.anime == nil {
312 return 509 return
@@ -327,43 +524,66 @@ func (c *MPVPlaylistController) probeAndAttachAlternateAudio() {
327 c.suppress.Store(true) 524 c.suppress.Store(true)
328 defer c.suppress.Store(false) 525 defer c.suppress.Store(false)
329 526
330 // Insert alternate entry right after the current episode index.
331 c.mu.Lock() 527 c.mu.Lock()
332 curIdx := c.currentPlaying - 1 528 curIdx := c.episodeIndexLocked(c.currentPlaying, c.currentMode)
333 if curIdx < 0 { 529 if curIdx < 0 {
334 curIdx = 0 530 curIdx = 0
335 } 531 }
336 label := c.episodeLabel(c.currentPlaying, alt) 532 label := c.episodeLabel(c.currentPlaying, alt)
337 // Physical insert in mpv
338 insertAt := curIdx + 1 533 insertAt := curIdx + 1
339 c.mu.Unlock() 534 c.mu.Unlock()
340 535
341 if _, err := MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "insert-at", insertAt}); err != nil { 536 slot := playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label}
342 // Fallback append 537 if err := c.insertTitledPlaceholderAt(insertAt, slot); err != nil {
343 if err := c.appendPlaceholder(c.currentPlaying, alt); err != nil { 538 Log(fmt.Sprintf("MPV playlist: failed to add %s entry: %v", alt, err))
344 Log(fmt.Sprintf("MPV playlist: failed to add %s entry: %v", alt, err))
345 return
346 }
347 c.mu.Lock()
348 c.slots = append(c.slots, playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label})
349 c.mu.Unlock()
350 return 539 return
351 } 540 }
352 _ = c.setPlaylistTitle(insertAt, label)
353 541
354 c.mu.Lock() 542 c.mu.Lock()
355 // Insert into slots map at insertAt
356 if insertAt >= len(c.slots) { 543 if insertAt >= len(c.slots) {
357 c.slots = append(c.slots, playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label}) 544 c.slots = append(c.slots, slot)
358 } else { 545 } else {
359 slot := playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label}
360 c.slots = append(c.slots[:insertAt], append([]playlistSlot{slot}, c.slots[insertAt:]...)...) 546 c.slots = append(c.slots[:insertAt], append([]playlistSlot{slot}, c.slots[insertAt:]...)...)
361 } 547 }
362 c.mu.Unlock() 548 c.mu.Unlock()
363 Log(fmt.Sprintf("MPV playlist: added %s option for ep %d", alt, c.currentPlaying)) 549 Log(fmt.Sprintf("MPV playlist: added %s option for ep %d", alt, c.currentPlaying))
364} 550}
365 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
366func (c *MPVPlaylistController) watchPlaylistSelection() { 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
367 for { 587 for {
368 if c.closed() { 588 if c.closed() {
369 return 589 return
@@ -371,62 +591,532 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
371 if !IsMPVRunning(c.socket) { 591 if !IsMPVRunning(c.socket) {
372 return 592 return
373 } 593 }
374 if c.suppress.Load() { 594 if c.suppress.Load() || MPVPlaylistIsSwitching() {
375 time.Sleep(mpvPlaylistPollInterval) 595 time.Sleep(poll)
376 continue 596 continue
377 } 597 }
378 pos, err := c.playlistPos() 598
379 if err != nil { 599 path := mpvStringProperty(c.socket, "path")
380 time.Sleep(mpvPlaylistPollInterval) 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")
381 continue 640 continue
382 } 641 }
383 if pos < 0 { 642
384 time.Sleep(mpvPlaylistPollInterval) 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")
385 continue 694 continue
386 } 695 }
387 if pos == c.lastPos { 696
388 time.Sleep(mpvPlaylistPollInterval) 697 if path != "" {
389 continue 698 lastSeenPath = path
390 } 699 }
391 // Debounce rapid scrubbing through the playlist UI. 700 time.Sleep(poll)
392 time.Sleep(200 * time.Millisecond) 701 }
393 pos2, err2 := c.playlistPos() 702}
394 if err2 != nil || pos2 != pos { 703
395 continue 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
396 } 723 }
397 c.lastPos = pos 724 action, pErr := promptPlaylistEpisodeLeave(curEp, slot.Episode, pct, threshold)
398 c.handlePlaylistJump(pos) 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
399 } 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 }()
400} 769}
401 770
402func (c *MPVPlaylistController) handlePlaylistJump(pos int) { 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
403 c.mu.Lock() 881 c.mu.Lock()
882 defer c.mu.Unlock()
404 if pos < 0 || pos >= len(c.slots) { 883 if pos < 0 || pos >= len(c.slots) {
405 c.mu.Unlock() 884 return playlistSlot{}, fmt.Errorf("playlist pos %d out of range (slots=%d)", pos, len(c.slots))
406 return
407 } 885 }
408 slot := c.slots[pos] 886 slot := c.slots[pos]
409 curEp, curMode := c.currentPlaying, c.currentMode 887 Log(fmt.Sprintf("MPV playlist: pos %d slots fallback → ep %d", pos, slot.Episode))
410 c.mu.Unlock() 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
411 937
412 if slot.Episode == curEp && normalizeTranslationType(slot.Mode) == normalizeTranslationType(curMode) { 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()
413 return 949 return
414 } 950 }
415 951
416 Log(fmt.Sprintf("MPV playlist: user selected ep %d (%s) at index %d", slot.Episode, slot.Mode, pos)) 952 c.handlePlaylistJumpSlot(slot, curEp)
417 if err := c.playSlot(slot); err != nil { 953}
418 Log(fmt.Sprintf("MPV playlist: failed to play ep %d: %v", slot.Episode, err)) 954
419 CurdOut(fmt.Sprintf("Could not play episode %d: %v", slot.Episode, err)) 955// finalizePlaylistEpisodeChange updates local history, last-played id, episode
420 // Try to restore previous playlist position without thrashing. 956// metadata, optional remote progress, and prefetches the next episode.
421 c.suppress.Store(true) 957func (c *MPVPlaylistController) finalizePlaylistEpisodeChange(fromEp, toEp int, mode string, leave playlistLeaveAction) {
422 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "playlist-pos", c.episodeIndex(curEp, curMode)}) 958 if c.anime == nil || c.config == nil {
423 c.suppress.Store(false) 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))
424 } 1084 }
425} 1085}
426 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
427func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int { 1113func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int {
428 c.mu.Lock() 1114 c.mu.Lock()
429 defer c.mu.Unlock() 1115 defer c.mu.Unlock()
1116 return c.episodeIndexLocked(ep, mode)
1117}
1118
1119func (c *MPVPlaylistController) episodeIndexLocked(ep int, mode string) int {
430 mode = normalizeTranslationType(mode) 1120 mode = normalizeTranslationType(mode)
431 for i, s := range c.slots { 1121 for i, s := range c.slots {
432 if s.Episode == ep && normalizeTranslationType(s.Mode) == mode { 1122 if s.Episode == ep && normalizeTranslationType(s.Mode) == mode {
@@ -446,6 +1136,9 @@ func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int {
446} 1136}
447 1137
448func (c *MPVPlaylistController) playSlot(slot playlistSlot) error { 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).
449 c.suppress.Store(true) 1142 c.suppress.Store(true)
450 defer c.suppress.Store(false) 1143 defer c.suppress.Store(false)
451 1144
@@ -457,16 +1150,34 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
457 cfg := *c.config 1150 cfg := *c.config
458 cfg.SubOrDub = mode 1151 cfg.SubOrDub = mode
459 1152
460 // Work on a shallow copy for provider id resolution side effects, then copy back.
461 anime := c.anime 1153 anime := c.anime
462 prevEp := anime.Ep.Number 1154 prevEp := anime.Ep.Number
463 anime.Ep.Number = slot.Episode 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")
464 1174
465 result, err := ResolveEpisodeURLForPlayback(cfg, anime, slot.Episode) 1175 // Preferred mode only — no nested DynamicSelect prompts from this goroutine.
1176 result, err := ResolveEpisodeURL(cfg, anime, targetEp)
466 if err != nil || len(result.Links) == 0 { 1177 if err != nil || len(result.Links) == 0 {
467 anime.Ep.Number = prevEp 1178 anime.Ep.Number = prevEp
468 if err == nil { 1179 if err == nil {
469 err = fmt.Errorf("no streams") 1180 err = fmt.Errorf("no streams for episode %d", targetEp)
470 } 1181 }
471 return err 1182 return err
472 } 1183 }
@@ -476,29 +1187,86 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
476 link := PrioritizeLink(result.Links) 1187 link := PrioritizeLink(result.Links)
477 if link == "" { 1188 if link == "" {
478 anime.Ep.Number = prevEp 1189 anime.Ep.Number = prevEp
479 return fmt.Errorf("empty stream link") 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) + ")"
480 } 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)))
481 1204
482 title := c.episodeLabel(slot.Episode, mode)
483 // Reuse running MPV instance — loadfile replace is the intentional user switch.
484 anime.Ep.Player.SocketPath = c.socket 1205 anime.Ep.Player.SocketPath = c.socket
485 if _, err := StartVideo(link, []string{}, title, anime); err != nil { 1206 if err := loadEpisodeInRunningMPV(c.socket, link, title, anime); err != nil {
486 anime.Ep.Number = prevEp 1207 anime.Ep.Number = prevEp
487 return err 1208 return err
488 } 1209 }
489 1210
490 anime.Ep.Number = slot.Episode 1211 // Wait until path actually changes away from the old media (not just time-pos).
491 anime.Ep.Started = false 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
492 anime.Ep.IsCompleted = false 1225 anime.Ep.IsCompleted = false
493 anime.Ep.Player.PlaybackTime = 0 1226 anime.Ep.Player.PlaybackTime = 0
494 anime.Ep.Duration = 0 1227 anime.Ep.Duration = 0
495 anime.Ep.SkipTimes = SkipTimes{} 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)
496 1256
497 c.mu.Lock() 1257 c.mu.Lock()
498 c.currentPlaying = slot.Episode 1258 c.currentPlaying = targetEp
499 c.currentMode = mode 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
500 c.mu.Unlock() 1265 c.mu.Unlock()
501 1266
1267 // Stream is live — safe for the main loop again.
1268 endMPVPlaylistSwitch()
1269
502 // Refresh skip times in background (non-blocking for playback). 1270 // Refresh skip times in background (non-blocking for playback).
503 go func(ep int) { 1271 go func(ep int) {
504 if c.anime.MalId > 0 { 1272 if c.anime.MalId > 0 {
@@ -510,38 +1278,218 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
510 _ = SendSkipTimesToMPV(c.anime) 1278 _ = SendSkipTimesToMPV(c.anime)
511 } 1279 }
512 } 1280 }
513 }(slot.Episode) 1281 }(targetEp)
514 1282
515 // Rebuild playlist markers after a short idle (titles ◀ indicator, alternate audio). 1283 // Re-probe alternate for the new episode only after placeholders are rebuilt.
516 go func() { 1284 go func() {
517 time.Sleep(mpvPlaylistIdleDelay) 1285 time.Sleep(mpvPlaylistIdleDelay + time.Second)
518 if c.closed() { 1286 if c.closed() || alreadyAlt {
519 return 1287 return
520 } 1288 }
521 // Soft retitle only — avoid full playlist rebuild (would stutter).
522 c.retitleSlots()
523 // Re-probe alternate for the new episode.
524 c.hasAlternate = false 1289 c.hasAlternate = false
525 c.probeAndAttachAlternateAudio() 1290 c.probeAndAttachAlternateAudio()
526 }() 1291 }()
527 1292
528 CurdOut(fmt.Sprintf("Playing episode %d (%s)", slot.Episode, mode)) 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 }
529 return nil 1337 return nil
530} 1338}
531 1339
532func (c *MPVPlaylistController) retitleSlots() { 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
533 c.suppress.Store(true) 1452 c.suppress.Store(true)
534 defer c.suppress.Store(false) 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
535 c.mu.Lock() 1487 c.mu.Lock()
536 slots := append([]playlistSlot(nil), c.slots...) 1488 c.slots = slots
537 curEp, curMode := c.currentPlaying, c.currentMode 1489 c.lastPos = len(before)
538 c.mu.Unlock() 1490 c.mu.Unlock()
539 for i, s := range slots { 1491
540 label := c.episodeLabel(s.Episode, s.Mode) 1492 Log(fmt.Sprintf("MPV playlist rebuilt around ep %d (%d entries)", currentEp, len(slots)))
541 // episodeLabel uses c.currentPlaying for ◀ marker 1493 return nil
542 _ = curEp
543 _ = curMode
544 _ = c.setPlaylistTitle(i, label)
545 time.Sleep(15 * time.Millisecond)
546 }
547} 1494}
1495
internal/mpv_playlist_test.go +354 −1
@@ -1,6 +1,10 @@
1package internal 1package internal
2 2
3import ( 3import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "strconv"
4 "strings" 8 "strings"
5 "testing" 9 "testing"
6) 10)
@@ -17,9 +21,12 @@ func TestEpisodeLabelMarksCurrentAndFiller(t *testing.T) {
17 currentMode: "sub", 21 currentMode: "sub",
18 } 22 }
19 label := c.episodeLabel(2, "sub") 23 label := c.episodeLabel(2, "sub")
20 if !strings.Contains(label, "Ep 02") || !strings.Contains(label, "◀") { 24 if !strings.Contains(label, "Episode 2") || !strings.Contains(label, "◀") {
21 t.Fatalf("current ep label: %q", label) 25 t.Fatalf("current ep label: %q", label)
22 } 26 }
27 if !strings.Contains(label, "Demo") {
28 t.Fatalf("expected show name in label: %q", label)
29 }
23 filler := c.episodeLabel(3, "sub") 30 filler := c.episodeLabel(3, "sub")
24 if !strings.Contains(filler, "Filler") { 31 if !strings.Contains(filler, "Filler") {
25 t.Fatalf("expected filler mark, got %q", filler) 32 t.Fatalf("expected filler mark, got %q", filler)
@@ -28,6 +35,13 @@ func TestEpisodeLabelMarksCurrentAndFiller(t *testing.T) {
28 if !strings.Contains(strings.ToUpper(dub), "DUB") { 35 if !strings.Contains(strings.ToUpper(dub), "DUB") {
29 t.Fatalf("expected dub mark, got %q", dub) 36 t.Fatalf("expected dub mark, got %q", dub)
30 } 37 }
38 // Preferred dub should not spam DUB on every preferred row.
39 c.preferredMode = "dub"
40 c.currentMode = "dub"
41 preferredDub := c.episodeLabel(1, "dub")
42 if strings.Contains(preferredDub, "(DUB)") {
43 t.Fatalf("preferred dub row should not add (DUB): %q", preferredDub)
44 }
31} 45}
32 46
33func TestEpisodeIndexFindsAlternateModeSlot(t *testing.T) { 47func TestEpisodeIndexFindsAlternateModeSlot(t *testing.T) {
@@ -58,3 +72,342 @@ func TestIsEpisodeFillerHelper(t *testing.T) {
58 t.Fatal("expected non-filler") 72 t.Fatal("expected non-filler")
59 } 73 }
60} 74}
75
76func TestParseEpisodeNumberListDedupesAndSorts(t *testing.T) {
77 got := parseEpisodeNumberList([]string{"3", "1", "2", "2", " 12.0 ", "bad", "0", "-1"})
78 want := []int{1, 2, 3, 12}
79 if len(got) != len(want) {
80 t.Fatalf("got %v want %v", got, want)
81 }
82 for i := range want {
83 if got[i] != want[i] {
84 t.Fatalf("got %v want %v", got, want)
85 }
86 }
87}
88
89func TestWritePlaceholderM3UHasEXTINFTitles(t *testing.T) {
90 c := &MPVPlaylistController{
91 config: &CurdConfig{StoragePath: t.TempDir()},
92 anime: &Anime{Title: AnimeTitle{English: "Demo"}},
93 }
94 slots := []playlistSlot{
95 {Episode: 1, Mode: "sub", Label: "Demo - Episode 1"},
96 {Episode: 2, Mode: "sub", Label: "Demo - Episode 2 [Filler]"},
97 }
98 path, err := c.writePlaceholderM3U(slots)
99 if err != nil {
100 t.Fatal(err)
101 }
102 defer os.Remove(path)
103
104 raw, err := os.ReadFile(path)
105 if err != nil {
106 t.Fatal(err)
107 }
108 body := string(raw)
109 if !strings.HasPrefix(body, "#EXTM3U\n") {
110 t.Fatalf("missing EXTM3U header: %q", body)
111 }
112 if !strings.Contains(body, "#EXTINF:-1,Demo - Episode 1\n") {
113 t.Fatalf("missing titled entry 1: %q", body)
114 }
115 if !strings.Contains(body, "#EXTINF:-1,Demo - Episode 2 [Filler]\n") {
116 t.Fatalf("missing titled entry 2: %q", body)
117 }
118 if !strings.Contains(body, placeholderURL(1)) || !strings.Contains(body, placeholderURL(2)) {
119 t.Fatalf("missing unique placeholder urls: %q", body)
120 }
121 // Must not leave bare lavfi as the only human-visible line without EXTINF.
122 lines := strings.Split(strings.TrimSpace(body), "\n")
123 for i, line := range lines {
124 if strings.HasPrefix(line, "av://") && i > 0 && !strings.HasPrefix(lines[i-1], "#EXTINF:") {
125 t.Fatalf("placeholder without preceding EXTINF at line %d", i)
126 }
127 }
128}
129
130func TestSanitizeM3UTitleStripsNewlines(t *testing.T) {
131 got := sanitizeM3UTitle("Foo\nBar\rBaz")
132 if strings.ContainsAny(got, "\n\r") {
133 t.Fatalf("newlines remain: %q", got)
134 }
135 if got == "" {
136 t.Fatal("empty after sanitize")
137 }
138}
139
140func TestMPVPlaylistSwitchingFlag(t *testing.T) {
141 endMPVPlaylistSwitch()
142 if MPVPlaylistIsSwitching() {
143 t.Fatal("expected switch flag clear")
144 }
145 beginMPVPlaylistSwitch()
146 if !MPVPlaylistIsSwitching() {
147 t.Fatal("expected switch flag set")
148 }
149 endMPVPlaylistSwitch()
150 if MPVPlaylistIsSwitching() {
151 t.Fatal("expected switch flag clear after end")
152 }
153}
154
155func TestClassifyPlaybackLossDoesNotExitWhileMPVAlive(t *testing.T) {
156 endMPVPlaylistSwitch()
157 // Incomplete watch + empty socket (IsMPVRunning false) → exit
158 if got := ClassifyPlaybackLoss("", true, 11, 85); got != PlaybackLossExit {
159 t.Fatalf("empty socket incomplete: got %d want Exit", got)
160 }
161 // Complete threshold → complete regardless of socket
162 if got := ClassifyPlaybackLoss("", true, 90, 85); got != PlaybackLossComplete {
163 t.Fatalf("complete: got %d want Complete", got)
164 }
165 // Switching flag forces wait
166 beginMPVPlaylistSwitch()
167 if got := ClassifyPlaybackLoss("", true, 11, 85); got != PlaybackLossWait {
168 t.Fatalf("switching: got %d want Wait", got)
169 }
170 endMPVPlaylistSwitch()
171 // Not started → wait
172 if got := ClassifyPlaybackLoss("", false, 0, 85); got != PlaybackLossWait {
173 t.Fatalf("not started: got %d want Wait", got)
174 }
175}
176
177func TestPlaceholderIsLongLivedAndUniquePerEpisode(t *testing.T) {
178 a := placeholderURL(39)
179 b := placeholderURL(40)
180 if a == b {
181 t.Fatal("placeholder URLs must differ per episode")
182 }
183 if !strings.Contains(a, "d=86400") {
184 t.Fatalf("placeholder should be long-lived: %q", a)
185 }
186 // Fragments break lavfi in mpv — ensure we never emit them.
187 if strings.Contains(a, "#") {
188 t.Fatalf("must not use URL fragments: %q", a)
189 }
190 for _, ep := range []int{1, 39, 40, 366, 1000} {
191 url := placeholderURL(ep)
192 got, ok := parseEpisodeFromPlaceholder(url)
193 if !ok || got != ep {
194 t.Fatalf("ep %d: url=%q parsed=%d ok=%v", ep, url, got, ok)
195 }
196 }
197}
198
199func TestPromptPlaylistPlusOneAutoNoMenu(t *testing.T) {
200 prev := promptSelectOrdered
201 t.Cleanup(func() { promptSelectOrdered = prev })
202 called := false
203 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
204 called = true
205 return options[0], nil
206 }
207
208 // +1 early → no remote mark, no menu
209 action, err := defaultPromptPlaylistEpisodeLeave(40, 41, 11, 85)
210 if err != nil {
211 t.Fatal(err)
212 }
213 if action != playlistLeaveNone {
214 t.Fatalf("+1 early → %s want none", action)
215 }
216 if called {
217 t.Fatal("+1 must not open a menu")
218 }
219
220 // +1 nearly done → auto mark left
221 action, err = defaultPromptPlaylistEpisodeLeave(40, 41, 90, 85)
222 if err != nil {
223 t.Fatal(err)
224 }
225 if action != playlistLeaveMarkLeft {
226 t.Fatalf("+1 nearly done → %s want mark", action)
227 }
228}
229
230func TestPromptPlaylistJumpOffersUpstreamOptions(t *testing.T) {
231 prev := promptSelectOrdered
232 t.Cleanup(func() { promptSelectOrdered = prev })
233
234 var keys []string
235 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
236 keys = nil
237 for _, o := range options {
238 keys = append(keys, o.Key)
239 }
240 return options[0], nil
241 }
242
243 action, err := defaultPromptPlaylistEpisodeLeave(40, 39, 11, 85)
244 if err != nil {
245 t.Fatal(err)
246 }
247 if action != playlistLeaveNone { // first option for early jump
248 t.Fatalf("jump early default=%s want none", action)
249 }
250 want := map[string]bool{"none": true, "mark": true, "setwatch": true, "cancel": true}
251 for _, k := range keys {
252 delete(want, k)
253 }
254 if len(want) != 0 {
255 t.Fatalf("missing options %v (got %v)", want, keys)
256 }
257
258 // Nearly done jump leads with mark
259 action, err = defaultPromptPlaylistEpisodeLeave(40, 10, 90, 85)
260 if err != nil {
261 t.Fatal(err)
262 }
263 if action != playlistLeaveMarkLeft {
264 t.Fatalf("jump nearly-done default=%s want mark", action)
265 }
266 if keys[0] != "mark" {
267 t.Fatalf("first option=%s want mark", keys[0])
268 }
269}
270
271func TestPromptPlaylistJumpCancelAndPromptError(t *testing.T) {
272 prev := promptSelectOrdered
273 t.Cleanup(func() { promptSelectOrdered = prev })
274
275 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
276 return SelectionOption{Key: "cancel"}, nil
277 }
278 action, err := defaultPromptPlaylistEpisodeLeave(40, 10, 10, 85)
279 if err != nil {
280 t.Fatal(err)
281 }
282 if action != playlistLeaveCancel {
283 t.Fatalf("cancel → %s", action)
284 }
285
286 promptSelectOrdered = func(options []SelectionOption) (SelectionOption, error) {
287 return SelectionOption{}, fmt.Errorf("tty busy")
288 }
289 action, err = defaultPromptPlaylistEpisodeLeave(40, 10, 10, 85)
290 if err != nil {
291 t.Fatal(err)
292 }
293 if action != playlistLeaveNone {
294 t.Fatalf("prompt error → %s want none (still play target)", action)
295 }
296}
297
298func TestParsePlaylistEpisodeTitle(t *testing.T) {
299 ep, mode, ok := parsePlaylistEpisodeTitle("Bleach - Episode 39", "sub")
300 if !ok || ep != 39 || mode != "sub" {
301 t.Fatalf("got ep=%d mode=%s ok=%v", ep, mode, ok)
302 }
303 ep, mode, ok = parsePlaylistEpisodeTitle("Bleach - Episode 40 (DUB)", "sub")
304 if !ok || ep != 40 || mode != "dub" {
305 t.Fatalf("dub got ep=%d mode=%s ok=%v", ep, mode, ok)
306 }
307 _, _, ok = parsePlaylistEpisodeTitle("av://lavfi:color", "sub")
308 if ok {
309 t.Fatal("lavfi should not parse")
310 }
311}
312
313func TestMediaURLKeyStripsQuery(t *testing.T) {
314 a := mediaURLKey("https://cdn.example/x/playlist.m3u8?token=abc")
315 b := mediaURLKey("https://cdn.example/x/playlist.m3u8?token=xyz")
316 if a != b {
317 t.Fatalf("keys should match without query: %q vs %q", a, b)
318 }
319 if mediaURLKey("https://cdn.example/a/p.m3u8") == mediaURLKey("https://cdn.example/b/p.m3u8") {
320 t.Fatal("different paths should differ")
321 }
322}
323
324func TestEscapeMPVOptionValueQuotes(t *testing.T) {
325 got := escapeMPVOptionValue(`Show - Episode 1`)
326 if !strings.HasPrefix(got, `"`) || !strings.HasSuffix(got, `"`) {
327 t.Fatalf("expected quoted: %q", got)
328 }
329 got = escapeMPVOptionValue(`a"b`)
330 if !strings.Contains(got, `\"`) {
331 t.Fatalf("expected escaped quote: %q", got)
332 }
333}
334
335func TestFinalizePlaylistEpisodeChangeUpdatesLocalHistory(t *testing.T) {
336 dir := t.TempDir()
337 db := filepath.Join(dir, "curd_history.txt")
338 anime := &Anime{
339 AnilistId: 269,
340 ProviderId: "269",
341 ProviderName: "senshi",
342 Title: AnimeTitle{English: "Bleach"},
343 FillerEpisodes: []int{33},
344 Ep: Episode{Number: 40},
345 }
346 c := &MPVPlaylistController{
347 config: &CurdConfig{StoragePath: dir, SubOrDub: "sub"},
348 anime: anime,
349 preferredMode: "sub",
350 socket: "", // skip MPV title commands failures are fine
351 }
352
353 c.finalizePlaylistEpisodeChange(40, 39, "sub", playlistLeaveNone)
354
355 if anime.Ep.Number != 39 {
356 t.Fatalf("episode number=%d want 39", anime.Ep.Number)
357 }
358 if anime.Ep.IsFiller {
359 t.Fatal("ep 39 should not be filler")
360 }
361 // curd_id written
362 idRaw, err := os.ReadFile(filepath.Join(dir, "curd_id"))
363 if err != nil {
364 t.Fatal(err)
365 }
366 if strings.TrimSpace(string(idRaw)) != "269" {
367 t.Fatalf("curd_id=%q", idRaw)
368 }
369 // history row
370 list := LocalGetAllAnime(db)
371 found := LocalFindAnime(list, 269, "269")
372 if found == nil {
373 t.Fatal("expected history entry")
374 }
375 if found.Ep.Number != 39 {
376 t.Fatalf("history ep=%d want 39", found.Ep.Number)
377 }
378 if found.Ep.Player.PlaybackTime != 0 {
379 t.Fatalf("playback time should reset, got %d", found.Ep.Player.PlaybackTime)
380 }
381}
382
383func TestFinalizePlaylistMarksFillerFromList(t *testing.T) {
384 dir := t.TempDir()
385 anime := &Anime{
386 AnilistId: 1,
387 ProviderId: "x",
388 ProviderName: "senshi",
389 Title: AnimeTitle{English: "Demo"},
390 FillerEpisodes: []int{5},
391 Ep: Episode{Number: 1},
392 }
393 c := &MPVPlaylistController{
394 config: &CurdConfig{StoragePath: dir},
395 anime: anime,
396 }
397 c.finalizePlaylistEpisodeChange(1, 5, "sub", playlistLeaveNone)
398 if !anime.Ep.IsFiller {
399 t.Fatal("expected filler flag for ep 5")
400 }
401 // silence unused if LocalGetAllAnime not needed
402 _ = strconv.Itoa(anime.Ep.Number)
403}
404
405func TestLocalHistoryPath(t *testing.T) {
406 if localHistoryPath("") != "" {
407 t.Fatal("empty storage")
408 }
409 got := localHistoryPath("/tmp/curd-test-store")
410 if !strings.HasSuffix(got, "curd_history.txt") {
411 t.Fatalf("got %q", got)
412 }
413}
internal/player.go +142 −40
@@ -1,9 +1,11 @@
1package internal 1package internal
2 2
3import ( 3import (
4 "bufio"
4 "crypto/rand" 5 "crypto/rand"
5 "encoding/json" 6 "encoding/json"
6 "fmt" 7 "fmt"
8 "io"
7 "net/url" 9 "net/url"
8 "os" 10 "os"
9 "os/exec" 11 "os/exec"
@@ -11,11 +13,15 @@ import (
11 "runtime" 13 "runtime"
12 "strings" 14 "strings"
13 "sync" 15 "sync"
16 "sync/atomic"
14 "time" 17 "time"
15 18
16 "github.com/wraient/curd/internal/providers" 19 "github.com/wraient/curd/internal/providers"
17) 20)
18 21
22// Monotonic request id for mpv JSON IPC so we can ignore interleaved events.
23var mpvRequestID atomic.Int64
24
19var logFile = "debug.log" 25var logFile = "debug.log"
20 26
21const mpvPlaybackPollInterval = 500 * time.Millisecond 27const mpvPlaybackPollInterval = 500 * time.Millisecond
@@ -604,6 +610,46 @@ func isMPVConnectionGoneError(err error) bool {
604 return false 610 return false
605} 611}
606 612
613func isMPVPropertyUnavailableError(err error) bool {
614 if err == nil {
615 return false
616 }
617 return strings.Contains(strings.ToLower(err.Error()), "property unavailable")
618}
619
620// PlaybackLossAction tells the monitor how to react when time-pos/has-playback fails.
621type PlaybackLossAction int
622
623const (
624 // PlaybackLossWait: transient gap (playlist switch, demuxer reload). Keep monitoring.
625 PlaybackLossWait PlaybackLossAction = iota
626 // PlaybackLossComplete: episode reached the completion threshold (or MPV quit after enough watch).
627 PlaybackLossComplete
628 // PlaybackLossExit: user quit MPV before the completion threshold.
629 PlaybackLossExit
630)
631
632// ClassifyPlaybackLoss decides what to do when the monitor loses time-pos.
633// Critical: "property unavailable" while MPV is still running is normal during
634// playlist episode switches and must NOT exit curd. Only a dead MPV process
635// (or a finished episode past the completion %) should end the session.
636func ClassifyPlaybackLoss(socketPath string, started bool, percentageWatched float64, completeThreshold int) PlaybackLossAction {
637 if !started {
638 return PlaybackLossWait
639 }
640 if MPVPlaylistIsSwitching() {
641 return PlaybackLossWait
642 }
643 if int(percentageWatched) >= completeThreshold {
644 return PlaybackLossComplete
645 }
646 // MPV still open with incomplete watch → wait (playlist jump, pause, buffer).
647 if socketPath != "" && IsMPVRunning(socketPath) {
648 return PlaybackLossWait
649 }
650 return PlaybackLossExit
651}
652
607// Helper function to join args with a space 653// Helper function to join args with a space
608func joinArgs(args []string) string { 654func joinArgs(args []string) string {
609 result := "" 655 result := ""
@@ -628,63 +674,119 @@ func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, e
628 Log(fmt.Sprintf("Retrying MPV command, attempt %d/%d", attempt+1, maxRetries)) 674 Log(fmt.Sprintf("Retrying MPV command, attempt %d/%d", attempt+1, maxRetries))
629 } 675 }
630 676
631 conn, err := connectToPipe(ipcSocketPath) 677 data, err := mpvSendCommandOnce(ipcSocketPath, command)
632 if err != nil { 678 if err == nil {
633 lastErr = err 679 return data, nil
634 Log(fmt.Sprintf("Connect error (attempt %d/%d): %v", attempt+1, maxRetries, err))
635 continue // Try again
636 } 680 }
637 defer conn.Close() 681 lastErr = err
638 682 // property unavailable is a valid answer — don't spin retries on it
639 commandStr, err := json.Marshal(map[string]interface{}{ 683 if isMPVPropertyUnavailableError(err) {
640 "command": command, 684 return nil, err
641 })
642 if err != nil {
643 return nil, err // Don't retry on JSON marshalling errors
644 } 685 }
686 Log(fmt.Sprintf("MPV command error (attempt %d/%d): %v", attempt+1, maxRetries, err))
687 }
645 688
646 // Send the command 689 return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr)
647 _, err = conn.Write(append(commandStr, '\n')) 690}
648 if err != nil {
649 lastErr = err
650 Log(fmt.Sprintf("Write error (attempt %d/%d): %v", attempt+1, maxRetries, err))
651 continue // Try again
652 }
653 691
654 // Receive the response with timeout 692func mpvSendCommandOnce(ipcSocketPath string, command []interface{}) (interface{}, error) {
655 buf := make([]byte, 4096) 693 conn, err := connectToPipe(ipcSocketPath)
656 // Set read deadline for 1 second 694 if err != nil {
657 if deadline, ok := conn.(interface{ SetReadDeadline(time.Time) error }); ok { 695 return nil, fmt.Errorf("connect: %w", err)
658 deadline.SetReadDeadline(time.Now().Add(1 * time.Second)) 696 }
659 } 697 defer conn.Close()
660 698
661 n, err := conn.Read(buf) 699 reqID := mpvRequestID.Add(1)
700 payload, err := json.Marshal(map[string]interface{}{
701 "command": command,
702 "request_id": reqID,
703 })
704 if err != nil {
705 return nil, err
706 }
707
708 if deadline, ok := conn.(interface{ SetReadDeadline(time.Time) error }); ok {
709 _ = deadline.SetReadDeadline(time.Now().Add(3 * time.Second))
710 }
711 if deadline, ok := conn.(interface{ SetWriteDeadline(time.Time) error }); ok {
712 _ = deadline.SetWriteDeadline(time.Now().Add(2 * time.Second))
713 }
714
715 if _, err := conn.Write(append(payload, '\n')); err != nil {
716 return nil, fmt.Errorf("write: %w", err)
717 }
718
719 // Read newline-delimited JSON; skip event messages until our request_id matches.
720 reader := bufio.NewReader(conn)
721 deadline := time.Now().Add(3 * time.Second)
722 for time.Now().Before(deadline) {
723 if d, ok := conn.(interface{ SetReadDeadline(time.Time) error }); ok {
724 _ = d.SetReadDeadline(time.Now().Add(2 * time.Second))
725 }
726 line, err := reader.ReadBytes('\n')
662 if err != nil { 727 if err != nil {
663 lastErr = err 728 if err == io.EOF && len(line) == 0 {
664 Log(fmt.Sprintf("Read error (attempt %d/%d): %v", attempt+1, maxRetries, err)) 729 return nil, fmt.Errorf("read: %w", err)
665 continue // Try again 730 }
731 if len(line) == 0 {
732 return nil, fmt.Errorf("read: %w", err)
733 }
734 // fall through with partial line if any
735 }
736 line = bytesTrimSpace(line)
737 if len(line) == 0 {
738 continue
666 } 739 }
667 740
668 var response map[string]interface{} 741 var response map[string]interface{}
669 if err := json.Unmarshal(buf[:n], &response); err != nil { 742 if err := json.Unmarshal(line, &response); err != nil {
670 lastErr = err 743 // Multi-object garbage — try first line only already; skip bad line
671 Log(fmt.Sprintf("JSON parse error (attempt %d/%d): %v", attempt+1, maxRetries, err)) 744 continue
672 continue // Try again
673 } 745 }
674 746
675 data, responseErr := mpvResponseData(response) 747 // Skip pure events (property-change, etc.) that have no matching request_id.
676 if responseErr != nil { 748 if rid, ok := response["request_id"]; ok {
677 lastErr = responseErr 749 if idNum, ok := asInt64(rid); !ok || idNum != reqID {
678 Log(fmt.Sprintf("MPV command error (attempt %d/%d): %v", attempt+1, maxRetries, responseErr)) 750 continue
751 }
752 } else if _, isEvent := response["event"]; isEvent {
679 continue 753 continue
680 } 754 }
681 return data, nil 755
756 // Response without request_id but with error/data — accept as command reply
757 // only when it looks like a command result (has "error" field).
758 if _, hasErr := response["error"]; !hasErr {
759 if _, isEvent := response["event"]; isEvent {
760 continue
761 }
762 }
763
764 return mpvResponseData(response)
682 } 765 }
766 return nil, fmt.Errorf("timed out waiting for mpv response to request_id=%d", reqID)
767}
683 768
684 // All retries failed 769func bytesTrimSpace(b []byte) []byte {
685 return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr) 770 return []byte(strings.TrimSpace(string(b)))
686} 771}
687 772
773func asInt64(v interface{}) (int64, bool) {
774 switch n := v.(type) {
775 case float64:
776 return int64(n), true
777 case int64:
778 return n, true
779 case int:
780 return int64(n), true
781 case json.Number:
782 i, err := n.Int64()
783 return i, err == nil
784 default:
785 return 0, false
786 }
787}
788
789
688func mpvResponseData(response map[string]interface{}) (interface{}, error) { 790func mpvResponseData(response map[string]interface{}) (interface{}, error) {
689 if errorValue, exists := response["error"]; exists { 791 if errorValue, exists := response["error"]; exists {
690 errorText, ok := errorValue.(string) 792 errorText, ok := errorValue.(string)