Skip to content

基于自定义规则的番剧采集APP,支持流媒体在线观看,支持弹幕,支持实时超分辨率。

refactor: centralize video async ownership (#2089)

Predidit750b30a14052
diff --git a/lib/pages/download/download_page.dart b/lib/pages/download/download_page.dart
index 16fd0607..2aba43ba 100644
--- a/lib/pages/download/download_page.dart
+++ b/lib/pages/download/download_page.dart
@@ -374,9 +374,7 @@ class _DownloadPageState extends State<DownloadPage> {
bangumiItem: bangumiItem,
pluginName: record.pluginName,
episodeNumber: episode.episodeNumber,
- episodeName: episode.episodeName,
road: episode.road,
- videoPath: localPath,
downloadedEpisodes: downloadedEpisodes,
);
diff --git a/lib/pages/info/info_page.dart b/lib/pages/info/info_page.dart
index 65fa1dcb..4b237a79 100644
--- a/lib/pages/info/info_page.dart
+++ b/lib/pages/info/info_page.dart
@@ -161,7 +161,7 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
infoController.commentsList.clear();
infoController.staffList.clear();
infoController.pluginSearchResponseList.clear();
- videoPageController.currentEpisode = 1;
+ videoPageController.resetEpisodeState();
// Because the gap between different bangumi API response is too large, sometimes we need to query the bangumi info again
// We need the type parameter to determine whether to attach the new data to the old data
// We can't generally replace the old data with the new data, because the old data contains images url, update them will cause the image to reload and flicker
@@ -210,7 +210,7 @@ class _InfoPageState extends State<InfoPage> with TickerProviderStateMixin {
infoController.commentsList.clear();
infoController.staffList.clear();
infoController.pluginSearchResponseList.clear();
- videoPageController.currentEpisode = 1;
+ videoPageController.resetEpisodeState();
sourceTabController.dispose();
infoTabController.dispose();
super.dispose();
diff --git a/lib/pages/player/controller/player_danmaku_controller.dart b/lib/pages/player/controller/player_danmaku_controller.dart
index 7d74ad37..d89ea273 100644
--- a/lib/pages/player/controller/player_danmaku_controller.dart
+++ b/lib/pages/player/controller/player_danmaku_controller.dart
@@ -17,6 +17,16 @@ part 'player_danmaku_controller.g.dart';
class PlayerDanmakuController = _PlayerDanmakuController
with _$PlayerDanmakuController;
+class DanmakuLoadResult {
+ const DanmakuLoadResult({
+ required this.danmakus,
+ required this.bangumiID,
+ });
+
+ final List<Danmaku> danmakus;
+ final int bangumiID;
+}
+
abstract class _PlayerDanmakuController with Store {
_PlayerDanmakuController({
required this.setting,
@@ -36,32 +46,49 @@ abstract class _PlayerDanmakuController with Store {
bool danmakuLoading = false;
DanmakuDestination danmakuDestination = DanmakuDestination.remoteDanmaku;
- // DanDanPlay 弹幕ID
int bangumiID = 0;
- /// 加载弹幕 (离线模式优先从缓存加载,无缓存时尝试在线获取)
- Future<void> loadDanmaku(
- int bangumiId, String pluginName, int episode) async {
+ // Fetching must not mutate current danmaku state; VideoPageController applies
+ // the result only after confirming the playback session is still current.
+ Future<DanmakuLoadResult> fetchDanmaku(
+ int bangumiId,
+ String pluginName,
+ int episode,
+ ) async {
if (isLocalPlayback()) {
- await _loadCachedDanmaku(bangumiId, pluginName, episode);
- } else {
- await getDanDanmakuByBgmBangumiID(bangumiId, episode);
+ return await _fetchCachedDanmaku(
+ bangumiId,
+ pluginName,
+ episode,
+ );
}
+ return await _fetchDanDanmakuByBgmBangumiID(
+ bangumiId,
+ episode,
+ );
}
- Future<void> _loadCachedDanmaku(
- int bangumiId, String pluginName, int episode) async {
- if (danmakuLoading) {
- KazumiLogger()
- .i('PlayerController: danmaku is loading, ignore duplicate request');
- return;
- }
+ void beginDanmakuLoad() {
+ danDanmakus.clear();
+ danmakuLoading = true;
+ }
+
+ void applyDanmakuLoad(DanmakuLoadResult result) {
+ bangumiID = result.bangumiID;
+ addDanmakus(result.danmakus);
+ danmakuLoading = false;
+ }
+
+ void finishDanmakuLoad() {
+ danmakuLoading = false;
+ }
+ Future<DanmakuLoadResult> _fetchCachedDanmaku(
+ int bangumiId, String pluginName, int episode) async {
KazumiLogger().i(
'PlayerController: attempting to load cached danmaku for episode $episode');
- danmakuLoading = true;
+ var nextBangumiID = bangumiID;
try {
- danDanmakus.clear();
final downloadController = Modular.get<DownloadController>();
final cachedDanmakus = await downloadController.getCachedDanmakus(
bangumiId,
@@ -70,24 +97,30 @@ abstract class _PlayerDanmakuController with Store {
);
if (cachedDanmakus != null && cachedDanmakus.isNotEmpty) {
- addDanmakus(cachedDanmakus);
KazumiLogger().i(
'PlayerController: loaded ${cachedDanmakus.length} cached danmakus');
+ return DanmakuLoadResult(
+ danmakus: cachedDanmakus,
+ bangumiID: nextBangumiID,
+ );
} else {
KazumiLogger()
.i('PlayerController: no cached danmaku, attempting online fetch');
try {
- bangumiID =
+ nextBangumiID =
await DanmakuApi.getDanDanBangumiIDByBgmBangumiID(bangumiId);
- if (bangumiID != 0) {
- var res = await DanmakuApi.getDanDanmaku(bangumiID, episode);
+ if (nextBangumiID != 0) {
+ var res = await DanmakuApi.getDanDanmaku(nextBangumiID, episode);
if (res.isNotEmpty) {
- addDanmakus(res);
KazumiLogger()
.i('PlayerController: fetched ${res.length} danmakus online');
- _saveDanmakuToCache(
- downloadController, bangumiId, pluginName, episode, res);
+ _saveDanmakuToCache(downloadController, bangumiId, pluginName,
+ episode, res, nextBangumiID);
}
+ return DanmakuLoadResult(
+ danmakus: res,
+ bangumiID: nextBangumiID,
+ );
}
} catch (e) {
KazumiLogger().w(
@@ -98,20 +131,19 @@ abstract class _PlayerDanmakuController with Store {
} catch (e) {
KazumiLogger()
.w('PlayerController: failed to load cached danmaku', error: e);
- } finally {
- danmakuLoading = false;
}
+ return DanmakuLoadResult(danmakus: const [], bangumiID: nextBangumiID);
}
void _saveDanmakuToCache(DownloadController downloadController, int bangumiId,
- String pluginName, int episode, List<Danmaku> danmakus) {
+ String pluginName, int episode, List<Danmaku> danmakus, int danDanID) {
try {
downloadController.updateCachedDanmakus(
bangumiId,
pluginName,
episode,
danmakus,
- bangumiID,
+ danDanID,
);
KazumiLogger()
.i('PlayerController: saved ${danmakus.length} danmakus to cache');
@@ -121,39 +153,25 @@ abstract class _PlayerDanmakuController with Store {
}
}
- Future<void> getDanDanmakuByBgmBangumiID(
+ Future<DanmakuLoadResult> _fetchDanDanmakuByBgmBangumiID(
int bgmBangumiID, int episode) async {
- if (danmakuLoading) {
- KazumiLogger()
- .i('PlayerController: danmaku is loading, ignore duplicate request');
- return;
- }
-
KazumiLogger().i(
'PlayerController: attempting to get danmaku [BgmBangumiID] $bgmBangumiID');
- danmakuLoading = true;
+ var nextBangumiID = bangumiID;
try {
- danDanmakus.clear();
- bangumiID =
+ nextBangumiID =
await DanmakuApi.getDanDanBangumiIDByBgmBangumiID(bgmBangumiID);
- var res = await DanmakuApi.getDanDanmaku(bangumiID, episode);
- addDanmakus(res);
+ var res = await DanmakuApi.getDanDanmaku(nextBangumiID, episode);
+ return DanmakuLoadResult(danmakus: res, bangumiID: nextBangumiID);
} catch (e) {
KazumiLogger().w(
'PlayerController: failed to get danmaku [BgmBangumiID] $bgmBangumiID',
error: e);
- } finally {
- danmakuLoading = false;
}
+ return DanmakuLoadResult(danmakus: const [], bangumiID: nextBangumiID);
}
Future<void> getDanDanmakuByEpisodeID(int episodeID) async {
- if (danmakuLoading) {
- KazumiLogger()
- .i('PlayerController: danmaku is loading, ignore duplicate request');
- return;
- }
-
KazumiLogger().i('PlayerController: attempting to get danmaku $episodeID');
danmakuLoading = true;
try {
@@ -171,7 +189,6 @@ abstract class _PlayerDanmakuController with Store {
final bool danmakuDeduplicationEnable =
setting.get(SettingBoxKey.danmakuDeduplication, defaultValue: false);
- // 如果启用了弹幕去重功能则处理5秒内相邻重复类似的弹幕进行合并
final List<Danmaku> listToAdd = danmakuDeduplicationEnable
? Utils.mergeDuplicateDanmakus(danmakus, timeWindowSeconds: 5)
: danmakus;
diff --git a/lib/pages/player/controller/player_debug_controller.dart b/lib/pages/player/controller/player_debug_controller.dart
index adc22ead..611ee9e2 100644
--- a/lib/pages/player/controller/player_debug_controller.dart
+++ b/lib/pages/player/controller/player_debug_controller.dart
@@ -45,12 +45,11 @@ abstract class _PlayerDebugController with Store {
Future<void> setup(
Player player, {
- required int lifecycleId,
- required bool Function(int lifecycleId, Player player) isCurrentPlayer,
+ required bool Function(Player player) isCurrentPlayer,
required bool playerDebugMode,
}) async {
await playerLogSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerLogSubscription = player.stream.log.listen((event) {
playerLog.add(event.toString());
if (playerDebugMode) {
@@ -58,38 +57,38 @@ abstract class _PlayerDebugController with Store {
}
});
await playerWidthSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerWidthSubscription = player.stream.width.listen((event) {
playerWidth = event ?? 0;
});
await playerHeightSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerHeightSubscription = player.stream.height.listen((event) {
playerHeight = event ?? 0;
});
await playerVideoParamsSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerVideoParamsSubscription = player.stream.videoParams.listen((event) {
playerVideoParams = event.toString();
});
await playerAudioParamsSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerAudioParamsSubscription = player.stream.audioParams.listen((event) {
playerAudioParams = event.toString();
});
await playerPlaylistSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerPlaylistSubscription = player.stream.playlist.listen((event) {
playerPlaylist = event.toString();
});
await playerTracksSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerTracksSubscription = player.stream.track.listen((event) {
playerAudioTracks = event.audio.toString();
playerVideoTracks = event.video.toString();
});
await playerAudioBitrateSubscription?.cancel();
- if (!isCurrentPlayer(lifecycleId, player)) return;
+ if (!isCurrentPlayer(player)) return;
playerAudioBitrateSubscription = player.stream.audioBitrate.listen((event) {
playerAudioBitrate = event.toString();
});
diff --git a/lib/pages/player/controller/player_playback_controller.dart b/lib/pages/player/controller/player_playback_controller.dart
index bc8f4774..800292aa 100644
--- a/lib/pages/player/controller/player_playback_controller.dart
+++ b/lib/pages/player/controller/player_playback_controller.dart
@@ -39,7 +39,6 @@ abstract class _PlayerPlaybackController with Store {
Player? mediaPlayer;
VideoController? videoController;
- int lifecycleId = 0;
bool hAenable = true;
late String hardwareDecoder;
@@ -57,7 +56,6 @@ abstract class _PlayerPlaybackController with Store {
@observable
int superResolutionType = 1;
- // 视频音量
@observable
double volume = -1;
@@ -78,14 +76,18 @@ abstract class _PlayerPlaybackController with Store {
@observable
double playerSpeed = 1.0;
- int beginInit() => ++lifecycleId;
-
- void cancelActiveInit() {
- lifecycleId++;
+ bool isCurrentPlayer(Player player) {
+ return identical(mediaPlayer, player);
}
- bool isCurrentPlayer(int expectedLifecycleId, Player player) {
- return lifecycleId == expectedLifecycleId && identical(mediaPlayer, player);
+ Future<Player?> _discardIfNotCurrent(Player player) async {
+ if (isCurrentPlayer(player)) {
+ return player;
+ }
+ try {
+ await player.dispose();
+ } catch (_) {}
+ return null;
}
@action
@@ -157,7 +159,7 @@ abstract class _PlayerPlaybackController with Store {
Future<Player?> createVideoController(
Map<String, String> httpHeaders, bool adBlockerEnabled,
- {int offset = 0, required int lifecycleId}) async {
+ {int offset = 0}) async {
superResolutionType =
setting.get(SettingBoxKey.defaultSuperResolutionType, defaultValue: 1);
hAenable = setting.get(SettingBoxKey.hAenable, defaultValue: true);
@@ -184,32 +186,40 @@ abstract class _PlayerPlaybackController with Store {
debug.playerLog.clear();
await debug.setup(
player,
- lifecycleId: lifecycleId,
isCurrentPlayer: isCurrentPlayer,
playerDebugMode: playerDebugMode,
);
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
var pp = player.platform as NativePlayer;
// media-kit 默认启用硬盘作为双重缓存,这可以维持大缓存的前提下减轻内存压力
// media-kit 内部硬盘缓存目录按照 Linux 配置,这导致该功能在其他平台上被损坏
// 该设置可以在所有平台上正确启用双重缓存
await pp.setProperty("demuxer-cache-dir", await Utils.getPlayerTempPath());
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
await pp.setProperty("af", "scaletempo2=max-speed=8");
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
if (Platform.isAndroid) {
await pp.setProperty("volume-max", "100");
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
if (androidEnableOpenSLES) {
await pp.setProperty("ao", "opensles");
} else {
await pp.setProperty("ao", "audiotrack");
}
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
}
- // 设置 HTTP 代理
final bool proxyEnable =
setting.get(SettingBoxKey.proxyEnable, defaultValue: false);
if (proxyEnable) {
@@ -218,7 +228,9 @@ abstract class _PlayerPlaybackController with Store {
final formattedProxy = ProxyUtils.getFormattedProxyUrl(proxyUrl);
if (formattedProxy != null) {
await pp.setProperty("http-proxy", formattedProxy);
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
KazumiLogger().i('Player: HTTP 代理设置成功 $formattedProxy');
}
}
@@ -226,7 +238,9 @@ abstract class _PlayerPlaybackController with Store {
await player.setAudioTrack(
AudioTrack.auto(),
);
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
String? videoRenderer;
if (Platform.isAndroid) {
@@ -238,6 +252,9 @@ abstract class _PlayerPlaybackController with Store {
// GPU-NEXT 需要 Vulkan 1.2 支持
// 避免 Android 14 及以下设备上部分机型 Vulkan 支持不佳导致的黑屏问题
final int androidSdkVersion = await Utils.getAndroidSdkVersion();
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
if (androidSdkVersion >= 34) {
videoRenderer = 'gpu-next';
} else {
@@ -264,14 +281,15 @@ abstract class _PlayerPlaybackController with Store {
),
);
player.setPlaylistMode(PlaylistMode.none);
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
- // error handle
bool showPlayerError =
setting.get(SettingBoxKey.showPlayerError, defaultValue: true);
player.stream.error.listen((event) {
if (showPlayerError) {
- if (!isCurrentPlayer(lifecycleId, player)) {
+ if (!isCurrentPlayer(player)) {
return;
}
if (event.toString().contains('Failed to open') && playerBuffering) {
@@ -290,7 +308,9 @@ abstract class _PlayerPlaybackController with Store {
if (superResolutionType != 1) {
await setShader(superResolutionType, player: player);
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
}
await player.open(
@@ -298,7 +318,9 @@ abstract class _PlayerPlaybackController with Store {
start: Duration(seconds: offset), httpHeaders: httpHeaders),
play: autoPlay,
);
- if (!isCurrentPlayer(lifecycleId, player)) return null;
+ if (!isCurrentPlayer(player)) {
+ return await _discardIfNotCurrent(player);
+ }
return player;
}
@@ -409,12 +431,7 @@ abstract class _PlayerPlaybackController with Store {
Future<void> dispose({
bool disposeSyncPlayController = true,
- bool cancelActiveInit = true,
}) async {
- // Bump the generation first so late init continuations cannot touch it.
- if (cancelActiveInit) {
- this.cancelActiveInit();
- }
final player = mediaPlayer;
mediaPlayer = null;
videoController = null;
@@ -435,7 +452,11 @@ abstract class _PlayerPlaybackController with Store {
Future<void> stop() async {
try {
final player = mediaPlayer;
+ mediaPlayer = null;
+ videoController = null;
+ await debug.cancel();
await player?.stop();
+ await player?.dispose();
loading = true;
} catch (_) {}
}
diff --git a/lib/pages/player/episode_comments_sheet.dart b/lib/pages/player/episode_comments_sheet.dart
index 2ad4fab0..328433bb 100644
--- a/lib/pages/player/episode_comments_sheet.dart
+++ b/lib/pages/player/episode_comments_sheet.dart
@@ -10,8 +10,6 @@ import 'package:kazumi/pages/video/video_controller.dart';
import 'package:kazumi/request/apis/bangumi_api.dart';
class EpisodeInfoWidget extends InheritedWidget {
- /// This widget receives changes of episode and notify it's child,
- /// trigger [didChangeDependencies] of it's child.
const EpisodeInfoWidget(
{super.key, required this.episode, required super.child});
@@ -39,24 +37,16 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
bool commentsIsEmpty = false;
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey =
GlobalKey<RefreshIndicatorState>();
- int _loadCommentsRequestId = 0;
- /// episode input by [showEpisodeSelection]
int ep = 0;
- @override
- void initState() {
- super.initState();
- }
-
Future<void> loadComments(int episode) async {
- final int requestId = ++_loadCommentsRequestId;
commentsQueryTimeout = false;
commentsIsEmpty = false;
try {
- await videoPageController.queryBangumiEpisodeCommentsByID(
+ final applied = await videoPageController.queryBangumiEpisodeCommentsByID(
videoPageController.bangumiItem.id, episode);
- if (!mounted || requestId != _loadCommentsRequestId) {
+ if (!mounted || !applied) {
return;
}
if (videoPageController.episodeCommentsList.isEmpty && mounted) {
@@ -65,13 +55,13 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
});
}
} catch (e) {
- if (mounted && requestId == _loadCommentsRequestId) {
+ if (mounted) {
setState(() {
commentsQueryTimeout = true;
});
}
}
- if (mounted && requestId == _loadCommentsRequestId) {
+ if (mounted) {
setState(() {});
}
}
@@ -83,30 +73,21 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
@override
void didChangeDependencies() {
ep = 0;
- // wait until currentState is not null
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) {
return;
}
if (videoPageController.episodeCommentsList.isEmpty) {
- // trigger RefreshIndicator onRefresh and show animation
_refreshIndicatorKey.currentState?.show();
}
});
super.didChangeDependencies();
}
- @override
- void dispose() {
- super.dispose();
- }
-
Widget get episodeCommentsBody {
return CustomScrollView(
scrollBehavior: const ScrollBehavior().copyWith(
- // Scrollbars' movement is not linear so hide it.
scrollbars: false,
- // Enable mouse drag to refresh
dragDevices: {
PointerDeviceKind.mouse,
PointerDeviceKind.touch,
@@ -142,8 +123,8 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
return SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
- // Fix scroll issue caused by height change of network images
- // by keeping loaded cards alive.
+ // Keep loaded image cards alive to avoid scroll jumps when
+ // network images report their final size.
return KeepAlive(
keepAlive: true,
child: IndexedSemantics(
@@ -233,7 +214,6 @@ class _EpisodeCommentsSheetState extends State<EpisodeCommentsSheet> {
);
}
- // 选择要查看评论的集数
void showEpisodeSelection() async {
final int selectedEpisode =
ep == 0 ? EpisodeInfoWidget.of(context)!.episode : ep;
diff --git a/lib/pages/player/player_controller.dart b/lib/pages/player/player_controller.dart
index 2bc86150..86f27d75 100644
--- a/lib/pages/player/player_controller.dart
+++ b/lib/pages/player/player_controller.dart
@@ -64,8 +64,7 @@ class PlayerController {
bool isLocalPlayback = false;
Timer? hideVolumeUITimer;
- Future<void> init(PlaybackInitParams params) async {
- final int lifecycleId = playback.beginInit();
+ Future<bool> init(PlaybackInitParams params) async {
videoUrl = params.videoUrl;
isLocalPlayback = params.isLocalPlayback;
bangumiId = params.bangumiId;
@@ -91,66 +90,47 @@ class PlayerController {
try {
await dispose(
disposeSyncPlayController: false,
- cancelActiveInit: false,
);
} catch (_) {}
- if (playback.lifecycleId != lifecycleId) {
- return;
- }
- int episodeFromTitle = 0;
- try {
- episodeFromTitle = Utils.extractEpisodeNumber(params.episodeTitle);
- } catch (e) {
- KazumiLogger().e(
- 'PlayerController: failed to extract episode number from title',
- error: e);
- }
- if (episodeFromTitle == 0) {
- episodeFromTitle = params.episode;
- }
- _loadDanmaku(params.bangumiId, params.pluginName, episodeFromTitle);
final Player? player;
try {
player = await playback.createVideoController(
params.httpHeaders,
params.adBlockerEnabled,
offset: params.offset,
- lifecycleId: lifecycleId,
);
} catch (e) {
- if (playback.lifecycleId == lifecycleId) {
- playback.loading = false;
- KazumiLogger()
- .e('PlayerController: failed to initialize video', error: e);
- }
- return;
+ playback.loading = false;
+ KazumiLogger()
+ .e('PlayerController: failed to initialize video', error: e);
+ return false;
}
- if (player == null || !playback.isCurrentPlayer(lifecycleId, player)) {
- return;
+ if (player == null || !playback.isCurrentPlayer(player)) {
+ return false;
}
if (Utils.isDesktop()) {
playback.volume = playback.volume != -1 ? playback.volume : 100;
await setVolume(playback.volume);
- if (!playback.isCurrentPlayer(lifecycleId, player)) {
- return;
+ if (!playback.isCurrentPlayer(player)) {
+ return false;
}
} else {
await FlutterVolumeController.getVolume().then((value) {
playback.volume = (value ?? 0.0) * 100;
});
- if (!playback.isCurrentPlayer(lifecycleId, player)) {
- return;
+ if (!playback.isCurrentPlayer(player)) {
+ return false;
}
await FlutterVolumeController.updateShowSystemUI(false);
- if (!playback.isCurrentPlayer(lifecycleId, player)) {
+ if (!playback.isCurrentPlayer(player)) {
await FlutterVolumeController.updateShowSystemUI(true);
- return;
+ return false;
}
FlutterVolumeController.addListener((volume) {
- if (player == null || !playback.isCurrentPlayer(lifecycleId, player)) {
+ if (player == null || !playback.isCurrentPlayer(player)) {
return;
}
playback.volume = volume * 100;
@@ -163,13 +143,13 @@ class PlayerController {
});
}
}, category: AudioSessionCategory.playback, emitOnStart: false);
- if (!playback.isCurrentPlayer(lifecycleId, player)) {
- return;
+ if (!playback.isCurrentPlayer(player)) {
+ return false;
}
}
setPlaybackSpeed(playback.playerSpeed);
- if (!playback.isCurrentPlayer(lifecycleId, player)) {
- return;
+ if (!playback.isCurrentPlayer(player)) {
+ return false;
}
KazumiLogger().i('PlayerController: video initialized');
playback.loading = false;
@@ -183,6 +163,7 @@ class PlayerController {
forceSyncPlaying: true, forceSyncPosition: 0.0);
}
}
+ return true;
}
Future<void> setShader(int type,
@@ -273,14 +254,12 @@ class PlayerController {
Future<void> dispose({
bool disposeSyncPlayController = true,
- bool cancelActiveInit = true,
}) async {
hideVolumeUITimer?.cancel();
FlutterVolumeController.removeListener();
await FlutterVolumeController.updateShowSystemUI(true);
await playback.dispose(
disposeSyncPlayController: disposeSyncPlayController,
- cancelActiveInit: cancelActiveInit,
);
}
@@ -302,12 +281,6 @@ class PlayerController {
setting.put(SettingBoxKey.arrowKeySkipTime, time);
}
- /// 加载弹幕 (离线模式优先从缓存加载,无缓存时尝试在线获取)
- Future<void> _loadDanmaku(
- int bangumiId, String pluginName, int episode) async {
- await danmaku.loadDanmaku(bangumiId, pluginName, episode);
- }
-
Future<void> launchExternalPlayer() async {
await externalPlayback.launch();
}
diff --git a/lib/pages/player/player_item.dart b/lib/pages/player/player_item.dart
index d1b2d330..213fbd63 100644
--- a/lib/pages/player/player_item.dart
+++ b/lib/pages/player/player_item.dart
@@ -307,13 +307,14 @@ class _PlayerItemState extends State<PlayerItem>
//上一集下一集动作
Future<void> handlePreNextEpisode(String direction) async {
if (videoPageController.loading) return;
- final currentRoad = videoPageController.currentRoad;
+ final selection = videoPageController.selectedEpisode;
+ final currentRoad = selection.road;
final episodes = videoPageController.roadList[currentRoad].data;
int targetEpisode;
if (direction == 'next') {
- targetEpisode = videoPageController.currentEpisode + 1;
+ targetEpisode = selection.episode + 1;
} else if (direction == 'prev') {
- targetEpisode = videoPageController.currentEpisode - 1;
+ targetEpisode = selection.episode - 1;
} else {
return;
}
@@ -505,8 +506,9 @@ class _PlayerItemState extends State<PlayerItem>
void _syncAudioServiceState() {
try {
- final currentRoad = videoPageController.currentRoad;
- final currentEpisode = videoPageController.currentEpisode;
+ final selection = videoPageController.playbackEpisode;
+ final currentRoad = selection.road;
+ final currentEpisode = selection.episode;
if (videoPageController.roadList.isEmpty ||
currentRoad < 0 ||
currentRoad >= videoPageController.roadList.length) {
@@ -895,31 +897,32 @@ class _PlayerItemState extends State<PlayerItem>
final pluginName = videoPageController.isOfflineMode
? videoPageController.offlinePluginName
: videoPageController.currentPlugin.name;
+ final selection = videoPageController.playbackEpisode;
historyController.updateHistory(
- videoPageController.actualEpisodeNumber,
- videoPageController.currentRoad,
+ videoPageController.playingActualEpisodeNumber,
+ selection.road,
pluginName,
videoPageController.bangumiItem,
playerController.playback.playerPosition,
videoPageController.src,
- videoPageController.roadList[videoPageController.currentRoad]
- .identifier[videoPageController.currentEpisode - 1]);
+ videoPageController
+ .roadList[selection.road].identifier[selection.episode - 1]);
}
// 自动播放下一集
+ final playingSelection = videoPageController.playbackEpisode;
if (playerController.playback.completed &&
- videoPageController.currentEpisode <
- videoPageController
- .roadList[videoPageController.currentRoad].data.length &&
+ playingSelection.episode <
+ videoPageController.roadList[playingSelection.road].data.length &&
!videoPageController.loading &&
autoPlayNext) {
KazumiDialog.showToast(
message:
- '正在加载${videoPageController.roadList[videoPageController.currentRoad].identifier[videoPageController.currentEpisode]}');
+ '正在加载${videoPageController.roadList[playingSelection.road].identifier[playingSelection.episode]}');
try {
playerTimer!.cancel();
} catch (_) {}
- widget.changeEpisode(videoPageController.currentEpisode + 1,
- currentRoad: videoPageController.currentRoad);
+ widget.changeEpisode(playingSelection.episode + 1,
+ currentRoad: playingSelection.road);
}
// 一起去看相关
playerController.setSyncPlayCurrentPosition();
@@ -983,6 +986,8 @@ class _PlayerItemState extends State<PlayerItem>
onTap: () async {
KazumiDialog.dismiss();
try {
+ videoPageController
+ .cancelAutomaticDanmakuLoad();
await playerController.danmaku
.getDanDanmakuByEpisodeID(
episode.episodeId);
@@ -1253,11 +1258,12 @@ class _PlayerItemState extends State<PlayerItem>
child: ListBody(
children: <Widget>[
DropdownButtonFormField<String>(
+ key: ValueKey(selectedSyncPlayEndPoint),
decoration: InputDecoration(
border: OutlineInputBorder(),
),
isExpanded: true,
- value: selectedSyncPlayEndPoint,
+ initialValue: selectedSyncPlayEndPoint,
items: syncPlayEndPoints.map((String value) {
return DropdownMenuItem<String>(
value: value,
@@ -1560,9 +1566,8 @@ class _PlayerItemState extends State<PlayerItem>
@override
void dispose() {
- // Don't dispose player here
- // We need to reuse the player after episode is changed and player item is disposed
- // We dispose player after video page disposed
+ // Playback lifetime is owned by the route-scoped PlayerController.
+ // This widget only detaches UI listeners and timers.
_fullscreenListener();
_playerSizeListener();
WidgetsBinding.instance.removeObserver(this);
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index ac25d4ad..8715b5b3 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -1116,7 +1116,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
Expanded(
child: dtb.DragToMoveArea(
child: Text(
- ' ${videoPageController.title} [${videoPageController.roadList[videoPageController.currentRoad].identifier[videoPageController.currentEpisode - 1]}]',
+ ' ${videoPageController.title} [${videoPageController.roadList[videoPageController.selectedEpisode.road].identifier[videoPageController.selectedEpisode.episode - 1]}]',
style: TextStyle(
color: Colors.white,
fontSize:
diff --git a/lib/pages/video/video_controller.dart b/lib/pages/video/video_controller.dart
index b5b5f7af..8d99f56f 100644
--- a/lib/pages/video/video_controller.dart
+++ b/lib/pages/video/video_controller.dart
@@ -17,6 +17,7 @@ import 'package:kazumi/utils/logger.dart';
import 'package:window_manager/window_manager.dart';
import 'package:kazumi/modules/bangumi/episode_item.dart';
import 'package:kazumi/modules/comments/comment_item.dart';
+import 'package:kazumi/modules/comments/comment_response.dart';
import 'package:kazumi/request/apis/bangumi_api.dart';
import 'package:dio/dio.dart';
import 'package:hive_ce/hive.dart';
@@ -26,6 +27,61 @@ part 'video_controller.g.dart';
class VideoPageController = _VideoPageController with _$VideoPageController;
+// Controller-local ownership token for async work. Keep it private so playback
+// and comment freshness checks stay inside VideoPageController instead of
+// leaking through player, danmaku, or widget APIs.
+class _AsyncSessionOwner {
+ int _version = 0;
+
+ _AsyncSession begin() {
+ return _AsyncSession(this, ++_version);
+ }
+
+ void cancel() {
+ _version++;
+ }
+
+ bool owns(_AsyncSession session) {
+ return identical(session.owner, this) && session.version == _version;
+ }
+}
+
+class _AsyncSession {
+ const _AsyncSession(this.owner, this.version);
+
+ final _AsyncSessionOwner owner;
+ final int version;
+
+ bool get isActive => owner.owns(this);
+
+ bool get isStale => !isActive;
+}
+
+class VideoEpisodeSelection {
+ const VideoEpisodeSelection({
+ required this.episode,
+ required this.road,
+ });
+
+ final int episode;
+ final int road;
+
+ @override
+ bool operator ==(Object other) {
+ return other is VideoEpisodeSelection &&
+ other.episode == episode &&
+ other.road == road;
+ }
+
+ @override
+ int get hashCode => Object.hash(episode, road);
+
+ @override
+ String toString() {
+ return 'VideoEpisodeSelection(episode: $episode, road: $road)';
+ }
+}
+
abstract class _VideoPageController with Store {
late BangumiItem bangumiItem;
EpisodeInfo episodeInfo = EpisodeInfo.fromTemplate();
@@ -40,40 +96,50 @@ abstract class _VideoPageController with Store {
String? errorMessage;
@observable
- int currentEpisode = 1;
+ VideoEpisodeSelection selectedEpisode =
+ const VideoEpisodeSelection(episode: 1, road: 0);
@observable
- int currentRoad = 0;
+ VideoEpisodeSelection? playingEpisode;
+
+ @observable
+ int commentsEpisode = 1;
+
+ void resetEpisodeState({int episode = 1, int road = 0}) {
+ final selection = VideoEpisodeSelection(episode: episode, road: road);
+ selectedEpisode = selection;
+ playingEpisode = null;
+ commentsEpisode = commentEpisodeForSelection(selection);
+ }
+
+ VideoEpisodeSelection get playbackEpisode =>
+ playingEpisode ?? selectedEpisode;
- /// 全屏状态
@observable
bool isFullscreen = false;
- /// 评论正序或倒序
@observable
bool isCommentsAscending = false;
- int _episodeCommentsRequestId = 0;
+ // Playback, automatic danmaku loading, and comment loading have separate
+ // owners. Manual danmaku selection can cancel auto danmaku without touching
+ // playback; comment refreshes never cancel playback.
+ final _AsyncSessionOwner _playbackSessions = _AsyncSessionOwner();
+ final _AsyncSessionOwner _danmakuSessions = _AsyncSessionOwner();
+ final _AsyncSessionOwner _commentSessions = _AsyncSessionOwner();
- /// 桌面画中画状态,Android 画中画状态不需要单独维护,进入画中画后会直接切换到系统的全局播放器界面
@observable
bool isPip = false;
- /// 播放列表显示状态
@observable
bool showTabBody = true;
- /// 上次观看位置
@observable
int historyOffset = 0;
- /// 离线播放模式
@observable
bool isOfflineMode = false;
- /// 离线视频本地路径
- String? _offlineVideoPath;
-
/// 和 bangumiItem 中的标题不同,此标题来自于视频源
String title = '';
@@ -84,10 +150,8 @@ abstract class _VideoPageController with Store {
late Plugin currentPlugin;
- /// 离线模式下的虚拟插件名
String _offlinePluginName = '';
- /// 用于取消正在进行的 queryRoads 操作
CancelToken? _queryRoadsCancelToken;
final PluginsController pluginsController = Modular.get<PluginsController>();
@@ -97,10 +161,8 @@ abstract class _VideoPageController with Store {
final IDownloadManager downloadManager = Modular.get<IDownloadManager>();
final Box setting = GStorage.setting;
- /// 长生命周期的视频源提供者(页面生命周期内复用,WebView 实例在 Provider 内复用)
WebViewVideoSourceProvider? _videoSourceProvider;
- /// 视频提供者日志流控制器
final StreamController<String> _logStreamController =
StreamController<String>.broadcast();
@@ -108,50 +170,46 @@ abstract class _VideoPageController with Store {
StreamSubscription<String>? _logSubscription;
- /// 初始化离线播放模式
void initForOfflinePlayback({
required BangumiItem bangumiItem,
required String pluginName,
required int episodeNumber,
- required String episodeName,
required int road,
- required String videoPath,
required List<DownloadEpisode> downloadedEpisodes,
}) {
this.bangumiItem = bangumiItem;
_offlinePluginName = pluginName;
- currentRoad = road;
+ var selectedRoad = road;
title =
bangumiItem.nameCn.isNotEmpty ? bangumiItem.nameCn : bangumiItem.name;
isOfflineMode = true;
- _offlineVideoPath = videoPath;
- // 离线模式不需要解析视频源,直接设置 loading 为 false
loading = false;
- // 构建仅包含已下载集数的 roadList
_buildOfflineRoadList(downloadedEpisodes);
- // 离线模式下 roadList 长度为 1 , currentRoad 可能访问越界,需要校正
- if (currentRoad < 0 || currentRoad >= roadList.length) {
- currentRoad = 0;
+ if (selectedRoad < 0 || selectedRoad >= roadList.length) {
+ selectedRoad = 0;
}
- // currentEpisode 是列表中的 1-based 位置,而非实际集数编号
- // 在 roadList.data 中查找 episodeNumber 对应的位置
- final index = roadList[currentRoad].data.indexOf(episodeNumber.toString());
- currentEpisode = index >= 0 ? index + 1 : 1;
+ // Offline road data stores the real episode number, while selection uses
+ // the 1-based position shown in the playlist.
+ final index = roadList[selectedRoad].data.indexOf(episodeNumber.toString());
+ final selected = VideoEpisodeSelection(
+ episode: index >= 0 ? index + 1 : 1,
+ road: selectedRoad,
+ );
+ selectedEpisode = selected;
+ playingEpisode = null;
+ commentsEpisode = commentEpisodeForSelection(selected);
KazumiLogger().i(
- 'VideoPageController: initialized for offline playback, episode $episodeNumber (position: $currentEpisode)');
+ 'VideoPageController: initialized for offline playback, episode $episodeNumber (position: ${selected.episode})');
}
- /// 构建离线模式的 roadList
void _buildOfflineRoadList(List<DownloadEpisode> episodes) {
roadList.clear();
episodes.sort((a, b) => a.episodeNumber.compareTo(b.episodeNumber));
- // 使用 '播放列表1' 作为名称,与 UI 代码兼容
roadList.add(Road(
name: '播放列表1',
- // data 存储实际的 episodeNumber(字符串形式),用于离线播放时查找本地文件
data: episodes.map((e) => e.episodeNumber.toString()).toList(),
identifier: episodes
.map((e) =>
@@ -162,26 +220,45 @@ abstract class _VideoPageController with Store {
void resetOfflineMode() {
isOfflineMode = false;
- _offlineVideoPath = null;
_offlinePluginName = '';
}
- String? get offlineVideoPath => _offlineVideoPath;
-
String get offlinePluginName => _offlinePluginName;
- /// 获取当前实际的集数编号
- /// 在线模式下直接返回 currentEpisode
- /// 离线模式下从 roadList.data 中获取实际的 episodeNumber
- int get actualEpisodeNumber {
+ int get playingActualEpisodeNumber =>
+ actualEpisodeNumberForSelection(playbackEpisode);
+
+ int actualEpisodeNumberForSelection(VideoEpisodeSelection selection) {
if (isOfflineMode && roadList.isNotEmpty) {
try {
- return int.parse(roadList[currentRoad].data[currentEpisode - 1]);
+ return int.parse(roadList[selection.road].data[selection.episode - 1]);
} catch (_) {
- return currentEpisode;
+ return selection.episode;
}
}
- return currentEpisode;
+ return selection.episode;
+ }
+
+ int commentEpisodeForSelection(VideoEpisodeSelection selection) {
+ if (roadList.isEmpty ||
+ selection.road < 0 ||
+ selection.road >= roadList.length) {
+ return selection.episode;
+ }
+ final road = roadList[selection.road];
+ final index = selection.episode - 1;
+ if (index < 0 || index >= road.identifier.length) {
+ return selection.episode;
+ }
+
+ final extractedEpisode = Utils.extractEpisodeNumber(road.identifier[index]);
+ if (extractedEpisode == 0 ||
+ (!isOfflineMode && extractedEpisode > road.identifier.length)) {
+ return isOfflineMode
+ ? actualEpisodeNumberForSelection(selection)
+ : selection.episode;
+ }
+ return extractedEpisode;
}
Future<void> changeEpisode(
@@ -190,49 +267,65 @@ abstract class _VideoPageController with Store {
int offset = 0,
required PlayerController playerController,
}) async {
- currentEpisode = episode;
- this.currentRoad = currentRoad;
+ final session = _playbackSessions.begin();
+ final selection = VideoEpisodeSelection(
+ episode: episode,
+ road: currentRoad,
+ );
+ selectedEpisode = selection;
+ playingEpisode = null;
+ commentsEpisode = commentEpisodeForSelection(selection);
+ resetEpisodeComments();
+ _danmakuSessions.cancel();
+ playerController.danmaku.finishDanmakuLoad();
+ _videoSourceProvider?.cancel();
+ loading = true;
errorMessage = null;
+ await playerController.stop();
+ if (session.isStale) {
+ return;
+ }
+
if (isOfflineMode) {
await _changeOfflineEpisode(
- episode,
- 0,
+ selection,
+ offset,
+ session: session,
playerController: playerController,
);
return;
}
- String chapterName = roadList[currentRoad].identifier[episode - 1];
+ String chapterName =
+ roadList[selection.road].identifier[selection.episode - 1];
KazumiLogger().i('VideoPageController: changed to $chapterName');
- String urlItem = roadList[currentRoad].data[episode - 1];
- if (urlItem.contains(currentPlugin.baseUrl) ||
- urlItem.contains(currentPlugin.baseUrl.replaceAll('https', 'http'))) {
- urlItem = urlItem;
- } else {
+ String urlItem = roadList[selection.road].data[selection.episode - 1];
+ if (!urlItem.contains(currentPlugin.baseUrl) &&
+ !urlItem.contains(currentPlugin.baseUrl.replaceAll('https', 'http'))) {
urlItem = currentPlugin.baseUrl + urlItem;
}
await _resolveWithProvider(
urlItem,
offset,
+ selection: selection,
+ session: session,
playerController: playerController,
);
}
- /// 离线模式下切换集数
- /// [episode] 是列表中的位置(从 1 开始),需要从 roadList.data 中获取实际的 episodeNumber
Future<void> _changeOfflineEpisode(
- int episode,
+ VideoEpisodeSelection selection,
int offset, {
+ required _AsyncSession session,
required PlayerController playerController,
}) async {
- // 从 roadList.data 中获取实际的 episodeNumber
final actualEpisodeNumber =
- int.tryParse(roadList[currentRoad].data[episode - 1]);
+ int.tryParse(roadList[selection.road].data[selection.episode - 1]);
if (actualEpisodeNumber == null) {
KazumiLogger().e(
- 'VideoPageController: failed to parse episode number from roadList data: ${roadList[currentRoad].data[episode - 1]}');
+ 'VideoPageController: failed to parse episode number from roadList data: ${roadList[selection.road].data[selection.episode - 1]}');
KazumiDialog.showToast(message: '集数解析失败');
return;
}
@@ -246,11 +339,13 @@ abstract class _VideoPageController with Store {
KazumiDialog.showToast(message: '该集数未下载');
return;
}
- _offlineVideoPath = localPath;
+ if (session.isStale) {
+ return;
+ }
loading = false;
KazumiLogger().i(
- 'VideoPageController: offline episode changed to $actualEpisodeNumber (index: $episode), path: $localPath');
+ 'VideoPageController: offline episode changed to $actualEpisodeNumber (index: ${selection.episode}), path: $localPath');
final params = PlaybackInitParams(
videoUrl: localPath,
@@ -261,18 +356,66 @@ abstract class _VideoPageController with Store {
episode: actualEpisodeNumber,
httpHeaders: {},
adBlockerEnabled: false,
- episodeTitle: roadList[currentRoad].identifier[episode - 1],
+ episodeTitle: roadList[selection.road].identifier[selection.episode - 1],
referer: '',
- currentRoad: currentRoad,
+ currentRoad: selection.road,
coverUrl: bangumiItem.images['large'],
bangumiName:
bangumiItem.nameCn.isNotEmpty ? bangumiItem.nameCn : bangumiItem.name,
);
- await playerController.init(params);
+ final initialized = await playerController.init(params);
+ if (session.isActive && initialized) {
+ playingEpisode = selection;
+ unawaited(_loadPlaybackDanmaku(playerController, params, session));
+ } else if (session.isActive) {
+ _playbackSessions.cancel();
+ }
+ }
+
+ int _danmakuEpisodeForPlayback(PlaybackInitParams params) {
+ try {
+ final episodeFromTitle = Utils.extractEpisodeNumber(params.episodeTitle);
+ if (episodeFromTitle != 0) {
+ return episodeFromTitle;
+ }
+ } catch (e) {
+ KazumiLogger().e(
+ 'VideoPageController: failed to extract episode number from title',
+ error: e,
+ );
+ }
+ return params.episode;
+ }
+
+ Future<void> _loadPlaybackDanmaku(
+ PlayerController playerController,
+ PlaybackInitParams params,
+ _AsyncSession session,
+ ) async {
+ final danmakuSession = _danmakuSessions.begin();
+ playerController.danmaku.beginDanmakuLoad();
+ try {
+ final result = await playerController.danmaku.fetchDanmaku(
+ params.bangumiId,
+ params.pluginName,
+ _danmakuEpisodeForPlayback(params),
+ );
+ if (session.isActive && danmakuSession.isActive) {
+ playerController.danmaku.applyDanmakuLoad(result);
+ }
+ } catch (e) {
+ if (session.isActive && danmakuSession.isActive) {
+ playerController.danmaku.finishDanmakuLoad();
+ }
+ KazumiLogger().w('VideoPageController: failed to load danmaku', error: e);
+ }
+ }
+
+ void cancelAutomaticDanmakuLoad() {
+ _danmakuSessions.cancel();
}
- /// 获取本地视频路径
String? _getLocalVideoPath(
int bangumiId, String pluginName, int episodeNumber) {
final episode =
@@ -280,15 +423,13 @@ abstract class _VideoPageController with Store {
return downloadManager.getLocalVideoPath(episode);
}
- /// 使用 VideoSourceProvider 解析视频源
Future<void> _resolveWithProvider(
String url,
int offset, {
+ required VideoEpisodeSelection selection,
+ required _AsyncSession session,
required PlayerController playerController,
}) async {
- _videoSourceProvider?.cancel();
-
- loading = true;
_videoSourceProvider ??= WebViewVideoSourceProvider();
await _logSubscription?.cancel();
@@ -305,6 +446,9 @@ abstract class _VideoPageController with Store {
offset: offset,
);
+ if (session.isStale) {
+ return;
+ }
loading = false;
KazumiLogger()
.i('VideoPageController: resolved video URL: ${source.url}');
@@ -318,7 +462,7 @@ abstract class _VideoPageController with Store {
isLocalPlayback: false,
bangumiId: bangumiItem.id,
pluginName: currentPlugin.name,
- episode: currentEpisode,
+ episode: selection.episode,
httpHeaders: {
'user-agent': currentPlugin.userAgent.isEmpty
? Utils.getRandomUA()
@@ -327,30 +471,43 @@ abstract class _VideoPageController with Store {
'referer': currentPlugin.referer,
},
adBlockerEnabled: forceAdBlocker || currentPlugin.adBlocker,
- episodeTitle: roadList[currentRoad].identifier[currentEpisode - 1],
+ episodeTitle:
+ roadList[selection.road].identifier[selection.episode - 1],
referer: currentPlugin.referer,
- currentRoad: currentRoad,
+ currentRoad: selection.road,
coverUrl: bangumiItem.images['large'],
bangumiName: bangumiItem.nameCn.isNotEmpty
? bangumiItem.nameCn
: bangumiItem.name,
);
- await playerController.init(params);
+ final initialized = await playerController.init(params);
+ if (session.isActive && initialized) {
+ playingEpisode = selection;
+ unawaited(_loadPlaybackDanmaku(playerController, params, session));
+ } else if (session.isActive) {
+ _playbackSessions.cancel();
+ }
} on VideoSourceTimeoutException {
+ if (session.isStale) {
+ return;
+ }
loading = false;
errorMessage = '视频解析超时,请重试';
} on VideoSourceCancelledException {
KazumiLogger().i('VideoPageController: video URL resolution cancelled');
- // 不设置 loading = false,因为可能是切换到新的集数
} catch (e) {
+ if (session.isStale) {
+ return;
+ }
loading = false;
errorMessage = '视频解析失败:${e.toString()}';
}
}
- /// 取消当前视频源解析并销毁 Provider(页面退出时调用)
void cancelVideoSourceResolution() {
+ _playbackSessions.cancel();
+ _danmakuSessions.cancel();
_logSubscription?.cancel();
_logSubscription = null;
if (!_logStreamController.isClosed) {
@@ -360,15 +517,40 @@ abstract class _VideoPageController with Store {
_videoSourceProvider = null;
}
- Future<void> queryBangumiEpisodeCommentsByID(int id, int episode) async {
- final int requestId = ++_episodeCommentsRequestId;
- final EpisodeInfo latestEpisodeInfo =
- await BangumiApi.getBangumiEpisodeByID(id, episode);
- final value =
- await BangumiApi.getBangumiCommentsByEpisodeID(latestEpisodeInfo.id);
- if (requestId != _episodeCommentsRequestId) {
- return;
+ void resetEpisodeComments() {
+ _commentSessions.cancel();
+ episodeInfo.reset();
+ episodeCommentsList.clear();
+ }
+
+ Future<bool> queryBangumiEpisodeCommentsByID(int id, int episode) async {
+ final session = _commentSessions.begin();
+ final EpisodeInfo latestEpisodeInfo;
+ try {
+ latestEpisodeInfo = await BangumiApi.getBangumiEpisodeByID(id, episode);
+ } catch (_) {
+ if (session.isStale) {
+ return false;
+ }
+ rethrow;
+ }
+ if (session.isStale) {
+ return false;
+ }
+ final EpisodeCommentResponse value;
+ try {
+ value =
+ await BangumiApi.getBangumiCommentsByEpisodeID(latestEpisodeInfo.id);
+ } catch (_) {
+ if (session.isStale) {
+ return false;
+ }
+ rethrow;
+ }
+ if (session.isStale) {
+ return false;
}
+ commentsEpisode = episode;
episodeInfo = latestEpisodeInfo;
final commentsList = value.commentList;
if (!isCommentsAscending) {
@@ -381,6 +563,7 @@ abstract class _VideoPageController with Store {
episodeCommentsList = ObservableList.of(commentsList);
KazumiLogger().i(
'VideoPageController: loaded comments list length ${episodeCommentsList.length}');
+ return true;
}
Future<void> queryRoads(String url, String pluginName,
diff --git a/lib/pages/video/video_controller.g.dart b/lib/pages/video/video_controller.g.dart
index 0b216bd9..92b35695 100644
--- a/lib/pages/video/video_controller.g.dart
+++ b/lib/pages/video/video_controller.g.dart
@@ -57,35 +57,51 @@ mixin _$VideoPageController on _VideoPageController, Store {
});
}
- late final _$currentEpisodeAtom =
- Atom(name: '_VideoPageController.currentEpisode', context: context);
+ late final _$selectedEpisodeAtom =
+ Atom(name: '_VideoPageController.selectedEpisode', context: context);
@override
- int get currentEpisode {
- _$currentEpisodeAtom.reportRead();
- return super.currentEpisode;
+ VideoEpisodeSelection get selectedEpisode {
+ _$selectedEpisodeAtom.reportRead();
+ return super.selectedEpisode;
}
@override
- set currentEpisode(int value) {
- _$currentEpisodeAtom.reportWrite(value, super.currentEpisode, () {
- super.currentEpisode = value;
+ set selectedEpisode(VideoEpisodeSelection value) {
+ _$selectedEpisodeAtom.reportWrite(value, super.selectedEpisode, () {
+ super.selectedEpisode = value;
});
}
- late final _$currentRoadAtom =
- Atom(name: '_VideoPageController.currentRoad', context: context);
+ late final _$playingEpisodeAtom =
+ Atom(name: '_VideoPageController.playingEpisode', context: context);
@override
- int get currentRoad {
- _$currentRoadAtom.reportRead();
- return super.currentRoad;
+ VideoEpisodeSelection? get playingEpisode {
+ _$playingEpisodeAtom.reportRead();
+ return super.playingEpisode;
}
@override
- set currentRoad(int value) {
- _$currentRoadAtom.reportWrite(value, super.currentRoad, () {
- super.currentRoad = value;
+ set playingEpisode(VideoEpisodeSelection? value) {
+ _$playingEpisodeAtom.reportWrite(value, super.playingEpisode, () {
+ super.playingEpisode = value;
+ });
+ }
+
+ late final _$commentsEpisodeAtom =
+ Atom(name: '_VideoPageController.commentsEpisode', context: context);
+
+ @override
+ int get commentsEpisode {
+ _$commentsEpisodeAtom.reportRead();
+ return super.commentsEpisode;
+ }
+
+ @override
+ set commentsEpisode(int value) {
+ _$commentsEpisodeAtom.reportWrite(value, super.commentsEpisode, () {
+ super.commentsEpisode = value;
});
}
@@ -207,8 +223,9 @@ mixin _$VideoPageController on _VideoPageController, Store {
episodeCommentsList: ${episodeCommentsList},
loading: ${loading},
errorMessage: ${errorMessage},
-currentEpisode: ${currentEpisode},
-currentRoad: ${currentRoad},
+selectedEpisode: ${selectedEpisode},
+playingEpisode: ${playingEpisode},
+commentsEpisode: ${commentsEpisode},
isFullscreen: ${isFullscreen},
isCommentsAscending: ${isCommentsAscending},
isPip: ${isPip},
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index d020fcad..f79c6775 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -53,28 +53,19 @@ class _VideoPageState extends State<VideoPage>
late Animation<double> _maskOpacityAnimation;
late TabController tabController;
- // 当前播放列表
- int currentRoad = 0;
+ int visibleRoad = 0;
- // disable animation.
late final bool disableAnimations;
- // SyncPlayChatMessage
StreamSubscription<SyncPlayChatMessage>? _syncChatSubscription;
static const Duration _offlinePlayerInitDelay = Duration(milliseconds: 400);
- int _playbackRequestId = 0;
-
- bool _isActivePlaybackRequest(int requestId) {
- return mounted && requestId == _playbackRequestId;
- }
@override
void initState() {
super.initState();
windowManager.addListener(this);
- // Check fullscreen when enter video page
- // in case user use system controls to enter fullscreen outside video page
+ // Window fullscreen can be changed outside this page through system chrome.
videoPageController.isDesktopFullscreen();
tabController = TabController(length: 2, vsync: this);
observerController = GridObserverController(controller: scrollController);
@@ -101,7 +92,8 @@ class _VideoPageState extends State<VideoPage>
disableAnimations =
setting.get(SettingBoxKey.playerDisableAnimations, defaultValue: false);
- // Resolve the route-scoped player after the page survives its first frame.
+ // PlayerController is route-scoped and may not be registered until after
+ // the first frame.
WidgetsBinding.instance.addPostFrameCallback((_) {
_loadPlayerController();
});
@@ -145,7 +137,6 @@ class _VideoPageState extends State<VideoPage>
playerController.syncplay.syncplayController?.username ?? '';
final String displayText = '${event.username}:${event.message}';
- // 只有在弹幕开启时渲染弹幕并确保是别人发送的弹幕
if (playerController.danmaku.danmakuOn &&
event.username != localUsername &&
event.fromRemote) {
@@ -165,44 +156,24 @@ class _VideoPageState extends State<VideoPage>
void _initOfflineMode(PlayerController playerController) {
videoPageController.showTabBody = true;
videoPageController.historyOffset = 0;
- currentRoad = videoPageController.currentRoad;
- // A newer request or dispose must make this delayed init a no-op.
- final int requestId = ++_playbackRequestId;
+ visibleRoad = videoPageController.selectedEpisode.road;
WidgetsBinding.instance.addPostFrameCallback((_) async {
await Future.delayed(_offlinePlayerInitDelay);
- if (!_isActivePlaybackRequest(requestId)) {
+ if (!mounted) {
return;
}
- if (videoPageController.offlineVideoPath != null) {
- final params = PlaybackInitParams(
- videoUrl: videoPageController.offlineVideoPath!,
- offset: videoPageController.historyOffset,
- isLocalPlayback: true,
- bangumiId: videoPageController.bangumiItem.id,
- pluginName: videoPageController.offlinePluginName,
- episode: videoPageController.actualEpisodeNumber,
- httpHeaders: {},
- adBlockerEnabled: false,
- episodeTitle: videoPageController
- .roadList[videoPageController.currentRoad]
- .identifier[videoPageController.currentEpisode - 1],
- referer: '',
- currentRoad: videoPageController.currentRoad,
- coverUrl: videoPageController.bangumiItem.images['large'],
- bangumiName: videoPageController.bangumiItem.nameCn.isNotEmpty
- ? videoPageController.bangumiItem.nameCn
- : videoPageController.bangumiItem.name,
- );
- await playerController.init(params);
- }
+ await changeEpisode(
+ videoPageController.selectedEpisode.episode,
+ currentRoad: videoPageController.selectedEpisode.road,
+ offset: videoPageController.historyOffset,
+ );
});
}
void _initOnlineMode(PlayerController playerController) {
- videoPageController.currentEpisode = 1;
- videoPageController.currentRoad = 0;
+ videoPageController.resetEpisodeState();
videoPageController.historyOffset = 0;
videoPageController.showTabBody = true;
@@ -213,15 +184,17 @@ class _VideoPageState extends State<VideoPage>
if (videoPageController.roadList.length > progress.road) {
if (videoPageController.roadList[progress.road].data.length >=
progress.episode) {
- videoPageController.currentEpisode = progress.episode;
- videoPageController.currentRoad = progress.road;
+ videoPageController.resetEpisodeState(
+ episode: progress.episode,
+ road: progress.road,
+ );
if (playResume) {
videoPageController.historyOffset = progress.progress.inSeconds;
}
}
}
}
- currentRoad = videoPageController.currentRoad;
+ visibleRoad = videoPageController.selectedEpisode.road;
_logSubscription = videoPageController.logStream.listen((log) {
if (mounted) {
@@ -238,8 +211,8 @@ class _VideoPageState extends State<VideoPage>
if (!mounted) {
return;
}
- changeEpisode(videoPageController.currentEpisode,
- currentRoad: videoPageController.currentRoad,
+ changeEpisode(videoPageController.selectedEpisode.episode,
+ currentRoad: videoPageController.selectedEpisode.road,
offset: videoPageController.historyOffset);
});
}
@@ -261,7 +234,7 @@ class _VideoPageState extends State<VideoPage>
try {
_logSubscription?.cancel();
} catch (_) {}
- _playbackRequestId++;
+ videoPageController.cancelVideoSourceResolution();
try {
_playerController?.dispose();
} catch (e) {
@@ -269,23 +242,19 @@ class _VideoPageState extends State<VideoPage>
'VideoPageController: failed to dispose playerController',
error: e);
}
- videoPageController.cancelVideoSourceResolution();
if (!Utils.isDesktop()) {
try {
ScreenBrightnessPlatform.instance.resetApplicationScreenBrightness();
} catch (_) {}
}
- videoPageController.episodeInfo.reset();
- videoPageController.episodeCommentsList.clear();
+ videoPageController.resetEpisodeComments();
videoPageController.resetOfflineMode();
Utils.unlockScreenRotation();
tabController.dispose();
- // Cancel timed shutdown when leaving anime page
TimedShutdownService().cancel();
super.dispose();
}
- // Handle fullscreen change invoked by system controls
@override
void onWindowEnterFullScreen() {
videoPageController.handleOnEnterFullScreen();
@@ -326,20 +295,11 @@ class _VideoPageState extends State<VideoPage>
if (playerController == null) {
return;
}
- final int requestId = ++_playbackRequestId;
if (!mounted) {
return;
}
clearWebviewLog();
hideDebugConsole();
- videoPageController.loading = true;
- videoPageController.errorMessage = null;
- videoPageController.episodeInfo.reset();
- videoPageController.episodeCommentsList.clear();
- await playerController.stop();
- if (!_isActivePlaybackRequest(requestId)) {
- return;
- }
await videoPageController.changeEpisode(episode,
currentRoad: currentRoad,
offset: offset,
@@ -352,9 +312,9 @@ class _VideoPageState extends State<VideoPage>
return;
}
await observerController.jumpTo(
- index: videoPageController.currentEpisode > 1
- ? videoPageController.currentEpisode - 1
- : videoPageController.currentEpisode);
+ index: videoPageController.selectedEpisode.episode > 1
+ ? videoPageController.selectedEpisode.episode - 1
+ : videoPageController.selectedEpisode.episode);
});
}
@@ -406,7 +366,6 @@ class _VideoPageState extends State<VideoPage>
Navigator.of(context).pop();
}
- /// Callback for timed shutdown - pauses video when timer expires
void pauseForTimedShutdown() {
final playerController = _playerController;
if (playerController != null && playerController.playback.playing) {
@@ -414,7 +373,6 @@ class _VideoPageState extends State<VideoPage>
}
}
- /// 发送弹幕 由于接口限制, 暂时未提交云端
void sendDanmaku(String msg) async {
final playerController = _playerController;
if (playerController == null) {
@@ -447,7 +405,6 @@ class _VideoPageState extends State<VideoPage>
playerController.syncplay.syncplayController?.username ?? '我';
final String displayText = '$sender:$msg';
- // 在播放器渲染自己发送的弹幕
playerController.danmaku.canvasController.addDanmaku(
DanmakuContentItem(
displayText,
@@ -458,11 +415,10 @@ class _VideoPageState extends State<VideoPage>
),
);
- // 发送弹幕到聊天室
playerController.sendSyncPlayChatMessage(msg);
} else {
- // Todo 接口方限制
-
+ // The remote danmaku provider does not expose a send API here; render the
+ // local echo so the user still sees their message immediately.
playerController.danmaku.canvasController
.addDanmaku(DanmakuContentItem(msg, selfSend: true));
}
@@ -812,8 +768,10 @@ class _VideoPageState extends State<VideoPage>
icon: const Icon(Icons.refresh_outlined,
color: Colors.white),
onPressed: () {
- changeEpisode(videoPageController.currentEpisode,
- currentRoad: videoPageController.currentRoad);
+ changeEpisode(
+ videoPageController.selectedEpisode.episode,
+ currentRoad:
+ videoPageController.selectedEpisode.road);
},
),
Visibility(
@@ -908,7 +866,7 @@ class _VideoPageState extends State<VideoPage>
}
},
child: Text(
- '播放列表${currentRoad + 1} ',
+ '播放列表${visibleRoad + 1} ',
style: const TextStyle(fontSize: 13),
),
),
@@ -919,7 +877,7 @@ class _VideoPageState extends State<VideoPage>
(int i) => MenuItemButton(
onPressed: () {
setState(() {
- currentRoad = i;
+ visibleRoad = i;
});
},
child: Container(
@@ -930,7 +888,7 @@ class _VideoPageState extends State<VideoPage>
child: Text(
'播放列表${i + 1}',
style: TextStyle(
- color: i == currentRoad
+ color: i == visibleRoad
? Theme.of(context).colorScheme.primary
: null,
),
@@ -1006,7 +964,7 @@ class _VideoPageState extends State<VideoPage>
builder: (context) {
var cardList = <Widget>[];
for (var road in videoPageController.roadList) {
- if (road.name == '播放列表${currentRoad + 1}') {
+ if (road.name == '播放列表${visibleRoad + 1}') {
int count = 1;
for (var urlItem in road.data) {
int count0 = count;
@@ -1018,14 +976,16 @@ class _VideoPageState extends State<VideoPage>
clipBehavior: Clip.hardEdge,
child: InkWell(
onTap: () async {
- if (count0 == videoPageController.currentEpisode &&
- videoPageController.currentRoad == currentRoad) {
+ if (count0 ==
+ videoPageController.selectedEpisode.episode &&
+ videoPageController.selectedEpisode.road ==
+ visibleRoad) {
return;
}
KazumiLogger()
.i('VideoPageController: video URL is $urlItem');
closeTabBodyAnimated();
- changeEpisode(count0, currentRoad: currentRoad);
+ changeEpisode(count0, currentRoad: visibleRoad);
},
child: Padding(
padding: const EdgeInsets.symmetric(
@@ -1036,10 +996,11 @@ class _VideoPageState extends State<VideoPage>
Row(
children: [
if (count0 ==
- (videoPageController.currentEpisode) &&
- currentRoad ==
+ (videoPageController
+ .selectedEpisode.episode) &&
+ visibleRoad ==
videoPageController
- .currentRoad) ...<Widget>[
+ .selectedEpisode.road) ...<Widget>[
Image.asset(
'assets/images/playing.gif',
color: Theme.of(context).colorScheme.primary,
@@ -1056,9 +1017,10 @@ class _VideoPageState extends State<VideoPage>
fontSize: 13,
color: (count0 ==
videoPageController
- .currentEpisode &&
- currentRoad ==
- videoPageController.currentRoad)
+ .selectedEpisode.episode &&
+ visibleRoad ==
+ videoPageController
+ .selectedEpisode.road)
? Theme.of(context).colorScheme.primary
: Theme.of(context)
.colorScheme
@@ -1105,19 +1067,7 @@ class _VideoPageState extends State<VideoPage>
Widget get tabBody {
final playerController = _playerController;
final bool danmakuOn = playerController?.danmaku.danmakuOn ?? false;
- int episodeNum = 0;
- episodeNum = Utils.extractEpisodeNumber(videoPageController
- .roadList[videoPageController.currentRoad]
- .identifier[videoPageController.currentEpisode - 1]);
- if (episodeNum == 0 ||
- (!videoPageController.isOfflineMode &&
- episodeNum >
- videoPageController.roadList[videoPageController.currentRoad]
- .identifier.length)) {
- episodeNum = videoPageController.isOfflineMode
- ? videoPageController.actualEpisodeNumber
- : videoPageController.currentEpisode;
- }
+ final int episodeNum = videoPageController.commentsEpisode;
return Container(
color: Theme.of(context).canvasColor,
@@ -1224,7 +1174,7 @@ class _VideoPageState extends State<VideoPage>
context: context,
isScrollControlled: true,
builder: (context) =>
- DownloadEpisodeSheet(road: currentRoad),
+ DownloadEpisodeSheet(road: visibleRoad),
);
},
),