| @@ -2,15 +2,53 @@ package internal |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "fmt" |
| 5 | "os" |
| 6 | "path/filepath" |
| 7 | "regexp" |
| 8 | "sort" |
| 9 | "strconv" |
| 5 | 10 | "strings" |
| 6 | 11 | "sync" |
| 7 | 12 | "sync/atomic" |
| 8 | 13 | "time" |
| 9 | 14 | ) |
| 10 | 15 | |
| 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. |
| 13 | | const mpvEpisodePlaceholder = "av://lavfi:color=c=0x101010:s=16x16:d=1" |
| 16 | // Matches "Episode 12" / "Ep 12" in MPV playlist titles we set. |
| 17 | var playlistEpisodeTitleRE = regexp.MustCompile(`(?i)\b(?:episode|ep)\s*(\d+)\b`) |
| 18 | |
| 19 | // Matches s=WWxHH inside our placeholder URLs (episode encoded in size). |
| 20 | var placeholderSizeRE = regexp.MustCompile(`s=(\d+)x(\d+)`) |
| 21 | |
| 22 | const 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). |
| 26 | func 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 | |
| 36 | func 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 | |
| 15 | 53 | const ( |
| 16 | 54 | mpvPlaylistIdleDelay = 3 * time.Second |
| @@ -18,6 +56,24 @@ const ( |
| 18 | 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". |
| 62 | var mpvPlaylistSwitching atomic.Bool |
| 63 | |
| 64 | // MPVPlaylistIsSwitching reports whether a playlist episode switch is underway. |
| 65 | func MPVPlaylistIsSwitching() bool { |
| 66 | return mpvPlaylistSwitching.Load() |
| 67 | } |
| 68 | |
| 69 | func beginMPVPlaylistSwitch() { |
| 70 | mpvPlaylistSwitching.Store(true) |
| 71 | } |
| 72 | |
| 73 | func endMPVPlaylistSwitch() { |
| 74 | mpvPlaylistSwitching.Store(false) |
| 75 | } |
| 76 | |
| 21 | 77 | // playlistSlot maps an MPV playlist index to curd episode + audio mode. |
| 22 | 78 | type playlistSlot struct { |
| 23 | 79 | Episode int |
| @@ -28,6 +84,9 @@ type playlistSlot struct { |
| 28 | 84 | // MPVPlaylistController maintains a seamless MPV playlist of episodes (and |
| 29 | 85 | // optional alternate audio entry) without interrupting active playback while |
| 30 | 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. |
| 31 | 90 | type MPVPlaylistController struct { |
| 32 | 91 | config *CurdConfig |
| 33 | 92 | anime *Anime |
| @@ -44,6 +103,7 @@ type MPVPlaylistController struct { |
| 44 | 103 | alternateMode string |
| 45 | 104 | currentPlaying int // episode number currently intended |
| 46 | 105 | currentMode string |
| 106 | episodeNums []int // provider episode list (sorted), preferred mode |
| 47 | 107 | } |
| 48 | 108 | |
| 49 | 109 | // StartMPVPlaylistController waits until playback is stable, then builds the |
| @@ -94,20 +154,20 @@ func (c *MPVPlaylistController) run() { |
| 94 | 154 | } |
| 95 | 155 | |
| 96 | 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 | 158 | if err := c.buildEpisodePlaylist(); err != nil { |
| 99 | 159 | Log(fmt.Sprintf("MPV playlist build failed: %v", err)) |
| 100 | 160 | // Still watch in case a partial list exists. |
| 101 | 161 | } else { |
| 102 | 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 | 166 | if c.closed() { |
| 107 | 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 | 171 | c.probeAndAttachAlternateAudio() |
| 112 | 172 | |
| 113 | 173 | c.watchPlaylistSelection() |
| @@ -149,36 +209,88 @@ func (c *MPVPlaylistController) waitUntilIdleStable() bool { |
| 149 | 209 | return false |
| 150 | 210 | } |
| 151 | 211 | |
| 152 | | func (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). |
| 214 | func (c *MPVPlaylistController) fetchEpisodeNumbers() []int { |
| 156 | 215 | 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 | } |
| 159 | 235 | } |
| 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) |
| 163 | 242 | } |
| 164 | | c.anime.TotalEpisodes = total |
| 165 | | return total |
| 243 | return nums |
| 244 | } |
| 245 | |
| 246 | func 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 | |
| 168 | 278 | func (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) |
| 171 | 281 | if name != "" { |
| 172 | | base = fmt.Sprintf("%s · Ep %02d", name, ep) |
| 282 | base = fmt.Sprintf("%s - Episode %d", name, ep) |
| 173 | 283 | } |
| 174 | 284 | if c.anime.FillerEpisodes != nil && IsEpisodeFiller(c.anime.FillerEpisodes, ep) { |
| 175 | 285 | base += " [Filler]" |
| 176 | 286 | } |
| 177 | 287 | mode = normalizeTranslationType(mode) |
| 178 | 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 | 292 | } else if mode == "dub" { |
| 181 | | base += " · DUB" |
| 293 | base += " (DUB)" |
| 182 | 294 | } |
| 183 | 295 | if ep == c.currentPlaying && mode == c.currentMode { |
| 184 | 296 | base += " ◀" |
| @@ -187,105 +299,191 @@ func (c *MPVPlaylistController) episodeLabel(ep int, mode string) string { |
| 187 | 299 | } |
| 188 | 300 | |
| 189 | 301 | func (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 |
| 193 | 309 | } |
| 310 | |
| 194 | 311 | currentEp := c.anime.Ep.Number |
| 195 | 312 | if currentEp < 1 { |
| 196 | | currentEp = 1 |
| 313 | currentEp = episodes[0] |
| 197 | 314 | } |
| 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 |
| 200 | 321 | } |
| 201 | 322 | |
| 202 | 323 | c.suppress.Store(true) |
| 203 | 324 | defer c.suppress.Store(false) |
| 204 | 325 | |
| 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"}) |
| 207 | 328 | |
| 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 | }) |
| 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. |
| 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)) |
| 227 | 355 | } |
| 228 | | time.Sleep(30 * time.Millisecond) |
| 229 | 356 | } |
| 230 | 357 | |
| 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 | } |
| 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 | 375 | c.mu.Lock() |
| 241 | 376 | c.slots = slots |
| 242 | 377 | c.currentPlaying = currentEp |
| 243 | 378 | c.mu.Unlock() |
| 244 | 379 | |
| 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) |
| 253 | 381 | c.lastPos = wantPos |
| 254 | 382 | if pos, err := c.playlistPos(); err == nil { |
| 255 | 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 | 388 | return nil |
| 258 | 389 | } |
| 259 | 390 | |
| 260 | | func (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). |
| 393 | func (c *MPVPlaylistController) loadTitledPlaceholders(slots []playlistSlot, moveToFront bool) error { |
| 394 | if len(slots) == 0 { |
| 395 | return nil |
| 396 | } |
| 397 | path, err := c.writePlaceholderM3U(slots) |
| 263 | 398 | 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)) |
| 268 | 429 | } |
| 269 | 430 | } |
| 270 | | return c.setPlaylistTitle(index, c.episodeLabel(ep, mode)) |
| 431 | return nil |
| 271 | 432 | } |
| 272 | 433 | |
| 273 | | func (c *MPVPlaylistController) appendPlaceholder(ep int, mode string) error { |
| 274 | | _, err := MPVSendCommand(c.socket, []interface{}{"loadfile", mpvEpisodePlaceholder, "append"}) |
| 434 | func (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") |
| 275 | 441 | if err != nil { |
| 276 | | return err |
| 442 | return "", err |
| 277 | 443 | } |
| 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') |
| 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 | |
| 285 | | func (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. |
| 470 | func 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 | |
| 480 | func 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 | |
| 291 | 489 | func (c *MPVPlaylistController) playlistPos() (int, error) { |
| @@ -305,8 +503,7 @@ func (c *MPVPlaylistController) playlistCount() (int, error) { |
| 305 | 503 | } |
| 306 | 504 | |
| 307 | 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 |
| 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). |
| 310 | 507 | func (c *MPVPlaylistController) probeAndAttachAlternateAudio() { |
| 311 | 508 | if c.closed() || c.anime == nil { |
| 312 | 509 | return |
| @@ -327,43 +524,66 @@ func (c *MPVPlaylistController) probeAndAttachAlternateAudio() { |
| 327 | 524 | c.suppress.Store(true) |
| 328 | 525 | defer c.suppress.Store(false) |
| 329 | 526 | |
| 330 | | // Insert alternate entry right after the current episode index. |
| 331 | 527 | c.mu.Lock() |
| 332 | | curIdx := c.currentPlaying - 1 |
| 528 | curIdx := c.episodeIndexLocked(c.currentPlaying, c.currentMode) |
| 333 | 529 | if curIdx < 0 { |
| 334 | 530 | curIdx = 0 |
| 335 | 531 | } |
| 336 | 532 | label := c.episodeLabel(c.currentPlaying, alt) |
| 337 | | // Physical insert in mpv |
| 338 | 533 | insertAt := curIdx + 1 |
| 339 | 534 | c.mu.Unlock() |
| 340 | 535 | |
| 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)) |
| 350 | 539 | return |
| 351 | 540 | } |
| 352 | | _ = c.setPlaylistTitle(insertAt, label) |
| 353 | 541 | |
| 354 | 542 | c.mu.Lock() |
| 355 | | // Insert into slots map at insertAt |
| 356 | 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 | 545 | } else { |
| 359 | | slot := playlistSlot{Episode: c.currentPlaying, Mode: alt, Label: label} |
| 360 | 546 | c.slots = append(c.slots[:insertAt], append([]playlistSlot{slot}, c.slots[insertAt:]...)...) |
| 361 | 547 | } |
| 362 | 548 | c.mu.Unlock() |
| 363 | 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. |
| 553 | func (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 | |
| 366 | 579 | func (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 | 587 | for { |
| 368 | 588 | if c.closed() { |
| 369 | 589 | return |
| @@ -371,62 +591,532 @@ func (c *MPVPlaylistController) watchPlaylistSelection() { |
| 371 | 591 | if !IsMPVRunning(c.socket) { |
| 372 | 592 | return |
| 373 | 593 | } |
| 374 | | if c.suppress.Load() { |
| 375 | | time.Sleep(mpvPlaylistPollInterval) |
| 594 | if c.suppress.Load() || MPVPlaylistIsSwitching() { |
| 595 | time.Sleep(poll) |
| 376 | 596 | continue |
| 377 | 597 | } |
| 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") |
| 381 | 640 | continue |
| 382 | 641 | } |
| 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") |
| 385 | 694 | continue |
| 386 | 695 | } |
| 387 | | if pos == c.lastPos { |
| 388 | | time.Sleep(mpvPlaylistPollInterval) |
| 389 | | continue |
| 696 | |
| 697 | if path != "" { |
| 698 | lastSeenPath = path |
| 390 | 699 | } |
| 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 | |
| 704 | func 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). |
| 709 | func (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 |
| 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 |
| 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 | |
| 402 | | func (c *MPVPlaylistController) handlePlaylistJump(pos int) { |
| 771 | // playlistLeaveAction is the user's choice when leaving an episode via playlist. |
| 772 | type playlistLeaveAction string |
| 773 | |
| 774 | const ( |
| 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. |
| 783 | var promptPlaylistEpisodeLeave = defaultPromptPlaylistEpisodeLeave |
| 784 | |
| 785 | func 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 | |
| 847 | func 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. |
| 857 | func (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 | 881 | c.mu.Lock() |
| 882 | defer c.mu.Unlock() |
| 404 | 883 | 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)) |
| 407 | 885 | } |
| 408 | 886 | 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 | |
| 891 | func (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 | |
| 913 | func 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 | |
| 935 | func (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 | 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)) |
| 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. |
| 957 | func (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 | |
| 1061 | func 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 | |
| 1069 | func 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 | |
| 1087 | func (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 | |
| 427 | 1113 | func (c *MPVPlaylistController) episodeIndex(ep int, mode string) int { |
| 428 | 1114 | c.mu.Lock() |
| 429 | 1115 | defer c.mu.Unlock() |
| 1116 | return c.episodeIndexLocked(ep, mode) |
| 1117 | } |
| 1118 | |
| 1119 | func (c *MPVPlaylistController) episodeIndexLocked(ep int, mode string) int { |
| 430 | 1120 | mode = normalizeTranslationType(mode) |
| 431 | 1121 | for i, s := range c.slots { |
| 432 | 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 | |
| 448 | 1138 | func (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 | 1142 | c.suppress.Store(true) |
| 450 | 1143 | defer c.suppress.Store(false) |
| 451 | 1144 | |
| @@ -457,16 +1150,34 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error { |
| 457 | 1150 | cfg := *c.config |
| 458 | 1151 | cfg.SubOrDub = mode |
| 459 | 1152 | |
| 460 | | // Work on a shallow copy for provider id resolution side effects, then copy back. |
| 461 | 1153 | anime := c.anime |
| 462 | 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 | 1177 | if err != nil || len(result.Links) == 0 { |
| 467 | 1178 | anime.Ep.Number = prevEp |
| 468 | 1179 | if err == nil { |
| 469 | | err = fmt.Errorf("no streams") |
| 1180 | err = fmt.Errorf("no streams for episode %d", targetEp) |
| 470 | 1181 | } |
| 471 | 1182 | return err |
| 472 | 1183 | } |
| @@ -476,29 +1187,86 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error { |
| 476 | 1187 | link := PrioritizeLink(result.Links) |
| 477 | 1188 | if link == "" { |
| 478 | 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 | 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 | 1207 | anime.Ep.Number = prevEp |
| 487 | 1208 | return err |
| 488 | 1209 | } |
| 489 | 1210 | |
| 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 |
| 492 | 1225 | anime.Ep.IsCompleted = false |
| 493 | 1226 | anime.Ep.Player.PlaybackTime = 0 |
| 494 | 1227 | anime.Ep.Duration = 0 |
| 495 | 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 | 1257 | c.mu.Lock() |
| 498 | | c.currentPlaying = slot.Episode |
| 1258 | c.currentPlaying = targetEp |
| 499 | 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 | 1265 | c.mu.Unlock() |
| 501 | 1266 | |
| 1267 | // Stream is live — safe for the main loop again. |
| 1268 | endMPVPlaylistSwitch() |
| 1269 | |
| 502 | 1270 | // Refresh skip times in background (non-blocking for playback). |
| 503 | 1271 | go func(ep int) { |
| 504 | 1272 | if c.anime.MalId > 0 { |
| @@ -510,38 +1278,218 @@ func (c *MPVPlaylistController) playSlot(slot playlistSlot) error { |
| 510 | 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 | 1284 | go func() { |
| 517 | | time.Sleep(mpvPlaylistIdleDelay) |
| 518 | | if c.closed() { |
| 1285 | time.Sleep(mpvPlaylistIdleDelay + time.Second) |
| 1286 | if c.closed() || alreadyAlt { |
| 519 | 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 | 1289 | c.hasAlternate = false |
| 525 | 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). |
| 1299 | func 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 | 1337 | return nil |
| 530 | 1338 | } |
| 531 | 1339 | |
| 532 | | func (c *MPVPlaylistController) retitleSlots() { |
| 1340 | func 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). |
| 1353 | func 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). |
| 1400 | func 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 | |
| 1412 | func 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 | |
| 1421 | func 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. |
| 1430 | func (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 | 1452 | c.suppress.Store(true) |
| 534 | 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 | 1487 | 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) |
| 538 | 1490 | 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 |
| 547 | 1494 | } |
| 1495 | |