Improve LibVLC stability and add external playback host

- Add LibVLCManager singleton for safer LibVLC lifetime management
- Introduce VlcHostClient and VlcHost.exe for external playback via JSON commands
- Enhance VideoPlayer with error recovery and dependency property for SourceUrl
- Implement IDisposable in ProgramsData and ViewModels for better cleanup
- Update NuGet packages: LibVLCSharp to 3.9.6, System.Reactive to 6.1.0
- Add robust error handling and resource disposal throughout
- Improve program guide handling in PlayerViewModel
This commit is contained in:
2026-04-10 14:29:00 +03:00
parent 24ca481b64
commit 64a337ffe8
10 changed files with 554 additions and 35 deletions
+2
View File
@@ -38,6 +38,8 @@ namespace TV_Player
protected override void OnExit(ExitEventArgs e)
{
_tvPlayer.Dispose();
// dispose shared LibVLC instance
try { LibVLCManager.Dispose(); } catch { }
base.OnExit(e);
}
}
+47
View File
@@ -0,0 +1,47 @@
using LibVLCSharp.Shared;
namespace TV_Player
{
public static class LibVLCManager
{
private static readonly object _lock = new object();
private static LibVLC _instance;
public static LibVLC Instance
{
get
{
if (_instance != null) return _instance;
lock (_lock)
{
if (_instance == null)
{
Core.Initialize();
// Use conservative libvlc options to reduce native crashes
var options = new[]
{
"--ignore-config",
"--no-osd",
"--no-snapshot-preview",
"--avcodec-hw=none",
"--network-caching=3000",
"--http-reconnect",
"--rtsp-tcp"
};
_instance = new LibVLC(options);
}
return _instance;
}
}
}
public static void Dispose()
{
lock (_lock)
{
try { _instance?.Dispose(); } catch { }
_instance = null;
}
}
}
}
+3 -3
View File
@@ -22,12 +22,12 @@
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0" />
<PackageReference Include="LibVLCSharp" Version="3.9.4">
<PackageReference Include="LibVLCSharp" Version="3.9.6">
<TreatAsUsed>true</TreatAsUsed>
</PackageReference>
<PackageReference Include="LibVLCSharp.WPF" Version="3.9.4" />
<PackageReference Include="LibVLCSharp.WPF" Version="3.9.6" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="System.Reactive" Version="6.0.2" />
<PackageReference Include="System.Reactive" Version="6.1.0" />
</ItemGroup>
<ItemGroup>
+109 -22
View File
@@ -3,7 +3,6 @@ using LibVLCSharp.WPF;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace TV_Player
{
@@ -12,59 +11,142 @@ namespace TV_Player
/// </summary>
public partial class VideoPlayer : UserControl
{
public string SourceUrl { get; set; }
public static readonly DependencyProperty SourceUrlProperty = DependencyProperty.Register(
nameof(SourceUrl), typeof(string), typeof(VideoPlayer), new PropertyMetadata(string.Empty, OnSourceUrlChanged));
private LibVLC _libVLC;
public string SourceUrl
{
get => (string)GetValue(SourceUrlProperty);
set => SetValue(SourceUrlProperty, value);
}
private static void OnSourceUrlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is VideoPlayer vp && e.NewValue is string url)
{
vp.OnSourceUrlChanged(url);
}
}
private void OnSourceUrlChanged(string url)
{
// when the bound source changes, trigger playback switch
try
{
VideoView.MediaPlayer?.Stop();
VideoView.MediaPlayer?.Media?.Dispose();
}
catch { }
AutoPlay();
}
private LibVLC _libVLC => LibVLCManager.Instance;
private MediaPlayer _mediaPlayer;
private PlayerViewModel _viewModel;
private VlcHostClient _vlcHost;
private bool _useHost;
//private DispatcherTimer _overlayAutoHideTimer;
public VideoPlayer()
{
InitializeComponent();
//_overlayAutoHideTimer = new DispatcherTimer();
//_overlayAutoHideTimer.Interval = TimeSpan.FromSeconds(3);
//_overlayAutoHideTimer.Tick += _overlayAutoHideTimer_Tick;
//_overlayAutoHideTimer.Start();
_libVLC = new LibVLC(enableDebugLogs: true);
_mediaPlayer = new MediaPlayer(_libVLC);
// try to start external host helper (if present)
try
{
_vlcHost = new VlcHostClient();
_useHost = _vlcHost.EnsureStarted();
}
catch { _useHost = false; }
// subscribe to error events to recover from playback errors
_mediaPlayer.EncounteredError += MediaPlayer_EncounteredError;
this.DataContextChanged += (sender, e) =>
{
_viewModel = (PlayerViewModel)e.NewValue;
_viewModel.SourceUrlChangedEvent += _viewModel_SourceUrlChangedEvent;
if (_viewModel != null)
{
try { _viewModel.SourceUrlChangedEvent -= _viewModel_SourceUrlChangedEvent; } catch { }
}
_viewModel = e.NewValue as PlayerViewModel;
if (_viewModel != null)
{
_viewModel.SourceUrlChangedEvent += _viewModel_SourceUrlChangedEvent;
}
};
VideoView.Loaded += (sender, e) =>
{
VideoView.MediaPlayer = _mediaPlayer;
VideoView.MouseLeftButtonDown += VideoView_MouseLeftButtonDown;
VideoView.MediaPlayer.EnableMouseInput = false;
if (VideoView.MediaPlayer != null)
VideoView.MediaPlayer.EnableMouseInput = false;
VideoView.PreviewMouseLeftButtonDown += VideoView_MouseLeftButtonDown;
AutoPlay();
};
Unloaded += VideoPlayer_Unloaded;
}
}
private void MediaPlayer_EncounteredError(object? sender, EventArgs e)
{
// MediaPlayer.EncounteredError can be raised on a native thread; marshal to UI thread
try
{
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
System.Diagnostics.Debug.WriteLine("[VideoPlayer] MediaPlayer encountered error — attempting recovery");
try { VideoView.MediaPlayer?.Stop(); } catch { }
try { VideoView.MediaPlayer?.Media?.Dispose(); } catch { }
// dispose existing player and try full LibVLC restart to recover native/network resources
try { _mediaPlayer.EncounteredError -= MediaPlayer_EncounteredError; } catch { }
try { VideoView.MediaPlayer?.Stop(); } catch { }
try { VideoView.MediaPlayer?.Media?.Dispose(); } catch { }
try { _mediaPlayer?.Dispose(); } catch { }
try { LibVLCManager.Dispose(); } catch { }
// recreate LibVLC and MediaPlayer
var lib = LibVLCManager.Instance;
_mediaPlayer = new MediaPlayer(lib);
_mediaPlayer.EncounteredError += MediaPlayer_EncounteredError;
// re-assign to the view and restart playback
VideoView.MediaPlayer = _mediaPlayer;
AutoPlay();
}));
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"[VideoPlayer] Error handling encountered error: {ex}");
}
}
private void _viewModel_SourceUrlChangedEvent(string videoURL)
{
SourceUrl = videoURL;
VideoView.MediaPlayer.Stop();
VideoView.MediaPlayer.Media.Dispose();
try
{
VideoView.MediaPlayer?.Stop();
VideoView.MediaPlayer?.Media?.Dispose();
}
catch { }
AutoPlay();
}
private void VideoView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ToggleOverlay();
}
private void VideoPlayer_Unloaded(object sender, RoutedEventArgs e)
{
VideoView.Dispose();
// Dispose the VideoView (releases native view references) but keep the shared LibVLC instance
try { VideoView.Dispose(); } catch { }
}
void PauseButton_Click(object sender, RoutedEventArgs e)
{
@@ -75,7 +157,9 @@ namespace TV_Player
}
private void AutoPlay()
{
if (!VideoView.MediaPlayer.IsPlaying)
if (VideoView?.MediaPlayer == null) return;
if (!VideoView.MediaPlayer.IsPlaying && !string.IsNullOrWhiteSpace(SourceUrl))
{
using (var media = new Media(_libVLC, new Uri(SourceUrl)))
VideoView.MediaPlayer.Play(media);
@@ -90,7 +174,8 @@ namespace TV_Player
{
if (overlayPanel.Visibility == Visibility.Visible)
{
_viewModel.ProgramGuideVisible = false;
if (_viewModel != null)
_viewModel.ProgramGuideVisible = false;
HideOverlay();
}
else
@@ -116,8 +201,10 @@ namespace TV_Player
}
private void UserControl_Unloaded(object sender, RoutedEventArgs e)
{
_viewModel.SourceUrlChangedEvent -= _viewModel_SourceUrlChangedEvent;
VideoView.MediaPlayer?.Dispose();
try { if(VideoView.MediaPlayer.IsPlaying) VideoView.MediaPlayer?.Stop(); } catch { }
try { _mediaPlayer?.Dispose(); } catch { }
try { if (_viewModel != null) _viewModel.SourceUrlChangedEvent -= _viewModel_SourceUrlChangedEvent; } catch { }
try { VideoView.MediaPlayer?.Dispose(); } catch { }
}
}
}
+23 -1
View File
@@ -163,8 +163,30 @@ namespace TV_Player
try
{
if (_currentProgram == null) return;
// make sure guide and programs list exist
if (_currentGuide?.Programs == null || _currentGuide.Programs.Count == 0)
{
IsProgramInfoVisible = false;
Programs = new List<ProgramInfo>();
return;
}
_currentProgramInfo = _currentGuide.Programs.FirstOrDefault(d => d.StartTime <= DateTime.Now && d.EndTime >= DateTime.Now);
Programs = _currentGuide.Programs.Skip(_currentGuide.Programs.FindIndex(x=>x.Title==_currentProgramInfo.Title)).Take(7).ToList();
if (_currentProgramInfo == null)
{
// no current program found: hide info and show the first N programs as a fallback
IsProgramInfoVisible = false;
Programs = _currentGuide.Programs.Take(7).ToList();
}
else
{
// find the index of the current program safely
int idx = _currentGuide.Programs.FindIndex(x => string.Equals(x.Title, _currentProgramInfo.Title, StringComparison.Ordinal));
if (idx < 0) idx = 0;
Programs = _currentGuide.Programs.Skip(idx).Take(7).ToList();
}
if (_currentProgramInfo == null)
{
@@ -188,6 +188,19 @@ namespace TV_Player.ViewModels
{
if (_mainViewModel.Control is IDisposable disposable)
disposable.Dispose();
if (PlayListsData != null)
{
foreach (var kv in PlayListsData)
{
try { kv.Value.Dispose(); } catch { }
}
PlayListsData.Clear();
}
if (CurrentProgrmsData != null)
{
try { CurrentProgrmsData.Dispose(); } catch { }
}
}
}
}