mirror of
https://github.com/R0m1k3/xtremflow.git
synced 2026-10-19 05:06:21 +02:00
feat: security hardening, streaming overhaul, design polish, tests
Security: - Replace unsalted SHA-256 password hashing with bcrypt (lazy rehash on login) - Add authenticated /api/xtream-api gateway: Xtream credentials are injected server-side and never sent to the frontend; /api/playlists no longer returns passwords - Redact credentials from all logs (login body, proxy/FFmpeg/scheduler URLs) - Add auth to recordings, EPG, season-passes and streaming routes (HttpOnly session cookie for hls.js; loopback bypass for local FFmpeg) - Lock player postMessage to same-origin in both directions - Vendor and pin hls.js 1.6.7 / mpegts.js 1.7.3 (drop CDN @latest) - Fix rate limiter (client IP was never resolved), add login rate limit, restrict CORS, add CSP Report-Only, block private-IP SSRF targets, fix path traversal in recording log retrieval, chmod 777 -> 770 - Remove dead HiveService (seeded admin/admin into IndexedDB with SHA-256) - Fix authMiddleware not populating 'user' context (getPlaylist ignored the logged-in user; admin purge always returned 403) Streaming: - New FfmpegSessionManager: process registry, idle reaper (4 min live / 15 min VOD), orphan cleanup at startup, clean SIGTERM shutdown, fast-fail with stderr instead of 30 s timeout - Quality selection (source/high/medium/low) for live and VOD; source mode streams with -c:v copy (zero transcoding); selector wired into the player - Concurrent recordings (MAX_CONCURRENT_RECORDINGS, default 2); conflicts retry on the next tick instead of silently failing - Lower live latency (HLS window 20 -> 10 segments, liveSync 10 -> 3) - Fix recording log lookup (.mp4 vs .mkv mismatch) Design: - Replace hardcoded colors with AppColors tokens (12 files) - web/theme.css syncs HTML players with the Flutter palette - DPAD/keyboard navigation (arrow-key focus, player shortcuts) - Tooltips on player icon buttons, Semantics on content cards - Remove 7 dead widgets broken since the Stitch merge Quality: - bin/test/: 21 unit tests (bcrypt, redaction, traversal, SSRF, recording conflicts) plus a quality-selector widget test - GitHub Actions CI (analyze + test + build web) - Archive stale status docs into docs/archive/ Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb5eca7547
commit
60d3f42901
107 files changed
+4525
-3815
No files matched your search
@@ -1,346 +0,0 @@
|
||||
/// Adaptive Bitrate (ABR) Streaming Handler for HLS
|
||||
///
|
||||
/// Supports multi-bitrate HLS playlists for adaptive streaming
|
||||
/// with fallback options for poor network conditions
|
||||
library;
|
||||
|
||||
/// Represents a video quality level for adaptive bitrate streaming
|
||||
class QualityLevel {
|
||||
final String resolution;
|
||||
final int bitrateBps;
|
||||
final int width;
|
||||
final int height;
|
||||
final String ffmpegPreset; // ultrafast, fast, medium, slow
|
||||
final String label;
|
||||
|
||||
const QualityLevel({
|
||||
required this.resolution,
|
||||
required this.bitrateBps,
|
||||
required this.width,
|
||||
required this.height,
|
||||
this.ffmpegPreset = 'medium',
|
||||
required this.label,
|
||||
});
|
||||
|
||||
/// Get FFmpeg video bitrate argument
|
||||
String get videoBitrateArg => '${(bitrateBps * 0.75).toInt() ~/ 1000}k';
|
||||
|
||||
/// Get FFmpeg maxrate argument (150% of bitrate)
|
||||
String get maxRateArg => '${((bitrateBps * 1.5).toInt() ~/ 1000)}k';
|
||||
|
||||
/// Get FFmpeg buffer size argument
|
||||
String get bufferSizeArg => '${((bitrateBps * 2).toInt() ~/ 1000)}k';
|
||||
|
||||
@override
|
||||
String toString() => '$label ($resolution - ${bitrateBps ~/ 1000000}Mbps)';
|
||||
}
|
||||
|
||||
/// Standard quality profiles for adaptive streaming
|
||||
class QualityProfiles {
|
||||
// Mobile & Low Bandwidth
|
||||
static const mobile240p = QualityLevel(
|
||||
resolution: '426x240',
|
||||
bitrateBps: 500000, // 0.5 Mbps
|
||||
width: 426,
|
||||
height: 240,
|
||||
ffmpegPreset: 'ultrafast',
|
||||
label: '240p (Low)',
|
||||
);
|
||||
|
||||
static const mobile360p = QualityLevel(
|
||||
resolution: '640x360',
|
||||
bitrateBps: 1200000, // 1.2 Mbps
|
||||
width: 640,
|
||||
height: 360,
|
||||
ffmpegPreset: 'ultrafast',
|
||||
label: '360p (Mobile)',
|
||||
);
|
||||
|
||||
// Standard Quality
|
||||
static const hd480p = QualityLevel(
|
||||
resolution: '854x480',
|
||||
bitrateBps: 2500000, // 2.5 Mbps
|
||||
width: 854,
|
||||
height: 480,
|
||||
ffmpegPreset: 'fast',
|
||||
label: '480p (SD)',
|
||||
);
|
||||
|
||||
static const hd720p = QualityLevel(
|
||||
resolution: '1280x720',
|
||||
bitrateBps: 5000000, // 5 Mbps
|
||||
width: 1280,
|
||||
height: 720,
|
||||
ffmpegPreset: 'medium',
|
||||
label: '720p (HD)',
|
||||
);
|
||||
|
||||
// High Quality
|
||||
static const fhd1080p = QualityLevel(
|
||||
resolution: '1920x1080',
|
||||
bitrateBps: 8000000, // 8 Mbps
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
ffmpegPreset: 'medium',
|
||||
label: '1080p (Full HD)',
|
||||
);
|
||||
|
||||
// Ultra HD
|
||||
static const uhd2k = QualityLevel(
|
||||
resolution: '2560x1440',
|
||||
bitrateBps: 15000000, // 15 Mbps
|
||||
width: 2560,
|
||||
height: 1440,
|
||||
ffmpegPreset: 'slow',
|
||||
label: '2K (QHD)',
|
||||
);
|
||||
|
||||
static const uhd4k = QualityLevel(
|
||||
resolution: '3840x2160',
|
||||
bitrateBps: 25000000, // 25 Mbps
|
||||
width: 3840,
|
||||
height: 2160,
|
||||
ffmpegPreset: 'slow',
|
||||
label: '4K',
|
||||
);
|
||||
|
||||
/// Get default profiles for balanced streaming
|
||||
static List<QualityLevel> getBalancedProfiles() => [
|
||||
mobile240p,
|
||||
mobile360p,
|
||||
hd480p,
|
||||
hd720p,
|
||||
fhd1080p,
|
||||
];
|
||||
|
||||
/// Get all available profiles
|
||||
static List<QualityLevel> getAllProfiles() => [
|
||||
mobile240p,
|
||||
mobile360p,
|
||||
hd480p,
|
||||
hd720p,
|
||||
fhd1080p,
|
||||
uhd2k,
|
||||
uhd4k,
|
||||
];
|
||||
|
||||
/// Get profiles suitable for streaming type
|
||||
static List<QualityLevel> getProfiles({
|
||||
required String type, // 'live', 'vod', 'low-bandwidth'
|
||||
int? maxBitrateBps,
|
||||
}) {
|
||||
List<QualityLevel> profiles = getBalancedProfiles();
|
||||
|
||||
// Filter by streaming type
|
||||
if (type == 'live') {
|
||||
// Live TV prefers lower bitrates for stability
|
||||
profiles = [mobile240p, mobile360p, hd480p, hd720p];
|
||||
} else if (type == 'low-bandwidth') {
|
||||
// Mobile/low bandwidth - only lower profiles
|
||||
profiles = [mobile240p, mobile360p, hd480p];
|
||||
}
|
||||
|
||||
// Filter by max bitrate if specified
|
||||
if (maxBitrateBps != null) {
|
||||
profiles = profiles.where((p) => p.bitrateBps <= maxBitrateBps).toList();
|
||||
}
|
||||
|
||||
// Ensure at least one profile
|
||||
if (profiles.isEmpty) {
|
||||
profiles = [mobile240p];
|
||||
}
|
||||
|
||||
return profiles;
|
||||
}
|
||||
}
|
||||
|
||||
/// Bandwidth detector for adaptive bitrate selection
|
||||
class BandwidthDetector {
|
||||
final _samples = <DateTime, int>{}; // timestamp -> bytes downloaded
|
||||
final int _totalBytesLastPeriod = 0;
|
||||
final Duration _sampleWindow = const Duration(seconds: 10);
|
||||
|
||||
/// Record bytes downloaded at current time
|
||||
void recordBytes(int bytes) {
|
||||
final now = DateTime.now();
|
||||
_samples[now] = bytes;
|
||||
|
||||
// Clean up old samples
|
||||
final cutoff = now.subtract(_sampleWindow);
|
||||
_samples.removeWhere((time, _) => time.isBefore(cutoff));
|
||||
}
|
||||
|
||||
/// Estimate current bandwidth in bps
|
||||
int estimateBandwidthBps() {
|
||||
if (_samples.isEmpty) return 0;
|
||||
|
||||
int totalBytes = 0;
|
||||
for (var bytes in _samples.values) {
|
||||
totalBytes += bytes;
|
||||
}
|
||||
|
||||
final timeSpan = DateTime.now()
|
||||
.difference(
|
||||
_samples.keys.reduce((a, b) => a.isBefore(b) ? a : b),
|
||||
)
|
||||
.inMilliseconds;
|
||||
|
||||
if (timeSpan == 0) return 0;
|
||||
|
||||
// bytes per second * 8 = bits per second
|
||||
return ((totalBytes / (timeSpan / 1000)) * 8).toInt();
|
||||
}
|
||||
|
||||
/// Get estimated bandwidth in Mbps
|
||||
double estimateBandwidthMbps() {
|
||||
return estimateBandwidthBps() / 1000000;
|
||||
}
|
||||
|
||||
/// Select best quality level based on bandwidth
|
||||
static QualityLevel selectBestQuality(
|
||||
int bandwidthBps,
|
||||
List<QualityLevel> availableProfiles,
|
||||
) {
|
||||
// Use 75% of detected bandwidth for conservative selection
|
||||
final targetBitrate = (bandwidthBps * 0.75).toInt();
|
||||
|
||||
// Find highest quality that fits our bandwidth
|
||||
var best = availableProfiles[0];
|
||||
for (final profile in availableProfiles) {
|
||||
if (profile.bitrateBps <= targetBitrate) {
|
||||
best = profile;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
||||
/// Master playlist generator for HLS variant streams
|
||||
class HlsMasterPlaylistGenerator {
|
||||
/// Generate M3U8 master playlist with multiple quality variants
|
||||
static String generateMasterPlaylist({
|
||||
required List<QualityLevel> qualityLevels,
|
||||
required String baseUrl,
|
||||
bool includeSubtitles = false,
|
||||
}) {
|
||||
final buffer = StringBuffer();
|
||||
|
||||
// HLS version 3 for compatibility
|
||||
buffer.writeln('#EXTM3U');
|
||||
buffer.writeln('#EXT-X-VERSION:3');
|
||||
buffer.writeln('#EXT-X-TARGET-DURATION:10');
|
||||
buffer.writeln('#EXT-X-MEDIA-SEQUENCE:0');
|
||||
|
||||
// Variant streams (quality levels)
|
||||
for (final quality in qualityLevels) {
|
||||
buffer.writeln('#EXT-X-STREAM-INF:BANDWIDTH=${quality.bitrateBps},'
|
||||
'RESOLUTION=${quality.width}x${quality.height}');
|
||||
buffer
|
||||
.writeln('$baseUrl/variant_${quality.width}x${quality.height}.m3u8');
|
||||
}
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/// Generate variant playlist for specific quality level
|
||||
static String generateVariantPlaylist({
|
||||
required String segmentPrefix,
|
||||
required int totalSegments,
|
||||
required double targetDuration,
|
||||
required bool isFinal,
|
||||
}) {
|
||||
final buffer = StringBuffer();
|
||||
|
||||
buffer.writeln('#EXTM3U');
|
||||
buffer.writeln('#EXT-X-VERSION:3');
|
||||
buffer.writeln('#EXT-X-TARGET-DURATION:${targetDuration.ceil()}');
|
||||
buffer.writeln('#EXT-X-MEDIA-SEQUENCE:0');
|
||||
|
||||
// Add segment entries
|
||||
for (int i = 0; i < totalSegments; i++) {
|
||||
buffer.writeln('#EXTINF:$targetDuration,');
|
||||
buffer.writeln('${segmentPrefix}_$i.ts');
|
||||
}
|
||||
|
||||
if (isFinal) {
|
||||
buffer.writeln('#EXT-X-ENDLIST');
|
||||
}
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/// Quality selector based on network conditions
|
||||
class QualitySelector {
|
||||
final _detector = BandwidthDetector();
|
||||
QualityLevel _currentQuality;
|
||||
final _listeners = <VoidCallback>[];
|
||||
|
||||
QualitySelector({
|
||||
required QualityLevel initialQuality,
|
||||
}) : _currentQuality = initialQuality;
|
||||
|
||||
QualityLevel get currentQuality => _currentQuality;
|
||||
|
||||
/// Record bandwidth and auto-adjust quality
|
||||
void recordBandwidth(int bytesDownloaded) {
|
||||
_detector.recordBytes(bytesDownloaded);
|
||||
|
||||
// Check if we should switch quality
|
||||
_maybeAdjustQuality();
|
||||
}
|
||||
|
||||
/// Manually set quality
|
||||
void setQuality(QualityLevel quality) {
|
||||
if (_currentQuality != quality) {
|
||||
_currentQuality = quality;
|
||||
_notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Force rebuffer wait before switching down
|
||||
void rebufferDetected() {
|
||||
// Switch to lower quality if rebuffering occurs
|
||||
final allProfiles = QualityProfiles.getAllProfiles();
|
||||
final currentIndex = allProfiles.indexOf(_currentQuality);
|
||||
if (currentIndex > 0) {
|
||||
setQuality(allProfiles[currentIndex - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
void _maybeAdjustQuality() {
|
||||
final bandwidthBps = _detector.estimateBandwidthBps();
|
||||
final availableProfiles = QualityProfiles.getBalancedProfiles();
|
||||
|
||||
// Only switch if significantly different from current
|
||||
final overhead = _currentQuality.bitrateBps * 1.2;
|
||||
if (bandwidthBps > overhead ||
|
||||
bandwidthBps < _currentQuality.bitrateBps * 0.5) {
|
||||
final bestQuality =
|
||||
BandwidthDetector.selectBestQuality(bandwidthBps, availableProfiles);
|
||||
setQuality(bestQuality);
|
||||
}
|
||||
}
|
||||
|
||||
void addListener(VoidCallback listener) {
|
||||
_listeners.add(listener);
|
||||
}
|
||||
|
||||
void removeListener(VoidCallback listener) {
|
||||
_listeners.remove(listener);
|
||||
}
|
||||
|
||||
void _notifyListeners() {
|
||||
for (final listener in _listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
double getEstimatedBandwidthMbps() => _detector.estimateBandwidthMbps();
|
||||
}
|
||||
|
||||
// Type alias for void callback
|
||||
typedef VoidCallback = void Function();
|
||||
@@ -1,267 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../core/services/adaptive_bitrate_service.dart';
|
||||
|
||||
/// Video streaming performance metrics
|
||||
class StreamingMetrics {
|
||||
final double averageNetworkBitrate;
|
||||
final double currentNetworkBitrate;
|
||||
final int bufferDurationMs;
|
||||
final int segmentDownloadTimeMs;
|
||||
final int rebufferCount;
|
||||
final DateTime startTime;
|
||||
final DateTime? endTime;
|
||||
|
||||
StreamingMetrics({
|
||||
required this.averageNetworkBitrate,
|
||||
required this.currentNetworkBitrate,
|
||||
required this.bufferDurationMs,
|
||||
required this.segmentDownloadTimeMs,
|
||||
required this.rebufferCount,
|
||||
required this.startTime,
|
||||
this.endTime,
|
||||
});
|
||||
|
||||
double get totalPlaybackSeconds =>
|
||||
(endTime ?? DateTime.now()).difference(startTime).inSeconds.toDouble();
|
||||
|
||||
double get qualityScore {
|
||||
// Score based on metrics
|
||||
var score = 100.0;
|
||||
|
||||
// Penalize for rebuffering
|
||||
score -= rebufferCount * 10;
|
||||
|
||||
// Penalize for low bitrate
|
||||
if (currentNetworkBitrate < 1000000) score -= 20;
|
||||
if (currentNetworkBitrate < 500000) score -= 30;
|
||||
|
||||
// Reward for smooth playback
|
||||
if (rebufferCount == 0) score += 10;
|
||||
|
||||
return (score).clamp(0, 100);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() => '''
|
||||
StreamingMetrics:
|
||||
- Avg Bitrate: ${(averageNetworkBitrate / 1000000).toStringAsFixed(2)} Mbps
|
||||
- Current Bitrate: ${(currentNetworkBitrate / 1000000).toStringAsFixed(2)} Mbps
|
||||
- Buffer: ${bufferDurationMs}ms
|
||||
- Segment DL Time: ${segmentDownloadTimeMs}ms
|
||||
- Rebuffers: $rebufferCount
|
||||
- Quality Score: ${qualityScore.toStringAsFixed(1)}
|
||||
- Duration: $totalPlaybackSeconds seconds
|
||||
''';
|
||||
}
|
||||
|
||||
/// Advanced streaming optimizer
|
||||
class StreamingOptimizer {
|
||||
final QualitySelector qualitySelector;
|
||||
final _metrics = <StreamingMetrics>[];
|
||||
late StreamingMetrics _currentMetrics;
|
||||
final StreamController<StreamingMetrics> _metricsController =
|
||||
StreamController.broadcast();
|
||||
late Timer _metricsTimer;
|
||||
|
||||
final int _segmentStartTime = 0;
|
||||
int _totalBytesDownloaded = 0;
|
||||
int _rebufferCount = 0;
|
||||
int _lastBufferNotificationTime = 0;
|
||||
|
||||
StreamingOptimizer({required this.qualitySelector}) {
|
||||
_initializeMetrics();
|
||||
_startMetricsCollection();
|
||||
}
|
||||
|
||||
void _initializeMetrics() {
|
||||
_currentMetrics = StreamingMetrics(
|
||||
averageNetworkBitrate: 0,
|
||||
currentNetworkBitrate: 0,
|
||||
bufferDurationMs: 0,
|
||||
segmentDownloadTimeMs: 0,
|
||||
rebufferCount: 0,
|
||||
startTime: DateTime.now(),
|
||||
);
|
||||
}
|
||||
|
||||
void _startMetricsCollection() {
|
||||
_metricsTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
|
||||
_updateMetrics();
|
||||
});
|
||||
}
|
||||
|
||||
void _updateMetrics() {
|
||||
final bandwidthBps = qualitySelector.getEstimatedBandwidthMbps() * 1000000;
|
||||
_currentMetrics = StreamingMetrics(
|
||||
averageNetworkBitrate: _totalBytesDownloaded > 0
|
||||
? (_totalBytesDownloaded * 8 / _currentMetrics.totalPlaybackSeconds)
|
||||
: 0,
|
||||
currentNetworkBitrate: bandwidthBps,
|
||||
bufferDurationMs: _currentMetrics.bufferDurationMs,
|
||||
segmentDownloadTimeMs: _currentMetrics.segmentDownloadTimeMs,
|
||||
rebufferCount: _rebufferCount,
|
||||
startTime: _currentMetrics.startTime,
|
||||
);
|
||||
|
||||
_metrics.add(_currentMetrics);
|
||||
_metricsController.add(_currentMetrics);
|
||||
}
|
||||
|
||||
/// Record segment download
|
||||
void recordSegmentDownload(int bytes, Duration downloadTime) {
|
||||
_totalBytesDownloaded += bytes;
|
||||
final downloadMs = downloadTime.inMilliseconds;
|
||||
|
||||
_currentMetrics = _currentMetrics;
|
||||
qualitySelector.recordBandwidth(bytes);
|
||||
}
|
||||
|
||||
/// Handle rebuffer event
|
||||
void rebufferDetected(Duration duration) {
|
||||
_rebufferCount++;
|
||||
_lastBufferNotificationTime = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
_currentMetrics = StreamingMetrics(
|
||||
averageNetworkBitrate: _currentMetrics.averageNetworkBitrate,
|
||||
currentNetworkBitrate: _currentMetrics.currentNetworkBitrate,
|
||||
bufferDurationMs: duration.inMilliseconds,
|
||||
segmentDownloadTimeMs: _currentMetrics.segmentDownloadTimeMs,
|
||||
rebufferCount: _rebufferCount,
|
||||
startTime: _currentMetrics.startTime,
|
||||
);
|
||||
|
||||
// Auto downgrade quality on rebuffer
|
||||
qualitySelector.rebufferDetected();
|
||||
}
|
||||
|
||||
/// Get current streaming metrics
|
||||
StreamingMetrics getMetrics() => _currentMetrics;
|
||||
|
||||
/// Get metrics stream for real-time monitoring
|
||||
Stream<StreamingMetrics> get metricsStream => _metricsController.stream;
|
||||
|
||||
/// Get metrics history
|
||||
List<StreamingMetrics> getMetricsHistory() => List.from(_metrics);
|
||||
|
||||
/// Finalize streaming session
|
||||
void finalize() {
|
||||
_currentMetrics = StreamingMetrics(
|
||||
averageNetworkBitrate: _currentMetrics.averageNetworkBitrate,
|
||||
currentNetworkBitrate: _currentMetrics.currentNetworkBitrate,
|
||||
bufferDurationMs: _currentMetrics.bufferDurationMs,
|
||||
segmentDownloadTimeMs: _currentMetrics.segmentDownloadTimeMs,
|
||||
rebufferCount: _rebufferCount,
|
||||
startTime: _currentMetrics.startTime,
|
||||
endTime: DateTime.now(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Clean up resources
|
||||
void dispose() {
|
||||
_metricsTimer.cancel();
|
||||
_metricsController.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Buffer size calculator for adaptive streaming
|
||||
class BufferCalculator {
|
||||
static const _minBufferMs = 1000; // 1 second
|
||||
static const _targetBufferMs = 8000; // 8 seconds
|
||||
static const _maxBufferMs = 30000; // 30 seconds
|
||||
|
||||
/// Calculate optimal buffer size based on bandwidth
|
||||
static int calculateOptimalBuffer(
|
||||
int estimatedBandwidthBps,
|
||||
int bitrateOfCurrentQuality,
|
||||
) {
|
||||
// Rule: buffer should be able to hold 8 seconds worth of content
|
||||
final neededBytes = (bitrateOfCurrentQuality * _targetBufferMs) ~/ 8000;
|
||||
final availableBytes = (estimatedBandwidthBps * _targetBufferMs) ~/ 8000;
|
||||
|
||||
// If we can't sustain the bitrate + have buffer, reduce target
|
||||
if (availableBytes < neededBytes) {
|
||||
return _minBufferMs;
|
||||
}
|
||||
|
||||
// Normal case
|
||||
return _targetBufferMs;
|
||||
}
|
||||
|
||||
/// Calculate recommended segment duration
|
||||
static Duration calculateSegmentDuration(int estimatedBandwidthBps) {
|
||||
if (estimatedBandwidthBps < 500000) {
|
||||
// Very low bandwidth: shorter segments
|
||||
return const Duration(seconds: 2);
|
||||
} else if (estimatedBandwidthBps < 2000000) {
|
||||
// Low bandwidth
|
||||
return const Duration(seconds: 4);
|
||||
} else {
|
||||
// Good bandwidth
|
||||
return const Duration(seconds: 6);
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate maximum playback quality
|
||||
static QualityLevel selectQualityForBandwidth(
|
||||
int estimatedBandwidthBps,
|
||||
) {
|
||||
final availableProfiles = QualityProfiles.getBalancedProfiles();
|
||||
return BandwidthDetector.selectBestQuality(
|
||||
estimatedBandwidthBps,
|
||||
availableProfiles,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Riverpod providers
|
||||
|
||||
final streamingOptimizerProvider =
|
||||
StateNotifierProvider<StreamingOptimizerNotifier, StreamingMetrics>((ref) {
|
||||
final qualitySelector = ref.watch(qualitySelectorProvider);
|
||||
return StreamingOptimizerNotifier(qualitySelector);
|
||||
});
|
||||
|
||||
final qualitySelectorProvider = Provider<QualitySelector>((ref) {
|
||||
return QualitySelector(initialQuality: QualityProfiles.hd720p);
|
||||
});
|
||||
|
||||
class StreamingOptimizerNotifier extends StateNotifier<StreamingMetrics> {
|
||||
final QualitySelector _qualitySelector;
|
||||
late StreamingOptimizer _optimizer;
|
||||
|
||||
StreamingOptimizerNotifier(this._qualitySelector)
|
||||
: super(
|
||||
StreamingMetrics(
|
||||
averageNetworkBitrate: 0,
|
||||
currentNetworkBitrate: 0,
|
||||
bufferDurationMs: 0,
|
||||
segmentDownloadTimeMs: 0,
|
||||
rebufferCount: 0,
|
||||
startTime: DateTime.now(),
|
||||
),
|
||||
) {
|
||||
_optimizer = StreamingOptimizer(qualitySelector: _qualitySelector);
|
||||
|
||||
// Listen to metrics updates
|
||||
_optimizer.metricsStream.listen((metrics) {
|
||||
state = metrics;
|
||||
});
|
||||
}
|
||||
|
||||
void recordSegmentDownload(int bytes, Duration duration) {
|
||||
_optimizer.recordSegmentDownload(bytes, duration);
|
||||
}
|
||||
|
||||
void rebufferDetected(Duration duration) {
|
||||
_optimizer.rebufferDetected(duration);
|
||||
}
|
||||
|
||||
List<StreamingMetrics> getHistory() => _optimizer.getMetricsHistory();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_optimizer.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user