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
+223 -96

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;
}
+26 -14
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/iptv_models.dart';
import '../models/xtream_models.dart' as xm;
import 'dart:html' as html;
import '../../../core/utils/platform_utils.dart' as platform;
/// Xtream Codes API Service
///
@@ -16,10 +16,12 @@ class XtreamService {
PlaylistConfig? _currentPlaylist;
XtreamService() {
_dio = Dio(BaseOptions(
_dio = Dio(
BaseOptions(
connectTimeout: const Duration(seconds: 15),
receiveTimeout: const Duration(seconds: 15),
),);
),
);
// Setup caching for API responses
_cacheOptions = CacheOptions(
@@ -34,14 +36,14 @@ class XtreamService {
/// Check if we're running on HTTPS (production)
bool get _isHttps {
return html.window.location.protocol == 'https:';
return platform.isHttps();
}
/// Wrap URL with proxy if needed (for HTTPS to HTTP bridge)
String _wrapWithProxy(String url) {
// If we're on HTTPS and the target URL is HTTP, use the proxy
if (_isHttps && url.startsWith('http://')) {
final baseUrl = html.window.location.origin;
final baseUrl = platform.getWindowOrigin();
return '$baseUrl/api/xtream/$url';
}
return url;
@@ -60,10 +62,11 @@ class XtreamService {
if (_currentPlaylist == null) throw Exception('No playlist configured');
// 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
final baseUrl = html.window.location.origin;
final baseUrl = platform.getWindowOrigin();
final encodedUrl = Uri.encodeComponent(iptvUrl);
return '$baseUrl/api/stream/$streamId?url=$encodedUrl';
}
@@ -72,7 +75,8 @@ class XtreamService {
String getVodStreamUrl(String streamId, String containerExtension) {
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);
}
@@ -80,7 +84,8 @@ class XtreamService {
String getSeriesStreamUrl(String streamId, String containerExtension) {
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);
}
@@ -326,7 +331,8 @@ class XtreamService {
}
/// 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');
try {
@@ -346,7 +352,9 @@ class XtreamService {
final List<dynamic> allMovies = response.data as List<dynamic>;
// 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 [];
final paginatedMovies = allMovies.sublist(offset, endIndex);
@@ -403,7 +411,8 @@ class XtreamService {
}
/// 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');
try {
@@ -423,7 +432,9 @@ class XtreamService {
final List<dynamic> allSeries = response.data as List<dynamic>;
// 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 [];
final paginatedSeries = allSeries.sublist(offset, endIndex);
@@ -529,7 +540,8 @@ class XtreamService {
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
.map((entry) => EpgEntry.fromJson(entry as Map<String, dynamic>))
.toList();
@@ -53,7 +53,8 @@ class NativePlayerScreen extends ConsumerStatefulWidget {
ConsumerState<NativePlayerScreen> createState() => _NativePlayerScreenState();
}
class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with WidgetsBindingObserver {
class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen>
with WidgetsBindingObserver {
late final Player _player;
late final VideoController _controller;
@@ -82,8 +83,6 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
String _currentTime = '';
bool _hasMarkedAsWatched = false; // Flag to mark watched only once at 80%
void _resetControlsTimer() {
_controlsTimer?.cancel();
_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);
debugPrint('MediaKitPlayer: Decoder Mode set to $decoderMode');
// ============ PERFORMANCE 2.0 (LOW MEMORY 1GB PROFILE) ============
// Tuned for Low-End Android TV hardware (1GB RAM Sticks)
// Goal: Prevent OOM Kills & Crashes
// ============ PERFORMANCE 3.0 (ANTI MICRO-COUPURE PROFILE) ============
// Tuned to eliminate micro-stuttering during live TV playback
// 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-secs', '60'); // 1 minute cache
(_player.platform as dynamic)?.setProperty('demuxer-max-bytes', '50000000'); // 50MB buffer
(_player.platform as dynamic)?.setProperty('demuxer-max-back-bytes', '10000000'); // 10MB back buffer
(_player.platform as dynamic)
?.setProperty('cache-secs', '120'); // 2 minutes cache
(_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-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)
(_player.platform as dynamic)?.setProperty('video-sync', 'audio');
(_player.platform as dynamic)?.setProperty('interpolation', 'no'); // Keep off for safety
(_player.platform as dynamic)?.setProperty('audio-buffer', '0.5'); // Standard audio buffer
// Audio/Video Sync - critical for smooth playback
(_player.platform as dynamic)
?.setProperty('video-sync', 'display-resample'); // Better A/V sync
(_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('stream-timeout', '120');
(_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
(_player.platform as dynamic)?.setProperty('stream-lavf-o', 'reconnect=1,reconnect_streamed=1,reconnect_on_network_error=1,reconnect_delay_max=5');
// 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=10,reconnect_on_http_error=4xx,5xx');
(_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
(_player.platform as dynamic)?.setProperty('demuxer-readahead-secs', '60'); // Read 60s ahead
(_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
// Prevent stalls with more aggressive read-ahead
(_player.platform as dynamic)?.setProperty(
'demuxer-readahead-secs', '120'); // Read 2 min ahead (doubled)
(_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);
@@ -211,7 +229,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// Smart Retry for Codec/Decoder errors
// If we haven't tried SW decoding yet, retry with it enabled.
if (!_useSoftwareDecoder) {
debugPrint('MediaKitPlayer: Error encountered. Auto-retrying with Software Decoding...');
debugPrint(
'MediaKitPlayer: Error encountered. Auto-retrying with Software Decoding...');
setState(() => _useSoftwareDecoder = true);
// 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)
_player.stream.completed.listen((completed) {
if (completed && mounted && widget.streamType == StreamType.live) {
debugPrint('MediaKitPlayer: Live stream completed unexpectedly, attempting reconnect...');
debugPrint(
'MediaKitPlayer: Live stream completed unexpectedly, attempting reconnect...');
_attemptReconnect();
}
});
@@ -249,7 +269,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
void _startClock() {
if (_clockTimer != null && _clockTimer!.isActive) return;
_updateTime();
_clockTimer = Timer.periodic(const Duration(seconds: 1), (_) => _updateTime());
_clockTimer =
Timer.periodic(const Duration(seconds: 1), (_) => _updateTime());
}
void _stopClock() {
@@ -261,7 +282,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (mounted) {
final now = DateTime.now();
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.season != 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;
}
@@ -329,11 +352,14 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
void _saveResumePositionOnExit() {
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 (_hasMarkedAsWatched) {
ref.read(mobileWatchHistoryProvider.notifier).clearResumePosition(_contentId);
ref
.read(mobileWatchHistoryProvider.notifier)
.clearResumePosition(_contentId);
debugPrint('MediaKitPlayer: Already watched, clearing position');
return;
}
@@ -342,8 +368,11 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (_duration.inSeconds > 0) {
final progress = _position.inSeconds / _duration.inSeconds;
if (progress > 0.90) {
ref.read(mobileWatchHistoryProvider.notifier).clearResumePosition(_contentId);
debugPrint('MediaKitPlayer: Almost finished (${(progress * 100).toStringAsFixed(1)}%), clearing position');
ref
.read(mobileWatchHistoryProvider.notifier)
.clearResumePosition(_contentId);
debugPrint(
'MediaKitPlayer: Almost finished (${(progress * 100).toStringAsFixed(1)}%), clearing position');
return;
}
}
@@ -363,7 +392,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (!mounted) return;
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));
// Show visual notification
@@ -371,13 +401,15 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
final seconds = positionSeconds % 60;
ScaffoldMessenger.of(context).showSnackBar(
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),
backgroundColor: Colors.green.shade700,
),
);
} 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);
}
});
@@ -395,7 +427,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
}
_reconnectAttempts++;
debugPrint('MediaKitPlayer: Reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts');
debugPrint(
'MediaKitPlayer: Reconnect attempt $_reconnectAttempts/$_maxReconnectAttempts');
// Delay before reconnect to avoid hammering the server
Future.delayed(Duration(seconds: 2 * _reconnectAttempts), () {
@@ -420,7 +453,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (widget.streamType == StreamType.vod) {
// Mark movie as watched
ref.read(mobileWatchHistoryProvider.notifier).markMovieWatched(widget.streamId);
ref
.read(mobileWatchHistoryProvider.notifier)
.markMovieWatched(widget.streamId);
} else if (widget.streamType == StreamType.series &&
widget.seriesId != null &&
widget.season != null &&
@@ -431,7 +466,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
widget.season!,
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 (!_isPlaying && !_isLoading && _errorMessage == null) {
debugPrint('MediaKitPlayer: Watchdog detected stalled stream, reconnecting...');
debugPrint(
'MediaKitPlayer: Watchdog detected stalled stream, reconnecting...');
_attemptReconnect();
}
});
@@ -456,7 +494,6 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// Update build method to show clock in top bar
// ...
Future<void> _initializeServiceAndPlayer() async {
try {
final dir = await getApplicationDocumentsDirectory();
@@ -489,7 +526,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
});
// Determine effective Stream ID
final currentStreamId = widget.channels != null && widget.channels!.isNotEmpty
final currentStreamId =
widget.channels != null && widget.channels!.isNotEmpty
? widget.channels![_currentIndex].streamId
: widget.streamId;
@@ -505,9 +543,11 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
if (widget.streamType == StreamType.live) {
streamUrl = _xtreamService!.getLiveStreamUrl(currentStreamId);
} else if (widget.streamType == StreamType.vod) {
streamUrl = _xtreamService!.getVodStreamUrl(currentStreamId, widget.containerExtension ?? 'mp4');
streamUrl = _xtreamService!.getVodStreamUrl(
currentStreamId, widget.containerExtension ?? 'mp4');
} else {
streamUrl = _xtreamService!.getSeriesStreamUrl(currentStreamId, widget.containerExtension ?? 'mp4');
streamUrl = _xtreamService!.getSeriesStreamUrl(
currentStreamId, widget.containerExtension ?? 'mp4');
}
debugPrint('MediaKitPlayer: Loading stream: $streamUrl');
@@ -539,8 +579,10 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
// Resume from saved position (VOD/Series only)
if (widget.streamType != StreamType.live) {
final resumePos = ref.read(mobileWatchHistoryProvider).getResumePosition(_contentId);
debugPrint('MediaKitPlayer: Resume check - contentId: $_contentId, resumePos: $resumePos');
final resumePos =
ref.read(mobileWatchHistoryProvider).getResumePosition(_contentId);
debugPrint(
'MediaKitPlayer: Resume check - contentId: $_contentId, resumePos: $resumePos');
if (resumePos > 30) {
_seekToResume(resumePos);
}
@@ -587,7 +629,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
void _playPrevious() {
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);
}
@@ -696,8 +739,7 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
}
// Escape / Back - Exit player
if (key == LogicalKeyboardKey.escape ||
key == LogicalKeyboardKey.goBack) {
if (key == LogicalKeyboardKey.escape || key == LogicalKeyboardKey.goBack) {
// If controls are visible, close them first
if (_showControls) {
setState(() => _showControls = false);
@@ -710,10 +752,6 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
return false;
}
@override
Widget build(BuildContext context) {
final title = widget.channels != null && widget.channels!.isNotEmpty
@@ -760,9 +798,11 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
right: 0,
child: SafeArea(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
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(
children: [
@@ -774,17 +814,24 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50),
child: IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
icon: const Icon(Icons.arrow_back,
color: Colors.white),
onPressed: () => Navigator.pop(context),
),
),
// Hidden Debug Trigger (Invisible InkWell next to back button)
InkWell(
onLongPress: () {
final current = ref.read(mobileSettingsProvider).showDebugStats;
ref.read(mobileSettingsProvider.notifier).toggleShowDebugStats(!current);
final current =
ref.read(mobileSettingsProvider).showDebugStats;
ref
.read(mobileSettingsProvider.notifier)
.toggleShowDebugStats(!current);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('Debug Mode: ${!current ? "ON" : "OFF"}'), duration: const Duration(seconds: 1)),
SnackBar(
content: Text(
'Debug Mode: ${!current ? "ON" : "OFF"}'),
duration: const Duration(seconds: 1)),
);
},
child: const SizedBox(width: 20, height: 40),
@@ -836,7 +883,6 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
);
}
String _formatDuration(Duration duration) {
String twoDigits(int n) => n.toString().padLeft(2, '0');
String twoDigitMinutes = twoDigits(duration.inMinutes.remainder(60));
@@ -859,14 +905,17 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
mainAxisSize: MainAxisSize.min,
children: [
// 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(
focusNode: _prevFocusNode,
onPressed: _playPrevious,
onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50),
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,
),
)
@@ -881,7 +930,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50),
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 {
final pos = await _player.stream.position.first;
_player.seek(pos - const Duration(seconds: 5));
@@ -901,7 +951,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
child: IconButton(
iconSize: 72,
icon: Icon(
_isPlaying ? Icons.pause_circle_filled : Icons.play_circle_filled,
_isPlaying
? Icons.pause_circle_filled
: Icons.play_circle_filled,
color: Colors.white,
),
onPressed: _togglePlayPause,
@@ -911,14 +963,17 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
const SizedBox(width: 32),
// 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(
focusNode: _nextFocusNode,
onPressed: _playNext,
onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50),
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,
),
)
@@ -933,7 +988,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
onFocus: _resetControlsTimer,
borderRadius: BorderRadius.circular(50),
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 {
final pos = await _player.stream.position.first;
_player.seek(pos + const Duration(seconds: 5));
@@ -945,7 +1001,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
),
// 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(
bottom: 80, // Above progress/bottom bar
left: 24,
@@ -970,7 +1028,10 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
children: [
Text(
_epg!.nowPlaying!,
style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.bold),
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
@@ -979,7 +1040,9 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
padding: const EdgeInsets.only(top: 4),
child: Text(
"A suivre: ${_epg!.nextPlaying}",
style: const TextStyle(color: Colors.white70, fontSize: 14),
style: const TextStyle(
color: Colors.white70,
fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
@@ -989,13 +1052,18 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
),
// LIVE Badge inside the box, right side
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 4),
margin: const EdgeInsets.only(left: 8),
decoration: BoxDecoration(
color: Colors.red,
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: [
Text(
_formatDuration(_position),
style: const TextStyle(color: Colors.white, fontSize: 14),
style: const TextStyle(
color: Colors.white, fontSize: 14),
),
Expanded(
child: Slider(
value: _position.inSeconds.toDouble().clamp(0, _duration.inSeconds.toDouble()),
value: _position.inSeconds
.toDouble()
.clamp(0, _duration.inSeconds.toDouble()),
min: 0,
max: _duration.inSeconds.toDouble(),
// 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,
inactiveColor: Colors.white24,
onChangeStart: (_) => _isSeeking = true,
onChangeEnd: (value) async {
await _player.seek(Duration(seconds: value.toInt()));
await _player
.seek(Duration(seconds: value.toInt()));
_isSeeking = false;
},
onChanged: (value) {
@@ -1052,7 +1126,8 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
),
Text(
_formatDuration(_duration),
style: const TextStyle(color: Colors.white, fontSize: 14),
style: const TextStyle(
color: Colors.white, fontSize: 14),
),
],
)
@@ -1062,16 +1137,21 @@ class _NativePlayerScreenState extends ConsumerState<NativePlayerScreen> with Wi
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
if (widget.streamType == StreamType.live && settings.showClock)
if (widget.streamType == StreamType.live &&
settings.showClock)
// Clock
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 6),
margin: const EdgeInsets.only(right: 12),
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(4),
),
child: Text(_currentTime, style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)),
child: Text(_currentTime,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold)),
),
// LIVE Badge removed from here
],
@@ -1195,7 +1275,8 @@ class _StatsOverlayWidgetState extends ConsumerState<StatsOverlayWidget> {
@override
Widget build(BuildContext context) {
if (!ref.watch(mobileSettingsProvider).showDebugStats) return const SizedBox.shrink();
if (!ref.watch(mobileSettingsProvider).showDebugStats)
return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.all(8),
@@ -1209,7 +1290,10 @@ class _StatsOverlayWidgetState extends ConsumerState<StatsOverlayWidget> {
mainAxisSize: MainAxisSize.min,
children: [
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),
Text('Buffer: ${_buffer.inSeconds}s',
style: const TextStyle(color: Colors.white, fontSize: 12)),