Initial commit: watch-together phases 0-4 + presence hardening, internet-tested
This commit is contained in:
commit
427d851a5b
101 files changed
+11326
No files matched your search
@@ -0,0 +1,80 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:yaml/yaml.dart';
|
||||
|
||||
import 'errors.dart';
|
||||
|
||||
class AppConfig {
|
||||
final int port;
|
||||
final String secret;
|
||||
final String name;
|
||||
final String mediaPath;
|
||||
final String logLevel;
|
||||
final String advertiseHost;
|
||||
|
||||
const AppConfig({
|
||||
required this.port,
|
||||
required this.secret,
|
||||
required this.name,
|
||||
this.mediaPath = '',
|
||||
this.logLevel = 'INFO',
|
||||
this.advertiseHost = '127.0.0.1',
|
||||
});
|
||||
|
||||
factory AppConfig.defaults() =>
|
||||
const AppConfig(port: 8080, secret: 'change-me', name: 'room');
|
||||
|
||||
factory AppConfig.fromMap(Map<String, Object?> map) {
|
||||
try {
|
||||
return AppConfig(
|
||||
port: (map['port'] as num?)?.toInt() ?? 8080,
|
||||
secret: (map['secret'] as String?) ?? 'change-me',
|
||||
name: (map['name'] as String?) ?? 'room',
|
||||
mediaPath: (map['mediaPath'] as String?) ?? '',
|
||||
logLevel: (map['logLevel'] as String?) ?? 'INFO',
|
||||
advertiseHost: (map['advertiseHost'] as String?) ?? '127.0.0.1',
|
||||
);
|
||||
} catch (e) {
|
||||
throw ConfigException('invalid config map: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Object?> toMap() => {
|
||||
'port': port,
|
||||
'secret': secret,
|
||||
'name': name,
|
||||
'mediaPath': mediaPath,
|
||||
'logLevel': logLevel,
|
||||
'advertiseHost': advertiseHost,
|
||||
};
|
||||
|
||||
static Future<AppConfig> loadFile(String path) async {
|
||||
final file = File(path);
|
||||
if (!await file.exists()) {
|
||||
throw ConfigException('config file not found: $path');
|
||||
}
|
||||
final text = await file.readAsString();
|
||||
try {
|
||||
if (path.endsWith('.json')) {
|
||||
final decoded = jsonDecode(text);
|
||||
if (decoded is! Map) throw const ConfigException('root must be a map');
|
||||
return AppConfig.fromMap(Map<String, Object?>.from(decoded));
|
||||
}
|
||||
final yamlMap = loadYaml(text);
|
||||
if (yamlMap is! YamlMap) throw const ConfigException('root must be a map');
|
||||
return AppConfig.fromMap(
|
||||
Map<String, Object?>.from(yamlMap.map((k, v) => MapEntry('$k', v))));
|
||||
} catch (e) {
|
||||
if (e is ConfigException) rethrow;
|
||||
throw ConfigException('failed to parse $path: $e');
|
||||
}
|
||||
}
|
||||
|
||||
static String defaultPath(String appName) {
|
||||
final home =
|
||||
Platform.environment['HOME'] ?? Platform.environment['USERPROFILE'] ?? '.';
|
||||
return p.join(home, '.config', appName, 'config.yaml');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
abstract class RelayConstants {
|
||||
static const int protoVersion = 4;
|
||||
|
||||
static const int chunkBytes = 256 * 1024;
|
||||
static const int creditWindowChunks = 8;
|
||||
static const int maxConcurrentOpen = 16;
|
||||
|
||||
static const int seekDebounceMs = 300;
|
||||
static const double driftSeekThresholdSecs = 5.0;
|
||||
static const double slowDownThresholdSecs = 1.5;
|
||||
static const double slowDownRate = 0.95;
|
||||
static const double minBufferSecs = 4.0;
|
||||
static const double resumeHysteresisSecs = 4.0;
|
||||
|
||||
static const int stateHeartbeatSecs = 1;
|
||||
static const int pingIntervalSecs = 5;
|
||||
|
||||
static const int maxAvatarBytes = 64 * 1024;
|
||||
static const int maxNameLength = 32;
|
||||
static const int maxChatLength = 500;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
abstract class SyncRelayException implements Exception {
|
||||
final String message;
|
||||
const SyncRelayException(this.message);
|
||||
|
||||
@override
|
||||
String toString() => '$runtimeType: $message';
|
||||
}
|
||||
|
||||
class ConfigException extends SyncRelayException {
|
||||
const ConfigException(super.message);
|
||||
}
|
||||
|
||||
class ProtocolException extends SyncRelayException {
|
||||
const ProtocolException(super.message);
|
||||
}
|
||||
|
||||
class AuthException extends SyncRelayException {
|
||||
const AuthException(super.message);
|
||||
}
|
||||
|
||||
class MediaException extends SyncRelayException {
|
||||
const MediaException(super.message);
|
||||
}
|
||||
|
||||
class TunnelException extends SyncRelayException {
|
||||
const TunnelException(super.message);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:logging/logging.dart';
|
||||
|
||||
Logger createLogger(String name) => Logger(name);
|
||||
|
||||
void initLogging({Level level = Level.INFO}) {
|
||||
Logger.root.level = level;
|
||||
Logger.root.onRecord.listen((r) {
|
||||
// ignore: avoid_print
|
||||
print('${r.time.toIso8601String()} ${r.level.name} ${r.loggerName}: ${r.message}');
|
||||
if (r.error != null) {
|
||||
// ignore: avoid_print
|
||||
print(' error: ${r.error}');
|
||||
}
|
||||
if (r.stackTrace != null) {
|
||||
// ignore: avoid_print
|
||||
print('${r.stackTrace}');
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'dart:io';
|
||||
import 'dart:typed_data';
|
||||
|
||||
abstract class MediaSource {
|
||||
Future<int> get size;
|
||||
String get displayName;
|
||||
Future<Uint8List> read(int start, int length);
|
||||
Future<void> close();
|
||||
}
|
||||
|
||||
class FileMediaSource implements MediaSource { final File file;
|
||||
RandomAccessFile? _handle;
|
||||
|
||||
FileMediaSource(this.file);
|
||||
|
||||
@override
|
||||
String get displayName => file.path.split(Platform.pathSeparator).last;
|
||||
|
||||
@override
|
||||
Future<int> get size async => file.length();
|
||||
|
||||
@override
|
||||
Future<Uint8List> read(int start, int length) async {
|
||||
_handle ??= await file.open();
|
||||
await _handle!.setPosition(start);
|
||||
return _handle!.read(length);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() async {
|
||||
await _handle?.close();
|
||||
_handle = null;
|
||||
}
|
||||
}
|
||||
|
||||
class RangeRequest {
|
||||
final int start;
|
||||
final int? end;
|
||||
final int size;
|
||||
const RangeRequest({required this.start, required this.end, required this.size});
|
||||
|
||||
int get contentLength => (end ?? (size - 1)) - start + 1;
|
||||
|
||||
String get contentRange => 'bytes $start-${end ?? size - 1}/$size';
|
||||
|
||||
static RangeRequest? parse(String? header, int size) {
|
||||
if (header == null || header.isEmpty) return null;
|
||||
final value = header.trim();
|
||||
if (!value.startsWith('bytes=')) return null;
|
||||
final spec = value.substring(6);
|
||||
if (spec.startsWith('-')) {
|
||||
final suffix = int.tryParse(spec.substring(1));
|
||||
if (suffix == null || suffix <= 0) return null;
|
||||
final start = (size - suffix).clamp(0, size);
|
||||
return RangeRequest(start: start, end: null, size: size);
|
||||
}
|
||||
final parts = spec.split('-');
|
||||
if (parts.length != 2) return null;
|
||||
final start = int.tryParse(parts[0].trim());
|
||||
if (start == null || start < 0 || start >= size) return null;
|
||||
if (parts[1].trim().isEmpty) return RangeRequest(start: start, end: null, size: size);
|
||||
final end = int.tryParse(parts[1].trim());
|
||||
if (end == null || end < start) return null;
|
||||
return RangeRequest(start: start, end: end.clamp(0, size - 1), size: size);
|
||||
}
|
||||
}
|
||||
|
||||
String contentTypeForFile(String filename) {
|
||||
final dot = filename.lastIndexOf('.');
|
||||
final ext = dot < 0 ? '' : filename.substring(dot).toLowerCase();
|
||||
switch (ext) {
|
||||
case '.mkv':
|
||||
return 'video/x-matroska';
|
||||
case '.mp4':
|
||||
case '.m4v':
|
||||
return 'video/mp4';
|
||||
case '.webm':
|
||||
return 'video/webm';
|
||||
case '.avi':
|
||||
return 'video/x-msvideo';
|
||||
case '.mov':
|
||||
return 'video/quicktime';
|
||||
case '.ts':
|
||||
return 'video/mp2t';
|
||||
case '.mp3':
|
||||
return 'audio/mpeg';
|
||||
case '.mka':
|
||||
return 'audio/x-matroska';
|
||||
default:
|
||||
return 'application/octet-stream';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
import 'constants.dart';
|
||||
import 'errors.dart';
|
||||
|
||||
enum MessageKind {
|
||||
hello,
|
||||
welcome,
|
||||
state,
|
||||
event,
|
||||
chat,
|
||||
buffered,
|
||||
kicked,
|
||||
kick,
|
||||
eof,
|
||||
err,
|
||||
open,
|
||||
ack,
|
||||
cancel,
|
||||
}
|
||||
|
||||
class HelloUser {
|
||||
final String name;
|
||||
final String avatar;
|
||||
const HelloUser({required this.name, this.avatar = ''});
|
||||
|
||||
Map<String, Object?> toJson() => {'name': name, 'avatar': avatar};
|
||||
|
||||
factory HelloUser.fromJson(Map<String, Object?> json) =>
|
||||
HelloUser(name: (json['name'] as String?) ?? '', avatar: (json['avatar'] as String?) ?? '');
|
||||
}
|
||||
|
||||
class HelloMedia {
|
||||
final String name;
|
||||
final int size;
|
||||
final double duration;
|
||||
final String? url;
|
||||
const HelloMedia({required this.name, required this.size, required this.duration, this.url});
|
||||
|
||||
Map<String, Object?> toJson() => {'name': name, 'size': size, 'duration': duration, if (url != null) 'url': url};
|
||||
|
||||
factory HelloMedia.fromJson(Map<String, Object?> json) => HelloMedia(
|
||||
name: (json['name'] as String?) ?? '',
|
||||
size: (json['size'] as num?)?.toInt() ?? 0,
|
||||
duration: (json['duration'] as num?)?.toDouble() ?? 0.0,
|
||||
url: json['url'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
class HelloMessage {
|
||||
final int proto;
|
||||
final String secret;
|
||||
final HelloUser user;
|
||||
final HelloMedia media;
|
||||
const HelloMessage({required this.proto, required this.secret, required this.user, required this.media});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
't': 'hello',
|
||||
'proto': proto,
|
||||
'secret': secret,
|
||||
'user': user.toJson(),
|
||||
'media': media.toJson(),
|
||||
};
|
||||
|
||||
factory HelloMessage.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'hello') throw const ProtocolException('not a hello message');
|
||||
final user = json['user'];
|
||||
final media = json['media'];
|
||||
if (user is! Map || media is! Map) throw const ProtocolException('hello missing user/media');
|
||||
return HelloMessage(
|
||||
proto: (json['proto'] as num?)?.toInt() ?? RelayConstants.protoVersion,
|
||||
secret: (json['secret'] as String?) ?? '',
|
||||
user: HelloUser.fromJson(Map<String, Object?>.from(user)),
|
||||
media: HelloMedia.fromJson(Map<String, Object?>.from(media)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class RoomState {
|
||||
final double position;
|
||||
final bool paused;
|
||||
final int mediaId;
|
||||
final DateTime serverTime;
|
||||
const RoomState({required this.position, required this.paused, required this.mediaId, required this.serverTime});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'position': position,
|
||||
'paused': paused,
|
||||
'mediaId': mediaId,
|
||||
'serverTime': serverTime.toIso8601String(),
|
||||
};
|
||||
|
||||
factory RoomState.fromJson(Map<String, Object?> json) => RoomState(
|
||||
position: (json['position'] as num?)?.toDouble() ?? 0.0,
|
||||
paused: (json['paused'] as bool?) ?? true,
|
||||
mediaId: (json['mediaId'] as num?)?.toInt() ?? 0,
|
||||
serverTime: DateTime.tryParse('${json['serverTime']}') ?? DateTime.now().toUtc(),
|
||||
);
|
||||
}
|
||||
|
||||
class WelcomeMessage {
|
||||
final String token;
|
||||
final String memberId;
|
||||
final String? mediaUrl;
|
||||
final Map<String, Object?>? state;
|
||||
const WelcomeMessage({required this.token, this.memberId = '', this.mediaUrl, this.state});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
't': 'welcome',
|
||||
'token': token,
|
||||
'memberId': memberId,
|
||||
if (mediaUrl != null) 'mediaUrl': mediaUrl,
|
||||
if (state != null) 'state': state,
|
||||
};
|
||||
|
||||
factory WelcomeMessage.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'welcome') throw const ProtocolException('not a welcome message');
|
||||
final state = json['state'];
|
||||
return WelcomeMessage(
|
||||
token: (json['token'] as String?) ?? '',
|
||||
memberId: (json['memberId'] as String?) ?? '',
|
||||
mediaUrl: json['mediaUrl'] as String?,
|
||||
state: state is Map ? Map<String, Object?>.from(state) : null,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class KickedMessage {
|
||||
final String reason;
|
||||
const KickedMessage({this.reason = ''});
|
||||
|
||||
Map<String, Object?> toJson() => {'t': 'kicked', 'reason': reason};
|
||||
|
||||
factory KickedMessage.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'kicked') throw const ProtocolException('not a kicked message');
|
||||
return KickedMessage(reason: (json['reason'] as String?) ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
class KickRequest {
|
||||
final String target;
|
||||
final String reason;
|
||||
const KickRequest({required this.target, this.reason = ''});
|
||||
|
||||
Map<String, Object?> toJson() => {'t': 'kick', 'target': target, 'reason': reason};
|
||||
|
||||
factory KickRequest.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'kick') throw const ProtocolException('not a kick request');
|
||||
return KickRequest(
|
||||
target: (json['target'] as String?) ?? '',
|
||||
reason: (json['reason'] as String?) ?? '',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ReadyIntent {
|
||||
final bool ready;
|
||||
final String source;
|
||||
const ReadyIntent({required this.ready, this.source = 'manual'});
|
||||
|
||||
Map<String, Object?> toJson() => {'t': 'ready', 'ready': ready, 'source': source};
|
||||
|
||||
factory ReadyIntent.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'ready') throw const ProtocolException('not a ready intent');
|
||||
return ReadyIntent(
|
||||
ready: (json['ready'] as bool?) ?? false,
|
||||
source: (json['source'] as String?) ?? 'manual',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ForceIntent {
|
||||
final String target;
|
||||
final bool ready;
|
||||
const ForceIntent({required this.target, required this.ready});
|
||||
|
||||
Map<String, Object?> toJson() => {'t': 'force', 'target': target, 'ready': ready};
|
||||
|
||||
factory ForceIntent.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'force') throw const ProtocolException('not a force intent');
|
||||
return ForceIntent(
|
||||
target: (json['target'] as String?) ?? '',
|
||||
ready: (json['ready'] as bool?) ?? false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SeekIntent {
|
||||
final double position;
|
||||
const SeekIntent({required this.position});
|
||||
|
||||
Map<String, Object?> toJson() => {'t': 'seek', 'position': position};
|
||||
|
||||
factory SeekIntent.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'seek') throw const ProtocolException('not a seek intent');
|
||||
return SeekIntent(position: (json['position'] as num?)?.toDouble() ?? 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
class SwapIntent {
|
||||
final HelloMedia media;
|
||||
const SwapIntent({required this.media});
|
||||
|
||||
Map<String, Object?> toJson() => {'t': 'swap', 'media': media.toJson()};
|
||||
|
||||
factory SwapIntent.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'swap') throw const ProtocolException('not a swap intent');
|
||||
final media = json['media'];
|
||||
if (media is! Map) throw const ProtocolException('swap missing media');
|
||||
return SwapIntent(media: HelloMedia.fromJson(Map<String, Object?>.from(media)));
|
||||
}
|
||||
}
|
||||
|
||||
class ReportMessage {
|
||||
final double position;
|
||||
final double buffered;
|
||||
final int eventId;
|
||||
const ReportMessage({required this.position, required this.buffered, required this.eventId});
|
||||
|
||||
Map<String, Object?> toJson() =>
|
||||
{'t': 'report', 'position': position, 'buffered': buffered, 'eventId': eventId};
|
||||
|
||||
factory ReportMessage.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'report') throw const ProtocolException('not a report');
|
||||
return ReportMessage(
|
||||
position: (json['position'] as num?)?.toDouble() ?? 0.0,
|
||||
buffered: (json['buffered'] as num?)?.toDouble() ?? 0.0,
|
||||
eventId: (json['eventId'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ChatMessage {
|
||||
final String text;
|
||||
const ChatMessage({required this.text});
|
||||
|
||||
Map<String, Object?> toJson() => {'t': 'chat', 'text': text};
|
||||
|
||||
factory ChatMessage.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'chat') throw const ProtocolException('not a chat message');
|
||||
return ChatMessage(text: (json['text'] as String?) ?? '');
|
||||
}
|
||||
}
|
||||
|
||||
class MemberView {
|
||||
final String id;
|
||||
final String name;
|
||||
final String avatar;
|
||||
final bool ready;
|
||||
final bool inSet;
|
||||
final double buffered;
|
||||
final bool stale;
|
||||
const MemberView({
|
||||
required this.id,
|
||||
required this.name,
|
||||
this.avatar = '',
|
||||
required this.ready,
|
||||
required this.inSet,
|
||||
required this.buffered,
|
||||
required this.stale,
|
||||
});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'avatar': avatar,
|
||||
'ready': ready,
|
||||
'inSet': inSet,
|
||||
'buffered': buffered,
|
||||
'stale': stale,
|
||||
};
|
||||
|
||||
factory MemberView.fromJson(Map<String, Object?> json) => MemberView(
|
||||
id: (json['id'] as String?) ?? '',
|
||||
name: (json['name'] as String?) ?? '',
|
||||
avatar: (json['avatar'] as String?) ?? '',
|
||||
ready: (json['ready'] as bool?) ?? false,
|
||||
inSet: (json['inSet'] as bool?) ?? false,
|
||||
buffered: (json['buffered'] as num?)?.toDouble() ?? 0.0,
|
||||
stale: (json['stale'] as bool?) ?? false,
|
||||
);
|
||||
}
|
||||
|
||||
class RoomBroadcast {
|
||||
final int eventId;
|
||||
final String transport;
|
||||
final double position;
|
||||
final DateTime serverTime;
|
||||
final int mediaId;
|
||||
final Map<String, Object?>? media;
|
||||
final List<MemberView> members;
|
||||
const RoomBroadcast({
|
||||
required this.eventId,
|
||||
required this.transport,
|
||||
required this.position,
|
||||
required this.serverTime,
|
||||
required this.mediaId,
|
||||
this.media,
|
||||
required this.members,
|
||||
});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
't': 'room',
|
||||
'eventId': eventId,
|
||||
'transport': transport,
|
||||
'position': position,
|
||||
'serverTime': serverTime.toIso8601String(),
|
||||
'mediaId': mediaId,
|
||||
if (media != null) 'media': media,
|
||||
'members': members.map((m) => m.toJson()).toList(),
|
||||
};
|
||||
|
||||
factory RoomBroadcast.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'room') throw const ProtocolException('not a room broadcast');
|
||||
final members = json['members'];
|
||||
final media = json['media'];
|
||||
return RoomBroadcast(
|
||||
eventId: (json['eventId'] as num?)?.toInt() ?? 0,
|
||||
transport: (json['transport'] as String?) ?? 'held',
|
||||
position: (json['position'] as num?)?.toDouble() ?? 0.0,
|
||||
serverTime: DateTime.tryParse('${json['serverTime']}') ?? DateTime.now().toUtc(),
|
||||
mediaId: (json['mediaId'] as num?)?.toInt() ?? 0,
|
||||
media: media is Map ? Map<String, Object?>.from(media) : null,
|
||||
members: members is List
|
||||
? members
|
||||
.whereType<Map>()
|
||||
.map((m) => MemberView.fromJson(Map<String, Object?>.from(m)))
|
||||
.toList()
|
||||
: const [],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class FeedMessage {
|
||||
final String actor;
|
||||
final String action;
|
||||
final String? target;
|
||||
final String reason;
|
||||
final DateTime at;
|
||||
const FeedMessage({
|
||||
required this.actor,
|
||||
required this.action,
|
||||
this.target,
|
||||
this.reason = '',
|
||||
required this.at,
|
||||
});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
't': 'feed',
|
||||
'actor': actor,
|
||||
'action': action,
|
||||
if (target != null) 'target': target,
|
||||
'reason': reason,
|
||||
'at': at.toIso8601String(),
|
||||
};
|
||||
|
||||
factory FeedMessage.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'feed') throw const ProtocolException('not a feed message');
|
||||
return FeedMessage(
|
||||
actor: (json['actor'] as String?) ?? '',
|
||||
action: (json['action'] as String?) ?? '',
|
||||
target: json['target'] as String?,
|
||||
reason: (json['reason'] as String?) ?? '',
|
||||
at: DateTime.tryParse('${json['at']}') ?? DateTime.now().toUtc(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SyncEvent { final String kind;
|
||||
final double position;
|
||||
final bool doSeek;
|
||||
final int ignoringOnTheFly;
|
||||
const SyncEvent({required this.kind, required this.position, this.doSeek = false, this.ignoringOnTheFly = 0});
|
||||
|
||||
Map<String, Object?> toJson() => {
|
||||
't': 'event',
|
||||
'kind': kind,
|
||||
'position': position,
|
||||
'doSeek': doSeek,
|
||||
'ignoringOnTheFly': ignoringOnTheFly,
|
||||
};
|
||||
|
||||
factory SyncEvent.fromJson(Map<String, Object?> json) {
|
||||
if (json['t'] != 'event') throw const ProtocolException('not an event message');
|
||||
return SyncEvent(
|
||||
kind: (json['kind'] as String?) ?? '',
|
||||
position: (json['position'] as num?)?.toDouble() ?? 0.0,
|
||||
doSeek: (json['doSeek'] as bool?) ?? false,
|
||||
ignoringOnTheFly: (json['ignoringOnTheFly'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import 'constants.dart';
|
||||
import 'protocol.dart';
|
||||
|
||||
typedef RoomClock = DateTime Function();
|
||||
|
||||
enum Transport { playing, held }
|
||||
|
||||
enum Correction { none, slowDown, seek }
|
||||
|
||||
Correction correctionFor({required double ownPosition, required double roomPosition}) {
|
||||
final drift = ownPosition - roomPosition;
|
||||
if (drift.abs() > RelayConstants.driftSeekThresholdSecs) return Correction.seek;
|
||||
if (drift > RelayConstants.slowDownThresholdSecs) return Correction.slowDown;
|
||||
return Correction.none;
|
||||
}
|
||||
|
||||
class EngineMember {
|
||||
final String id;
|
||||
final String token;
|
||||
String name;
|
||||
String avatar;
|
||||
bool ready = false;
|
||||
bool inSet = false;
|
||||
double buffered = 0;
|
||||
DateTime lastSeen;
|
||||
EngineMember({
|
||||
required this.id,
|
||||
required this.token,
|
||||
required this.name,
|
||||
this.avatar = '',
|
||||
required DateTime now,
|
||||
}) : lastSeen = now;
|
||||
|
||||
MemberView view({required bool stale}) => MemberView(
|
||||
id: id,
|
||||
name: name,
|
||||
avatar: avatar,
|
||||
ready: ready,
|
||||
inSet: inSet,
|
||||
buffered: buffered,
|
||||
stale: stale,
|
||||
);
|
||||
}
|
||||
|
||||
class EngineFeed {
|
||||
final List<FeedMessage> pending = [];
|
||||
void add(FeedMessage message) => pending.add(message);
|
||||
List<FeedMessage> drain() {
|
||||
final out = List<FeedMessage>.from(pending);
|
||||
pending.clear();
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
class RoomEngine {
|
||||
final RoomClock clock;
|
||||
final Duration staleAfter;
|
||||
final Duration dropAfter;
|
||||
final EngineFeed feed = EngineFeed();
|
||||
final Map<String, EngineMember> members = {};
|
||||
|
||||
int eventId = 0;
|
||||
Transport transport = Transport.held;
|
||||
double position = 0;
|
||||
DateTime serverTime;
|
||||
int mediaId = 1;
|
||||
HelloMedia? media;
|
||||
int _nextId = 1;
|
||||
|
||||
RoomEngine({RoomClock? clock, Duration? staleAfter, Duration? dropAfter})
|
||||
: clock = clock ?? (() => DateTime.now().toUtc()),
|
||||
staleAfter = staleAfter ?? const Duration(seconds: 15),
|
||||
dropAfter = dropAfter ?? const Duration(seconds: 30),
|
||||
serverTime = (clock ?? (() => DateTime.now().toUtc()))();
|
||||
|
||||
DateTime get now => clock();
|
||||
|
||||
double positionAt([DateTime? at]) {
|
||||
final t = at ?? now;
|
||||
if (transport != Transport.playing) return position;
|
||||
return position + t.difference(serverTime).inMilliseconds / 1000.0;
|
||||
}
|
||||
|
||||
bool isStale(EngineMember member, [DateTime? at]) =>
|
||||
(at ?? now).difference(member.lastSeen) > staleAfter;
|
||||
|
||||
String applyJoin(String token, String name, String avatar) {
|
||||
final id = 'm${_nextId++}';
|
||||
members[token] =
|
||||
EngineMember(id: id, token: token, name: name, avatar: avatar, now: now);
|
||||
feed.add(FeedMessage(actor: name, action: 'join', at: now));
|
||||
return id;
|
||||
}
|
||||
|
||||
String? applyLeave(String token) {
|
||||
final removed = members.remove(token);
|
||||
if (removed == null) return null;
|
||||
feed.add(FeedMessage(actor: removed.name, action: 'leave', at: now));
|
||||
evaluate();
|
||||
return removed.id;
|
||||
}
|
||||
|
||||
EngineMember? byId(String id) {
|
||||
for (final member in members.values) {
|
||||
if (member.id == id) return member;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
void applyReady(String token, bool ready, {String source = 'manual'}) {
|
||||
final member = members[token];
|
||||
if (member == null) return;
|
||||
member.lastSeen = now;
|
||||
if (member.ready == ready && member.inSet) {
|
||||
evaluate();
|
||||
return;
|
||||
}
|
||||
member.ready = ready;
|
||||
if (ready) member.inSet = true;
|
||||
feed.add(FeedMessage(
|
||||
actor: member.name,
|
||||
action: ready ? 'ready' : 'unready',
|
||||
reason: source,
|
||||
at: now));
|
||||
evaluate();
|
||||
}
|
||||
|
||||
void applyForce(String actorToken, String target, bool ready) {
|
||||
final actor = members[actorToken];
|
||||
final actorName = actor?.name ?? '?';
|
||||
if (target == 'all') {
|
||||
for (final member in members.values) {
|
||||
member.ready = ready;
|
||||
if (ready) member.inSet = true;
|
||||
}
|
||||
} else {
|
||||
final member = byId(target);
|
||||
if (member == null) return;
|
||||
member.ready = ready;
|
||||
if (ready) member.inSet = true;
|
||||
feed.add(FeedMessage(
|
||||
actor: actorName,
|
||||
action: ready ? 'force-ready' : 'force-unready',
|
||||
target: member.name,
|
||||
at: now));
|
||||
evaluate();
|
||||
return;
|
||||
}
|
||||
feed.add(FeedMessage(
|
||||
actor: actorName,
|
||||
action: ready ? 'force-play' : 'force-hold',
|
||||
at: now));
|
||||
evaluate();
|
||||
}
|
||||
|
||||
void applySeek(String token, double seekPosition) {
|
||||
final member = members[token];
|
||||
if (member == null) return;
|
||||
if (seekPosition.isNaN || seekPosition < 0) return;
|
||||
member.lastSeen = now;
|
||||
position = seekPosition;
|
||||
serverTime = now;
|
||||
eventId++;
|
||||
feed.add(FeedMessage(actor: member.name, action: 'seek', at: now));
|
||||
}
|
||||
|
||||
void applySwap(String actorToken, HelloMedia next) {
|
||||
final actor = members[actorToken];
|
||||
mediaId++;
|
||||
media = next;
|
||||
position = 0;
|
||||
serverTime = now;
|
||||
eventId++;
|
||||
transport = Transport.held;
|
||||
for (final member in members.values) {
|
||||
member.ready = false;
|
||||
member.inSet = false;
|
||||
member.buffered = 0;
|
||||
}
|
||||
feed.add(FeedMessage(actor: actor?.name ?? '?', action: 'swap', at: now));
|
||||
}
|
||||
|
||||
void applyReport(String token, double reportPosition, double buffered, int reportEventId) {
|
||||
final member = members[token];
|
||||
if (member == null) return;
|
||||
member.lastSeen = now;
|
||||
member.buffered = buffered.isNaN || buffered < 0 ? 0 : buffered;
|
||||
if (reportEventId < eventId) return;
|
||||
evaluate();
|
||||
}
|
||||
|
||||
void sweepStale() {
|
||||
var changed = false;
|
||||
for (final member in members.values) {
|
||||
if (isStale(member) && member.inSet) {
|
||||
member.inSet = false;
|
||||
changed = true;
|
||||
feed.add(FeedMessage(actor: member.name, action: 'stale', reason: 'no signal', at: now));
|
||||
}
|
||||
}
|
||||
if (changed) evaluate();
|
||||
}
|
||||
|
||||
List<String> sweepDropped() {
|
||||
final t = now;
|
||||
final dropped = <String>[];
|
||||
for (final member in members.values.toList()) {
|
||||
if (t.difference(member.lastSeen) > dropAfter) {
|
||||
members.remove(member.token);
|
||||
dropped.add(member.token);
|
||||
feed.add(FeedMessage(actor: member.name, action: 'leave', reason: 'silent too long', at: t));
|
||||
}
|
||||
}
|
||||
if (dropped.isNotEmpty) evaluate();
|
||||
return dropped;
|
||||
}
|
||||
|
||||
void evaluate() {
|
||||
final t = now;
|
||||
if (transport == Transport.playing) {
|
||||
final blocked = members.values
|
||||
.where((m) => m.inSet)
|
||||
.any((m) => !m.ready || m.buffered < RelayConstants.minBufferSecs || isStale(m, t));
|
||||
if (blocked) {
|
||||
position = positionAt(t);
|
||||
serverTime = t;
|
||||
eventId++;
|
||||
transport = Transport.held;
|
||||
feed.add(FeedMessage(actor: 'server', action: 'pause', at: t));
|
||||
}
|
||||
return;
|
||||
}
|
||||
final inSet = members.values.where((m) => m.inSet).toList();
|
||||
if (inSet.isEmpty) return;
|
||||
final freshCount =
|
||||
members.values.where((m) => !isStale(m, t)).length;
|
||||
final quorum = inSet.length >= 2 || freshCount <= 1;
|
||||
final allGood = inSet.every(
|
||||
(m) => m.ready && m.buffered >= RelayConstants.minBufferSecs && !isStale(m, t));
|
||||
if (allGood && quorum) {
|
||||
serverTime = t;
|
||||
eventId++;
|
||||
transport = Transport.playing;
|
||||
feed.add(FeedMessage(actor: 'server', action: 'resume', at: t));
|
||||
}
|
||||
}
|
||||
|
||||
RoomBroadcast broadcast() => RoomBroadcast(
|
||||
eventId: eventId,
|
||||
transport: transport == Transport.playing ? 'playing' : 'held',
|
||||
position: position,
|
||||
serverTime: serverTime,
|
||||
mediaId: mediaId,
|
||||
media: media?.toJson(),
|
||||
members: members.values.map((m) => m.view(stale: isStale(m))).toList(),
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user