Skip to content

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

syncplay: basic syncplay support done

Predidit44a17abd4822
diff --git a/lib/bean/dialog/dialog_helper.dart b/lib/bean/dialog/dialog_helper.dart
index dbb28ecc..4b0f6051 100644
--- a/lib/bean/dialog/dialog_helper.dart
+++ b/lib/bean/dialog/dialog_helper.dart
@@ -42,7 +42,9 @@ class KazumiDialog {
static void showToast({
required String message,
BuildContext? context,
- bool showUndoButton = false,
+ bool showActionButton = false,
+ String? actionLabel,
+ Function()? onActionPressed,
Duration duration = const Duration(seconds: 2),
}) {
final ctx = context ?? observer.scaffoldContext;
@@ -54,10 +56,13 @@ class KazumiDialog {
SnackBar(
content: Text(message),
duration: duration,
- action: showUndoButton
+ action: showActionButton
? SnackBarAction(
- label: 'Dismiss',
- onPressed: () {},
+ label: actionLabel ?? 'Dismiss',
+ onPressed: () {
+ onActionPressed?.call();
+ ScaffoldMessenger.of(ctx).hideCurrentSnackBar();
+ },
)
: null,
),
diff --git a/lib/pages/player/player_controller.dart b/lib/pages/player/player_controller.dart
index 0943b212..74f108f3 100644
--- a/lib/pages/player/player_controller.dart
+++ b/lib/pages/player/player_controller.dart
@@ -183,7 +183,9 @@ abstract class _PlayerController with Store {
KazumiLogger().log(Level.info, 'VideoURL初始化完成');
loading = false;
if (syncplayController?.isConnected ?? false) {
- setSyncPlayPlayingBangumi();
+ if (syncplayController!.currentFileName != "${infoController.bangumiItem.id}[${videoPageController.currentEpisode}]") {
+ setSyncPlayPlayingBangumi();
+ }
}
}
@@ -261,7 +263,7 @@ abstract class _PlayerController with Store {
KazumiDialog.showToast(
message: '播放器内部错误 ${event.toString()} $videoUrl',
duration: const Duration(seconds: 5),
- showUndoButton: true);
+ showActionButton: true);
}
KazumiLogger().log(
Level.error, 'Player intent error: ${event.toString()} $videoUrl');
@@ -358,9 +360,9 @@ abstract class _PlayerController with Store {
playing = false;
if (syncplayController != null) {
setSyncPlayCurrentPosition();
- if (enableSync) {
- await requestSyncPlaySync();
- }
+ // if (enableSync) {
+ // await requestSyncPlaySync();
+ // }
}
}
@@ -370,9 +372,9 @@ abstract class _PlayerController with Store {
playing = true;
if (syncplayController != null) {
setSyncPlayCurrentPosition();
- if (enableSync) {
- await requestSyncPlaySync();
- }
+ // if (enableSync) {
+ // await requestSyncPlaySync();
+ // }
}
}
@@ -440,7 +442,8 @@ abstract class _PlayerController with Store {
}
}
- Future<void> createSyncPlayRoom(String room, String username) async {
+ Future<void> createSyncPlayRoom(
+ String room, String username, Function changeEpisode) async {
await syncplayController?.disconnect();
syncplayController = SyncplayClient(host: 'syncplay.pl', port: 8995);
try {
@@ -451,6 +454,17 @@ abstract class _PlayerController with Store {
},
onError: (error) {
print('SyncPlay: error: ${error.message}');
+ if (error is SyncplayConnectionException) {
+ exitSyncPlayRoom();
+ KazumiDialog.showToast(
+ message: 'SyncPlay: 同步中断 ${error.message}',
+ duration: const Duration(seconds: 5),
+ showActionButton: true,
+ actionLabel: '重新连接',
+ onActionPressed: () =>
+ createSyncPlayRoom(room, username, changeEpisode),
+ );
+ }
},
);
syncplayController!.onRoomMessage.listen(
@@ -482,17 +496,53 @@ abstract class _PlayerController with Store {
(message) {
print(
'SyncPlay: file changed by ${message['setBy']}: ${message['name']}');
+ RegExp regExp = RegExp(r'(\d+)\[(\d+)\]');
+ Match? match = regExp.firstMatch(message['name']);
+ if (match != null) {
+ int bangumiID = int.tryParse(match.group(1) ?? '0') ?? 0;
+ int episode = int.tryParse(match.group(2) ?? '0') ?? 0;
+ if (bangumiID != 0 &&
+ episode != 0 &&
+ episode != videoPageController.currentEpisode) {
+ KazumiDialog.showToast(
+ message:
+ 'SyncPlay: ${message['setBy'] ?? 'unknown'} 切换到第 $episode 话',
+ duration: const Duration(seconds: 3));
+ changeEpisode(episode,
+ currentRoad: videoPageController.currentRoad);
+ }
+ }
},
);
syncplayController!.onPositionChangedMessage.listen(
(message) {
+ syncplayClientRtt = (message['clientRtt'].toDouble() * 1000).toInt();
print(
'SyncPlay: position changed by ${message['setBy']}: ${message['calculatedPositon']} position: ${message['position']} paused: ${message['paused']} clientRtt: ${message['clientRtt']} serverRtt: ${message['serverRtt']} fd: ${message['fd']}');
- syncplayClientRtt = (message['clientRtt'].toDouble() * 1000).toInt();
+ if (message['setBy'] == syncplayController!.username) {
+ return;
+ }
+ if (message['paused'] != !playing) {
+ if (message['paused']) {
+ if (message['position'] != 0) {
+ KazumiDialog.showToast(
+ message: 'SyncPlay: ${message['setBy'] ?? 'unknown'} 暂停了播放',
+ duration: const Duration(seconds: 3));
+ pause(enableSync: false);
+ }
+ } else {
+ if (message['position'] != 0) {
+ KazumiDialog.showToast(
+ message: 'SyncPlay: ${message['setBy'] ?? 'unknown'} 开始了播放',
+ duration: const Duration(seconds: 3));
+ play(enableSync: false);
+ }
+ }
+ }
if ((currentPosition.inMilliseconds -
(message['calculatedPositon'].toDouble() * 1000).toInt())
.abs() >
- 3000) {
+ 1500) {
seek(
Duration(
milliseconds:
@@ -500,13 +550,6 @@ abstract class _PlayerController with Store {
.toInt()),
enableSync: false);
}
- if (message['paused'] != playing) {
- if (message['paused']) {
- pause(enableSync: false);
- } else {
- play(enableSync: false);
- }
- }
},
);
await syncplayController!.joinRoom(room, username);
@@ -536,16 +579,13 @@ abstract class _PlayerController with Store {
await syncplayController!.sendSyncPlaySyncRequest();
}
- Future<void> sendSyncPlayTestMessage() async {
+ Future<void> exitSyncPlayRoom() async {
if (syncplayController == null) {
- print('SyncPlay: please create a room first');
- KazumiDialog.showToast(message: 'SyncPlay: please create a room first');
return;
}
- try {
- await setSyncPlayPlayingBangumi();
- } catch (e) {
- print('Error: $e');
- }
+ await syncplayController!.disconnect();
+ syncplayController = null;
+ syncplayRoom = '';
+ syncplayClientRtt = 0;
}
}
diff --git a/lib/pages/player/player_item_panel.dart b/lib/pages/player/player_item_panel.dart
index 7f5b95f4..e7edcebf 100644
--- a/lib/pages/player/player_item_panel.dart
+++ b/lib/pages/player/player_item_panel.dart
@@ -275,7 +275,7 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
if (formKey.currentState!.validate()) {
KazumiDialog.dismiss();
playerController.createSyncPlayRoom(
- roomController.text, usernameController.text);
+ roomController.text, usernameController.text, widget.changeEpisode);
}
},
child: const Text('确定'),
@@ -1085,13 +1085,12 @@ class _PlayerItemPanelState extends State<PlayerItemPanel> {
),
MenuItemButton(
onPressed: () async {
- await playerController
- .sendSyncPlayTestMessage();
+ await playerController.exitSyncPlayRoom();
},
child: const Padding(
padding:
EdgeInsets.fromLTRB(0, 10, 10, 10),
- child: Text("强制同步"),
+ child: Text("断开连接"),
),
),
],
diff --git a/lib/pages/video/video_page.dart b/lib/pages/video/video_page.dart
index eeb9e8d5..cefb8eea 100644
--- a/lib/pages/video/video_page.dart
+++ b/lib/pages/video/video_page.dart
@@ -357,7 +357,6 @@ class _VideoPageState extends State<VideoPage>
return PopScope(
canPop: false,
onPopInvokedWithResult: (bool didPop, Object? result) {
- debugPrint("checkPoint: didPop: $didPop");
if (didPop) {
return;
}
diff --git a/lib/utils/syncplay.dart b/lib/utils/syncplay.dart
index db865e3f..16ee06f9 100644
--- a/lib/utils/syncplay.dart
+++ b/lib/utils/syncplay.dart
@@ -57,11 +57,11 @@ class StateMessage extends SyncplayMessage {
final double position;
final bool paused;
final bool? doSeek;
- final String setBy;
+ final String? setBy;
// syncplay controll message
- final bool clientAck;
- final bool serverAck;
+ final int? clientAck;
+ final int? serverAck;
// latency calculation
double clientLatencyCalculation;
@@ -71,10 +71,10 @@ class StateMessage extends SyncplayMessage {
StateMessage({
required this.position,
required this.paused,
- required this.setBy,
+ this.setBy,
this.doSeek,
- this.clientAck = false,
- this.serverAck = false,
+ this.clientAck,
+ this.serverAck,
required this.clientLatencyCalculation,
this.latencyCalculation,
this.clientRtt = 0.0,
@@ -83,10 +83,10 @@ class StateMessage extends SyncplayMessage {
@override
Map<String, dynamic> toJson() => {
'State': {
- if (clientAck || serverAck)
+ if (clientAck != null || serverAck != null)
'ignoringOnTheFly': {
- if (clientAck) 'client': 1,
- if (serverAck) 'server': 1,
+ if (clientAck != null) 'client': clientAck,
+ if (serverAck != null) 'server': serverAck,
},
'ping': {
'clientRtt': clientRtt,
@@ -97,8 +97,8 @@ class StateMessage extends SyncplayMessage {
'playstate': {
'position': position,
'paused': paused,
- 'setBy': setBy,
- if (doSeek != null) 'doSeek': doSeek,
+ if (setBy != null) 'setBy': setBy,
+ 'doSeek': doSeek,
},
},
};
@@ -167,6 +167,7 @@ class SyncplayClient {
Socket? _socket;
String? _username;
String? _currentRoom;
+ String? _currentFileName;
double _currentPositon = 0.0;
bool _isPaused = true;
bool _isLocked = false;
@@ -190,6 +191,7 @@ class SyncplayClient {
bool get isConnected => _socket != null;
String? get username => _username;
String? get currentRoom => _currentRoom;
+ String? get currentFileName => _currentFileName;
double get clientRtt => _clientRtt;
double get serverRtt => _serverRtt;
double get avgRtt => _avrRtt;
@@ -312,7 +314,7 @@ class SyncplayClient {
if (json.containsKey('Hello')) {
if (json['Hello'].containsKey('room') &&
json['Hello']['room'].containsKey('name')) {
- _setLocked(false);
+ // _setLocked(false);
_username = json['Hello']['username'];
_currentRoom = json['Hello']['room']['name'];
print(
@@ -338,7 +340,12 @@ class SyncplayClient {
json['State']["ping"]["clientLatencyCalculation"], _serverRtt);
}
if (json['State'].containsKey('ignoringOnTheFly')) {
- sendSyncPlaySyncRequestAck();
+ _setLocked(true);
+ _sendSyncPlaySyncRequestAck(
+ json['State']['playstate']['position']?.toDouble() ?? 0.0,
+ json['State']['playstate']['paused'] ?? true,
+ null,
+ json['State']['playstate']['doSeek']);
return;
}
if (!json['State'].containsKey('playstate')) {
@@ -367,30 +374,34 @@ class SyncplayClient {
'type': 'init',
'username': json['Set']['playlistIndex']['user'] ?? '',
});
+ _setLocked(false);
return;
}
if (json['Set'].containsKey('user')) {
Map<String, dynamic> userMap = data['Set']['user'];
userMap.forEach((username, details) {
+ if (!details.containsKey('event')) {
+ return;
+ }
var event = details['event'].keys.first ?? 'unknown';
_roomMessageController?.add({
'type': event,
'username': username,
});
});
- return;
- }
- if (!json['Set'].containsKey('file')) {
- return;
- }
- if (_isLocked) {
- return;
+ for (var username in userMap.keys) {
+ var userData = userMap[username];
+ if (userData is Map && userData.containsKey('file')) {
+ var fileData = userData['file'];
+ var fileName = fileData['name'];
+ _currentFileName = fileName;
+ _flieChangedMessageController?.add({
+ 'name': fileName,
+ 'setBy': username,
+ });
+ }
+ }
}
- _flieChangedMessageController?.add({
- 'name': json['Set']['file']['name'] ?? '',
- 'setBy': json['Set']['user'].keys.first ?? '',
- });
- return;
} else {
throw SyncplayProtocolException('SyncPlay: unknown message ty');
}
@@ -435,15 +446,16 @@ class SyncplayClient {
await _sendMessage(StateMessage(
position: _currentPositon,
paused: _isPaused,
- setBy: _username ?? '',
+ setBy: null,
doSeek: null,
clientLatencyCalculation:
DateTime.now().millisecondsSinceEpoch / 1000.0,
- clientAck: true));
+ clientAck: 1));
_setLocked(true);
}
- Future<void> sendSyncPlaySyncRequestAck() async {
+ Future<void> _sendSyncPlaySyncRequestAck(
+ double position, bool paused, String? username, bool? doSeek) async {
if (_socket == null) {
throw SyncplayConnectionException('SyncPlay: not connected to server');
}
@@ -452,13 +464,14 @@ class SyncplayClient {
}
await _sendMessage(
StateMessage(
- position: _currentPositon,
- paused: _isPaused,
- setBy: _username ?? '',
+ position: position,
+ paused: paused,
+ doSeek: doSeek,
+ setBy: username,
latencyCalculation: _lastLatencyCalculation,
clientLatencyCalculation:
DateTime.now().millisecondsSinceEpoch / 1000.0,
- serverAck: true),
+ serverAck: 1),
force: true);
_setLocked(false);
}
@@ -470,13 +483,17 @@ class SyncplayClient {
if (_currentRoom == null || _username == null) {
throw SyncplayProtocolException('SyncPlay: not in a room');
}
- await _sendMessage(SetMessage(
- setJoined: true,
- room: _currentRoom,
- ));
- await _sendMessage(SetMessage(
- setReady: true,
- ));
+ await _sendMessage(
+ SetMessage(
+ setJoined: true,
+ room: _currentRoom,
+ ),
+ force: true);
+ await _sendMessage(
+ SetMessage(
+ setReady: true,
+ ),
+ force: true);
}
Future<void> disconnect() async {
@@ -491,10 +508,13 @@ class SyncplayClient {
_positionChangedMessageController = null;
_heartbeatTimer?.cancel();
_heartbeatTimer = null;
- await _socket?.close();
+ try {
+ await _socket?.close();
+ } catch (_) {}
_socket = null;
_currentRoom = null;
_username = null;
+ _currentFileName = null;
_currentPositon = 0.0;
_isPaused = true;
_lastLatencyCalculation = null;