perf: anti micro-stutter buffer optimizations for live TV

This commit is contained in:
Michael committed 2025-12-16 21:35:47 +01:00
1 parent 4e694a2cc0
commit 02d13404fd
5 files changed
+303 -176

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
/// Platform utilities - conditional export
/// Uses web implementation on web, stub on other platforms
export 'platform_utils_stub.dart'
if (dart.library.html) 'platform_utils_web.dart';
+14
View File
@@ -0,0 +1,14 @@
/// Platform-specific utilities for web
/// This file is used when compiling for web
/// Check if we're running on HTTPS
bool isHttps() {
// Implemented in platform_utils_web.dart
return true;
}
/// Get the current window origin
String getWindowOrigin() {
// Implemented in platform_utils_web.dart
return '';
}
+13
View File
@@ -0,0 +1,13 @@
/// Platform-specific utilities for web
/// This file is used when compiling for web
import 'dart:html' as html;
/// Check if we're running on HTTPS
bool isHttps() {
return html.window.location.protocol == 'https:';
}
/// Get the current window origin
String getWindowOrigin() {
return html.window.location.origin;
}
+28 -16
View File
@@ -4,7 +4,7 @@ import 'package:dio_cache_interceptor_hive_store/dio_cache_interceptor_hive_stor
import '../../../core/models/playlist_config.dart'; import '../../../core/models/playlist_config.dart';
import '../../../core/models/iptv_models.dart'; import '../../../core/models/iptv_models.dart';
import '../models/xtream_models.dart' as xm; import '../models/xtream_models.dart' as xm;
import 'dart:html' as html; import '../../../core/utils/platform_utils.dart' as platform;
/// Xtream Codes API Service /// Xtream Codes API Service
/// ///
@@ -16,10 +16,12 @@ class XtreamService {
PlaylistConfig? _currentPlaylist; PlaylistConfig? _currentPlaylist;
XtreamService() { XtreamService() {
_dio = Dio(BaseOptions( _dio = Dio(
connectTimeout: const Duration(seconds: 15), BaseOptions(
receiveTimeout: const Duration(seconds: 15), connectTimeout: const Duration(seconds: 15),
),); receiveTimeout: const Duration(seconds: 15),
),
);
// Setup caching for API responses // Setup caching for API responses
_cacheOptions = CacheOptions( _cacheOptions = CacheOptions(
@@ -34,14 +36,14 @@ class XtreamService {
/// Check if we're running on HTTPS (production) /// Check if we're running on HTTPS (production)
bool get _isHttps { bool get _isHttps {
return html.window.location.protocol == 'https:'; return platform.isHttps();
} }
/// Wrap URL with proxy if needed (for HTTPS to HTTP bridge) /// Wrap URL with proxy if needed (for HTTPS to HTTP bridge)
String _wrapWithProxy(String url) { String _wrapWithProxy(String url) {
// If we're on HTTPS and the target URL is HTTP, use the proxy // If we're on HTTPS and the target URL is HTTP, use the proxy
if (_isHttps && url.startsWith('http://')) { if (_isHttps && url.startsWith('http://')) {
final baseUrl = html.window.location.origin; final baseUrl = platform.getWindowOrigin();
return '$baseUrl/api/xtream/$url'; return '$baseUrl/api/xtream/$url';
} }
return url; return url;
@@ -60,10 +62,11 @@ class XtreamService {
if (_currentPlaylist == null) throw Exception('No playlist configured'); if (_currentPlaylist == null) throw Exception('No playlist configured');
// Use .ts format for direct MPEG-TS streaming (FFmpeg handles this better) // Use .ts format for direct MPEG-TS streaming (FFmpeg handles this better)
final iptvUrl = '${_currentPlaylist!.dns}/live/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.ts'; final iptvUrl =
'${_currentPlaylist!.dns}/live/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.ts';
// Use FFmpeg transcoding endpoint // Use FFmpeg transcoding endpoint
final baseUrl = html.window.location.origin; final baseUrl = platform.getWindowOrigin();
final encodedUrl = Uri.encodeComponent(iptvUrl); final encodedUrl = Uri.encodeComponent(iptvUrl);
return '$baseUrl/api/stream/$streamId?url=$encodedUrl'; return '$baseUrl/api/stream/$streamId?url=$encodedUrl';
} }
@@ -72,7 +75,8 @@ class XtreamService {
String getVodStreamUrl(String streamId, String containerExtension) { String getVodStreamUrl(String streamId, String containerExtension) {
if (_currentPlaylist == null) throw Exception('No playlist configured'); if (_currentPlaylist == null) throw Exception('No playlist configured');
final url = '${_currentPlaylist!.dns}/movie/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.$containerExtension'; final url =
'${_currentPlaylist!.dns}/movie/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.$containerExtension';
return _wrapWithProxy(url); return _wrapWithProxy(url);
} }
@@ -80,7 +84,8 @@ class XtreamService {
String getSeriesStreamUrl(String streamId, String containerExtension) { String getSeriesStreamUrl(String streamId, String containerExtension) {
if (_currentPlaylist == null) throw Exception('No playlist configured'); if (_currentPlaylist == null) throw Exception('No playlist configured');
final url = '${_currentPlaylist!.dns}/series/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.$containerExtension'; final url =
'${_currentPlaylist!.dns}/series/${_currentPlaylist!.username}/${_currentPlaylist!.password}/$streamId.$containerExtension';
return _wrapWithProxy(url); return _wrapWithProxy(url);
} }
@@ -326,7 +331,8 @@ class XtreamService {
} }
/// Get movies with pagination support /// Get movies with pagination support
Future<List<xm.Movie>> getMoviesPaginated({int offset = 0, int limit = 100}) async { Future<List<xm.Movie>> getMoviesPaginated(
{int offset = 0, int limit = 100}) async {
if (_currentPlaylist == null) throw Exception('No playlist configured'); if (_currentPlaylist == null) throw Exception('No playlist configured');
try { try {
@@ -346,7 +352,9 @@ class XtreamService {
final List<dynamic> allMovies = response.data as List<dynamic>; final List<dynamic> allMovies = response.data as List<dynamic>;
// Apply pagination // Apply pagination
final endIndex = (offset + limit) > allMovies.length ? allMovies.length : offset + limit; final endIndex = (offset + limit) > allMovies.length
? allMovies.length
: offset + limit;
if (offset >= allMovies.length) return []; if (offset >= allMovies.length) return [];
final paginatedMovies = allMovies.sublist(offset, endIndex); final paginatedMovies = allMovies.sublist(offset, endIndex);
@@ -403,7 +411,8 @@ class XtreamService {
} }
/// Get series with pagination support (returns flat list) /// Get series with pagination support (returns flat list)
Future<List<xm.Series>> getSeriesPaginated({int offset = 0, int limit = 100}) async { Future<List<xm.Series>> getSeriesPaginated(
{int offset = 0, int limit = 100}) async {
if (_currentPlaylist == null) throw Exception('No playlist configured'); if (_currentPlaylist == null) throw Exception('No playlist configured');
try { try {
@@ -423,7 +432,9 @@ class XtreamService {
final List<dynamic> allSeries = response.data as List<dynamic>; final List<dynamic> allSeries = response.data as List<dynamic>;
// Apply pagination // Apply pagination
final endIndex = (offset + limit) > allSeries.length ? allSeries.length : offset + limit; final endIndex = (offset + limit) > allSeries.length
? allSeries.length
: offset + limit;
if (offset >= allSeries.length) return []; if (offset >= allSeries.length) return [];
final paginatedSeries = allSeries.sublist(offset, endIndex); final paginatedSeries = allSeries.sublist(offset, endIndex);
@@ -529,7 +540,8 @@ class XtreamService {
return []; return [];
} }
final List<dynamic> epgData = response.data['epg_listings'] as List<dynamic>; final List<dynamic> epgData =
response.data['epg_listings'] as List<dynamic>;
return epgData return epgData
.map((entry) => EpgEntry.fromJson(entry as Map<String, dynamic>)) .map((entry) => EpgEntry.fromJson(entry as Map<String, dynamic>))
.toList(); .toList();
@@ -53,7 +53,8 @@ class NativePlayerScreen extends ConsumerStatefulWidget {
ConsumerState<NativePlayerScreen> createState() => _NativePlayerScreenState(); ConsumerState<NativePlayerScreen> createState() => _NativePlayerScreenState();
} }
class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with WidgetsBindingObserver { class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen>
with WidgetsBindingObserver {
late final Player _player; late final Player _player;
late final VideoController _controller; late final VideoController _controller;
@@ -82,8 +83,6 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
String _currentTime = ''; String _currentTime = '';
bool _hasMarkedAsWatched = false; // Flag to mark watched only once at 80% bool _hasMarkedAsWatched = false; // Flag to mark watched only once at 80%
void _resetControlsTimer() { void _resetControlsTimer() {
_controlsTimer?.cancel(); _controlsTimer?.cancel();
_startClock(); // Ensure clock runs when controls are shown _startClock(); // Ensure clock runs when controls are shown
@@ -133,38 +132,57 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
(_player.platform as dynamic)?.setProperty('hwdec', decoderMode); (_player.platform as dynamic)?.setProperty('hwdec', decoderMode);
debugPrint('MediaKitPlayer: Decoder Mode set to $decoderMode'); debugPrint('MediaKitPlayer: Decoder Mode set to $decoderMode');
// ============ PERFORMANCE 2.0 (LOW MEMORY 1GB PROFILE) ============ // ============ PERFORMANCE 3.0 (ANTI MICRO-COUPURE PROFILE) ============
// Tuned for Low-End Android TV hardware (1GB RAM Sticks) // Tuned to eliminate micro-stuttering during live TV playback
// Goal: Prevent OOM Kills & Crashes // Increased buffers for smoother playback at cost of ~100MB RAM
// 50MB Cache = ~1 min of HD stream. Critical for 1GB RAM. // LARGE Cache for smoother playback (100MB = ~2 min of HD stream)
(_player.platform as dynamic)?.setProperty('cache', 'yes'); (_player.platform as dynamic)?.setProperty('cache', 'yes');
(_player.platform as dynamic)?.setProperty('cache-secs', '60'); // 1 minute cache (_player.platform as dynamic)
(_player.platform as dynamic)?.setProperty('demuxer-max-bytes', '50000000'); // 50MB buffer ?.setProperty('cache-secs', '120'); // 2 minutes cache
(_player.platform as dynamic)?.setProperty('demuxer-max-back-bytes', '10000000'); // 10MB back buffer (_player.platform as dynamic)?.setProperty(
'demuxer-max-bytes', '100000000'); // 100MB buffer (doubled)
(_player.platform as dynamic)
?.setProperty('demuxer-max-back-bytes', '20000000'); // 20MB back buffer
(_player.platform as dynamic)?.setProperty('cache-pause-initial', 'yes'); (_player.platform as dynamic)?.setProperty('cache-pause-initial', 'yes');
(_player.platform as dynamic)?.setProperty('cache-pause-wait', '3'); // Shorter wait to start (_player.platform as dynamic)?.setProperty('cache-pause-wait',
'5'); // Wait 5s before resuming after buffer underrun
// Standard Processing (Hardware handles it) // Audio/Video Sync - critical for smooth playback
(_player.platform as dynamic)?.setProperty('video-sync', 'audio'); (_player.platform as dynamic)
(_player.platform as dynamic)?.setProperty('interpolation', 'no'); // Keep off for safety ?.setProperty('video-sync', 'display-resample'); // Better A/V sync
(_player.platform as dynamic)?.setProperty('audio-buffer', '0.5'); // Standard audio buffer (_player.platform as dynamic)
?.setProperty('interpolation', 'no'); // Keep off for safety
(_player.platform as dynamic)
?.setProperty('audio-buffer', '1.0'); // Larger audio buffer (1 second)
(_player.platform as dynamic)
?.setProperty('audio-samplerate', '48000'); // Standard high quality
// Network resilience // Network resilience - more aggressive settings
(_player.platform as dynamic)?.setProperty('network-timeout', '120'); (_player.platform as dynamic)?.setProperty('network-timeout', '120');
(_player.platform as dynamic)?.setProperty('stream-timeout', '120'); (_player.platform as dynamic)?.setProperty('stream-timeout', '120');
(_player.platform as dynamic)?.setProperty('tls-verify', 'no'); (_player.platform as dynamic)?.setProperty('tls-verify', 'no');
(_player.platform as dynamic)?.setProperty('http-header-fields', 'User-Agent: XtremFlow/1.0'); (_player.platform as dynamic)
?.setProperty('http-header-fields', 'User-Agent: XtremFlow/1.0');
// Live Stream optimizations // Live Stream optimizations - aggressive reconnection
(_player.platform as dynamic)?.setProperty('stream-lavf-o', 'reconnect=1,reconnect_streamed=1,reconnect_on_network_error=1,reconnect_delay_max=5'); (_player.platform as dynamic)?.setProperty('stream-lavf-o',
'reconnect=1,reconnect_streamed=1,reconnect_on_network_error=1,reconnect_delay_max=10,reconnect_on_http_error=4xx,5xx');
(_player.platform as dynamic)?.setProperty('force-seekable', 'yes'); (_player.platform as dynamic)?.setProperty('force-seekable', 'yes');
(_player.platform as dynamic)?.setProperty('demuxer-lavf-o', 'live_start_index=-1'); // Removed large probesize (_player.platform as dynamic)?.setProperty('demuxer-lavf-o',
'live_start_index=-1,analyzeduration=10000000,probesize=5000000');
// Prevent stalls // Prevent stalls with more aggressive read-ahead
(_player.platform as dynamic)?.setProperty('demuxer-readahead-secs', '60'); // Read 60s ahead (_player.platform as dynamic)?.setProperty(
(_player.platform as dynamic)?.setProperty('hr-seek', 'yes'); // High-res seeking 'demuxer-readahead-secs', '120'); // Read 2 min ahead (doubled)
(_player.platform as dynamic)?.setProperty('hr-seek-framedrop', 'yes'); // Drop frames to catch up (_player.platform as dynamic)
?.setProperty('hr-seek', 'yes'); // High-res seeking
(_player.platform as dynamic)
?.setProperty('hr-seek-framedrop', 'yes'); // Drop frames to catch up
// Frame dropping policy - prefer dropping frames over stuttering
(_player.platform as dynamic)?.setProperty('framedrop',
'decoder+vo'); // Allow frame drops at decoder and video output
_controller = VideoController(_player); _controller = VideoController(_player);
@@ -177,7 +195,7 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// This masks initial glitches/re-buffering // This masks initial glitches/re-buffering
Future.delayed(const Duration(seconds: 1), () { Future.delayed(const Duration(seconds: 1), () {
if (mounted && _isPlaying) { if (mounted && _isPlaying) {
setState(() => _isLoading = false); setState(() => _isLoading = false);
} }
}); });
_resetControlsTimer(); // Start auto-hide timer _resetControlsTimer(); // Start auto-hide timer
@@ -211,7 +229,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// Smart Retry for Codec/Decoder errors // Smart Retry for Codec/Decoder errors
// If we haven't tried SW decoding yet, retry with it enabled. // If we haven't tried SW decoding yet, retry with it enabled.
if (!_useSoftwareDecoder) { if (!_useSoftwareDecoder) {
debugPrint('MediaKitPlayer: Error encountered. Auto-retrying with Software Decoding...'); debugPrint(
'MediaKitPlayer: Error encountered. Auto-retrying with Software Decoding...');
setState(() => _useSoftwareDecoder = true); setState(() => _useSoftwareDecoder = true);
// Short delay to allow player cleanup // Short delay to allow player cleanup
@@ -230,7 +249,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// Listen for stream completion (live streams shouldn't complete - means it stopped) // Listen for stream completion (live streams shouldn't complete - means it stopped)
_player.stream.completed.listen((completed) { _player.stream.completed.listen((completed) {
if (completed && mounted && widget.streamType == StreamType.live) { if (completed && mounted && widget.streamType == StreamType.live) {
debugPrint('MediaKitPlayer: Live stream completed unexpectedly, attempting reconnect...'); debugPrint(
'MediaKitPlayer: Live stream completed unexpectedly, attempting reconnect...');
_attemptReconnect(); _attemptReconnect();
} }
}); });
@@ -249,7 +269,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
void _startClock() { void _startClock() {
if (_clockTimer != null && _clockTimer!.isActive) return; if (_clockTimer != null && _clockTimer!.isActive) return;
_updateTime(); _updateTime();
_clockTimer = Timer.periodic(const Duration(seconds: 1), (_) => _updateTime()); _clockTimer =
Timer.periodic(const Duration(seconds: 1), (_) => _updateTime());
} }
void _stopClock() { void _stopClock() {
@@ -261,7 +282,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (mounted) { if (mounted) {
final now = DateTime.now(); final now = DateTime.now();
setState(() { setState(() {
_currentTime = "${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}"; _currentTime =
"${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}";
}); });
} }
} }
@@ -320,7 +342,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
widget.seriesId != null && widget.seriesId != null &&
widget.season != null && widget.season != null &&
widget.episodeNum != null) { widget.episodeNum != null) {
return MobileWatchHistory.episodeKey(widget.seriesId, widget.season!, widget.episodeNum!); return MobileWatchHistory.episodeKey(
widget.seriesId, widget.season!, widget.episodeNum!);
} }
return widget.streamId; return widget.streamId;
} }
@@ -329,11 +352,14 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
void _saveResumePositionOnExit() { void _saveResumePositionOnExit() {
if (widget.streamType == StreamType.live) return; if (widget.streamType == StreamType.live) return;
debugPrint('MediaKitPlayer: Saving position - pos: ${_position.inSeconds}s, dur: ${_duration.inSeconds}s, contentId: $_contentId'); debugPrint(
'MediaKitPlayer: Saving position - pos: ${_position.inSeconds}s, dur: ${_duration.inSeconds}s, contentId: $_contentId');
// If already marked as watched, clear any saved position // If already marked as watched, clear any saved position
if (_hasMarkedAsWatched) { if (_hasMarkedAsWatched) {
ref.read(mobileWatchHistoryProvider.notifier).clearResumePosition(_contentId); ref
.read(mobileWatchHistoryProvider.notifier)
.clearResumePosition(_contentId);
debugPrint('MediaKitPlayer: Already watched, clearing position'); debugPrint('MediaKitPlayer: Already watched, clearing position');
return; return;
} }
@@ -342,17 +368,20 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (_duration.inSeconds > 0) { if (_duration.inSeconds > 0) {
final progress = _position.inSeconds / _duration.inSeconds; final progress = _position.inSeconds / _duration.inSeconds;
if (progress > 0.90) { if (progress > 0.90) {
ref.read(mobileWatchHistoryProvider.notifier).clearResumePosition(_contentId); ref
debugPrint('MediaKitPlayer: Almost finished (${(progress * 100).toStringAsFixed(1)}%), clearing position'); .read(mobileWatchHistoryProvider.notifier)
.clearResumePosition(_contentId);
debugPrint(
'MediaKitPlayer: Almost finished (${(progress * 100).toStringAsFixed(1)}%), clearing position');
return; return;
} }
} }
// Save position (saveResumePosition handles the 30s minimum check) // Save position (saveResumePosition handles the 30s minimum check)
ref.read(mobileWatchHistoryProvider.notifier).saveResumePosition( ref.read(mobileWatchHistoryProvider.notifier).saveResumePosition(
_contentId, _contentId,
_position.inSeconds, _position.inSeconds,
); );
} }
/// Seek to resume position with retry logic /// Seek to resume position with retry logic
@@ -363,7 +392,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (!mounted) return; if (!mounted) return;
if (_isPlaying && _duration.inSeconds > 0) { if (_isPlaying && _duration.inSeconds > 0) {
debugPrint('MediaKitPlayer: Seeking to resume position ${positionSeconds}s (attempt $attempt)'); debugPrint(
'MediaKitPlayer: Seeking to resume position ${positionSeconds}s (attempt $attempt)');
_player.seek(Duration(seconds: positionSeconds)); _player.seek(Duration(seconds: positionSeconds));
// Show visual notification // Show visual notification
@@ -371,13 +401,15 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
final seconds = positionSeconds % 60; final seconds = positionSeconds % 60;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
content: Text('Reprise à ${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'), content: Text(
'Reprise à ${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}'),
duration: const Duration(seconds: 2), duration: const Duration(seconds: 2),
backgroundColor: Colors.green.shade700, backgroundColor: Colors.green.shade700,
), ),
); );
} else { } else {
debugPrint('MediaKitPlayer: Player not ready, retrying resume seek (attempt $attempt)'); debugPrint(
'MediaKitPlayer: Player not ready, retrying resume seek (attempt $attempt)');
_seekToResume(positionSeconds, attempt + 1); _seekToResume(positionSeconds, attempt + 1);
} }
}); });
@@ -395,7 +427,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
} }
_reconnectAttempts++; _reconnectAttempts++;
debugPrint('MediaKitPlayer: Reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts'); debugPrint(
'MediaKitPlayer: Reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts');
// Delay before reconnect to avoid hammering the server // Delay before reconnect to avoid hammering the server
Future.delayed(Duration(seconds: 2 * _reconnectAttempts), () { Future.delayed(Duration(seconds: 2 * _reconnectAttempts), () {
@@ -420,18 +453,22 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (widget.streamType == StreamType.vod) { if (widget.streamType == StreamType.vod) {
// Mark movie as watched // Mark movie as watched
ref.read(mobileWatchHistoryProvider.notifier).markMovieWatched(widget.streamId); ref
.read(mobileWatchHistoryProvider.notifier)
.markMovieWatched(widget.streamId);
} else if (widget.streamType == StreamType.series && } else if (widget.streamType == StreamType.series &&
widget.seriesId != null && widget.seriesId != null &&
widget.season != null && widget.season != null &&
widget.episodeNum != null) { widget.episodeNum != null) {
// Mark episode as watched // Mark episode as watched
final episodeKey = MobileWatchHistory.episodeKey( final episodeKey = MobileWatchHistory.episodeKey(
widget.seriesId, widget.seriesId,
widget.season!, widget.season!,
widget.episodeNum!, widget.episodeNum!,
); );
ref.read(mobileWatchHistoryProvider.notifier).markEpisodeWatched(episodeKey); ref
.read(mobileWatchHistoryProvider.notifier)
.markEpisodeWatched(episodeKey);
} }
} }
} }
@@ -447,7 +484,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// If we're supposedly playing but position hasn't changed, reconnect // If we're supposedly playing but position hasn't changed, reconnect
if (!_isPlaying && !_isLoading && _errorMessage == null) { if (!_isPlaying && !_isLoading && _errorMessage == null) {
debugPrint('MediaKitPlayer: Watchdog detected stalled stream, reconnecting...'); debugPrint(
'MediaKitPlayer: Watchdog detected stalled stream, reconnecting...');
_attemptReconnect(); _attemptReconnect();
} }
}); });
@@ -456,7 +494,6 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// Update build method to show clock in top bar // Update build method to show clock in top bar
// ... // ...
Future<void> _initializeServiceAndPlayer() async { Future<void> _initializeServiceAndPlayer() async {
try { try {
final dir = await getApplicationDocumentsDirectory(); final dir = await getApplicationDocumentsDirectory();
@@ -489,9 +526,10 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
}); });
// Determine effective Stream ID // Determine effective Stream ID
final currentStreamId = widget.channels != null && widget.channels!.isNotEmpty final currentStreamId =
? widget.channels![_currentIndex].streamId widget.channels != null && widget.channels!.isNotEmpty
: widget.streamId; ? widget.channels![_currentIndex].streamId
: widget.streamId;
// Load EPG if Live TV // Load EPG if Live TV
if (widget.streamType == StreamType.live) { if (widget.streamType == StreamType.live) {
@@ -505,9 +543,11 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (widget.streamType == StreamType.live) { if (widget.streamType == StreamType.live) {
streamUrl = _xtreamService!.getLiveStreamUrl(currentStreamId); streamUrl = _xtreamService!.getLiveStreamUrl(currentStreamId);
} else if (widget.streamType == StreamType.vod) { } else if (widget.streamType == StreamType.vod) {
streamUrl = _xtreamService!.getVodStreamUrl(currentStreamId, widget.containerExtension ?? 'mp4'); streamUrl = _xtreamService!.getVodStreamUrl(
currentStreamId, widget.containerExtension ?? 'mp4');
} else { } else {
streamUrl = _xtreamService!.getSeriesStreamUrl(currentStreamId, widget.containerExtension ?? 'mp4'); streamUrl = _xtreamService!.getSeriesStreamUrl(
currentStreamId, widget.containerExtension ?? 'mp4');
} }
debugPrint('MediaKitPlayer: Loading stream: $streamUrl'); debugPrint('MediaKitPlayer: Loading stream: $streamUrl');
@@ -516,9 +556,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// If we are in fallback mode, force software ('no') // If we are in fallback mode, force software ('no')
String hwdecValue; String hwdecValue;
if (_useSoftwareDecoder) { if (_useSoftwareDecoder) {
hwdecValue = 'no'; hwdecValue = 'no';
} else { } else {
hwdecValue = ref.read(mobileSettingsProvider).decoderMode; hwdecValue = ref.read(mobileSettingsProvider).decoderMode;
} }
(_player.platform as dynamic)?.setProperty('hwdec', hwdecValue); (_player.platform as dynamic)?.setProperty('hwdec', hwdecValue);
@@ -539,8 +579,10 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// Resume from saved position (VOD/Series only) // Resume from saved position (VOD/Series only)
if (widget.streamType != StreamType.live) { if (widget.streamType != StreamType.live) {
final resumePos = ref.read(mobileWatchHistoryProvider).getResumePosition(_contentId); final resumePos =
debugPrint('MediaKitPlayer: Resume check - contentId: $_contentId, resumePos: $resumePos'); ref.read(mobileWatchHistoryProvider).getResumePosition(_contentId);
debugPrint(
'MediaKitPlayer: Resume check - contentId: $_contentId, resumePos: $resumePos');
if (resumePos > 30) { if (resumePos > 30) {
_seekToResume(resumePos); _seekToResume(resumePos);
} }
@@ -587,7 +629,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
void _playPrevious() { void _playPrevious() {
if (widget.channels == null || widget.channels!.isEmpty) return; if (widget.channels == null || widget.channels!.isEmpty) return;
final prevIndex = (_currentIndex - 1 + widget.channels!.length) % widget.channels!.length; final prevIndex =
(_currentIndex - 1 + widget.channels!.length) % widget.channels!.length;
_switchChannel(prevIndex); _switchChannel(prevIndex);
} }
@@ -648,9 +691,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// We'll add a 'Debug' button in the settings or just map Key '0' if remote has it. // We'll add a 'Debug' button in the settings or just map Key '0' if remote has it.
// Debug Toggle: Long Press Key 'D' or 0 (if mapped) // Debug Toggle: Long Press Key 'D' or 0 (if mapped)
if (key == LogicalKeyboardKey.digit0) { if (key == LogicalKeyboardKey.digit0) {
final current = ref.read(mobileSettingsProvider).showDebugStats; final current = ref.read(mobileSettingsProvider).showDebugStats;
ref.read(mobileSettingsProvider.notifier).toggleShowDebugStats(!current); ref.read(mobileSettingsProvider.notifier).toggleShowDebugStats(!current);
return true; return true;
} }
// Left Arrow - Seek back 10 seconds // Left Arrow - Seek back 10 seconds
@@ -696,8 +739,7 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
} }
// Escape / Back - Exit player // Escape / Back - Exit player
if (key == LogicalKeyboardKey.escape || if (key == LogicalKeyboardKey.escape || key == LogicalKeyboardKey.goBack) {
key == LogicalKeyboardKey.goBack) {
// If controls are visible, close them first // If controls are visible, close them first
if (_showControls) { if (_showControls) {
setState(() => _showControls = false); setState(() => _showControls = false);
@@ -710,10 +752,6 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
return false; return false;
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final title = widget.channels != null && widget.channels!.isNotEmpty final title = widget.channels != null && widget.channels!.isNotEmpty
@@ -740,13 +778,13 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
), ),
), ),
// Loading Overlay (Stays on top until smooth playback starts) // Loading Overlay (Stays on top until smooth playback starts)
// We moved _buildLoadingView out of the if/else chain above to overlay it // We moved _buildLoadingView out of the if/else chain above to overlay it
if (_isLoading && _errorMessage == null) if (_isLoading && _errorMessage == null)
Container( Container(
color: Colors.black, color: Colors.black,
child: _buildLoadingView(), child: _buildLoadingView(),
), ),
// Custom controls overlay // Custom controls overlay
if (_showControls && _errorMessage == null && !_isLoading) if (_showControls && _errorMessage == null && !_isLoading)
@@ -760,34 +798,43 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
right: 0, right: 0,
child: SafeArea( child: SafeArea(
child: Container( child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: const BoxDecoration( decoration: const BoxDecoration(
color: Colors.black54, // Flat color instead of Gradient for performance color: Colors
.black54, // Flat color instead of Gradient for performance
), ),
child: Row( child: Row(
children: [ children: [
// Main Back Button // Main Back Button
// Main Back Button // Main Back Button
TVFocusable( TVFocusable(
focusNode: _backFocusNode, focusNode: _backFocusNode,
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
onFocus: _resetControlsTimer, onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50), borderRadius: BorderRadius.circular(50),
child: IconButton( child: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white), icon: const Icon(Icons.arrow_back,
color: Colors.white),
onPressed: () => Navigator.pop(context), onPressed: () => Navigator.pop(context),
), ),
), ),
// Hidden Debug Trigger (Invisible InkWell next to back button) // Hidden Debug Trigger (Invisible InkWell next to back button)
InkWell( InkWell(
onLongPress: () { onLongPress: () {
final current = ref.read(mobileSettingsProvider).showDebugStats; final current =
ref.read(mobileSettingsProvider.notifier).toggleShowDebugStats(!current); ref.read(mobileSettingsProvider).showDebugStats;
ScaffoldMessenger.of(context).showSnackBar( ref
SnackBar(content: Text('Debug Mode: ${!current ? "ON" : "OFF"}'), duration: const Duration(seconds: 1)), .read(mobileSettingsProvider.notifier)
); .toggleShowDebugStats(!current);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Debug Mode: ${!current ? "ON" : "OFF"}'),
duration: const Duration(seconds: 1)),
);
}, },
child: const SizedBox(width: 20, height: 40), child: const SizedBox(width: 20, height: 40),
), ),
Expanded( Expanded(
child: Column( child: Column(
@@ -824,19 +871,18 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
), ),
), ),
// Stats Overlay (Top Left) - Isolated to prevent main rebuilds // Stats Overlay (Top Left) - Isolated to prevent main rebuilds
Positioned( Positioned(
top: 80, top: 80,
left: 16, left: 16,
child: StatsOverlayWidget(player: _player), child: StatsOverlayWidget(player: _player),
), ),
], ],
), ),
), ),
); );
} }
String _formatDuration(Duration duration) { String _formatDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, '0'); String twoDigits(int n) => n.toString().padLeft(2, '0');
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60)); String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
@@ -859,14 +905,17 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
// Prev Channel / Replay 10s // Prev Channel / Replay 10s
if (widget.streamType == StreamType.live && widget.channels != null && widget.channels!.isNotEmpty) if (widget.streamType == StreamType.live &&
widget.channels != null &&
widget.channels!.isNotEmpty)
TVFocusable( TVFocusable(
focusNode: _prevFocusNode, focusNode: _prevFocusNode,
onPressed: _playPrevious, onPressed: _playPrevious,
onFocus: _resetControlsTimer, onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50), borderRadius: BorderRadius.circular(50),
child: IconButton( child: IconButton(
icon: const Icon(Icons.skip_previous, color: Colors.white, size: 48), icon: const Icon(Icons.skip_previous,
color: Colors.white, size: 48),
onPressed: _playPrevious, onPressed: _playPrevious,
), ),
) )
@@ -881,7 +930,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
onFocus: _resetControlsTimer, onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50), borderRadius: BorderRadius.circular(50),
child: IconButton( child: IconButton(
icon: const Icon(Icons.replay_10, color: Colors.white, size: 48), icon: const Icon(Icons.replay_10,
color: Colors.white, size: 48),
onPressed: () async { onPressed: () async {
final pos = await _player.stream.position.first; final pos = await _player.stream.position.first;
_player.seek(pos - const Duration(seconds: 5)); _player.seek(pos - const Duration(seconds: 5));
@@ -901,7 +951,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
child: IconButton( child: IconButton(
iconSize: 72, iconSize: 72,
icon: Icon( icon: Icon(
_isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled, _isPlaying
? Icons.pause_circle_filled
: Icons.play_circle_filled,
color: Colors.white, color: Colors.white,
), ),
onPressed: _togglePlayPause, onPressed: _togglePlayPause,
@@ -911,14 +963,17 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
const SizedBox(width: 32), const SizedBox(width: 32),
// Next Channel / Forward 10s // Next Channel / Forward 10s
if (widget.streamType == StreamType.live && widget.channels != null && widget.channels!.isNotEmpty) if (widget.streamType == StreamType.live &&
widget.channels != null &&
widget.channels!.isNotEmpty)
TVFocusable( TVFocusable(
focusNode: _nextFocusNode, focusNode: _nextFocusNode,
onPressed: _playNext, onPressed: _playNext,
onFocus: _resetControlsTimer, onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50), borderRadius: BorderRadius.circular(50),
child: IconButton( child: IconButton(
icon: const Icon(Icons.skip_next, color: Colors.white, size: 48), icon: const Icon(Icons.skip_next,
color: Colors.white, size: 48),
onPressed: _playNext, onPressed: _playNext,
), ),
) )
@@ -933,7 +988,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
onFocus: _resetControlsTimer, onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50), borderRadius: BorderRadius.circular(50),
child: IconButton( child: IconButton(
icon: const Icon(Icons.forward_10, color: Colors.white, size: 48), icon: const Icon(Icons.forward_10,
color: Colors.white, size: 48),
onPressed: () async { onPressed: () async {
final pos = await _player.stream.position.first; final pos = await _player.stream.position.first;
_player.seek(pos + const Duration(seconds: 5)); _player.seek(pos + const Duration(seconds: 5));
@@ -945,7 +1001,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
), ),
// EPG Box (Bottom Left) + LIVE Badge // EPG Box (Bottom Left) + LIVE Badge
if (widget.streamType == StreamType.live && _epg != null && _epg!.nowPlaying != null) if (widget.streamType == StreamType.live &&
_epg != null &&
_epg!.nowPlaying != null)
Positioned( Positioned(
bottom: 80, // Above progress/bottom bar bottom: 80, // Above progress/bottom bar
left: 24, left: 24,
@@ -962,42 +1020,52 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
border: Border.all(color: Colors.white24), border: Border.all(color: Colors.white24),
), ),
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Text( Text(
_epg!.nowPlaying!, _epg!.nowPlaying!,
style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold), style: const TextStyle(
maxLines: 2, color: Colors.white,
overflow: TextOverflow.ellipsis, fontSize: 16,
), fontWeight: FontWeight.bold),
if (_epg!.nextPlaying != null) maxLines: 2,
Padding( overflow: TextOverflow.ellipsis,
padding: const EdgeInsets.only(top: 4), ),
child: Text( if (_epg!.nextPlaying != null)
"A suivre: ${_epg!.nextPlaying}", Padding(
style: const TextStyle(color: Colors.white70, fontSize: 14), padding: const EdgeInsets.only(top: 4),
maxLines: 1, child: Text(
overflow: TextOverflow.ellipsis, "A suivre: ${_epg!.nextPlaying}",
), style: const TextStyle(
), color: Colors.white70,
], fontSize: 14),
), maxLines: 1,
), overflow: TextOverflow.ellipsis,
// LIVE Badge inside the box, right side ),
Container( ),
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), ],
),
),
// LIVE Badge inside the box, right side
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 4),
margin: const EdgeInsets.only(left: 8), margin: const EdgeInsets.only(left: 8),
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.red, color: Colors.red,
borderRadius: BorderRadius.circular(4), borderRadius: BorderRadius.circular(4),
), ),
child: const Text('LIVE', style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold, fontSize: 12)), child: const Text('LIVE',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12)),
), ),
], ],
), ),
), ),
), ),
@@ -1027,20 +1095,26 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
children: [ children: [
Text( Text(
_formatDuration(_position), _formatDuration(_position),
style: const TextStyle(color: Colors.white, fontSize: 14), style: const TextStyle(
color: Colors.white, fontSize: 14),
), ),
Expanded( Expanded(
child: Slider( child: Slider(
value: _position.inSeconds.toDouble().clamp(0, _duration.inSeconds.toDouble()), value: _position.inSeconds
.toDouble()
.clamp(0, _duration.inSeconds.toDouble()),
min: 0, min: 0,
max: _duration.inSeconds.toDouble(), max: _duration.inSeconds.toDouble(),
// Add divisions for precise seeking (1 step = 10 seconds) // Add divisions for precise seeking (1 step = 10 seconds)
divisions: _duration.inSeconds > 0 ? (_duration.inSeconds / 10).ceil() : null, divisions: _duration.inSeconds > 0
? (_duration.inSeconds / 10).ceil()
: null,
activeColor: AppColors.primary, activeColor: AppColors.primary,
inactiveColor: Colors.white24, inactiveColor: Colors.white24,
onChangeStart: (_) => _isSeeking = true, onChangeStart: (_) => _isSeeking = true,
onChangeEnd: (value) async { onChangeEnd: (value) async {
await _player.seek(Duration(seconds: value.toInt())); await _player
.seek(Duration(seconds: value.toInt()));
_isSeeking = false; _isSeeking = false;
}, },
onChanged: (value) { onChanged: (value) {
@@ -1052,7 +1126,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
), ),
Text( Text(
_formatDuration(_duration), _formatDuration(_duration),
style: const TextStyle(color: Colors.white, fontSize: 14), style: const TextStyle(
color: Colors.white, fontSize: 14),
), ),
], ],
) )
@@ -1062,18 +1137,23 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.end, mainAxisAlignment: MainAxisAlignment.end,
children: [ children: [
if (widget.streamType == StreamType.live && settings.showClock) if (widget.streamType == StreamType.live &&
// Clock settings.showClock)
Container( // Clock
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), Container(
margin: const EdgeInsets.only(right: 12), padding: const EdgeInsets.symmetric(
decoration: BoxDecoration( horizontal: 12, vertical: 6),
color: Colors.black54, margin: const EdgeInsets.only(right: 12),
borderRadius: BorderRadius.circular(4), decoration: BoxDecoration(
), color: Colors.black54,
child: Text(_currentTime, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), borderRadius: BorderRadius.circular(4),
), ),
// LIVE Badge removed from here child: Text(_currentTime,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold)),
),
// LIVE Badge removed from here
], ],
), ),
), ),
@@ -1177,12 +1257,12 @@ class _StatsOverlayWidgetState extends ConsumerState<StatsOverlayWidget> {
// This reduces UI thread load significantly on low-end devices // This reduces UI thread load significantly on low-end devices
_updateTimer = Timer.periodic(const Duration(milliseconds: 1000), (_) { _updateTimer = Timer.periodic(const Duration(milliseconds: 1000), (_) {
if (mounted) { if (mounted) {
setState(() { setState(() {
_buffer = widget.player.state.buffer; _buffer = widget.player.state.buffer;
// Accessing nested prop safely just in case // Accessing nested prop safely just in case
final track = widget.player.state.track.video; final track = widget.player.state.track.video;
_decoder = track.decoder ?? 'Auto'; _decoder = track.decoder ?? 'Auto';
}); });
} }
}); });
} }
@@ -1195,7 +1275,8 @@ class _StatsOverlayWidgetState extends ConsumerState<StatsOverlayWidget> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (!ref.watch(mobileSettingsProvider).showDebugStats) return const SizedBox.shrink(); if (!ref.watch(mobileSettingsProvider).showDebugStats)
return const SizedBox.shrink();
return Container( return Container(
padding: const EdgeInsets.all(8), padding: const EdgeInsets.all(8),
@@ -1209,12 +1290,15 @@ class _StatsOverlayWidgetState extends ConsumerState<StatsOverlayWidget> {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
const Text('STATS FOR NERDS 🤓', const Text('STATS FOR NERDS 🤓',
style: TextStyle(color: Colors.green, fontWeight: FontWeight.bold, fontSize: 12)), style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 12)),
const SizedBox(height: 4), const SizedBox(height: 4),
Text('Buffer: ${_buffer.inSeconds}s', Text('Buffer: ${_buffer.inSeconds}s',
style: const TextStyle(color: Colors.white, fontSize: 12)), style: const TextStyle(color: Colors.white, fontSize: 12)),
Text('Decoder: $_decoder', Text('Decoder: $_decoder',
style: const TextStyle(color: Colors.white, fontSize: 12)), style: const TextStyle(color: Colors.white, fontSize: 12)),
], ],
), ),
); );