diff --git a/bin/server.dart b/bin/server.dart index a55e074..2df756d 100644 --- a/bin/server.dart +++ b/bin/server.dart @@ -466,11 +466,12 @@ Handler _createStreamHandler() { '-b:a', '128k', '-ar', '44100', '-ac', '2', // Force stereo - // HLS output settings + // HLS output settings - optimized for stability '-f', 'hls', - '-hls_time', isVod ? '4' : '2', // 4 second segments for VOD, 2 for live - '-hls_list_size', isVod ? '0' : '5', // Keep all segments for VOD, last 5 for live - '-hls_flags', isVod ? 'independent_segments' : 'delete_segments+append_list+omit_endlist', + '-hls_time', isVod ? '4' : '3', // 4s for VOD, 3s for live (better buffering) + '-hls_list_size', isVod ? '0' : '10', // Keep all segments for VOD, 10 for live (30s buffer) + '-hls_flags', isVod ? 'independent_segments' : 'delete_segments+append_list+omit_endlist+program_date_time', + '-hls_start_number_source', 'datetime', // Better segment continuity '-hls_segment_filename', '${outputDir.path}/segment_%d.ts', outputPath, ]); diff --git a/lib/features/iptv/providers/playback_positions_provider.dart b/lib/features/iptv/providers/playback_positions_provider.dart new file mode 100644 index 0000000..aa0f7e3 --- /dev/null +++ b/lib/features/iptv/providers/playback_positions_provider.dart @@ -0,0 +1,121 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'dart:convert'; + +/// Playback position state - tracks resume positions for movies and episodes +class PlaybackPositions { + /// Map of content ID to position in seconds (for movies: streamId, for episodes: seriesId_seasonNum_episodeNum) + final Map positions; + + const PlaybackPositions({ + this.positions = const {}, + }); + + PlaybackPositions copyWith({ + Map? positions, + }) { + return PlaybackPositions( + positions: positions ?? this.positions, + ); + } + + /// Get saved position for a content (returns 0 if not found) + double getPosition(String contentId) => positions[contentId] ?? 0; + + /// Check if content has a saved position (beyond 30 seconds) + bool hasPosition(String contentId) => (positions[contentId] ?? 0) > 30; +} + +/// Playback positions notifier with persistence +class PlaybackPositionsNotifier extends StateNotifier { + static const String _storageKey = 'playback_positions'; + + SharedPreferences? _prefs; + bool _initialized = false; + + PlaybackPositionsNotifier() : super(const PlaybackPositions()) { + _loadPositions(); + } + + Future _loadPositions() async { + if (_initialized) return; + + try { + _prefs = await SharedPreferences.getInstance(); + + final positionsJson = _prefs?.getString(_storageKey); + + if (positionsJson != null) { + final decoded = jsonDecode(positionsJson) as Map; + final positions = decoded.map((key, value) => + MapEntry(key, (value as num).toDouble()) + ); + + state = PlaybackPositions(positions: positions); + print('Playback positions loaded: ${positions.length} entries'); + } + + _initialized = true; + } catch (e) { + print('Error loading playback positions: $e'); + } + } + + Future _savePositions() async { + try { + _prefs ??= await SharedPreferences.getInstance(); + await _prefs?.setString(_storageKey, jsonEncode(state.positions)); + } catch (e) { + print('Error saving playback positions: $e'); + } + } + + /// Save position for a content + void savePosition(String contentId, double positionSeconds, double durationSeconds) { + // Don't save if less than 30 seconds in or more than 95% complete + if (positionSeconds < 30 || (durationSeconds > 0 && positionSeconds / durationSeconds > 0.95)) { + // If 95% complete, remove any saved position (mark as fully watched) + if (durationSeconds > 0 && positionSeconds / durationSeconds > 0.95) { + clearPosition(contentId); + } + return; + } + + final newPositions = Map.from(state.positions); + newPositions[contentId] = positionSeconds; + state = state.copyWith(positions: newPositions); + _savePositions(); + } + + /// Clear position for a content + void clearPosition(String contentId) { + final newPositions = Map.from(state.positions); + newPositions.remove(contentId); + state = state.copyWith(positions: newPositions); + _savePositions(); + } + + /// Clear all positions + void clearAll() { + state = const PlaybackPositions(); + _savePositions(); + } + + /// Get formatted resume time + static String formatTime(double seconds) { + final mins = (seconds / 60).floor(); + final secs = (seconds % 60).floor(); + if (mins >= 60) { + final hours = (mins / 60).floor(); + final remainingMins = mins % 60; + return '${hours}h ${remainingMins}m'; + } + return '${mins}m ${secs}s'; + } +} + +/// Provider for playback positions +final playbackPositionsProvider = + StateNotifierProvider((ref) { + return PlaybackPositionsNotifier(); +}); diff --git a/lib/features/iptv/screens/player_screen.dart b/lib/features/iptv/screens/player_screen.dart index e765f59..7815cf0 100644 --- a/lib/features/iptv/screens/player_screen.dart +++ b/lib/features/iptv/screens/player_screen.dart @@ -3,8 +3,10 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'dart:html' as html; import 'dart:ui_web' as ui_web; import 'dart:convert'; +import 'dart:async'; import 'package:http/http.dart' as http; import '../providers/xtream_provider.dart'; +import '../providers/playback_positions_provider.dart'; import '../widgets/epg_overlay.dart'; import '../../../core/models/playlist_config.dart'; @@ -37,14 +39,51 @@ class _PlayerScreenState extends ConsumerState { String? _errorMessage; String? _statusMessage; late String _viewId; + late String _contentId; bool _isInitialized = false; bool _isLoading = true; + StreamSubscription? _messageSubscription; @override void initState() { super.initState(); _viewId = 'iptv-player-${widget.streamId}-${DateTime.now().millisecondsSinceEpoch}'; + // Content ID for resume feature + _contentId = widget.streamType == StreamType.live + ? '' // Live streams don't need resume + : '${widget.streamType.name}_${widget.streamId}'; _initializePlayer(); + _setupMessageListener(); + } + + void _setupMessageListener() { + // Listen for postMessage from player.html iframe + _messageSubscription = html.window.onMessage.listen((event) { + try { + final data = event.data; + if (data is Map) { + final type = data['type']; + if (type == 'playback_position' && _contentId.isNotEmpty) { + final currentTime = (data['currentTime'] as num).toDouble(); + final duration = (data['duration'] as num).toDouble(); + ref.read(playbackPositionsProvider.notifier).savePosition( + _contentId, currentTime, duration + ); + } else if (type == 'playback_ended' && _contentId.isNotEmpty) { + // Clear position when video ends + ref.read(playbackPositionsProvider.notifier).clearPosition(_contentId); + } + } + } catch (e) { + debugPrint('Error handling postMessage: $e'); + } + }); + } + + @override + void dispose() { + _messageSubscription?.cancel(); + super.dispose(); } Future _initializePlayer() async { @@ -145,9 +184,21 @@ class _PlayerScreenState extends ConsumerState { _statusMessage = 'Loading player...'; }); + // Get resume position for VOD/Series + double startTime = 0; + if (widget.streamType != StreamType.live && _contentId.isNotEmpty) { + final positions = ref.read(playbackPositionsProvider); + startTime = positions.getPosition(_contentId); + if (startTime > 0) { + debugPrint('PlayerScreen: Resuming from ${startTime.toStringAsFixed(0)}s'); + } + } + // Register the HTML view with an iframe pointing to our player.html final encodedHlsUrl = Uri.encodeComponent(hlsUrl); - final playerUrl = 'player.html?url=$encodedHlsUrl'; + final playerUrl = startTime > 0 + ? 'player.html?url=$encodedHlsUrl&startTime=${startTime.toStringAsFixed(0)}' + : 'player.html?url=$encodedHlsUrl'; debugPrint('PlayerScreen: Player URL: $playerUrl'); diff --git a/lib/features/iptv/widgets/movies_tab.dart b/lib/features/iptv/widgets/movies_tab.dart index 4f91609..5aac2e6 100644 --- a/lib/features/iptv/widgets/movies_tab.dart +++ b/lib/features/iptv/widgets/movies_tab.dart @@ -20,7 +20,9 @@ class MoviesTab extends ConsumerStatefulWidget { class _MoviesTabState extends ConsumerState { final ScrollController _scrollController = ScrollController(); + final TextEditingController _searchController = TextEditingController(); final List _movies = []; + String _searchQuery = ''; bool _isLoading = false; bool _hasMore = true; int _currentOffset = 0; @@ -36,6 +38,7 @@ class _MoviesTabState extends ConsumerState { @override void dispose() { _scrollController.dispose(); + _searchController.dispose(); super.dispose(); } @@ -83,56 +86,114 @@ class _MoviesTabState extends ConsumerState { final settings = ref.watch(iptvSettingsProvider); // Filter movies by category - final filteredMovies = settings.moviesKeywords.isEmpty + var filteredMovies = settings.moviesKeywords.isEmpty ? _movies : _movies.where((m) => settings.matchesMoviesFilter(m.categoryName)).toList(); + + // Apply search filter + if (_searchQuery.isNotEmpty) { + final query = _searchQuery.toLowerCase(); + filteredMovies = filteredMovies.where((m) => + m.name.toLowerCase().contains(query) + ).toList(); + } if (_movies.isEmpty && !_isLoading) { return const Center(child: Text('No movies available')); } - if (filteredMovies.isEmpty && _movies.isNotEmpty) { - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.filter_list_off, size: 48, color: Colors.grey), - const SizedBox(height: 16), - Text( - 'No movies match the filter', - style: GoogleFonts.roboto(color: Colors.grey), + return Column( + children: [ + // Search bar + Padding( + padding: const EdgeInsets.all(8.0), + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: 'Search movies...', + hintStyle: GoogleFonts.roboto(color: Colors.grey.shade500), + prefixIcon: const Icon(Icons.search, color: Colors.grey), + suffixIcon: _searchQuery.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, color: Colors.grey), + onPressed: () { + _searchController.clear(); + setState(() => _searchQuery = ''); + }, + ) + : null, + filled: true, + fillColor: Colors.grey.shade800, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide.none, + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), ), - const SizedBox(height: 8), - Text( - 'Filter: ${settings.moviesCategoryFilter}', - style: GoogleFonts.roboto(fontSize: 12, color: Colors.grey.shade600), - ), - ], + style: GoogleFonts.roboto(color: Colors.white), + onChanged: (value) => setState(() => _searchQuery = value), + ), ), - ); - } + + // Results count + if (_searchQuery.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + '${filteredMovies.length} result${filteredMovies.length != 1 ? 's' : ''} found', + style: GoogleFonts.roboto(fontSize: 12, color: Colors.grey.shade600), + ), + ), + ), + + // Movie grid + Expanded( + child: filteredMovies.isEmpty && _movies.isNotEmpty + ? Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + _searchQuery.isNotEmpty ? Icons.search_off : Icons.filter_list_off, + size: 48, + color: Colors.grey, + ), + const SizedBox(height: 16), + Text( + _searchQuery.isNotEmpty + ? 'No movies match "$_searchQuery"' + : 'No movies match the filter', + style: GoogleFonts.roboto(color: Colors.grey), + ), + ], + ), + ) + : GridView.builder( + controller: _scrollController, + padding: const EdgeInsets.all(8), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 7, + crossAxisSpacing: 6, + mainAxisSpacing: 6, + childAspectRatio: 0.65, + ), + itemCount: filteredMovies.length + (_hasMore && _searchQuery.isEmpty ? 1 : 0), + itemBuilder: (context, index) { + if (index >= filteredMovies.length) { + return const Center(child: CircularProgressIndicator()); + } - return GridView.builder( - controller: _scrollController, - padding: const EdgeInsets.all(8), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 7, - crossAxisSpacing: 6, - mainAxisSpacing: 6, - childAspectRatio: 0.65, - ), - itemCount: filteredMovies.length + (_hasMore ? 1 : 0), - itemBuilder: (context, index) { - if (index >= filteredMovies.length) { - return const Center(child: CircularProgressIndicator()); - } - - final movie = filteredMovies[index]; - return _MovieCard( - movie: movie, - playlist: widget.playlist, - ); - }, + final movie = filteredMovies[index]; + return _MovieCard( + movie: movie, + playlist: widget.playlist, + ); + }, + ), + ), + ], ); } } diff --git a/lib/features/iptv/widgets/series_tab.dart b/lib/features/iptv/widgets/series_tab.dart index d0e904b..af1fb5b 100644 --- a/lib/features/iptv/widgets/series_tab.dart +++ b/lib/features/iptv/widgets/series_tab.dart @@ -19,7 +19,9 @@ class SeriesTab extends ConsumerStatefulWidget { class _SeriesTabState extends ConsumerState { final ScrollController _scrollController = ScrollController(); + final TextEditingController _searchController = TextEditingController(); final List _series = []; + String _searchQuery = ''; bool _isLoading = false; bool _hasMore = true; int _currentOffset = 0; @@ -35,6 +37,7 @@ class _SeriesTabState extends ConsumerState { @override void dispose() { _scrollController.dispose(); + _searchController.dispose(); super.dispose(); } @@ -82,53 +85,111 @@ class _SeriesTabState extends ConsumerState { final settings = ref.watch(iptvSettingsProvider); // Filter series by category - final filteredSeries = settings.seriesKeywords.isEmpty + var filteredSeries = settings.seriesKeywords.isEmpty ? _series : _series.where((s) => settings.matchesSeriesFilter(s.categoryName)).toList(); + + // Apply search filter + if (_searchQuery.isNotEmpty) { + final query = _searchQuery.toLowerCase(); + filteredSeries = filteredSeries.where((s) => + s.name.toLowerCase().contains(query) + ).toList(); + } if (_series.isEmpty && !_isLoading) { return const Center(child: Text('No series available')); } - if (filteredSeries.isEmpty && _series.isNotEmpty) { - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Icon(Icons.filter_list_off, size: 48, color: Colors.grey), - const SizedBox(height: 16), - Text( - 'No series match the filter', - style: GoogleFonts.roboto(color: Colors.grey), + return Column( + children: [ + // Search bar + Padding( + padding: const EdgeInsets.all(8.0), + child: TextField( + controller: _searchController, + decoration: InputDecoration( + hintText: 'Search series...', + hintStyle: GoogleFonts.roboto(color: Colors.grey.shade500), + prefixIcon: const Icon(Icons.search, color: Colors.grey), + suffixIcon: _searchQuery.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, color: Colors.grey), + onPressed: () { + _searchController.clear(); + setState(() => _searchQuery = ''); + }, + ) + : null, + filled: true, + fillColor: Colors.grey.shade800, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide.none, + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), ), - const SizedBox(height: 8), - Text( - 'Filter: ${settings.seriesCategoryFilter}', - style: GoogleFonts.roboto(fontSize: 12, color: Colors.grey.shade600), - ), - ], + style: GoogleFonts.roboto(color: Colors.white), + onChanged: (value) => setState(() => _searchQuery = value), + ), ), - ); - } + + // Results count + if (_searchQuery.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: Align( + alignment: Alignment.centerLeft, + child: Text( + '${filteredSeries.length} result${filteredSeries.length != 1 ? 's' : ''} found', + style: GoogleFonts.roboto(fontSize: 12, color: Colors.grey.shade600), + ), + ), + ), + + // Series grid + Expanded( + child: filteredSeries.isEmpty && _series.isNotEmpty + ? Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + _searchQuery.isNotEmpty ? Icons.search_off : Icons.filter_list_off, + size: 48, + color: Colors.grey, + ), + const SizedBox(height: 16), + Text( + _searchQuery.isNotEmpty + ? 'No series match "$_searchQuery"' + : 'No series match the filter', + style: GoogleFonts.roboto(color: Colors.grey), + ), + ], + ), + ) + : GridView.builder( + controller: _scrollController, + padding: const EdgeInsets.all(8), + gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: 7, + crossAxisSpacing: 6, + mainAxisSpacing: 6, + childAspectRatio: 0.65, + ), + itemCount: filteredSeries.length + (_hasMore && _searchQuery.isEmpty ? 1 : 0), + itemBuilder: (context, index) { + if (index >= filteredSeries.length) { + return const Center(child: CircularProgressIndicator()); + } - return GridView.builder( - controller: _scrollController, - padding: const EdgeInsets.all(8), - gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount( - crossAxisCount: 7, - crossAxisSpacing: 6, - mainAxisSpacing: 6, - childAspectRatio: 0.65, - ), - itemCount: filteredSeries.length + (_hasMore ? 1 : 0), - itemBuilder: (context, index) { - if (index >= filteredSeries.length) { - return const Center(child: CircularProgressIndicator()); - } - - final serie = filteredSeries[index]; - return _SeriesCard(series: serie, playlist: widget.playlist); - }, + final serie = filteredSeries[index]; + return _SeriesCard(series: serie, playlist: widget.playlist); + }, + ), + ), + ], ); } } diff --git a/web/player.html b/web/player.html index eea1a4f..23dc2cd 100644 --- a/web/player.html +++ b/web/player.html @@ -76,6 +76,8 @@ } #debug { + display: none; + /* Hidden in production */ position: absolute; bottom: 10px; left: 10px; @@ -116,15 +118,60 @@ const errorMessage = document.getElementById('error-message'); const debug = document.getElementById('debug'); - // Get stream URL from query parameter + // Get parameters from query string const urlParams = new URLSearchParams(window.location.search); let streamUrl = urlParams.get('url'); + const startTime = parseFloat(urlParams.get('startTime') || '0'); + let lastReportedTime = 0; function log(msg) { console.log(msg); debug.textContent = msg; } + // Report current playback position to parent (for resume feature) + function reportPosition() { + if (video.currentTime > 0 && !video.paused && video.readyState > 2) { + // Only report every 5 seconds or if time changed significantly + if (Math.abs(video.currentTime - lastReportedTime) >= 5) { + lastReportedTime = video.currentTime; + window.parent.postMessage({ + type: 'playback_position', + currentTime: video.currentTime, + duration: video.duration || 0 + }, '*'); + } + } + } + + // Set up periodic position reporting + setInterval(reportPosition, 5000); + + // Also report on pause + video.addEventListener('pause', () => { + window.parent.postMessage({ + type: 'playback_position', + currentTime: video.currentTime, + duration: video.duration || 0 + }, '*'); + }); + + // Report when video ends + video.addEventListener('ended', () => { + window.parent.postMessage({ + type: 'playback_ended', + duration: video.duration || 0 + }, '*'); + }); + + // Seek to startTime when video is ready + video.addEventListener('loadedmetadata', () => { + if (startTime > 0 && startTime < video.duration) { + video.currentTime = startTime; + log('Resuming from ' + Math.floor(startTime / 60) + 'm ' + Math.floor(startTime % 60) + 's'); + } + }); + function showLoading(msg) { loading.style.display = 'block'; loadingText.textContent = msg || 'Loading stream...'; @@ -161,10 +208,41 @@ return false; } + // Optimized HLS.js configuration for stable live streaming const hls = new Hls({ - xhrSetup: function (xhr, url) { - // Don't add extra headers - the proxy already handles this - } + // Increase buffer for smoother playback + maxBufferLength: 30, // Max 30 seconds of buffer + maxMaxBufferLength: 60, // Allow up to 60 seconds in stressed conditions + maxBufferSize: 60 * 1000000, // 60MB max buffer size + maxBufferHole: 0.5, // Tolerate 0.5s gaps in buffer + + // Low latency settings (balanced) + liveSyncDurationCount: 3, // Sync to 3 segments behind live + liveMaxLatencyDurationCount: 6, // Max 6 segments behind before seeking + liveDurationInfinity: true, // Treat live streams as infinite + + // Faster recovery from errors + manifestLoadingTimeOut: 15000, // 15s timeout for manifest + manifestLoadingMaxRetry: 4, // Retry manifest 4 times + manifestLoadingRetryDelay: 1000, // 1s between retries + levelLoadingTimeOut: 15000, // 15s for level playlist + levelLoadingMaxRetry: 4, + levelLoadingRetryDelay: 1000, + fragLoadingTimeOut: 20000, // 20s for fragments + fragLoadingMaxRetry: 6, // Retry fragments 6 times + fragLoadingRetryDelay: 1000, + + // Better quality selection + startLevel: -1, // Auto-select start level + abrEwmaDefaultEstimate: 500000, // Start assuming 500kbps + abrBandWidthFactor: 0.95, // Use 95% of measured bandwidth + abrBandWidthUpFactor: 0.7, // Be cautious when upgrading quality + + // Enable worker for better performance + enableWorker: true, + + // Don't add extra headers + xhrSetup: function (xhr, url) { } }); hls.loadSource(url); @@ -176,10 +254,25 @@ video.play().catch(e => log('Autoplay prevented: ' + e)); }); + // Better error recovery hls.on(Hls.Events.ERROR, (event, data) => { log('HLS Error: ' + data.type + ' - ' + data.details); + if (data.fatal) { - showError('HLS Error: ' + data.details); + switch (data.type) { + case Hls.ErrorTypes.NETWORK_ERROR: + log('Network error, attempting recovery...'); + hls.startLoad(); // Try to recover network errors + break; + case Hls.ErrorTypes.MEDIA_ERROR: + log('Media error, attempting recovery...'); + hls.recoverMediaError(); // Try to recover media errors + break; + default: + showError('HLS Error: ' + data.details); + hls.destroy(); + break; + } } });