10 private readonly LibVLC _vlc;
11 private readonly MediaPlayer _player;
12 private readonly
object _control =
new();
13 private readonly
object _frames =
new();
14 private readonly VideoMetadataState _metadata =
new();
15 private readonly MediaPlayer.LibVLCVideoLockCb _lockCb;
16 private readonly MediaPlayer.LibVLCVideoUnlockCb _unlockCb;
17 private readonly MediaPlayer.LibVLCVideoDisplayCb _displayCb;
18 private readonly MediaPlayer.LibVLCVideoFormatCb _formatCb;
19 private readonly MediaPlayer.LibVLCVideoCleanupCb _cleanupCb;
20 private VideoDecodeBuffer? _decodeBuffer;
21 private Media? _media;
22 private StreamMediaInput? _input;
23 private Stream? _ownedStream;
24 private CancellationTokenSource? _parseCancellation;
25 private Task<MediaParsedStatus>? _parseTask;
26 private long _generation;
27 private long _playbackRevision;
28 private bool _disposed, _acceptFrames, _playRequested;
29 private volatile bool _loop;
30 private (
int width,
int height) _naturalSize;
31 private Exception? _lastError;
32 private float _volume = 1;
47 return !_disposed && _player.IsSeekable;
61 if (!
float.IsFinite(value) || value < 0 || value > 1)
62 throw new ArgumentOutOfRangeException(nameof(value),
"Volume must be between zero and one.");
92 private void ApplyAudioSettings()
94 _player.Volume = (int)Math.Round(_volume * 100);
95 _player.Mute = _muted;
99 public bool Loop {
get => _loop;
set => _loop = value; }
107 return !_disposed && _player.IsPlaying;
129 return _disposed ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Math.Max(0, _player.Time));
144 public Exception?
LastError => Volatile.Read(ref _lastError);
162 public event EventHandler<VideoFrameReadyEventArgs>?
FrameReady;
168 public VlcVideoPlayer(
string[]? vlcArgs =
null,
int initialWidth = 1280,
int initialHeight = 720)
170 if (initialWidth <= 0)
171 throw new ArgumentOutOfRangeException(nameof(initialWidth));
173 if (initialHeight <= 0)
174 throw new ArgumentOutOfRangeException(nameof(initialHeight));
176 if (OperatingSystem.IsBrowser() || !BitConverter.IsLittleEndian)
177 throw new PlatformNotSupportedException(
178 "Gondwana.Video requires a little-endian native desktop LibVLC 3 runtime.");
184 _vlc =
new LibVLC(vlcArgs ?? []);
188 _player =
new MediaPlayer(_vlc);
196 catch (Exception ex) when (ex is DllNotFoundException or BadImageFormatException or TypeInitializationException
199 throw new InvalidOperationException(
200 "Gondwana.Video could not load native LibVLC 3. Add VideoLAN.LibVLC.Windows to the Windows app, or VideoLAN.LibVLC.Mac to a compatible macOS app; on Linux install libvlc-dev and VLC codec plugins. Match the process architecture and deploy the plugins directory. See Gondwana.Video/README.md. For a custom runtime call LibVLCSharp.Shared.Core.Initialize(path) before creating the player.",
205 _unlockCb = (_, _, _) => { };
206 _displayCb = DisplayFrame;
207 _formatCb = SetupFormat;
208 _cleanupCb = CleanupFormat;
209 _player.SetVideoCallbacks(_lockCb, _unlockCb, _displayCb);
210 _player.SetVideoFormatCallbacks(_formatCb, _cleanupCb);
211 _player.Playing += OnStarted;
212 _player.Paused += OnPaused;
213 _player.Stopped += OnStopped;
214 _player.EndReached += OnEnded;
215 _player.EncounteredError += OnError;
221 ArgumentNullException.ThrowIfNull(source);
223 if (!source.IsAbsoluteUri)
224 source =
new Uri(Path.GetFullPath(source.OriginalString));
230 if (!ReplaceMedia(() =>
new Media(_vlc, source), out
long generation))
234 _parseCancellation =
new CancellationTokenSource();
236 _parseTask = media.Parse(
237 source.IsFile ? MediaParseOptions.ParseLocal : MediaParseOptions.ParseNetwork,
238 cancellationToken: _parseCancellation.Token);
242 _ = ObserveParseAsync(_parseTask, media, generation);
247 public void Open(Stream source,
bool leaveOpen =
false)
249 ArgumentNullException.ThrowIfNull(source);
252 throw new ArgumentException(
"Video stream must be readable.", nameof(source));
257 var input =
new StreamMediaInput(source);
261 if (!ReplaceMedia(() =>
new Media(_vlc, input), out _))
268 _ownedStream = leaveOpen ? null : source;
280 private bool ReplaceMedia(Func<Media> create, out
long generation)
283 _acceptFrames =
false;
286 long replacementGeneration = _generation;
290 _naturalSize = (0, 0);
293 Volatile.Write(ref _lastError,
null);
296 if (_disposed || replacementGeneration != _generation)
303 _player.Media = _media;
304 generation = _generation = _metadata.Begin();
307 if (_disposed || generation != _generation)
311 _acceptFrames =
true;
316 private async Task ObserveParseAsync(Task<MediaParsedStatus> parse, Media media,
long generation)
318 MediaParsedStatus status;
322 status = await parse.ConfigureAwait(
false);
324 catch (OperationCanceledException)
330 Volatile.Write(ref _lastError, ex);
331 status = MediaParsedStatus.Failed;
335 QueueForSource(generation, () => PublishMetadata(media, status == MediaParsedStatus.Done));
338 private void PublishMetadata(Media media,
bool ready)
343 media.Tracks is { } tracks && Array.Exists(tracks, t => t.TrackType == TrackType.Audio),
344 TimeSpan.FromMilliseconds(Math.Max(0, media.Duration)))
347 if (_metadata.Complete(_generation, metadata))
348 StateChanged?.Invoke(
this,
new(ready ?
"MetadataReady" :
"MetadataFailed"));
351 private void QueueForSource(
long generation, Action action) => ThreadPool.QueueUserWorkItem(_ =>
355 if (_disposed || generation != _generation)
364 Volatile.Write(ref _lastError, ex);
369 private void OnStarted(
object? sender, EventArgs e)
371 long generation = Volatile.Read(ref _generation);
378 PublishMetadata(_media!,
true);
380 ApplyAudioSettings();
381 Started?.Invoke(
this, EventArgs.Empty);
385 private void OnPaused(
object? sender, EventArgs e) => QueueForSource(
386 Volatile.Read(ref _generation),
387 () =>
Paused?.Invoke(
this, EventArgs.Empty));
389 private void OnStopped(
object? sender, EventArgs e) => QueueForSource(
390 Volatile.Read(ref _generation),
391 () =>
Stopped?.Invoke(
this, EventArgs.Empty));
393 private void OnError(
object? sender, EventArgs e) => QueueForSource(
394 Volatile.Read(ref _generation),
397 Interlocked.CompareExchange(
399 new InvalidOperationException(
400 "LibVLC could not play the active source. Check its format, access, and installed codec plugins."),
403 StateChanged?.Invoke(this, new(
"Error"));
406 private void OnEnded(
object? sender, EventArgs e)
408 long revision = Volatile.Read(ref _playbackRevision);
411 Volatile.Read(ref _generation),
414 long generation = _generation;
415 Ended?.Invoke(this, EventArgs.Empty);
417 if (!_disposed && _playRequested && generation == _generation && revision == _playbackRevision && Loop)
427 private uint SetupFormat(
437 var buffer =
new VideoDecodeBuffer(checked((
int)width), checked((
int)height), MaximumFramePixels);
441 _decodeBuffer?.Dispose();
442 _decodeBuffer = buffer;
448 new byte[] { (byte)
'R', (
byte)
'V', (byte)
'3', (
byte)
'2' },
453 pitches = (uint)buffer.Stride;
454 lines = (uint)buffer.Lines;
457 _naturalSize = (buffer.Width, buffer.Height);
463 Volatile.Write(ref _lastError, ex);
468 private IntPtr LockFrame(IntPtr opaque, IntPtr planes)
474 if (_decodeBuffer is not { } buffer || planes == IntPtr.Zero)
477 Marshal.WriteIntPtr(planes, buffer.Pixels);
483 private void DisplayFrame(IntPtr opaque, IntPtr picture)
489 if (!_acceptFrames || _decodeBuffer is not { } buffer)
504 Volatile.Write(ref _lastError, ex);
508 private void CleanupFormat(ref IntPtr opaque)
515 _decodeBuffer?.Dispose();
516 _decodeBuffer =
null;
527 _playRequested =
true;
539 _playRequested =
false;
540 _player.SetPause(
true);
551 _playRequested =
false;
557 public void Seek(TimeSpan position)
562 _player.Time = Math.Max(0, (
long)position.TotalMilliseconds);
569 if (!
double.IsFinite(rate) || rate <= 0)
570 throw new ArgumentOutOfRangeException(nameof(rate));
575 _player.SetRate((
float)rate);
579 private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed,
this);
581 private void ReleaseMedia()
583 _playRequested =
false;
588 _decodeBuffer?.Dispose();
589 _decodeBuffer =
null;
592 _parseCancellation?.Cancel();
594 if (_parseTask is not
null)
598 _parseTask.GetAwaiter().GetResult();
600 catch (OperationCanceledException)
605 Volatile.Write(ref _lastError, ex);
610 _parseCancellation?.Dispose();
611 _parseCancellation =
null;
612 _player.Media =
null;
617 _ownedStream?.Dispose();
633 _acceptFrames =
false;
637 _player.Playing -= OnStarted;
638 _player.Paused -= OnPaused;
639 _player.Stopped -= OnStopped;
640 _player.EndReached -= OnEnded;
641 _player.EncounteredError -= OnError;