Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 277x 1x 242x 242x 242x 1x 428x 1x 1630x 1630x 922x 1x 1x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 247x 247x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 87x 87x 87x 87x 28x 11x 1897x 1897x 1897x 1897x 1897x 1897x 232x 1897x 233x 233x 233x 233x 233x 1897x 1897x 341x 341x 341x 341x 341x 341x 341x 341x 341x 1897x 1897x 559x 559x 125x 125x 125x 69x 56x 1897x 460x 460x 460x 220x 210x 3x 2x 209x 202x 202x 202x 209x 1897x 1897x 240x 232x 15x 7x 232x 232x 232x 232x 232x 1897x 1897x 460x 460x 460x 460x 72x 72x 1897x 477x 477x 477x 238x 238x 1897x 239x 239x 239x 239x 239x 239x 239x 239x 1x 239x 238x 239x 239x 239x 238x 239x 239x 239x 1897x 256x 256x 256x 256x 256x 249x 15x 15x 15x 15x 15x 234x 1897x 12x 12x 12x 12x 12x 7x 7x 7x 5x 2x 2x 5x 1897x 199x 199x 15x 15x 15x 199x 14x 3x 3x 3x 1897x 243x 201x 201x 201x 201x 199x 199x 199x 2x 2x 2x 2x 2x 2x 42x 42x 36x 36x 36x 35x 35x 35x 35x 35x 42x 42x 15x 15x 1897x 1897x 1897x 507x 15x 1897x 513x 280x 1897x 303x 71x 1897x 1897x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 28x 28x 28x 28x 1897x 1897x 232x 232x 232x 232x 1897x 232x 222x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 1897x 424x 91x 35x 33x 33x 26x 26x 26x 26x 24x 28x 26x 18x 18x 18x 17x 17x 13x 13x 8x 6x 5x 1x 1x 9x 9x 9x 25x 26x 26x 1897x 513x 128x 128x 1897x 513x 280x 128x 128x 6x 128x 1897x 514x 514x 1897x 514x 281x 281x 156x 156x 1897x 514x 126x 140x 126x 514x 514x 1897x 514x 281x 281x 129x 285x 281x 1897x 8x 8x 7x 8x 8x 8x 8x 8x 8x 8x 8x 1897x 56x 56x 52x 52x 52x 52x 52x 52x 1897x 1897x 1897x 1897x 1897x 719x 235x 235x 218x 218x 218x 17x 17x 10x 10x 9x 8x 8x 1897x 1897x 455x 449x 449x 1897x 212x 212x 1897x 1897x 2x 1897x 1897x 1897x 1897x 341x 1897x 8x 8x 8x 8x 8x 1897x 1x 1x 1897x 7x 7x 1897x 1897x 1897x 1897x 2x 2x 1897x 1897x 1897x 1897x 1897x 2x 1x 1897x 6x 1897x 240x 1897x 14x 14x 14x 1897x 232x 1897x 98x 97x 95x 93x 92x 92x 91x 91x 89x 1x 88x 3x 3x 85x 85x 83x 83x 3x 1x 2x 3x 2x 2x 2x 2x 2x 6x 6x 3x 2x 2x 2x 3x 3x 3x 3x 3x 35x 35x 3x 3x 2x 2x 11x 11x 4x 4x 9x 2x 7x 1x 6x 1x 5x 1x 1x 4x 4x 4x 4x 9x 83x 1897x 6x 6x 6x 6x 6x 1897x 1897x 233x 1897x 1897x 1897x 1897x 1897x 1897x 2x 2x 1x 1x 1x 1x 1897x 3x 1897x 3x 2x 2x 1x 1x 4x 1x 7x 61x 2x 32x 32x 61x 48x 48x 48x 48x 46x 2x 2x 2x 3x 2x 1x 3x 2x 2x 1x 1x 2x 2x 1x 1x 1x 2x 3x 2x 7x | // SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Max Boksem. See NOTICE for additional terms under GPLv3 section 7.
import { Controls } from "./Controls";
import { ConnectionStatusOverlay } from "./ConnectionStatusOverlay";
import { OpeningIndicator } from "./OpeningIndicator";
import { SubtitlePicker, type SubtitlePick } from "./SubtitlePicker";
import { SubtitleOverlay } from "./SubtitleOverlay";
import { ResumePrompt } from "./ResumePrompt";
import { ShortcutsOverlay } from "./ShortcutsOverlay";
import { VideoTapLayer } from "./VideoTapLayer";
import { SkipSegmentPrompt } from "./SkipSegmentPrompt";
import { MovieInfoDrawer } from "@/components/channels/MovieInfoDrawer";
import { SeriesDetailModal } from "@/components/channels/SeriesDetailModal";
import { LiveInfoDrawer } from "@/components/channels/LiveInfoDrawer";
import { useState, useCallback, useEffect, useLayoutEffect, useRef, useMemo } from "react";
import { useLocation, useNavigate } from "react-router";
import { useMpv } from "@/hooks/useMpv";
import { useLatestRef } from "@/hooks/useLatestRef";
import { useChanged } from "@/hooks/useChanged";
import { useMediaDetails } from "@/hooks/useMediaDetails";
import { useChannels } from "@/hooks/useChannels";
import {
mpvSetBounds,
mpvSetMediaInfo,
recordPlayStart,
recordPlayEnd,
searchSubtitles,
downloadSubtitle,
readSubtitleFile,
mpvSubAdd,
mpvSubRemove,
mpvSetSubDelay,
mpvGetState,
getPlaybackPosition,
savePlaybackPosition,
deletePlaybackPosition,
handOffProgress,
resolveLocalDownload,
enqueueMovieDownload,
enqueueEpisodeDownload,
stopDownload,
removeDownload,
} from "@/lib/tauri";
import { parseSrt } from "@/lib/subtitle-parser";
import type { Channel, SubtitleCue, SubtitleEntry } from "@/lib/types";
import { useFullscreen } from "@/lib/fullscreen-context";
import { useLeaveFullscreenOnUnmount } from "@/hooks/useLeaveFullscreenOnUnmount";
import { useDownloads } from "@/hooks/useDownloads";
import { DownloadButton } from "@/components/downloads/DownloadButton";
import { playbackKey, isFinished, shouldOfferResume, MIN_RESUME_SECONDS } from "@/lib/playback";
import { channelSources, withSource } from "@/lib/sources";
import { downloadIconState } from "@/lib/download-status";
import { sortEpisodes } from "@/lib/episodes";
import { seriesTitleOf } from "@/lib/channels";
import {
resolvePlayerHotkey,
isInside,
isTypingTarget,
isKeyboardFocusedControl,
repeatsWhenHeld,
} from "@/lib/hotkeys";
import { usePlayerFocus } from "@/hooks/usePlayerFocus";
import { useSubtitleNudge } from "@/hooks/useSubtitleNudge";
import { DEFAULT_SUBTITLE_POSITION } from "@/lib/subtitle-position";
import {
readSubtitleSession,
saveSubtitleSession,
updateSubtitleSession,
type SubtitlePreference,
type SubtitleSession,
} from "@/lib/subtitle-session";
import { formatSkip, formatTime } from "@/lib/format";
import {
readSkipIntervals,
readSkipSegmentModes,
SKIP_INTERVALS_EVENT,
SKIP_SEGMENT_MODES_EVENT,
type SkipSegmentModes,
} from "@/lib/player-prefs";
import { nextSkip, type SkipRun } from "@/lib/skip";
import { addWatchedTime } from "@/lib/browse-state";
import { usePlatform } from "@/hooks/usePlatform";
import { usePlayerPref } from "@/hooks/usePlayerPref";
import { useSkipSegments } from "@/hooks/useSkipSegments";
import { skipButtonShows, useSegmentSkipping } from "@/hooks/useSegmentSkipping";
import { isMobilePlatform } from "@/lib/platform";
import { hasFullscreenButton } from "@/lib/fullscreen";
import { ChevronLeft } from "lucide-react";
/** How often (ms) watch progress is persisted while playing. */
const PROGRESS_SAVE_INTERVAL = 5000;
const MAX_VOLUME = 150;
const LOADED_URL_KEY = "mvp_lastLoadedUrl";
/** Position jumps larger than this between polls are seeks, not watching. */
const MAX_WATCH_STEP_SECONDS = 5;
/** How long the controls stay up after they appear or the player is clicked or tapped. */
const CONTROLS_HIDE_MS = 4000;
/**
* A poll this close to an episode's end counts as seeing the end coming. Polls
* come every second, so a hidden window whose polls slow to every few seconds
* still gets one.
*/
const END_LEAD_SECONDS = 10;
/**
* The poll that finds the end has to come within this long (ms) of the last one
* that saw it coming. A longer gap most likely means this page's timers were
* stopped while mpv played on, as iOS does in the background.
*/
const END_SEEN_WITHIN_MS = 30_000;
/**
* How many times a player page has read the subtitles the last one saved. A
* pick that mpv adds after its page closed only goes in them until another
* page reads them.
*/
let subtitleSessionReads = 0;
interface PlaybackProgress {
/** Resume key (see playbackKey); null for live or nothing playing. */
key: string | null;
/** URL the progress belongs to — mpv state for any other URL is ignored. */
url: string | null;
position: number;
duration: number;
/** Position changed since the last save. */
dirty: boolean;
lastSaved: number;
/**
* Resume point the load was started at. Until playback reaches it, earlier
* positions (mpv reporting the start of the file before the seek lands) are
* ignored so they can't overwrite or delete the saved resume point.
*/
pendingStart: number | null;
}
const EMPTY_PROGRESS: PlaybackProgress = {
key: null,
url: null,
position: 0,
duration: 0,
dirty: false,
lastSaved: 0,
pendingStart: null,
};
const progressFor = (ch: Channel, startPos?: number, url = ch.url): PlaybackProgress => ({
key: playbackKey(ch),
url,
position: startPos ?? 0,
duration: 0,
dirty: false,
lastSaved: Date.now(),
pendingStart: startPos ?? null,
});
/**
* Has Rust save `p`'s position from now on, or stop saving when `p` has
* nothing to save. The position `p` holds goes stale from here, and flushing
* it later, say on a stop right after the app comes back, would overwrite the
* newer one Rust saved.
*/
const handOffToRust = (p: PlaybackProgress) => {
p.dirty = false;
const { key, url, pendingStart } = p;
handOffProgress(key && url ? { key, url, pendingStart } : null).catch(() => {});
};
/** Same season + episode (duplicate entries of one episode from different sources). */
const isSameEpisode = (a: Channel, b: Channel): boolean =>
a.season != null && a.episode != null && a.season === b.season && a.episode === b.episode;
interface PendingResume {
channel: Channel;
position: number;
duration: number;
/** "nav" = opened from outside the player; cancelling goes back. */
origin: "nav" | "player";
/** Something was playing (and got paused) when the prompt opened. */
wasPlaying: boolean;
apply?: () => void;
}
/** Extract season/episode numbers from a channel name like "Show S01E05". */
const parseSeasonEpisode = (name: string): { season?: number; episode?: number } => {
const m = name.match(/S(\d{1,3})E(\d{1,3})/i);
if (m) return { season: parseInt(m[1], 10), episode: parseInt(m[2], 10) };
return {};
};
/** Used in place of Settings while the skip prompt can't show. */
const SKIPPING_OFF: SkipSegmentModes = { opening: "off", ending: "off" };
export const PlayerView = () => {
const mpv = useMpv();
const { channels } = useChannels();
const { byChannel } = useDownloads();
const location = useLocation();
const navigate = useNavigate();
const [showControls, setShowControls] = useState(true);
const containerRef = useRef<HTMLDivElement>(null);
const [showInfoDrawer, setShowInfoDrawer] = useState(false);
const [activeChannelName, setActiveChannelName] = useState<string | null>(null);
const [activeChannel, setActiveChannel] = useState<Channel | null>(null);
// Episode list for series navigation — set when navigating from SeriesDetailModal
const [seriesEpisodes, setSeriesEpisodes] = useState<Channel[]>([]);
const { isFullscreen, setFullscreen } = useFullscreen();
useLeaveFullscreenOnUnmount();
// The phone layout hides the tab bar on this route, so the player needs
// its own way back.
const { layoutMode } = usePlatform();
const showBack = layoutMode === "mobile";
// Phones and tablets set the volume with the hardware buttons. An Android
// TV box has no touch screen, so it keeps the volume and shortcut
// controls for its remote.
const touchDevice = isMobilePlatform() && navigator.maxTouchPoints > 0;
const fullscreenButton = hasFullscreenButton(touchDevice, layoutMode);
const [showSubtitlePicker, setShowSubtitlePicker] = useState(false);
const [selectedSubtitleId, setSelectedSubtitleId] = useState<number | null>(null);
const [subtitleCues, setSubtitleCues] = useState<SubtitleCue[]>([]);
const [selectedSubtitleEntry, setSelectedSubtitleEntry] = useState<SubtitleEntry | null>(null);
const [subtitleFontSize, setSubtitleFontSize] = useState(18);
const [subtitleFontFamily, setSubtitleFontFamily] = useState("system-ui, sans-serif");
const [subtitlePos, setSubtitlePos] = useState(DEFAULT_SUBTITLE_POSITION);
const [subtitleDelay, setSubtitleDelay] = useState(0);
const [subtitleEditMode, setSubtitleEditMode] = useState(false);
const [autoplay, setAutoplay] = useState(true);
const [pendingResume, setPendingResume] = useState<PendingResume | null>(null);
const [showShortcuts, setShowShortcuts] = useState(false);
// Brief centre-screen feedback for keyboard actions ("+10s", "Volume 80%", …).
const [osdText, setOsdText] = useState<{ text: string; id: number } | null>(null);
const osdTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const mpvStateRef = useLatestRef(mpv.state);
const activeChannelRef = useLatestRef(activeChannel);
const playStartTimeRef = useRef<number | null>(null);
const progressRef = useRef<PlaybackProgress>(EMPTY_PROGRESS);
// The URL mpv was last asked to play. For a download it's the file's path
// rather than the channel's URL.
const [loadedUrl, setLoadedUrl] = useState(() => sessionStorage.getItem(LOADED_URL_KEY));
const loadedUrlRef = useLatestRef(loadedUrl);
const rememberLoadedUrl = useCallback((url: string) => {
sessionStorage.setItem(LOADED_URL_KEY, url);
setLoadedUrl(url);
}, []);
// Guards against out-of-order resolution when items are opened in quick succession.
const startRequestRef = useRef(0);
const loadRequestRef = useRef(0);
// Set when the viewer stops playback, which also forgets the subtitles.
const stoppedRef = useRef(false);
// False once the page closes. A subtitle the viewer picked, which mpv
// draws and adds after that, goes to the ones the page saved, as long as
// no other page has read them since. Any other subtitle that loads after
// the page closed is dropped. An item still waiting to start doesn't
// start, since the page that would show it is gone.
const openRef = useRef(false);
// The value of subtitleSessionReads when this page opened, or when it last
// read the saved subtitles.
const readsSeenRef = useRef(0);
// Counts the viewer's subtitle picks, so a subtitle still downloading for
// an earlier pick, or for the auto-load, gives way to a newer one.
const subtitlePickRef = useRef(0);
/**
* Starts a subtitle choice for the item playing now. One the viewer makes
* replaces any choice before it. The auto-load replaces none, and gives way
* to the viewer's next pick.
*/
const followSubtitlePick = useCallback(
(byViewer: boolean): SubtitlePick => {
const pick = byViewer ? ++subtitlePickRef.current : subtitlePickRef.current;
const channelId = activeChannelRef.current?.id;
const latest = () => pick === subtitlePickRef.current;
return {
latest,
stream: () =>
latest() && openRef.current && activeChannelRef.current?.id === channelId
? loadedUrlRef.current
: null,
// The page saved its subtitles when it closed, and the next one
// opens with them, so the pick goes there. Once another page has
// read them, it shows what it read.
keep: (url, entry, rankInLanguage) =>
!openRef.current &&
subtitleSessionReads === readsSeenRef.current &&
channelId !== undefined &&
updateSubtitleSession(channelId, url, {
fileId: entry.fileId,
entry,
cues: [],
preference: { languageCode: entry.languageCode, rankInLanguage },
autoLoad: false,
}),
};
},
[activeChannelRef, loadedUrlRef]
);
// Remembers which language + rank-within-language the user last picked so the
// same subtitle can be auto-selected when navigating to the next episode.
const [subtitlePreference, setSubtitlePreference] = useState<SubtitlePreference | null>(null);
// Refs used by the auto-load effect to avoid stale closures.
const subtitlePreferenceRef = useLatestRef(subtitlePreference);
// Incremented each time an episode navigation should trigger subtitle auto-load.
// Using state (not a ref) so the effect dependency is tracked by React.
const [autoLoadTrigger, setAutoLoadTrigger] = useState(0);
// The last trigger whose load finished, so the page knows when it closes
// whether one was still running.
const [autoLoadFinished, setAutoLoadFinished] = useState(0);
const navState = location.state as {
url?: string;
channelName?: string;
channel?: Channel;
seriesEpisodes?: Channel[];
} | null;
// Opened without a new item, the page shows the one that played on while
// it was closed, and the subtitles it had then.
const [keptSubtitles, setKeptSubtitles] = useState(() =>
navState?.url ? null : readSubtitleSession()
);
// useLayoutEffect ensures the background is set BEFORE the browser paints,
// preventing a transparent flash when navigating to the player page.
useLayoutEffect(() => {
document.documentElement.style.backgroundColor = mpv.firstFrameReady
? "transparent"
: "black";
document.body.style.backgroundColor = mpv.firstFrameReady ? "transparent" : "black";
return () => {
document.documentElement.style.backgroundColor = "";
document.body.style.backgroundColor = "";
};
}, [mpv.firstFrameReady]);
usePlayerFocus(containerRef, mpv.state.currentUrl);
// Report video container bounds to the Rust renderer. The CSD header bar
// offset is applied on the Rust side via LinuxGlRenderer::csd_offset (x, y),
// so the frontend just sends raw getBoundingClientRect values.
useEffect(() => {
const el = containerRef.current;
Iif (!el) return;
const report = () => {
const r = el.getBoundingClientRect();
mpvSetBounds(r.x, r.y, r.width, r.height).catch(() => {});
};
report();
const ro = new ResizeObserver(report);
ro.observe(el);
return () => ro.disconnect();
}, [mpv.state.currentUrl]);
// Arrow keys reposition subtitle overlay when settings pane is open
useSubtitleNudge(subtitleEditMode, setSubtitlePos);
// --- Watch progress (resume support) ---
// Persist the tracked position for the current item. Finished items are
// forgotten, as are items rewound to the very start (e.g. "Start over"),
// so they don't keep offering a stale resume point.
const flushProgress = useCallback(() => {
const p = progressRef.current;
if (!p.key || !p.dirty || p.duration <= 0) return;
p.dirty = false;
p.lastSaved = Date.now();
if (isFinished(p.position, p.duration) || p.position < MIN_RESUME_SECONDS) {
deletePlaybackPosition(p.key).catch(() => {});
} else {
savePlaybackPosition(p.key, p.position, p.duration).catch(() => {});
}
}, []);
useEffect(() => {
const p = progressRef.current;
const { currentUrl, position, duration, isPaused } = mpv.state;
if (!p.key || !currentUrl || currentUrl !== p.url) return;
if (duration <= 0 || position <= 1) return;
if (p.pendingStart !== null) {
if (position < p.pendingStart - 5) return;
p.pendingStart = null;
}
if (position !== p.position || duration !== p.duration) {
p.position = position;
p.duration = duration;
p.dirty = true;
}
if (isPaused || Date.now() - p.lastSaved >= PROGRESS_SAVE_INTERVAL) flushProgress();
}, [mpv.state, flushProgress]);
useEffect(() => () => flushProgress(), [flushProgress]);
// This page can't save progress while it's hidden, because iOS stops its
// timers once the app is in the background though audio keeps playing, or
// after it closes with the item still playing. Rust saves it until the
// player is visible again.
useEffect(() => {
const handOff = () => handOffToRust(progressRef.current);
const onVisibilityChange = () => {
if (document.visibilityState === "hidden") handOff();
else handOffProgress(null).catch(() => {});
};
handOffProgress(null).catch(() => {});
document.addEventListener("visibilitychange", onVisibilityChange);
return () => {
document.removeEventListener("visibilitychange", onVisibilityChange);
handOff();
};
}, []);
// Watch time: the channel list keeps its search unless the user watched for
// a while (see lib/browse-state). Only forward playback counts, so time spent
// paused, buffering or loading doesn't.
const watchTickRef = useRef<{ url: string | null; position: number }>({
url: null,
position: 0,
});
useEffect(() => {
const { currentUrl, position, isPlaying, isPaused } = mpv.state;
const last = watchTickRef.current;
watchTickRef.current = { url: currentUrl, position };
if (!currentUrl || currentUrl !== last.url || !isPlaying || isPaused) return;
const advanced = position - last.position;
if (advanced > 0 && advanced <= MAX_WATCH_STEP_SECONDS) addWatchedTime(advanced * 1000);
}, [mpv.state]);
/** Saves how long the current item played, once per start. */
const recordEnd = useCallback(() => {
const ch = activeChannelRef.current;
const startedAt = playStartTimeRef.current;
if (!ch || startedAt === null) return;
playStartTimeRef.current = null;
recordPlayEnd(ch.id, Math.floor((Date.now() - startedAt) / 1000)).catch(() => {});
}, [activeChannelRef]);
/** Actually start playing `ch` (optionally from `startPos`), replacing whatever is playing. */
const commitPlayback = useCallback(
(ch: Channel, startPos?: number, apply?: () => void) => {
recordEnd();
playStartTimeRef.current = Date.now();
recordPlayStart(ch.id, ch.name, ch.logoUrl ?? null, ch.contentType).catch(() => {});
const progress = progressFor(ch, startPos);
progressRef.current = progress;
// Until the new stream loads, nothing may pair the old one's URL
// and length with the new channel, such as the skip time lookup.
setLoadedUrl(null);
// Prefer a completed download so playback works offline; fall back to
// the stream URL if there is none or the lookup fails.
const loadId = ++loadRequestRef.current;
resolveLocalDownload(ch.id)
.catch(() => null)
.then((local) => {
if (loadId !== loadRequestRef.current) return;
const target = local ?? ch.url;
progress.url = target;
rememberLoadedUrl(target);
// A page that closed while the player looked for a download
// saved its subtitles with no stream. They're for this one.
if (!openRef.current) updateSubtitleSession(ch.id, null, { url: target });
return mpv.load(target, startPos);
})
.catch(() => {});
setActiveChannelName(ch.name);
setActiveChannel(ch);
apply?.();
},
[mpv, rememberLoadedUrl, recordEnd]
);
/**
* Entry point for every "play this item" action. Movies and episodes with
* a saved mid-way position first show the resume prompt; everything else
* starts immediately. `apply` runs once playback actually starts (e.g.
* clearing subtitle state for a new episode).
*/
const startPlayback = useCallback(
async (ch: Channel, origin: "nav" | "player", apply?: () => void) => {
const requestId = ++startRequestRef.current;
flushProgress();
const key = playbackKey(ch);
const saved = key ? await getPlaybackPosition(key).catch(() => null) : null;
if (requestId !== startRequestRef.current || !openRef.current) return;
if (saved && shouldOfferResume(saved.positionSeconds, saved.durationSeconds)) {
const s = mpvStateRef.current;
const wasPlaying = s.isPlaying && !s.isPaused;
if (wasPlaying) mpv.pause();
setPendingResume({
channel: ch,
position: saved.positionSeconds,
duration: saved.durationSeconds,
origin,
wasPlaying,
apply,
});
return;
}
commitPlayback(ch, undefined, apply);
},
[mpv, mpvStateRef, flushProgress, commitPlayback]
);
const resolveResume = useCallback(
(choice: "resume" | "restart" | "cancel") => {
const pending = pendingResume;
Iif (!pending) return;
setPendingResume(null);
containerRef.current?.focus();
if (choice === "cancel") {
if (pending.wasPlaying) mpv.play();
if (pending.origin === "nav") navigate(-1);
return;
}
if (choice === "restart") {
// Forget the old resume point now; progress tracking only clears it
// once playback moves, which a quick stop would skip.
const key = playbackKey(pending.channel);
Eif (key) deletePlaybackPosition(key).catch(() => {});
}
commitPlayback(
pending.channel,
choice === "resume" ? pending.position : undefined,
pending.apply
);
},
[pendingResume, mpv, navigate, commitPlayback]
);
// When the player is re-entered with a new item while the previous one kept
// playing in the background, capture the previous item's latest position so
// the flush in startPlayback saves it.
const adoptBackgroundProgress = async (): Promise<void> => {
const saved = sessionStorage.getItem("mvp_lastChannel");
if (!saved || progressRef.current.key) return;
try {
const prev: Channel = JSON.parse(saved);
const loaded = sessionStorage.getItem(LOADED_URL_KEY) ?? prev.url;
const s = await mpvGetState();
if (s.currentUrl === loaded && s.duration > 0 && s.position > 1) {
const progress = {
...progressFor(prev, undefined, loaded),
position: s.position,
duration: s.duration,
dirty: true,
};
progressRef.current = progress;
// The page closed while it waited for mpv, when it had nothing
// to hand Rust yet, so nothing else would save this item's
// progress until the player opens again.
if (!openRef.current) handOffToRust(progress);
}
} catch {}
};
// The player's handler for arriving on its page. It takes what to play from
// the router, or from sessionStorage when the page opens without it, and
// starts mpv. It runs again when the router's URL changes on a mounted
// player, as when the sidebar's Player link is clicked on the player page,
// so starting values for the state wouldn't cover it.
useEffect(() => {
if (navState?.url) {
const navEpisodes = navState.seriesEpisodes?.length ? navState.seriesEpisodes : null;
const navChannel = navState.channel;
const navUrl = navState.url;
if (navChannel) {
const ch = navChannel.url === navUrl ? navChannel : withSource(navChannel, navUrl);
// The episode list belongs with the item, so it changes only if
// the item starts, not when the start is cancelled or dropped.
const apply = navEpisodes ? () => setSeriesEpisodes(navEpisodes) : undefined;
adoptBackgroundProgress().finally(() => startPlayback(ch, "nav", apply));
} else {
// eslint-disable-next-line react-hooks/set-state-in-effect -- applies the navigation, see above
Iif (navEpisodes) setSeriesEpisodes(navEpisodes);
loadRequestRef.current++;
rememberLoadedUrl(navUrl);
mpv.load(navUrl).catch(() => {});
setActiveChannelName(navState.channelName ?? null);
setActiveChannel(null);
}
} else {
// Navigating back to player without a new channel (e.g. via sidebar menu)
const saved = sessionStorage.getItem("mvp_lastChannel");
if (saved) {
try {
const ch: Channel = JSON.parse(saved);
// A page that opens has no item yet, so it reads the subtitles
// here, after a closed page could still change them. The page
// can also be open already, as over a resume prompt for another
// item, and then it read no subtitles when it opened.
if (ch.id !== activeChannel?.id) {
readsSeenRef.current = ++subtitleSessionReads;
setKeptSubtitles(readSubtitleSession());
}
setActiveChannel(ch);
setActiveChannelName(ch.name);
progressRef.current = progressFor(
ch,
undefined,
sessionStorage.getItem(LOADED_URL_KEY) ?? ch.url
);
} catch {}
}
const savedEpisodes = sessionStorage.getItem("mvp_lastSeriesEpisodes");
if (savedEpisodes) {
try {
setSeriesEpisodes(JSON.parse(savedEpisodes));
} catch {}
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- intentionally keyed on URL only; re-running on mpv/channel refs would cause loops
}, [navState?.url]);
// mpv only knows the stream URL, so tell the lock screen the channel name,
// whether it's live, and the logo to show.
const activeIsLive = activeChannel?.contentType === "live";
const activeLogo = activeChannel?.logoUrl ?? null;
useEffect(() => {
if (!isMobilePlatform()) return;
mpvSetMediaInfo(activeChannelName, activeIsLive, activeLogo).catch(() => {});
}, [activeChannelName, activeIsLive, activeLogo]);
// Persist last active channel and series episode list so they can be restored when navigating back
useEffect(() => {
if (activeChannel) {
sessionStorage.setItem("mvp_lastChannel", JSON.stringify(activeChannel));
}
}, [activeChannel]);
useEffect(() => {
if (seriesEpisodes.length > 0) {
sessionStorage.setItem("mvp_lastSeriesEpisodes", JSON.stringify(seriesEpisodes));
}
}, [seriesEpisodes]);
// A new item starts with no subtitles. Resetting them while rendering keeps
// the old item's from showing with it for a frame. The item that played on
// while the page was closed gets back the subtitles it had, as long as the
// player hasn't loaded anything else for it since.
const channelChanged = useChanged(activeChannel?.id);
if (channelChanged) {
const kept =
keptSubtitles?.channelId === activeChannel?.id && keptSubtitles?.url === loadedUrl
? keptSubtitles
: null;
setKeptSubtitles(null);
setShowSubtitlePicker(false);
setSelectedSubtitleId(kept?.fileId ?? null);
setSubtitleCues(kept?.cues ?? []);
setSelectedSubtitleEntry(kept?.entry ?? null);
setSubtitleEditMode(false);
setSubtitleDelay(kept?.delay ?? 0);
setSubtitlePos(kept?.position ?? DEFAULT_SUBTITLE_POSITION);
if (kept) {
setSubtitleFontSize(kept.fontSize);
setSubtitleFontFamily(kept.fontFamily);
setSubtitlePreference(kept.preference);
// The next episode's subtitles were still loading, so load them again.
if (kept.autoLoad) setAutoLoadTrigger((t) => t + 1);
}
}
// mpv doesn't draw the subtitles the overlay draws, so keep them for when
// this page opens again while the item plays on.
const subtitleSessionRef = useLatestRef<SubtitleSession | null>(
activeChannel && {
channelId: activeChannel.id,
url: loadedUrl,
fileId: selectedSubtitleId,
entry: selectedSubtitleEntry,
cues: subtitleCues,
delay: subtitleDelay,
position: subtitlePos,
fontSize: subtitleFontSize,
fontFamily: subtitleFontFamily,
preference: subtitlePreference,
autoLoad:
autoLoadTrigger > autoLoadFinished &&
subtitlePreference !== null &&
selectedSubtitleId === null,
}
);
// Layout effects, so the page counts as closed and has saved its
// subtitles once it's off the screen. A navigation runs passive cleanups
// later, and a subtitle that loads in between would go to the closed page.
// The page takes the count of reads as it opens, since one opened with a
// new item never reads the saved subtitles, and checks its own late pick
// against that.
useLayoutEffect(() => {
openRef.current = true;
readsSeenRef.current = subtitleSessionReads;
return () => {
openRef.current = false;
};
}, []);
useLayoutEffect(
() => () => {
if (stoppedRef.current) saveSubtitleSession(null);
// A page that never started an item, as when the viewer cancels the
// resume prompt, leaves the subtitles of the one that plays on.
else if (subtitleSessionRef.current) saveSubtitleSession(subtitleSessionRef.current);
},
[subtitleSessionRef]
);
// Load the details up front for a movie or series, so the info sheet opens
// with them and subtitles can search by IMDb id. A recording is live TV.
const mediaKind =
activeChannel?.contentType === "movie" || activeChannel?.contentType === "series"
? activeChannel.contentType
: null;
const mediaDetails = useMediaDetails(
activeChannel && mediaKind
? { id: activeChannel.id, title: seriesTitleOf(activeChannel), kind: mediaKind }
: null
);
// The sheets load their own until OMDb has answered here.
const prefetchedOmdbData = mediaDetails.loading ? undefined : mediaDetails.omdbData;
const prefetchedWhatsonData = mediaDetails.loading ? undefined : mediaDetails.whatsonData;
const activeImdbId = mediaDetails.omdbData?.imdbId ?? null;
// A recording has no info drawer.
const hasInfo = !!activeChannel && activeChannel.contentType !== "recording";
const canShowSubtitles =
activeImdbId !== null &&
(activeChannel?.contentType === "movie" || activeChannel?.contentType === "series");
// Season/episode for subtitle search: prefer structured channel data, fall back to parsing the name
const { season: parsedSeason, episode: parsedEpisode } = activeChannel
? parseSeasonEpisode(activeChannel.name)
: {};
const subtitleSeason = activeChannel?.season ?? parsedSeason;
const subtitleEpisode = activeChannel?.episode ?? parsedEpisode;
// Refs so the auto-load effect can read fresh values without stale closures.
const subtitleSeasonRef = useLatestRef(subtitleSeason);
const subtitleEpisodeRef = useLatestRef(subtitleEpisode);
// Auto-load: fires when playEpisode increments autoLoadTrigger, then waits for
// activeImdbId to resolve. Using a trigger counter avoids the cancellation bug
// where a new item's activeImdbId goes null mid-flight and kills the search.
// A load still to run waits while the player finds out whether a download
// of the item plays, and so which stream the subtitles go to. One that
// finished doesn't run again when the same item restarts.
const autoLoadWaits = autoLoadTrigger > autoLoadFinished && loadedUrl === null;
useEffect(() => {
if (autoLoadTrigger === 0) return; // no episode navigation yet
if (!activeImdbId) return; // OMDB still in-flight; re-run when it resolves
if (autoLoadWaits) return;
const pref = subtitlePreferenceRef.current;
if (!pref) return;
const pick = followSubtitlePick(false);
let cancelled = false;
searchSubtitles(activeImdbId, subtitleSeasonRef.current, subtitleEpisodeRef.current)
.then(async (result) => {
if (cancelled) return;
const langEntries = (result?.entries ?? []).filter(
(e) => e.languageCode === pref.languageCode
);
if (langEntries.length === 0) return; // preferred language not available, keep none
const entry = langEntries[Math.min(pref.rankInLanguage, langEntries.length - 1)];
const localPath = await downloadSubtitle(entry.fileId);
// mpv also reads a file that isn't UTF-8, and draws any file the
// overlay can't read.
const cues = await readSubtitleFile(localPath).then(parseSrt, () => []);
const url = pick.stream();
if (cancelled || url === null) return;
// When the overlay read no cues, only mpv can show the
// subtitles, so the choice changes once mpv has the track.
const added = mpvSubAdd(localPath, cues.length > 0, url);
if (cues.length > 0) added.catch(() => {});
else {
await added;
// mpv draws this track itself. A pick the viewer made during
// the add replaces it on its own. When the page closed or the
// player moved on, the track comes out again, so it doesn't
// show over the subtitles the player keeps.
if (!pick.latest()) return;
if (cancelled || pick.stream() === null) {
await mpvSubRemove(-1, url).catch(() => {});
return;
}
}
setSelectedSubtitleId(entry.fileId);
setSubtitleCues(cues);
setSelectedSubtitleEntry(entry);
})
.catch(() => {}) // silent, subtitle is best-effort
.finally(() => {
if (!cancelled) setAutoLoadFinished(autoLoadTrigger);
});
return () => {
cancelled = true;
};
}, [
autoLoadTrigger,
activeImdbId,
autoLoadWaits,
followSubtitlePick,
subtitlePreferenceRef,
subtitleSeasonRef,
subtitleEpisodeRef,
]);
// --- Series episode navigation ---
// Derive episodes from passed list (Xtream) or local cache (M3U)
const localSeriesEpisodes = useMemo(() => {
if (!activeChannel || activeChannel.contentType !== "series") return [];
const title = seriesTitleOf(activeChannel);
return channels.filter((ch) => ch.contentType === "series" && seriesTitleOf(ch) === title);
}, [activeChannel, channels]);
// Series container id used to group download records — matches the series
// card id in the channel list so download state stays consistent.
const seriesContainerId = useMemo(() => {
if (!activeChannel) return "";
if (activeChannel.contentType !== "series") return activeChannel.id;
const title = seriesTitleOf(activeChannel);
const container = channels.find(
(ch) => ch.contentType === "series" && seriesTitleOf(ch) === title
);
return container?.id ?? activeChannel.id;
}, [activeChannel, channels]);
const sortedEpisodes = useMemo(() => {
const source = seriesEpisodes.length > 0 ? seriesEpisodes : localSeriesEpisodes;
return sortEpisodes(source);
}, [seriesEpisodes, localSeriesEpisodes]);
// Match by id first: the URL changes when the user switches source.
const currentEpIdx = useMemo(() => {
if (!activeChannel) return -1;
const byId = sortedEpisodes.findIndex((ep) => ep.id === activeChannel.id);
if (byId >= 0) return byId;
const urls = channelSources(activeChannel);
return sortedEpisodes.findIndex((ep) => urls.includes(ep.url));
}, [activeChannel, sortedEpisodes]);
// Skip over duplicate entries of the current episode (same S/E from another source).
const { prevEpisode, nextEpisode } = useMemo(() => {
if (currentEpIdx < 0 || !activeChannel) return { prevEpisode: null, nextEpisode: null };
const current = sortedEpisodes[currentEpIdx];
const differs = (ep: Channel) => !isSameEpisode(ep, current) && ep.id !== current.id;
const prev = sortedEpisodes.slice(0, currentEpIdx).reverse().find(differs) ?? null;
const next = sortedEpisodes.slice(currentEpIdx + 1).find(differs) ?? null;
return { prevEpisode: prev, nextEpisode: next };
}, [activeChannel, sortedEpisodes, currentEpIdx]);
// Every stream URL for the current item: its own sources plus, for series,
// duplicate entries of the same episode elsewhere in the episode list.
const availableSources = useMemo(() => {
if (!activeChannel) return [];
const urls = [...channelSources(activeChannel)];
if (activeChannel.contentType === "series") {
for (const ep of sortedEpisodes) {
if (isSameEpisode(ep, activeChannel)) urls.push(...channelSources(ep));
}
}
return [...new Set(urls)];
}, [activeChannel, sortedEpisodes]);
/** Switch the current item to another source, keeping the playback position. */
const switchSource = useCallback(
(url: string) => {
const ch = activeChannelRef.current;
if (!ch || url === ch.url) return;
const resumeAt = ch.contentType === "live" ? 0 : mpv.getLastKnownPosition();
flushProgress();
const startPos = resumeAt > 1 ? resumeAt : undefined;
// The item stays the same, so its subtitles stay too. Before its
// first stream loads, mpv still has the last item's, so drop those.
const keepSubtitles = loadedUrlRef.current !== null;
progressRef.current = {
...progressRef.current,
url,
lastSaved: Date.now(),
pendingStart: startPos ?? null,
};
loadRequestRef.current++;
rememberLoadedUrl(url);
mpv.load(url, startPos, keepSubtitles).catch(() => {});
setActiveChannel({ ...ch, url, sourceList: availableSources });
},
[mpv, activeChannelRef, loadedUrlRef, flushProgress, availableSources, rememberLoadedUrl]
);
const playEpisode = useCallback(
(ep: Channel) => {
setShowInfoDrawer(false);
startPlayback(ep, "player", () => {
setSelectedSubtitleId(null);
setSubtitleCues([]);
setSelectedSubtitleEntry(null);
setSubtitleEditMode(false);
setSubtitleDelay(0);
// Increment trigger so the auto-load effect fires for this episode.
setAutoLoadTrigger((t) => t + 1);
});
},
[startPlayback]
);
// On unmount, record end of play
useEffect(() => recordEnd, [recordEnd]);
// --- Autoplay next episode ---
// Use refs to avoid stale closures while keeping the effect dependency minimal
const nextEpisodeRef = useLatestRef(nextEpisode);
const autoplayRef = useLatestRef(autoplay);
// Advance when the episode reaches its end, not when it stops near it. A
// pause in the last seconds, or the resume prompt pausing the player, leaves
// reachedEnd false. At the end, with keep-open=yes, mpv holds the last frame,
// paused, so with autoplay off, on a movie or on the last episode the
// controls stay up and nothing else needs doing.
//
// Only an end this player saw coming counts. The ref holds the stream that
// a poll last saw in its final seconds and when, and any poll from further
// back clears it. Coming back from another page to an episode that ended
// there leaves it on the last frame. So does coming back to the app after
// iOS held this page's timers in the background for longer than
// END_SEEN_WITHIN_MS while mpv played on.
const seenNearEndRef = useRef<{ url: string; at: number } | null>(null);
useEffect(() => {
// A poll can still describe the previous stream after the app loads
// another one, such as from the Next episode button near the end.
if (!loadedUrl || mpv.state.currentUrl !== loadedUrl) return;
const { reachedEnd, position, duration } = mpv.state;
if (!reachedEnd) {
// useMpv sets a new state on every poll, paused or not, so a long
// pause in the last seconds keeps this time fresh.
const nearEnd = duration > 0 && duration - position <= END_LEAD_SECONDS;
seenNearEndRef.current = nearEnd ? { url: loadedUrl, at: Date.now() } : null;
return;
}
const seen = seenNearEndRef.current;
if (!seen || seen.url !== loadedUrl) return;
seenNearEndRef.current = null;
if (Date.now() - seen.at > END_SEEN_WITHIN_MS) return;
if (autoplayRef.current && activeChannelRef.current?.contentType === "series") {
const next = nextEpisodeRef.current;
Eif (next) playEpisode(next);
}
}, [mpv.state, loadedUrl, playEpisode, autoplayRef, activeChannelRef, nextEpisodeRef]);
// --- Controls visibility ---
// Bumped by each click or tap so pressing a button, such as skip a few
// times in a row, keeps the controls up.
const [controlsActivity, setControlsActivity] = useState(0);
useEffect(() => {
if (!showControls) return;
const timer = setTimeout(() => setShowControls(false), CONTROLS_HIDE_MS);
return () => clearTimeout(timer);
}, [showControls, controlsActivity]);
const revealControls = useCallback(() => {
setShowControls(true);
setControlsActivity((n) => n + 1);
}, []);
const handleMouseMove = useCallback(() => setShowControls(true), []);
// A tap on a touch screen also sends a mousemove, which would undo the
// tap's toggle, so there only a real mouse or trackpad shows the controls.
const handlePointerMove = useCallback((e: React.PointerEvent) => {
if (e.pointerType === "mouse") setShowControls(true);
}, []);
// --- Skipping ---
const skip = usePlayerPref(readSkipIntervals, SKIP_INTERVALS_EVENT);
// Same test as the seek bar, which live channels usually don't get.
const seekable = mpv.state.duration > 0;
// Skips in a row add up, as nextSkip describes. The returned total is how
// far the run of skips has moved.
const lastSkipRef = useRef<SkipRun | null>(null);
useEffect(() => {
lastSkipRef.current = null;
}, [mpv.state.currentUrl]);
const skipBy = useCallback(
(seconds: number): number => {
const s = mpvStateRef.current;
const run = nextSkip(lastSkipRef.current, s.position, s.duration, seconds, Date.now());
lastSkipRef.current = run;
mpv.seek(run.target);
return run.total;
},
[mpv, mpvStateRef]
);
// The tap layer keeps its clicks from the player, so a double-tap skip
// restarts the hide timer here, as a press on a skip button does. Hidden
// controls stay hidden.
const skipFromTap = useCallback(
(seconds: number): number => {
setControlsActivity((n) => n + 1);
return skipBy(seconds);
},
[skipBy]
);
const seekTo = useCallback(
(position: number) => {
lastSkipRef.current = null;
mpv.seek(position);
},
[mpv]
);
// --- Intros, recaps, credits and previews ---
const savedSegmentModes = usePlayerPref(readSkipSegmentModes, SKIP_SEGMENT_MODES_EVENT);
// mpv's own window has no prompt, so nothing is skipped there.
const segmentModes = mpv.fallbackActive ? SKIPPING_OFF : savedSegmentModes;
const { video, segments } = useSkipSegments({
imdbId: activeImdbId,
contentType: activeChannel?.contentType,
season: subtitleSeason,
episode: subtitleEpisode,
// The polled length belongs to the stream mpv reports, which trails
// the one asked for by a moment after switching.
url: loadedUrl === mpv.state.currentUrl ? loadedUrl : null,
duration: mpv.state.duration,
enabled: segmentModes.opening !== "off" || segmentModes.ending !== "off",
});
const playNextEpisode = useCallback(() => {
const next = nextEpisodeRef.current;
Eif (next) playEpisode(next);
}, [playEpisode, nextEpisodeRef]);
// Something open over the prompt holds it, so the player doesn't skip
// where the notice and its Undo can't be seen.
const skipHeld = showShortcuts || !!pendingResume || showSubtitlePicker || showInfoDrawer;
// A stream that's reconnecting holds the countdown, as a pause does.
const videoPlaying = mpv.state.isPlaying && !mpv.state.isPaused && !mpv.reconnecting;
const skipping = useSegmentSkipping({
video,
segments,
position: mpv.state.position,
duration: mpv.state.duration,
reconnecting: mpv.reconnecting,
playing: videoPlaying && !skipHeld,
modes: segmentModes,
autoplay,
hasNext: nextEpisode !== null,
seek: seekTo,
onNextEpisode: playNextEpisode,
});
// Enter presses the prompt's button, so only while one is on screen.
const skipSegment = !skipHeld && skipButtonShows(skipping, showControls) ? skipping.skip : null;
const goBack = useCallback(() => {
// "default" is the first history entry, so there's nothing to go back to.
if (location.key !== "default") navigate(-1);
else navigate("/");
}, [location.key, navigate]);
// --- Fullscreen ---
const toggleFullscreen = useCallback(
() => setFullscreen(!isFullscreen),
[isFullscreen, setFullscreen]
);
// An iPad Split View pane narrow enough for the phone layout has no full
// screen button, so it leaves full screen instead of keeping the sidebar
// hidden.
useEffect(() => {
if (!fullscreenButton && isFullscreen) setFullscreen(false);
}, [fullscreenButton, isFullscreen, setFullscreen]);
// --- Keyboard ---
const flashOsd = useCallback((text: string) => {
if (osdTimerRef.current) clearTimeout(osdTimerRef.current);
setOsdText({ text, id: Date.now() });
osdTimerRef.current = setTimeout(() => setOsdText(null), 900);
}, []);
useEffect(
() => () => {
if (osdTimerRef.current) clearTimeout(osdTimerRef.current);
},
[]
);
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
// A confirm opened from the controls renders in a portal, and it keeps
// its keys while it's open.
if (!isInside(containerRef.current, e.target)) return;
// The resume prompt handles its own keys. Its dialog takes Escape
// first, even when focus is on the player behind it.
if (pendingResume) return;
if (isTypingTarget(e.target)) return;
// Space or Enter on a button reached with Tab presses that button.
if ((e.key === " " || e.key === "Enter") && isKeyboardFocusedControl(e.target)) return;
// While the subtitle settings pane is open, arrow keys belong to subtitle
// position/delay handlers — don't let them also seek or change volume.
const isArrow = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(e.key);
if (subtitleEditMode && isArrow) return;
const action = resolvePlayerHotkey(e, skip);
if (!action) return;
if (showShortcuts && action.type !== "toggleShortcuts" && action.type !== "escape")
return;
// Enter is only taken when the skip prompt shows a button, so it
// still presses a button that has focus. Held down, it skips once.
if (action.type === "skipSegment") {
if (!e.repeat && skipSegment?.()) e.preventDefault();
return;
}
e.preventDefault();
if (e.repeat && !repeatsWhenHeld(action)) return;
const s = mpv.state;
switch (action.type) {
case "togglePlay":
if (s.isPaused || !s.isPlaying) {
mpv.play();
} else {
mpv.pause();
}
break;
case "toggleFullscreen":
toggleFullscreen();
break;
case "toggleMute":
mpv.toggleMute();
flashOsd(s.volume > 0 ? "Muted" : "Unmuted");
break;
case "seekBy":
flashOsd(formatSkip(skipBy(action.seconds)));
break;
case "seekToPercent":
if (s.duration > 0) {
const target = (s.duration * action.percent) / 100;
seekTo(target);
flashOsd(formatTime(target));
}
break;
case "volumeBy": {
const v = Math.min(
MAX_VOLUME,
Math.max(0, Math.round(s.volume + action.delta))
);
mpv.setVolume(v);
flashOsd(`Volume ${v}%`);
break;
}
case "nextEpisode":
if (nextEpisode) playEpisode(nextEpisode);
break;
case "prevEpisode":
Eif (prevEpisode) playEpisode(prevEpisode);
break;
case "toggleSubtitles":
if (canShowSubtitles) setShowSubtitlePicker((v) => !v);
break;
case "toggleInfo":
if (hasInfo) setShowInfoDrawer((v) => !v);
break;
case "toggleShortcuts":
setShowShortcuts((v) => !v);
break;
case "escape":
if (showShortcuts) {
setShowShortcuts(false);
} else if (isFullscreen) {
setFullscreen(false);
} else if (showInfoDrawer) {
setShowInfoDrawer(false);
} else if (showSubtitlePicker) {
setShowSubtitlePicker(false);
setSubtitleEditMode(false);
} else {
// Note: playStartTimeRef is NOT nulled here intentionally.
// The unmount cleanup records the elapsed time when the route changes.
flushProgress();
stoppedRef.current = true;
mpv.stop();
navigate("/");
}
break;
}
setShowControls(true);
},
[
mpv,
pendingResume,
showShortcuts,
isFullscreen,
showInfoDrawer,
showSubtitlePicker,
navigate,
setFullscreen,
subtitleEditMode,
toggleFullscreen,
flashOsd,
nextEpisode,
prevEpisode,
playEpisode,
canShowSubtitles,
hasInfo,
flushProgress,
skip,
skipBy,
seekTo,
skipSegment,
]
);
const handleStop = useCallback(() => {
recordEnd();
flushProgress();
stoppedRef.current = true;
mpv.stop();
navigate("/");
}, [mpv, navigate, flushProgress, recordEnd]);
// Closing mpv's own window stops playback, like the stop button.
const handleStopRef = useLatestRef(handleStop);
useEffect(() => {
if (mpv.windowClosedId > 0) handleStopRef.current();
}, [mpv.windowClosedId, handleStopRef]);
// --- Info drawer episode source ---
const episodesForDrawer = sortedEpisodes.length > 0 ? sortedEpisodes : localSeriesEpisodes;
const showTitleForDrawer = activeChannel ? seriesTitleOf(activeChannel) : "";
// --- Player download control (movies + series episodes only) ---
const playerDl = activeChannel ? byChannel.get(activeChannel.id) : undefined;
const playerDownloadState = downloadIconState(playerDl);
const showPlayerDownload =
!!activeChannel &&
(activeChannel.contentType === "movie" || activeChannel.contentType === "series");
const downloadSlot = showPlayerDownload ? (
<DownloadButton
itemId={activeChannel.id}
state={playerDownloadState}
onStart={() => {
Iif (!activeChannel) return;
if (activeChannel.contentType === "series") {
void enqueueEpisodeDownload(
activeChannel,
seriesContainerId,
showTitleForDrawer
);
} else {
void enqueueMovieDownload(activeChannel.id);
}
}}
onStop={() => playerDl && void stopDownload(playerDl.id)}
onRemove={() => playerDl && removeDownload(playerDl.id)}
/>
) : undefined;
// Resumes where the stream broke, not from the start of the movie or episode.
const retryStream = () => {
mpv.reload().catch(() => {});
};
return (
<div
ref={containerRef}
className={
isFullscreen
? "player-container fixed inset-0 z-9999 bg-transparent focus:outline-hidden"
: "player-container relative h-full w-full bg-transparent focus:outline-hidden"
}
onMouseMove={touchDevice ? undefined : handleMouseMove}
onPointerMove={touchDevice ? handlePointerMove : undefined}
onClick={revealControls}
onKeyDown={handleKeyDown}
tabIndex={0}
>
{mpv.fallbackActive && (
<div className="absolute top-4 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 rounded-lg border border-yellow-500/40 bg-yellow-950/80 px-4 py-2 text-yellow-200 text-sm shadow-lg backdrop-blur-xs max-w-xl">
<span>⚠</span>
<span>
The video can't show here, so it plays in a window of its own. Closing that
window stops playback.
</span>
</div>
)}
<ConnectionStatusOverlay
reconnecting={mpv.reconnecting}
reconnectAttempt={mpv.reconnectAttempt}
// Buffering before the first frame is part of opening, which has
// its own spinner. Failures and reconnects still outrank it.
buffering={mpv.buffering && !mpv.opening}
loadFailed={mpv.loadFailed}
openFailed={mpv.openFailed}
recentlyRecovered={mpv.recentlyRecovered}
onRetry={retryStream}
belowTopBar={showBack}
/>
<div
className="absolute inset-0 flex flex-col items-center justify-center bg-transparent"
onDoubleClick={touchDevice ? undefined : toggleFullscreen}
>
{mpv.error && (
<div className="text-center p-6 max-w-md">
<p className="text-destructive text-sm mb-2 wrap-break-word">{mpv.error}</p>
{!isMobilePlatform() && (
<p className="text-muted-foreground text-xs">
Check that libmpv is installed. See README for setup instructions.
</p>
)}
</div>
)}
{!mpv.error &&
!mpv.opening &&
!mpv.state.currentUrl &&
!mpv.state.isPlaying &&
!mpv.state.isPaused && (
<p className="text-muted-foreground text-lg">
Select a channel to start watching
</p>
)}
{mpv.opening && <OpeningIndicator key={mpv.loadId} onRetry={retryStream} />}
</div>
{touchDevice && (
<VideoTapLayer
seekable={seekable}
skip={skip}
onSkip={skipFromTap}
onTap={() => setShowControls((v) => !v)}
/>
)}
{(activeChannelName || showBack) && showControls && (
<div className="absolute top-0 left-0 right-0 flex items-center gap-1 bg-linear-to-b from-black/60 to-transparent p-4 pt-[calc(1rem+env(safe-area-inset-top))] pl-[calc(1rem+env(safe-area-inset-left))] pr-[calc(1rem+env(safe-area-inset-right))]">
{showBack && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
goBack();
}}
aria-label="Back"
className="-my-2 -ml-3 flex h-11 w-11 shrink-0 items-center justify-center rounded-full text-white active:bg-white/10"
>
<ChevronLeft className="h-6 w-6" />
</button>
)}
{activeChannelName && (
<p className="min-w-0 truncate text-white text-sm font-medium">
{activeChannelName}
</p>
)}
</div>
)}
{osdText && (
<div
key={osdText.id}
className="pointer-events-none absolute top-1/4 left-1/2 -translate-x-1/2 z-30 rounded-lg bg-black/70 px-4 py-2 text-sm font-medium text-white tabular-nums shadow-lg"
>
{osdText.text}
</div>
)}
{!mpv.fallbackActive && (
<SkipSegmentPrompt
skipping={skipping}
controlsVisible={showControls}
playing={videoPlaying}
held={skipHeld}
onFocusLost={() => containerRef.current?.focus()}
/>
)}
{!mpv.fallbackActive && (
<Controls
state={{
isPlaying: mpv.state.isPlaying,
isPaused: mpv.state.isPaused,
currentUrl: mpv.state.currentUrl,
volume: mpv.state.volume,
position: mpv.state.position,
duration: mpv.state.duration,
}}
visible={showControls}
isFullscreen={isFullscreen}
onPlay={mpv.play}
onPause={mpv.pause}
onStop={handleStop}
onSeek={seekTo}
skip={seekable ? skip : undefined}
onSkip={(seconds) => flashOsd(formatSkip(skipBy(seconds)))}
touchLayout={touchDevice}
// Play, pause and skip do nothing useful while the stream opens
// or after it fails, and the spinner or the error has the middle
// to itself.
hideCenterControls={mpv.opening || mpv.openFailed || mpv.loadFailed}
onVolumeChange={mpv.setVolume}
onToggleMute={mpv.toggleMute}
onFullscreen={fullscreenButton ? toggleFullscreen : undefined}
onInfo={hasInfo ? () => setShowInfoDrawer(true) : undefined}
onPrevEpisode={prevEpisode ? () => playEpisode(prevEpisode) : undefined}
onNextEpisode={nextEpisode ? () => playEpisode(nextEpisode) : undefined}
autoplay={autoplay}
onAutoplayChange={setAutoplay}
hasSubtitles={selectedSubtitleId !== null}
onSubtitles={
canShowSubtitles ? () => setShowSubtitlePicker((v) => !v) : undefined
}
sources={availableSources}
currentSource={activeChannel?.url ?? null}
onSelectSource={switchSource}
onShortcuts={touchDevice ? undefined : () => setShowShortcuts((v) => !v)}
showVolumeSlider={!touchDevice}
downloadSlot={downloadSlot}
/>
)}
{showSubtitlePicker && activeImdbId && (
<SubtitlePicker
imdbId={activeImdbId}
season={subtitleSeason}
episode={subtitleEpisode}
onClose={() => {
setShowSubtitlePicker(false);
setSubtitleEditMode(false);
}}
startPick={() => followSubtitlePick(true)}
onSubtitleSelected={(id, cues, entry, rankInLanguage) => {
setSelectedSubtitleId(id);
setSubtitleCues(cues ?? []);
setSelectedSubtitleEntry(entry ?? null);
if (entry && rankInLanguage !== undefined) {
setSubtitlePreference({
languageCode: entry.languageCode,
rankInLanguage,
});
} else {
// User clicked None — clear preference so next episode gets no subtitle.
setSubtitlePreference(null);
}
}}
currentSelectedId={selectedSubtitleId}
currentSelectedEntry={selectedSubtitleEntry}
subtitleFontSize={subtitleFontSize}
subtitleFontFamily={subtitleFontFamily}
subtitleDelay={subtitleDelay}
onFontSizeChange={setSubtitleFontSize}
onFontFamilyChange={setSubtitleFontFamily}
onDelayChange={(d) => {
setSubtitleDelay(d);
mpvSetSubDelay(d).catch(() => {});
}}
onSettingsModeChange={(active) => setSubtitleEditMode(active)}
/>
)}
{/* mpv's own window shows the subtitles itself. */}
{!mpv.fallbackActive && (subtitleCues.length > 0 || subtitleEditMode) && (
<SubtitleOverlay
cues={subtitleCues}
position={mpv.state.position}
positionAt={mpv.state.positionAt}
playing={videoPlaying && !mpv.buffering && !mpv.state.waiting}
fontSize={subtitleFontSize}
fontFamily={subtitleFontFamily}
posX={subtitlePos.x}
posY={subtitlePos.y}
delay={subtitleDelay}
editMode={subtitleEditMode}
onPositionChange={(x, y) => setSubtitlePos({ x, y })}
/>
)}
{/* Info drawers */}
{showInfoDrawer && activeChannel && activeChannel.contentType === "series" && (
<SeriesDetailModal
showTitle={showTitleForDrawer}
episodes={episodesForDrawer}
seriesChannelId={seriesContainerId}
onClose={() => setShowInfoDrawer(false)}
currentUrl={activeChannel.url}
onPlay={(ch) => {
// Same episode, different source → switch in place and keep the position.
if (isSameEpisode(ch, activeChannel)) {
setShowInfoDrawer(false);
switchSource(ch.url);
} else {
playEpisode(ch);
}
}}
prefetchedOmdbData={prefetchedOmdbData}
prefetchedWhatsonData={prefetchedWhatsonData}
/>
)}
{showInfoDrawer && activeChannel && activeChannel.contentType === "movie" && (
<MovieInfoDrawer
movie={activeChannel}
onClose={() => setShowInfoDrawer(false)}
onPlay={(ch) => {
setShowInfoDrawer(false);
// Same movie, different source → switch in place and keep the position.
if (ch.id === activeChannel.id) {
switchSource(ch.url);
} else {
startPlayback(ch, "player");
}
}}
prefetchedOmdbData={prefetchedOmdbData}
prefetchedWhatsonData={prefetchedWhatsonData}
/>
)}
{showInfoDrawer && activeChannel && activeChannel.contentType === "live" && (
<LiveInfoDrawer channel={activeChannel} onClose={() => setShowInfoDrawer(false)} />
)}
{showShortcuts && (
<ShortcutsOverlay skip={skip} onClose={() => setShowShortcuts(false)} />
)}
{pendingResume && (
<ResumePrompt
title={pendingResume.channel.name}
position={pendingResume.position}
duration={pendingResume.duration}
onResume={() => resolveResume("resume")}
onStartOver={() => resolveResume("restart")}
onCancel={() => resolveResume("cancel")}
/>
)}
</div>
);
};
|