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() {
643643 continue
644644 }
645645
646 // Check if the error is due to invalid JSON
647 // User closed the video
648646 if anime.Ep.Started {
649647 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).
651672 internal.Log(fmt.Sprint(percentageWatched))
652673 internal.Log(fmt.Sprint(anime.Ep.Player.Speed))
653674 internal.Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
654675 internal.Log(fmt.Sprint(anime.Ep.Duration))
655676 internal.Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
656 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
657 anime.Ep.IsCompleted = true
658 if !userCurdConfig.NextEpisodePrompt {
659 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
660 } else {
661 // For Rofi mode, show prompt immediately after completion
662 if userCurdConfig.RofiSelection {
663 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
664 if shouldContinue {
665 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
666 } else {
667 // Episode was already marked as completed above
668 // Handle completion if this was the last episode
669 if anime.Ep.Number == anime.TotalEpisodes {
670 internal.HandleLastEpisodeCompletion(&userCurdConfig, &anime, user.Token)
671 }
672 // Update local database with completed episode
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())
674 if err != nil {
675 internal.Log("Error updating local database on quit: " + err.Error())
676 }
677 anime.Ep.IsCompleted = true
678 if !userCurdConfig.NextEpisodePrompt {
679 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
680 } else {
681 // For Rofi mode, show prompt immediately after completion
682 if userCurdConfig.RofiSelection {
683 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
684 if shouldContinue {
685 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
686 } else {
687 // Episode was already marked as completed above
688 // Handle completion if this was the last episode
689 if anime.Ep.Number == anime.TotalEpisodes {
690 internal.HandleLastEpisodeCompletion(&userCurdConfig, &anime, user.Token)
691 }
692 // 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())
694 if err != nil {
695 internal.Log("Error updating local database on quit: " + err.Error())
696 }
677697
678 // Update Anilist progress if not rewatching
679 if !anime.Rewatching {
680 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
681 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error())
682 } else {
683 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
684 }
698 // Update Anilist progress if not rewatching
699 if !anime.Rewatching {
700 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
701 internal.Log("Error updating Anilist progress on quit: " + progressErr.Error())
702 } else {
703 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
685704 }
686
687 internal.ExitCurd(nil)
688705 }
689 } else {
690 // For CLI mode, let the continuous prompt handle it
691 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
706
707 internal.ExitCurd(nil)
692708 }
693 // Exit the skip loop - only close if not already closed
694 select {
695 case isClosed := <-skipLoopClosed:
696 if !isClosed {
697 close(skipLoopDone)
698 skipLoopClosed <- true // Mark as closed
699 }
700 default:
701 // Channel is busy, another goroutine is handling closure
709 } else {
710 // For CLI mode, let the continuous prompt handle it
711 internal.Log("Episode completed, exiting monitoring to let CLI prompt handle next episode")
712 }
713 // Exit the skip loop - only close if not already closed
714 select {
715 case isClosed := <-skipLoopClosed:
716 if !isClosed {
717 close(skipLoopDone)
718 skipLoopClosed <- true // Mark as closed
702719 }
703 return
720 default:
721 // Channel is busy, another goroutine is handling closure
704722 }
705 } else {
706 internal.Log("Episode is not completed, exiting")
707 internal.ExitCurd(nil)
723 return
708724 }
709725 // Exit the skip loop - only close if not already closed
710726 select {
@@ -757,15 +773,14 @@ func main() {
757773 }
758774 }
759775
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.
761777 hasPlayback, err := internal.HasActivePlayback(anime.Ep.Player.SocketPath)
762778 if err != nil {
763779 internal.Log("Error checking playback status: " + err.Error())
764780 } else if !hasPlayback && anime.Ep.Started {
765 // Wait for a moment to allow playback to start
766 time.Sleep(2 * time.Second) // Wait for 2 seconds
781 // Wait for a moment to allow playback to start / playlist switch to settle
782 time.Sleep(2 * time.Second)
767783
768 // Check playback status again
769784 hasPlayback, err = internal.HasActivePlayback(anime.Ep.Player.SocketPath)
770785 if err != nil {
771786 internal.Log("Error checking playback status: " + err.Error())
@@ -775,75 +790,84 @@ func main() {
775790 continue
776791 }
777792
778 // Nothing is playing, check percentage watched
779793 percentageWatched := internal.PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
780 // fmt.Printf("[DEBUG] Playback stopped - Percentage watched: %d%%, Required: %d%%\n",
781 // int(percentageWatched),
782 // userCurdConfig.PercentageToMarkComplete)
783
784 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
785 anime.Ep.IsCompleted = true
786 if !userCurdConfig.NextEpisodePrompt {
787 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
788 } else {
789 // For Rofi mode, show prompt immediately after completion
790 if userCurdConfig.RofiSelection {
791 shouldContinue := internal.NextEpisodePromptRofi(&userCurdConfig)
792 if shouldContinue {
793 internal.StartNextEpisode(&anime, &userCurdConfig, databaseFile, user.Token)
794 } else {
795 // Episode was already marked as completed above
796 // Update local database with completed episode
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())
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 }
794 action := internal.ClassifyPlaybackLoss(
795 anime.Ep.Player.SocketPath,
796 anime.Ep.Started,
797 percentageWatched,
798 userCurdConfig.PercentageToMarkComplete,
799 )
800 internal.Log(fmt.Sprintf("no active playback: pct=%.1f action=%d", percentageWatched, action))
801
802 switch action {
803 case internal.PlaybackLossWait:
804 continue
805 case internal.PlaybackLossExit:
806 internal.Log("Episode is not completed, exiting")
807 internal.ExitCurd(nil)
808 return
809 case internal.PlaybackLossComplete:
810 // fall through
811 }
810812
811 internal.ExitCurd(nil)
812 }
813 anime.Ep.IsCompleted = true
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)
813822 } else {
814 // For CLI mode, update progress immediately since episode is 85%+ complete
823 // Episode was already marked as completed above
815824 // Update local database with completed episode
816825 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())
817826 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())
819828 }
820829
821830 // Update Anilist progress if not rewatching
822831 if !anime.Rewatching {
823832 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())
825834 } else {
826835 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
827836 }
828837 }
829838
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())
831847 }
832 // Exit the skip loop - only close if not already closed
833 select {
834 case isClosed := <-skipLoopClosed:
835 if !isClosed {
836 close(skipLoopDone)
837 skipLoopClosed <- true // Mark as closed
848
849 // Update Anilist progress if not rewatching
850 if !anime.Rewatching {
851 if progressErr := internal.UpdateAnimeProgress(user.Token, anime.AnilistId, anime.Ep.Number); progressErr != nil {
852 internal.Log("Error updating Anilist progress on completion: " + progressErr.Error())
853 } else {
854 internal.CurdOut(fmt.Sprintf("Episode completed! Progress updated: %d", anime.Ep.Number))
838855 }
839 default:
840 // Channel is busy, another goroutine is handling closure
841856 }
842 return
857
858 internal.Log("Episode completed, updated progress, exiting monitoring to let CLI prompt handle next episode")
843859 }
844 } else {
845 internal.Log("Episode is not completed, exiting")
846 internal.ExitCurd(nil)
860 // Exit the skip loop - only close if not already closed
861 select {
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
847871 }
848872 // Exit the skip loop - only close if not already closed
849873 select {
internal/localTracking.go +16 −9
@@ -545,19 +545,25 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
545545
546546 if anime.Ep.Started {
547547 percentageWatched := PercentageWatched(anime.Ep.Player.PlaybackTime, anime.Ep.Duration)
548 Log(fmt.Sprint(percentageWatched))
549 Log(fmt.Sprint(anime.Ep.Player.PlaybackTime))
550 Log(fmt.Sprint(anime.Ep.Duration))
551 Log(fmt.Sprint(userCurdConfig.PercentageToMarkComplete))
552 if int(percentageWatched) >= userCurdConfig.PercentageToMarkComplete {
548 action := ClassifyPlaybackLoss(
549 anime.Ep.Player.SocketPath,
550 anime.Ep.Started,
551 percentageWatched,
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:
553560 anime.Ep.Number++
554561 anime.Ep.Started = false
555562 Log("Completed episode, starting next.")
556563 anime.Ep.IsCompleted = true
557 break
558 } else if fmt.Sprintf("%v", err) == "invalid character '{' after top-level value" {
559 Log("Received invalid JSON response, continuing...")
560 } else {
564 // Break the playback monitor loop (not just the switch).
565 goto nextUntrackedEpisode
566 case PlaybackLossExit:
561567 Log("Episode is not completed, exiting")
562568 ExitCurd(nil)
563569 }
@@ -616,6 +622,7 @@ func WatchUntracked(userCurdConfig *CurdConfig) {
616622 }
617623 time.Sleep(1 * time.Second)
618624 }
625 nextUntrackedEpisode:
619626 }
620627
621628}
internal/mpv_playlist.go +1109 −161
@@ -2,15 +2,53 @@ package internal
22
33import (
44 "fmt"
5 "os"
6 "path/filepath"
7 "regexp"
8 "sort"
9 "strconv"
510 "strings"
611 "sync"
712 "sync/atomic"
813 "time"
914)
1015
11// Placeholder media for non-current playlist rows. Short black frame so idle
12// playlist construction never pulls real streams; on select we replace immediately.
13const mpvEpisodePlaceholder = "av://lavfi:color=c=0x101010:s=16x16:d=1"
16// Matches "Episode 12" / "Ep 12" in MPV playlist titles we set.
17var playlistEpisodeTitleRE = regexp.MustCompile(`(?i)\b(?:episode|ep)\s*(\d+)\b`)
18
19// Matches s=WWxHH inside our placeholder URLs (episode encoded in size).
20var placeholderSizeRE = regexp.MustCompile(`s=(\d+)x(\d+)`)
21
22const mpvPlaceholderDuration = 86400
23
24// placeholderURL returns a playable dummy path unique for episode ep.
25// Episode is encoded into lavfi size (fragments break lavfi in mpv).
26func placeholderURL(ep int) string {
27 if ep < 0 {
28 ep = 0
29 }
30 // ep = (h-16)*200 + (w-16); w,h >= 16
31 w := 16 + (ep % 200)
32 h := 16 + (ep / 200)
33 return fmt.Sprintf("av://lavfi:color=c=0x101010:s=%dx%d:d=%d", w, h, mpvPlaceholderDuration)
34}
35
36func parseEpisodeFromPlaceholder(path string) (int, bool) {
37 m := placeholderSizeRE.FindStringSubmatch(path)
38 if len(m) < 3 {
39 return 0, false
40 }
41 w, err1 := strconv.Atoi(m[1])
42 h, err2 := strconv.Atoi(m[2])
43 if err1 != nil || err2 != nil || w < 16 || h < 16 {
44 return 0, false
45 }
46 ep := (h-16)*200 + (w - 16)
47 if ep <= 0 {
48 return 0, false
49 }
50 return ep, true
51}
1452
1553const (
1654 mpvPlaylistIdleDelay = 3 * time.Second
@@ -18,6 +56,24 @@ const (
1856 mpvPlaylistStableSamples = 3
1957)
2058
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
2177// playlistSlot maps an MPV playlist index to curd episode + audio mode.
2278type playlistSlot struct {
2379 Episode int
@@ -28,6 +84,9 @@ type playlistSlot struct {
2884// MPVPlaylistController maintains a seamless MPV playlist of episodes (and
2985// optional alternate audio entry) without interrupting active playback while
3086// 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.
3190type MPVPlaylistController struct {
3291 config *CurdConfig
3392 anime *Anime
@@ -44,6 +103,7 @@ type MPVPlaylistController struct {
44103 alternateMode string
45104 currentPlaying int // episode number currently intended
46105 currentMode string
106 episodeNums []int // provider episode list (sorted), preferred mode
47107}
48108
49109// StartMPVPlaylistController waits until playback is stable, then builds the
@@ -94,20 +154,20 @@ func (c *MPVPlaylistController) run() {
94154 }
95155
96156 // 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).
98158 if err := c.buildEpisodePlaylist(); err != nil {
99159 Log(fmt.Sprintf("MPV playlist build failed: %v", err))
100160 // Still watch in case a partial list exists.
101161 } else {
102162 c.built = true
103 Log("MPV episode playlist ready")
163 Log(fmt.Sprintf("MPV episode playlist ready (%d episodes)", len(c.episodeNums)))
104164 }
105165
106166 if c.closed() {
107167 return
108168 }
109169
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.
111171 c.probeAndAttachAlternateAudio()
112172
113173 c.watchPlaylistSelection()
@@ -149,36 +209,88 @@ func (c *MPVPlaylistController) waitUntilIdleStable() bool {
149209 return false
150210}
151211
152func (c *MPVPlaylistController) totalEpisodes() int {
153 if c.anime.TotalEpisodes > 0 {
154 return c.anime.TotalEpisodes
155 }
212// fetchEpisodeNumbers loads the full episode number list from the provider in one
213// shot via EpisodesList. Never resolves per-episode streams (avoids 429s).
214func (c *MPVPlaylistController) fetchEpisodeNumbers() []int {
156215 providerName, providerID := AnimeProviderID(c.anime)
157 if providerID == "" {
158 return 0
216 if providerID != "" {
217 qualified := QualifyProviderID(providerName, providerID)
218 // Preferred mode only — one list request. Do not also hit alternate mode
219 // (GetProviderTotalEpisodes does that; we deliberately do not).
220 list, err := EpisodesList(qualified, c.preferredMode)
221 if err != nil {
222 Log(fmt.Sprintf("MPV playlist: EpisodesList(%s) failed: %v — falling back", providerName, err))
223 } else if nums := parseEpisodeNumberList(list); len(nums) > 0 {
224 return nums
225 }
226 }
227
228 // Fallback: contiguous 1..N from AniList / known total (still no stream probes).
229 total := c.anime.TotalEpisodes
230 if total <= 0 && providerID != "" {
231 if n, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), c.preferredMode); err == nil {
232 total = n
233 c.anime.TotalEpisodes = n
234 }
159235 }
160 total, err := GetProviderTotalEpisodes(QualifyProviderID(providerName, providerID), c.preferredMode)
161 if err != nil || total <= 0 {
162 return 0
236 if total <= 0 {
237 return nil
238 }
239 nums := make([]int, 0, total)
240 for ep := 1; ep <= total; ep++ {
241 nums = append(nums, ep)
163242 }
164 c.anime.TotalEpisodes = total
165 return total
243 return nums
244}
245
246func parseEpisodeNumberList(list []string) []int {
247 seen := make(map[int]struct{}, len(list))
248 for _, raw := range list {
249 raw = strings.TrimSpace(raw)
250 if raw == "" {
251 continue
252 }
253 // Accept "12" or "12.0"
254 f, err := strconv.ParseFloat(raw, 64)
255 if err != nil || f <= 0 {
256 continue
257 }
258 ep := int(f)
259 if float64(ep) != f {
260 // Fractional episode markers (specials) — keep as floor if whole part > 0
261 if ep <= 0 {
262 continue
263 }
264 }
265 seen[ep] = struct{}{}
266 }
267 if len(seen) == 0 {
268 return nil
269 }
270 nums := make([]int, 0, len(seen))
271 for ep := range seen {
272 nums = append(nums, ep)
273 }
274 sort.Ints(nums)
275 return nums
166276}
167277
168278func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string {
169 name := GetAnimeName(*c.anime)
170 base := fmt.Sprintf("Ep %02d", ep)
279 name := strings.TrimSpace(GetAnimeName(*c.anime))
280 base := fmt.Sprintf("Episode %d", ep)
171281 if name != "" {
172 base = fmt.Sprintf("%s · Ep %02d", name, ep)
282 base = fmt.Sprintf("%s - Episode %d", name, ep)
173283 }
174284 if c.anime.FillerEpisodes != nil && IsEpisodeFiller(c.anime.FillerEpisodes, ep) {
175285 base += " [Filler]"
176286 }
177287 mode = normalizeTranslationType(mode)
178288 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
180292 } else if mode == "dub" {
181 base += " · DUB"
293 base += " (DUB)"
182294 }
183295 if ep == c.currentPlaying && mode == c.currentMode {
184296 base += " ◀"
@@ -187,105 +299,191 @@ func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string {
187299}
188300
189301func (c *MPVPlaylistController) buildEpisodePlaylist() error {
190 total := c.totalEpisodes()
191 if total <= 0 {
192 return fmt.Errorf("unknown total episode count")
302 episodes := c.fetchEpisodeNumbers()
303 if len(episodes) == 0 {
304 return fmt.Errorf("no episode list from provider")
305 }
306 c.episodeNums = episodes
307 if max := episodes[len(episodes)-1]; max > c.anime.TotalEpisodes {
308 c.anime.TotalEpisodes = max
193309 }
310
194311 currentEp := c.anime.Ep.Number
195312 if currentEp < 1 {
196 currentEp = 1
313 currentEp = episodes[0]
197314 }
198 if currentEp > total {
199 currentEp = total
315 // Ensure current episode is in the list (AniList progress may point at an ep
316 // the provider still lists under a different numbering — keep a slot).
317 if !containsInt(episodes, currentEp) {
318 episodes = append(episodes, currentEp)
319 sort.Ints(episodes)
320 c.episodeNums = episodes
200321 }
201322
202323 c.suppress.Store(true)
203324 defer c.suppress.Store(false)
204325
205 // Title the currently playing item (index 0).
206 _ = c.setPlaylistTitle(0, c.episodeLabel(currentEp, c.currentMode))
326 // Prefer title display in the playlist OSD when mpv supports it.
327 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "osd-playlist-entry", "title"})
207328
208 // Insert previous episodes at the front (shifts current down).
209 for ep := currentEp - 1; ep >= 1; ep-- {
210 if c.closed() {
211 return nil
212 }
213 if err := c.insertPlaceholderAt(0, ep, c.preferredMode); err != nil {
214 Log(fmt.Sprintf("playlist insert ep %d: %v", ep, err))
329 // Title the currently playing item (force-media-title sticks for the active entry).
330 curLabel := c.episodeLabel(currentEp, c.currentMode)
331 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", curLabel})
332 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", curLabel})
333
334 var before, after []playlistSlot
335 for _, ep := range episodes {
336 if ep < currentEp {
337 before = append(before, playlistSlot{
338 Episode: ep,
339 Mode: c.preferredMode,
340 Label: c.episodeLabel(ep, c.preferredMode),
341 })
342 } else if ep > currentEp {
343 after = append(after, playlistSlot{
344 Episode: ep,
345 Mode: c.preferredMode,
346 Label: c.episodeLabel(ep, c.preferredMode),
347 })
215348 }
216 // Tiny yield so IPC is not flooded mid-watch.
217 time.Sleep(30 * time.Millisecond)
218349 }
219350
220 // Append future episodes.
221 for ep := currentEp + 1; ep <= total; ep++ {
222 if c.closed() {
223 return nil
224 }
225 if err := c.appendPlaceholder(ep, c.preferredMode); err != nil {
226 Log(fmt.Sprintf("playlist append ep %d: %v", ep, err))
351 // Future episodes: one M3U loadlist append (titled placeholders, no stream probes).
352 if len(after) > 0 {
353 if err := c.loadTitledPlaceholders(after, false); err != nil {
354 Log(fmt.Sprintf("playlist append future: %v", err))
227355 }
228 time.Sleep(30 * time.Millisecond)
229356 }
230357
231 // Rebuild slot map: index i => episode i+1 (preferred mode).
232 slots := make([]playlistSlot, 0, total)
233 for ep := 1; ep <= total; ep++ {
234 slots = append(slots, playlistSlot{
235 Episode: ep,
236 Mode: c.preferredMode,
237 Label: c.episodeLabel(ep, c.preferredMode),
238 })
358 // Previous episodes: append via M3U then playlist-move to the front.
359 if len(before) > 0 {
360 if err := c.loadTitledPlaceholders(before, true); err != nil {
361 Log(fmt.Sprintf("playlist insert previous: %v", err))
362 }
239363 }
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
240375 c.mu.Lock()
241376 c.slots = slots
242377 c.currentPlaying = currentEp
243378 c.mu.Unlock()
244379
245 // Ensure MPV is still on the current episode index without forcing a reload
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 }
380 wantPos := len(before)
253381 c.lastPos = wantPos
254382 if pos, err := c.playlistPos(); err == nil {
255383 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 }
256387 }
257388 return nil
258389}
259390
260func (c *MPVPlaylistController) insertPlaceholderAt(index, ep int, mode string) error {
261 // loadfile <url> insert-at <index>
262 _, err := MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "insert-at", index})
391// loadTitledPlaceholders writes a temp M3U with #EXTINF titles and loadlists it.
392// If moveToFront is true, entries are moved to the start of the playlist (preserving order).
393func (c *MPVPlaylistController) loadTitledPlaceholders(slots []playlistSlot, moveToFront bool) error {
394 if len(slots) == 0 {
395 return nil
396 }
397 path, err := c.writePlaceholderM3U(slots)
263398 if err != nil {
264 // Older mpv: fall back to append (order less perfect but non-fatal).
265 _, err = MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "append"})
266 if err != nil {
267 return err
399 return err
400 }
401 defer func() { _ = os.Remove(path) }()
402
403 beforeCount, _ := c.playlistCount()
404
405 if _, err := MPVSendCommand(c.socket, []interface{}{"loadlist", path, "append"}); err != nil {
406 return fmt.Errorf("loadlist: %w", err)
407 }
408
409 afterCount, err := c.playlistCount()
410 if err != nil {
411 return err
412 }
413 added := afterCount - beforeCount
414 if added <= 0 {
415 return fmt.Errorf("loadlist added 0 entries")
416 }
417
418 if !moveToFront {
419 return nil
420 }
421
422 // Move the newly appended block to the front, preserving relative order.
423 // Start: [current, ..., NEW0, NEW1, ...] → [NEW0, NEW1, ..., current, ...]
424 for i := 0; i < added; i++ {
425 from := beforeCount + i // shifts as we insert earlier
426 to := i
427 if _, err := MPVSendCommand(c.socket, []interface{}{"playlist-move", from, to}); err != nil {
428 Log(fmt.Sprintf("playlist-move %d→%d: %v", from, to, err))
268429 }
269430 }
270 return c.setPlaylistTitle(index, c.episodeLabel(ep, mode))
431 return nil
271432}
272433
273func (c *MPVPlaylistController) appendPlaceholder(ep int, mode string) error {
274 _, err := MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "append"})
434func (c *MPVPlaylistController) writePlaceholderM3U(slots []playlistSlot) (string, error) {
435 dir := os.TempDir()
436 if c.config != nil && strings.TrimSpace(c.config.StoragePath) != "" {
437 dir = os.ExpandEnv(c.config.StoragePath)
438 _ = os.MkdirAll(dir, 0o755)
439 }
440 f, err := os.CreateTemp(dir, "curd-playlist-*.m3u")
275441 if err != nil {
276 return err
442 return "", err
277443 }
278 count, err := c.playlistCount()
279 if err != nil || count <= 0 {
280 return err
444 path := f.Name()
445
446 var b strings.Builder
447 b.WriteString("#EXTM3U\n")
448 for _, s := range slots {
449 title := sanitizeM3UTitle(s.Label)
450 b.WriteString("#EXTINF:-1,")
451 b.WriteString(title)
452 b.WriteByte('\n')
453 // Unique URL per episode so mpv actually changes playlist-pos on select.
454 b.WriteString(placeholderURL(s.Episode))
455 b.WriteByte('\n')
281456 }
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
283467}
284468
285func (c *MPVPlaylistController) setPlaylistTitle(index int, title string) error {
286 // mpv property: playlist/N/title
287 _, err := MPVSendCommand(c.socket, []interface{}{"set_property", fmt.Sprintf("playlist/%d/title", index), title})
288 return err
469// sanitizeM3UTitle keeps #EXTINF titles single-line and free of control chars.
470func sanitizeM3UTitle(title string) string {
471 title = strings.ReplaceAll(title, "\r", " ")
472 title = strings.ReplaceAll(title, "\n", " ")
473 title = strings.TrimSpace(title)
474 if title == "" {
475 return "Episode"
476 }
477 return title
478}
479
480func containsInt(nums []int, want int) bool {
481 for _, n := range nums {
482 if n == want {
483 return true
484 }
485 }
486 return false
289487}
290488
291489func (c *MPVPlaylistController) playlistPos() (int, error) {
@@ -305,8 +503,7 @@ func (c *MPVPlaylistController) playlistCount() (int, error) {
305503}
306504
307505// 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
309// can switch audio by selecting it (full stream reload — only when chosen).
506// stream for the *current* episode only (one resolve — not every episode).
310507func (c *MPVPlaylistController) probeAndAttachAlternateAudio() {
311508 if c.closed() || c.anime == nil {
312509 return
@@ -327,43 +524,66 @@ func (c *MPVPlaylistController) probeAndAttachAlternateAudio() {
327524 c.suppress.Store(true)
328525 defer c.suppress.Store(false)
329526
330 // Insert alternate entry right after the current episode index.
331527 c.mu.Lock()
332 curIdx := c.currentPlaying - 1
528 curIdx := c.episodeIndexLocked(c.currentPlaying, c.currentMode)
333529 if curIdx < 0 {
334530 curIdx = 0
335531 }
336532 label := c.episodeLabel(c.currentPlaying, alt)
337 // Physical insert in mpv
338533 insertAt := curIdx + 1
339534 c.mu.Unlock()
340535
341 if _, err := MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "insert-at", insertAt}); err != nil {
342 // Fallback append
343 if err := c.appendPlaceholder(c.currentPlaying, alt); err != nil {
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()
536 slot := playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label}
537 if err := c.insertTitledPlaceholderAt(insertAt, slot); err != nil {
538 Log(fmt.Sprintf("MPV playlist: failed to add %s entry: %v", alt, err))
350539 return
351540 }
352 _ = c.setPlaylistTitle(insertAt, label)
353541
354542 c.mu.Lock()
355 // Insert into slots map at insertAt
356543 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)
358545 } else {
359 slot := playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label}
360546 c.slots = append(c.slots[:insertAt], append([]playlistSlot{slot}, c.slots[insertAt:]...)...)
361547 }
362548 c.mu.Unlock()
363549 Log(fmt.Sprintf("MPV playlist: added %s option for ep %d", alt, c.currentPlaying))
364550}
365551
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
366579func (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
367587 for {
368588 if c.closed() {
369589 return
@@ -371,62 +591,532 @@ func (c *MPVPlaylistController) watchPlaylistSelection() {
371591 if !IsMPVRunning(c.socket) {
372592 return
373593 }
374 if c.suppress.Load() {
375 time.Sleep(mpvPlaylistPollInterval)
594 if c.suppress.Load() || MPVPlaylistIsSwitching() {
595 time.Sleep(poll)
376596 continue
377597 }
378 pos, err := c.playlistPos()
379 if err != nil {
380 time.Sleep(mpvPlaylistPollInterval)
598
599 path := mpvStringProperty(c.socket, "path")
600 pos, posErr := c.playlistPos()
601
602 // --- Primary: path became a placeholder for episode N ---
603 if ep, ok := parseEpisodeFromPlaceholder(path); ok {
604 // Debounce: confirm path still that placeholder briefly (scrub).
605 time.Sleep(80 * time.Millisecond)
606 path2 := mpvStringProperty(c.socket, "path")
607 ep2, ok2 := parseEpisodeFromPlaceholder(path2)
608 if !ok2 {
609 continue
610 }
611 ep = ep2
612 path = path2
613
614 mode := c.preferredMode
615 if posErr == nil && pos >= 0 {
616 if _, title := c.playlistEntryMeta(pos); title != "" {
617 if _, m, ok3 := parsePlaylistEpisodeTitle(title, c.preferredMode); ok3 {
618 mode = m
619 }
620 }
621 }
622
623 c.mu.Lock()
624 curEp := c.currentPlaying
625 c.mu.Unlock()
626
627 Log(fmt.Sprintf("MPV playlist: DETECT path placeholder ep=%d mode=%s (was ep=%d prevPath=%s)",
628 ep, mode, curEp, truncateForLog(lastSeenPath, 50)))
629
630 beginMPVPlaylistSwitch()
631 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
632 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", ep), 5000})
633
634 if posErr == nil && pos >= 0 {
635 c.lastPos = pos
636 }
637 slot := playlistSlot{Episode: ep, Mode: mode, Label: c.episodeLabel(ep, mode)}
638 c.handlePlaylistJumpSlot(slot, curEp)
639 lastSeenPath = mpvStringProperty(c.socket, "path")
381640 continue
382641 }
383 if pos < 0 {
384 time.Sleep(mpvPlaylistPollInterval)
642
643 // --- Secondary: playlist-pos moved ---
644 // IMPORTANT: freeze the *first* new index and resolve that entry immediately.
645 // Re-reading pos after a sleep was overwriting 38→39 (current) so we always
646 // reloaded ep 40 when the user clicked 39 (see debug: DETECT 39→38 then
647 // "pos 39 title Episode 40").
648 if posErr == nil && pos >= 0 && pos != c.lastPos {
649 targetPos := pos
650 fromPos := c.lastPos
651 Log(fmt.Sprintf("MPV playlist: DETECT pos %d → %d (path=%s)", fromPos, targetPos, truncateForLog(path, 50)))
652
653 // Resolve the entry the user landed on *now*, before mpv can snap back.
654 slot, slotErr := c.resolveSlotAt(targetPos)
655 if slotErr != nil {
656 Log(fmt.Sprintf("MPV playlist: resolve pos %d failed: %v", targetPos, slotErr))
657 // Still try path / slots fallback inside handlePlaylistJump.
658 beginMPVPlaylistSwitch()
659 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
660 c.lastPos = targetPos
661 c.handlePlaylistJump(targetPos)
662 lastSeenPath = mpvStringProperty(c.socket, "path")
663 continue
664 }
665
666 c.mu.Lock()
667 curEp := c.currentPlaying
668 c.mu.Unlock()
669
670 Log(fmt.Sprintf("MPV playlist: frozen target pos=%d → ep %d (cur ep %d)", targetPos, slot.Episode, curEp))
671
672 // If resolve says same episode as current and path is still the live stream,
673 // this was a false pos blip — ignore.
674 if slot.Episode == curEp && !isPlaceholderPath(path) {
675 Log(fmt.Sprintf("MPV playlist: ignore pos blip %d→%d (still ep %d, live path)", fromPos, targetPos, curEp))
676 c.lastPos = targetPos
677 // If pos really moved within same ep (dub row), still switch mode.
678 if normalizeTranslationType(slot.Mode) != normalizeTranslationType(c.currentMode) {
679 beginMPVPlaylistSwitch()
680 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
681 c.handlePlaylistJumpSlot(slot, curEp)
682 lastSeenPath = mpvStringProperty(c.socket, "path")
683 }
684 time.Sleep(poll)
685 continue
686 }
687
688 beginMPVPlaylistSwitch()
689 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
690 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 5000})
691 c.lastPos = targetPos
692 c.handlePlaylistJumpSlot(slot, curEp)
693 lastSeenPath = mpvStringProperty(c.socket, "path")
385694 continue
386695 }
387 if pos == c.lastPos {
388 time.Sleep(mpvPlaylistPollInterval)
389 continue
696
697 if path != "" {
698 lastSeenPath = path
390699 }
391 // Debounce rapid scrubbing through the playlist UI.
392 time.Sleep(200 * time.Millisecond)
393 pos2, err2 := c.playlistPos()
394 if err2 != nil || pos2 != pos {
395 continue
700 time.Sleep(poll)
701 }
702}
703
704func isPlaceholderPath(path string) bool {
705 return strings.HasPrefix(path, "av://lavfi:") || strings.Contains(path, "lavfi:color=")
706}
707
708// handlePlaylistJumpSlot switches to a known target slot (from path or pos detection).
709func (c *MPVPlaylistController) handlePlaylistJumpSlot(slot playlistSlot, curEp int) {
710 curMode := c.currentMode
711 if curMode == "" {
712 curMode = c.preferredMode
713 }
714 beginMPVPlaylistSwitch()
715 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", true})
716
717 leaveAction := playlistLeaveNone
718 if slot.Episode != curEp {
719 pct := PercentageWatched(c.anime.Ep.Player.PlaybackTime, c.anime.Ep.Duration)
720 threshold := 85
721 if c.config != nil && c.config.PercentageToMarkComplete > 0 {
722 threshold = c.config.PercentageToMarkComplete
396723 }
397 c.lastPos = pos
398 c.handlePlaylistJump(pos)
724 action, pErr := promptPlaylistEpisodeLeave(curEp, slot.Episode, pct, threshold)
725 if pErr != nil {
726 Log(fmt.Sprintf("MPV playlist leave prompt: %v (playing target anyway)", pErr))
727 action = playlistLeaveNone
728 }
729 if action == playlistLeaveCancel {
730 Log("MPV playlist: user cancelled — reloading current ep real stream")
731 // We're sitting on a dummy placeholder; put real current ep back.
732 if err := c.playSlot(playlistSlot{Episode: curEp, Mode: curMode, Label: c.episodeLabel(curEp, curMode)}); err != nil {
733 Log(fmt.Sprintf("MPV playlist: reload current failed: %v", err))
734 endMPVPlaylistSwitch()
735 }
736 return
737 }
738 leaveAction = action
739 } else {
740 Log(fmt.Sprintf("MPV playlist: reloading real stream for ep %d (was on placeholder)", curEp))
741 }
742
743 _, _ = MPVSendCommand(c.socket, []interface{}{"show-text", fmt.Sprintf("Loading episode %d…", slot.Episode), 8000})
744 Log(fmt.Sprintf("MPV playlist: SWITCH ep %d → %d (%s) leave=%s", curEp, slot.Episode, slot.Mode, leaveAction))
745 CurdOut(fmt.Sprintf("Loading episode %d…", slot.Episode))
746
747 leftEp := curEp
748 if err := c.playSlot(slot); err != nil {
749 Log(fmt.Sprintf("MPV playlist: failed to play ep %d: %v", slot.Episode, err))
750 CurdOut(fmt.Sprintf("Could not play episode %d: %v", slot.Episode, err))
751 if err2 := c.playSlot(playlistSlot{Episode: curEp, Mode: curMode, Label: c.episodeLabel(curEp, curMode)}); err2 != nil {
752 Log(fmt.Sprintf("MPV playlist: recovery play failed: %v", err2))
753 endMPVPlaylistSwitch()
754 }
755 return
399756 }
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 }()
400769}
401770
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
403881 c.mu.Lock()
882 defer c.mu.Unlock()
404883 if pos < 0 || pos >= len(c.slots) {
405 c.mu.Unlock()
406 return
884 return playlistSlot{}, fmt.Errorf("playlist pos %d out of range (slots=%d)", pos, len(c.slots))
407885 }
408886 slot := c.slots[pos]
409 curEp, curMode := c.currentPlaying, c.currentMode
410 c.mu.Unlock()
887 Log(fmt.Sprintf("MPV playlist: pos %d slots fallback → ep %d", pos, slot.Episode))
888 return slot, nil
889}
890
891func (c *MPVPlaylistController) playlistEntryMeta(pos int) (filename, title string) {
892 v, err := MPVSendCommand(c.socket, []interface{}{"get_property", "playlist"})
893 if err != nil || v == nil {
894 return "", ""
895 }
896 entries, ok := v.([]interface{})
897 if !ok || pos < 0 || pos >= len(entries) {
898 return "", ""
899 }
900 entry, ok := entries[pos].(map[string]interface{})
901 if !ok {
902 return "", ""
903 }
904 if f, ok := entry["filename"].(string); ok {
905 filename = f
906 }
907 if t, ok := entry["title"].(string); ok {
908 title = strings.TrimSpace(t)
909 }
910 return filename, title
911}
912
913func parsePlaylistEpisodeTitle(title, preferredMode string) (ep int, mode string, ok bool) {
914 mode = normalizeTranslationType(preferredMode)
915 if mode == "" {
916 mode = "sub"
917 }
918 upper := strings.ToUpper(title)
919 if strings.Contains(upper, "(DUB)") || strings.Contains(upper, "· DUB") || strings.HasSuffix(strings.TrimSpace(upper), "DUB") {
920 mode = "dub"
921 } else if strings.Contains(upper, "(SUB)") {
922 mode = "sub"
923 }
924 m := playlistEpisodeTitleRE.FindStringSubmatch(title)
925 if len(m) < 2 {
926 return 0, mode, false
927 }
928 n, err := strconv.Atoi(m[1])
929 if err != nil || n <= 0 {
930 return 0, mode, false
931 }
932 return n, mode, true
933}
934
935func (c *MPVPlaylistController) handlePlaylistJump(pos int) {
936 curEp := c.currentPlaying
411937
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()
413949 return
414950 }
415951
416 Log(fmt.Sprintf("MPV playlist: user selected ep %d (%s) at index %d", slot.Episode, slot.Mode, pos))
417 if err := c.playSlot(slot); err != nil {
418 Log(fmt.Sprintf("MPV playlist: failed to play ep %d: %v", slot.Episode, err))
419 CurdOut(fmt.Sprintf("Could not play episode %d: %v", slot.Episode, err))
420 // Try to restore previous playlist position without thrashing.
421 c.suppress.Store(true)
422 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "playlist-pos", c.episodeIndex(curEp, curMode)})
423 c.suppress.Store(false)
952 c.handlePlaylistJumpSlot(slot, curEp)
953}
954
955// finalizePlaylistEpisodeChange updates local history, last-played id, episode
956// metadata, optional remote progress, and prefetches the next episode.
957func (c *MPVPlaylistController) finalizePlaylistEpisodeChange(fromEp, toEp int, mode string, leave playlistLeaveAction) {
958 if c.anime == nil || c.config == nil {
959 return
960 }
961 anime := c.anime
962 mode = normalizeTranslationType(mode)
963 if mode == "" {
964 mode = c.preferredMode
965 }
966
967 // Keep config + controller mode in sync (sub/dub playlist entries).
968 if mode != "" {
969 c.config.SubOrDub = mode
970 c.currentMode = mode
971 }
972
973 // Clear stale next-episode prefetch from the previous number.
974 anime.Ep.NextEpisode = NextEpisode{}
975 anime.Ep.IsCompleted = false
976 anime.Ep.LastWasSkipped = false
977 anime.Ep.Resume = false
978 anime.Ep.Number = toEp
979 anime.Ep.Player.PlaybackTime = 0
980 anime.Ep.IsFiller = IsEpisodeFiller(anime.FillerEpisodes, toEp)
981
982 // Episode titles / filler / recap from Jikan (non-fatal). Don't trust its duration.
983 if anime.MalId > 0 {
984 if err := GetEpisodeData(anime.MalId, toEp, anime); err != nil {
985 Log(fmt.Sprintf("MPV playlist: GetEpisodeData ep %d: %v", toEp, err))
986 }
987 // Playback duration comes from MPV, not Jikan.
988 anime.Ep.Duration = 0
989 }
990 // Filler list is authoritative when present.
991 if len(anime.FillerEpisodes) > 0 {
992 anime.Ep.IsFiller = IsEpisodeFiller(anime.FillerEpisodes, toEp)
993 }
994
995 // Last-played anime id (Continue Last Session).
996 writeLastPlayedAnimeID(c.config.StoragePath, anime.AnilistId)
997
998 // Local history: current episode is now toEp at position 0.
999 dbPath := localHistoryPath(c.config.StoragePath)
1000 if dbPath != "" {
1001 if err := LocalUpdateAnime(
1002 dbPath,
1003 anime.AnilistId,
1004 anime.ProviderId,
1005 toEp,
1006 0,
1007 0,
1008 GetAnimeName(*anime),
1009 CurrentAnimeProviderName(anime),
1010 ); err != nil {
1011 Log(fmt.Sprintf("MPV playlist: LocalUpdateAnime: %v", err))
1012 } else {
1013 Log(fmt.Sprintf("MPV playlist: last played → ep %d", toEp))
1014 }
1015 }
1016
1017 // Remote progress according to leave action.
1018 remoteProgress := 0
1019 switch leave {
1020 case playlistLeaveMarkLeft:
1021 if fromEp > 0 {
1022 remoteProgress = fromEp
1023 }
1024 case playlistLeaveSetWatch:
1025 if toEp > 1 {
1026 remoteProgress = toEp - 1
1027 }
1028 }
1029
1030 if remoteProgress > 0 {
1031 token := ""
1032 if u := GetGlobalUser(); u != nil {
1033 token = u.Token
1034 }
1035 if !anime.Rewatching && token != "" {
1036 go func(ep int) {
1037 if err := UpdateAnimeProgress(token, anime.AnilistId, ep); err != nil {
1038 Log(fmt.Sprintf("MPV playlist: UpdateAnimeProgress(%d): %v", ep, err))
1039 } else {
1040 CurdOut(fmt.Sprintf("Upstream progress → episode %d", ep))
1041 }
1042 }(remoteProgress)
1043 } else if anime.Rewatching {
1044 Log("MPV playlist: rewatching — skipped remote progress update")
1045 }
1046 CurdOut(fmt.Sprintf("Playing episode %d · upstream progress set to %d", toEp, remoteProgress))
1047 } else {
1048 CurdOut(fmt.Sprintf("Playing episode %d · last played updated (no upstream change)", toEp))
1049 }
1050
1051 // Prefetch next episode links in preferred mode (no audio prompts).
1052 go c.prefetchAfterPlaylistSwitch(toEp)
1053
1054 // Discord will pick up the new title/position on the next presence tick once
1055 // duration is known; force a soft title refresh for the window.
1056 title := fmt.Sprintf("%s - Episode %d", GetAnimeName(*anime), toEp)
1057 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", title})
1058 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", title})
1059}
1060
1061func localHistoryPath(storagePath string) string {
1062 storagePath = strings.TrimSpace(os.ExpandEnv(storagePath))
1063 if storagePath == "" {
1064 return ""
1065 }
1066 return filepath.Join(storagePath, "curd_history.txt")
1067}
1068
1069func writeLastPlayedAnimeID(storagePath string, anilistID int) {
1070 if anilistID <= 0 {
1071 return
1072 }
1073 storagePath = strings.TrimSpace(os.ExpandEnv(storagePath))
1074 if storagePath == "" {
1075 return
1076 }
1077 idPath := filepath.Join(storagePath, "curd_id")
1078 if err := os.MkdirAll(filepath.Dir(idPath), 0o755); err != nil {
1079 Log(fmt.Sprintf("MPV playlist: mkdir for curd_id: %v", err))
1080 return
1081 }
1082 if err := os.WriteFile(idPath, []byte(strconv.Itoa(anilistID)), 0o644); err != nil {
1083 Log(fmt.Sprintf("MPV playlist: write curd_id: %v", err))
4241084 }
4251085}
4261086
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
4271113func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int {
4281114 c.mu.Lock()
4291115 defer c.mu.Unlock()
1116 return c.episodeIndexLocked(ep, mode)
1117}
1118
1119func (c *MPVPlaylistController) episodeIndexLocked(ep int, mode string) int {
4301120 mode = normalizeTranslationType(mode)
4311121 for i, s := range c.slots {
4321122 if s.Episode == ep && normalizeTranslationType(s.Mode) == mode {
@@ -446,6 +1136,9 @@ func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int {
4461136}
4471137
4481138func (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).
4491142 c.suppress.Store(true)
4501143 defer c.suppress.Store(false)
4511144
@@ -457,16 +1150,34 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
4571150 cfg := *c.config
4581151 cfg.SubOrDub = mode
4591152
460 // Work on a shallow copy for provider id resolution side effects, then copy back.
4611153 anime := c.anime
4621154 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")
4641174
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)
4661177 if err != nil || len(result.Links) == 0 {
4671178 anime.Ep.Number = prevEp
4681179 if err == nil {
469 err = fmt.Errorf("no streams")
1180 err = fmt.Errorf("no streams for episode %d", targetEp)
4701181 }
4711182 return err
4721183 }
@@ -476,29 +1187,86 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
4761187 link := PrioritizeLink(result.Links)
4771188 if link == "" {
4781189 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) + ")"
4801201 }
1202 Log(fmt.Sprintf("MPV playlist: loading ep %d in running mpv (was path %s): %s",
1203 targetEp, truncateForLog(oldPath, 60), truncateForLog(link, 80)))
4811204
482 title := c.episodeLabel(slot.Episode, mode)
483 // Reuse running MPV instance — loadfile replace is the intentional user switch.
4841205 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 {
4861207 anime.Ep.Number = prevEp
4871208 return err
4881209 }
4891210
490 anime.Ep.Number = slot.Episode
491 anime.Ep.Started = false
1211 // Wait until path actually changes away from the old media (not just time-pos).
1212 // WaitForMPVPlaybackStart alone is wrong — old episode still has time-pos.
1213 if !waitForMPVMediaChange(c.socket, oldPath, link, 30*time.Second) {
1214 anime.Ep.Number = prevEp
1215 return fmt.Errorf("episode %d did not become the active media (still on previous file?)", targetEp)
1216 }
1217 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "time-pos", 0})
1218 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "pause", false})
1219 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "force-media-title", title})
1220 _, _ = MPVSendCommand(c.socket, []interface{}{"set_property", "title", title})
1221
1222 anime.Ep.Number = targetEp
1223 // Keep Started=true so the main monitor stays in "watching" mode continuously.
1224 anime.Ep.Started = true
4921225 anime.Ep.IsCompleted = false
4931226 anime.Ep.Player.PlaybackTime = 0
4941227 anime.Ep.Duration = 0
4951228 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)
4961256
4971257 c.mu.Lock()
498 c.currentPlaying = slot.Episode
1258 c.currentPlaying = targetEp
4991259 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
5001265 c.mu.Unlock()
5011266
1267 // Stream is live — safe for the main loop again.
1268 endMPVPlaylistSwitch()
1269
5021270 // Refresh skip times in background (non-blocking for playback).
5031271 go func(ep int) {
5041272 if c.anime.MalId > 0 {
@@ -510,38 +1278,218 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error {
5101278 _ = SendSkipTimesToMPV(c.anime)
5111279 }
5121280 }
513 }(slot.Episode)
1281 }(targetEp)
5141282
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.
5161284 go func() {
517 time.Sleep(mpvPlaylistIdleDelay)
518 if c.closed() {
1285 time.Sleep(mpvPlaylistIdleDelay + time.Second)
1286 if c.closed() || alreadyAlt {
5191287 return
5201288 }
521 // Soft retitle only — avoid full playlist rebuild (would stutter).
522 c.retitleSlots()
523 // Re-probe alternate for the new episode.
5241289 c.hasAlternate = false
5251290 c.probeAndAttachAlternateAudio()
5261291 }()
5271292
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 }
5291337 return nil
5301338}
5311339
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
5331452 c.suppress.Store(true)
5341453 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
5351487 c.mu.Lock()
536 slots := append([]playlistSlot(nil), c.slots...)
537 curEp, curMode := c.currentPlaying, c.currentMode
1488 c.slots = slots
1489 c.lastPos = len(before)
5381490 c.mu.Unlock()
539 for i, s := range slots {
540 label := c.episodeLabel(s.Episode, s.Mode)
541 // episodeLabel uses c.currentPlaying for ◀ marker
542 _ = curEp
543 _ = curMode
544 _ = c.setPlaylistTitle(i, label)
545 time.Sleep(15 * time.Millisecond)
546 }
1491
1492 Log(fmt.Sprintf("MPV playlist rebuilt around ep %d (%d entries)", currentEp, len(slots)))
1493 return nil
5471494}
1495
internal/mpv_playlist_test.go +354 −1
@@ -1,6 +1,10 @@
11package internal
22
33import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "strconv"
48 "strings"
59 "testing"
610)
@@ -17,9 +21,12 @@ func TestEpisodeLabelMarksCurrentAndFiller(t *testing.T) {
1721 currentMode: "sub",
1822 }
1923 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, "◀") {
2125 t.Fatalf("current ep label: %q", label)
2226 }
27 if !strings.Contains(label, "Demo") {
28 t.Fatalf("expected show name in label: %q", label)
29 }
2330 filler := c.episodeLabel(3, "sub")
2431 if !strings.Contains(filler, "Filler") {
2532 t.Fatalf("expected filler mark, got %q", filler)
@@ -28,6 +35,13 @@ func TestEpisodeLabelMarksCurrentAndFiller(t *testing.T) {
2835 if !strings.Contains(strings.ToUpper(dub), "DUB") {
2936 t.Fatalf("expected dub mark, got %q", dub)
3037 }
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 }
3145}
3246
3347func TestEpisodeIndexFindsAlternateModeSlot(t *testing.T) {
@@ -58,3 +72,342 @@ func TestIsEpisodeFillerHelper(t *testing.T) {
5872 t.Fatal("expected non-filler")
5973 }
6074}
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 @@
11package internal
22
33import (
4 "bufio"
45 "crypto/rand"
56 "encoding/json"
67 "fmt"
8 "io"
79 "net/url"
810 "os"
911 "os/exec"
@@ -11,11 +13,15 @@ import (
1113 "runtime"
1214 "strings"
1315 "sync"
16 "sync/atomic"
1417 "time"
1518
1619 "github.com/wraient/curd/internal/providers"
1720)
1821
22// Monotonic request id for mpv JSON IPC so we can ignore interleaved events.
23var mpvRequestID atomic.Int64
24
1925var logFile = "debug.log"
2026
2127const mpvPlaybackPollInterval = 500 * time.Millisecond
@@ -604,6 +610,46 @@ func isMPVConnectionGoneError(err error) bool {
604610 return false
605611}
606612
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
607653// Helper function to join args with a space
608654func joinArgs(args []string) string {
609655 result := ""
@@ -628,63 +674,119 @@ func MPVSendCommand(ipcSocketPath string, command []interface{}) (interface{}, e
628674 Log(fmt.Sprintf("Retrying MPV command, attempt %d/%d", attempt+1, maxRetries))
629675 }
630676
631 conn, err := connectToPipe(ipcSocketPath)
632 if err != nil {
633 lastErr = err
634 Log(fmt.Sprintf("Connect error (attempt %d/%d): %v", attempt+1, maxRetries, err))
635 continue // Try again
677 data, err := mpvSendCommandOnce(ipcSocketPath, command)
678 if err == nil {
679 return data, nil
636680 }
637 defer conn.Close()
638
639 commandStr, err := json.Marshal(map[string]interface{}{
640 "command": command,
641 })
642 if err != nil {
643 return nil, err // Don't retry on JSON marshalling errors
681 lastErr = err
682 // property unavailable is a valid answer — don't spin retries on it
683 if isMPVPropertyUnavailableError(err) {
684 return nil, err
644685 }
686 Log(fmt.Sprintf("MPV command error (attempt %d/%d): %v", attempt+1, maxRetries, err))
687 }
645688
646 // Send the command
647 _, err = conn.Write(append(commandStr, '\n'))
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 }
689 return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr)
690}
653691
654 // Receive the response with timeout
655 buf := make([]byte, 4096)
656 // Set read deadline for 1 second
657 if deadline, ok := conn.(interface{ SetReadDeadline(time.Time) error }); ok {
658 deadline.SetReadDeadline(time.Now().Add(1 * time.Second))
659 }
692func mpvSendCommandOnce(ipcSocketPath string, command []interface{}) (interface{}, error) {
693 conn, err := connectToPipe(ipcSocketPath)
694 if err != nil {
695 return nil, fmt.Errorf("connect: %w", err)
696 }
697 defer conn.Close()
660698
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')
662727 if err != nil {
663 lastErr = err
664 Log(fmt.Sprintf("Read error (attempt %d/%d): %v", attempt+1, maxRetries, err))
665 continue // Try again
728 if err == io.EOF && len(line) == 0 {
729 return nil, fmt.Errorf("read: %w", err)
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
666739 }
667740
668741 var response map[string]interface{}
669 if err := json.Unmarshal(buf[:n], &response); err != nil {
670 lastErr = err
671 Log(fmt.Sprintf("JSON parse error (attempt %d/%d): %v", attempt+1, maxRetries, err))
672 continue // Try again
742 if err := json.Unmarshal(line, &response); err != nil {
743 // Multi-object garbage — try first line only already; skip bad line
744 continue
673745 }
674746
675 data, responseErr := mpvResponseData(response)
676 if responseErr != nil {
677 lastErr = responseErr
678 Log(fmt.Sprintf("MPV command error (attempt %d/%d): %v", attempt+1, maxRetries, responseErr))
747 // Skip pure events (property-change, etc.) that have no matching request_id.
748 if rid, ok := response["request_id"]; ok {
749 if idNum, ok := asInt64(rid); !ok || idNum != reqID {
750 continue
751 }
752 } else if _, isEvent := response["event"]; isEvent {
679753 continue
680754 }
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)
682765 }
766 return nil, fmt.Errorf("timed out waiting for mpv response to request_id=%d", reqID)
767}
683768
684 // All retries failed
685 return nil, fmt.Errorf("command failed after %d attempts: %w", maxRetries, lastErr)
769func bytesTrimSpace(b []byte) []byte {
770 return []byte(strings.TrimSpace(string(b)))
686771}
687772
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
688790func mpvResponseData(response map[string]interface{}) (interface{}, error) {
689791 if errorValue, exists := response["error"]; exists {
690792 errorText, ok := errorValue.(string)