Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
VlcVideoPlayer.cs
1using System.Runtime.InteropServices;
2using LibVLCSharp.Shared;
3
4namespace Gondwana.Video;
5
8public sealed class VlcVideoPlayer : IVideoPlayer
9{
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;
33 private bool _muted;
34
36 public int MaximumFramePixels { get; init; } = int.MaxValue / 4;
37
39 public bool CanControlAudio => true;
40
42 public bool CanSeek
43 {
44 get
45 {
46 lock (_control)
47 return !_disposed && _player.IsSeekable;
48 }
49 }
50
52 public float Volume
53 {
54 get
55 {
56 lock (_control)
57 return _volume;
58 }
59 set
60 {
61 if (!float.IsFinite(value) || value < 0 || value > 1)
62 throw new ArgumentOutOfRangeException(nameof(value), "Volume must be between zero and one.");
63
64 lock (_control)
65 {
66 ThrowIfDisposed();
67 _volume = value;
68 ApplyAudioSettings();
69 }
70 }
71 }
72
74 public bool IsMuted
75 {
76 get
77 {
78 lock (_control)
79 return _muted;
80 }
81 set
82 {
83 lock (_control)
84 {
85 ThrowIfDisposed();
86 _muted = value;
87 ApplyAudioSettings();
88 }
89 }
90 }
91
92 private void ApplyAudioSettings()
93 {
94 _player.Volume = (int)Math.Round(_volume * 100);
95 _player.Mute = _muted;
96 }
97
99 public bool Loop { get => _loop; set => _loop = value; }
100
102 public bool IsPlaying
103 {
104 get
105 {
106 lock (_control)
107 return !_disposed && _player.IsPlaying;
108 }
109 }
110
112 public VideoMetadata Metadata => _metadata.Current;
113
115 public bool IsMetadataReady => Metadata.Status == VideoMetadataStatus.Ready;
116
118 public bool HasAudio => Metadata.HasAudio;
119
121 public TimeSpan Duration => Metadata.Duration;
122
124 public TimeSpan Position
125 {
126 get
127 {
128 lock (_control)
129 return _disposed ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Math.Max(0, _player.Time));
130 }
131 }
132
134 public (int width, int height) NaturalSize
135 {
136 get
137 {
138 lock (_frames)
139 return _naturalSize;
140 }
141 }
142
144 public Exception? LastError => Volatile.Read(ref _lastError);
145
147 public event EventHandler? Started;
148
150 public event EventHandler? Paused;
151
153 public event EventHandler? Stopped;
154
156 public event EventHandler? Ended;
157
159 public event EventHandler<VideoStateChangedEventArgs>? StateChanged;
160
162 public event EventHandler<VideoFrameReadyEventArgs>? FrameReady;
163
168 public VlcVideoPlayer(string[]? vlcArgs = null, int initialWidth = 1280, int initialHeight = 720)
169 {
170 if (initialWidth <= 0)
171 throw new ArgumentOutOfRangeException(nameof(initialWidth));
172
173 if (initialHeight <= 0)
174 throw new ArgumentOutOfRangeException(nameof(initialHeight));
175
176 if (OperatingSystem.IsBrowser() || !BitConverter.IsLittleEndian)
177 throw new PlatformNotSupportedException(
178 "Gondwana.Video requires a little-endian native desktop LibVLC 3 runtime.");
179
180 try
181 {
182 // LibVLCSharp serializes process-wide initialization itself.
183 Core.Initialize();
184 _vlc = new LibVLC(vlcArgs ?? []);
185
186 try
187 {
188 _player = new MediaPlayer(_vlc);
189 }
190 catch
191 {
192 _vlc.Dispose();
193 throw;
194 }
195 }
196 catch (Exception ex) when (ex is DllNotFoundException or BadImageFormatException or TypeInitializationException
197 or VLCException)
198 {
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.",
201 ex);
202 }
203
204 _lockCb = LockFrame;
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;
216 }
217
219 public void Open(Uri source)
220 {
221 ArgumentNullException.ThrowIfNull(source);
222
223 if (!source.IsAbsoluteUri)
224 source = new Uri(Path.GetFullPath(source.OriginalString));
225
226 lock (_control)
227 {
228 ThrowIfDisposed();
229
230 if (!ReplaceMedia(() => new Media(_vlc, source), out long generation))
231 return;
232
233 var media = _media!;
234 _parseCancellation = new CancellationTokenSource();
235
236 _parseTask = media.Parse(
237 source.IsFile ? MediaParseOptions.ParseLocal : MediaParseOptions.ParseNetwork,
238 cancellationToken: _parseCancellation.Token);
239
240 // The continuation does not own the media. Generation validation under _control
241 // prevents any access after replacement/disposal. Open never waits for network parse.
242 _ = ObserveParseAsync(_parseTask, media, generation);
243 }
244 }
245
247 public void Open(Stream source, bool leaveOpen = false)
248 {
249 ArgumentNullException.ThrowIfNull(source);
250
251 if (!source.CanRead)
252 throw new ArgumentException("Video stream must be readable.", nameof(source));
253
254 lock (_control)
255 {
256 ThrowIfDisposed();
257 var input = new StreamMediaInput(source);
258
259 try
260 {
261 if (!ReplaceMedia(() => new Media(_vlc, input), out _))
262 {
263 input.Dispose();
264 return;
265 }
266
267 _input = input;
268 _ownedStream = leaveOpen ? null : source;
269 }
270 catch
271 {
272 input.Dispose();
273 throw;
274 }
275 // Do not preparse and play against the same stream cursor concurrently.
276 // LibVLC discovers stream tracks during playback; Playing publishes metadata.
277 }
278 }
279
280 private bool ReplaceMedia(Func<Media> create, out long generation)
281 {
282 lock (_frames)
283 _acceptFrames = false;
284
285 ++_generation;
286 long replacementGeneration = _generation;
287 ReleaseMedia();
288
289 lock (_frames)
290 _naturalSize = (0, 0);
291
292 _metadata.Reset();
293 Volatile.Write(ref _lastError, null);
294 StateChanged?.Invoke(this, new("MediaOpening"));
295
296 if (_disposed || replacementGeneration != _generation)
297 {
298 generation = 0;
299 return false;
300 }
301
302 _media = create();
303 _player.Media = _media;
304 generation = _generation = _metadata.Begin();
305 StateChanged?.Invoke(this, new("MediaOpened"));
306
307 if (_disposed || generation != _generation)
308 return false;
309
310 lock (_frames)
311 _acceptFrames = true;
312
313 return true;
314 }
315
316 private async Task ObserveParseAsync(Task<MediaParsedStatus> parse, Media media, long generation)
317 {
318 MediaParsedStatus status;
319
320 try
321 {
322 status = await parse.ConfigureAwait(false);
323 }
324 catch (OperationCanceledException)
325 {
326 return;
327 }
328 catch (Exception ex)
329 {
330 Volatile.Write(ref _lastError, ex);
331 status = MediaParsedStatus.Failed;
332 }
333
334 // Always queue: even a synchronous Parse completion must not raise user events inside Open.
335 QueueForSource(generation, () => PublishMetadata(media, status == MediaParsedStatus.Done));
336 }
337
338 private void PublishMetadata(Media media, bool ready)
339 {
340 var metadata = ready
341 ? new VideoMetadata(
343 media.Tracks is { } tracks && Array.Exists(tracks, t => t.TrackType == TrackType.Audio),
344 TimeSpan.FromMilliseconds(Math.Max(0, media.Duration)))
345 : new VideoMetadata(VideoMetadataStatus.Failed, false, TimeSpan.Zero);
346
347 if (_metadata.Complete(_generation, metadata))
348 StateChanged?.Invoke(this, new(ready ? "MetadataReady" : "MetadataFailed"));
349 }
350
351 private void QueueForSource(long generation, Action action) => ThreadPool.QueueUserWorkItem(_ =>
352 {
353 lock (_control)
354 {
355 if (_disposed || generation != _generation)
356 return;
357
358 try
359 {
360 action();
361 }
362 catch (Exception ex)
363 {
364 Volatile.Write(ref _lastError, ex);
365 }
366 }
367 });
368
369 private void OnStarted(object? sender, EventArgs e)
370 {
371 long generation = Volatile.Read(ref _generation);
372
373 QueueForSource(
374 generation,
375 () =>
376 {
377 if (_input is not null && !IsMetadataReady)
378 PublishMetadata(_media!, true);
379
380 ApplyAudioSettings();
381 Started?.Invoke(this, EventArgs.Empty);
382 });
383 }
384
385 private void OnPaused(object? sender, EventArgs e) => QueueForSource(
386 Volatile.Read(ref _generation),
387 () => Paused?.Invoke(this, EventArgs.Empty));
388
389 private void OnStopped(object? sender, EventArgs e) => QueueForSource(
390 Volatile.Read(ref _generation),
391 () => Stopped?.Invoke(this, EventArgs.Empty));
392
393 private void OnError(object? sender, EventArgs e) => QueueForSource(
394 Volatile.Read(ref _generation),
395 () =>
396 {
397 Interlocked.CompareExchange(
398 ref _lastError,
399 new InvalidOperationException(
400 "LibVLC could not play the active source. Check its format, access, and installed codec plugins."),
401 null);
402
403 StateChanged?.Invoke(this, new("Error"));
404 });
405
406 private void OnEnded(object? sender, EventArgs e)
407 {
408 long revision = Volatile.Read(ref _playbackRevision);
409
410 QueueForSource(
411 Volatile.Read(ref _generation),
412 () =>
413 {
414 long generation = _generation;
415 Ended?.Invoke(this, EventArgs.Empty);
416
417 if (!_disposed && _playRequested && generation == _generation && revision == _playbackRevision && Loop)
418 {
419 // Explicit controls, including Stop from an Ended handler, cancel a queued loop.
420 // Never reenter libvlc from its EndReached callback (documented deadlock risk).
421 _player.Stop();
422 _player.Play();
423 }
424 });
425 }
426
427 private uint SetupFormat(
428 ref IntPtr opaque,
429 IntPtr chroma,
430 ref uint width,
431 ref uint height,
432 ref uint pitches,
433 ref uint lines)
434 {
435 try
436 {
437 var buffer = new VideoDecodeBuffer(checked((int)width), checked((int)height), MaximumFramePixels);
438
439 lock (_frames)
440 {
441 _decodeBuffer?.Dispose();
442 _decodeBuffer = buffer;
443 }
444
445 // LibVLC 3 vmem masks: R=0xff0000 G=0xff00 B=0xff. On little endian
446 // RV32 is B,G,R,X (not alpha). Skia uses Bgra8888 + Opaque without swizzling.
447 Marshal.Copy(
448 new byte[] { (byte)'R', (byte)'V', (byte)'3', (byte)'2' },
449 0,
450 chroma,
451 4);
452
453 pitches = (uint)buffer.Stride;
454 lines = (uint)buffer.Lines;
455
456 lock (_frames)
457 _naturalSize = (buffer.Width, buffer.Height);
458
459 return 1;
460 }
461 catch (Exception ex)
462 {
463 Volatile.Write(ref _lastError, ex);
464 return 0;
465 }
466 }
467
468 private IntPtr LockFrame(IntPtr opaque, IntPtr planes)
469 {
470 // vmem serializes lock -> copy -> display for one active video output.
471 // The buffer remains alive until that output's cleanup callback or Stop joins it.
472 lock (_frames)
473 {
474 if (_decodeBuffer is not { } buffer || planes == IntPtr.Zero)
475 return IntPtr.Zero;
476
477 Marshal.WriteIntPtr(planes, buffer.Pixels);
478 }
479
480 return IntPtr.Zero;
481 }
482
483 private void DisplayFrame(IntPtr opaque, IntPtr picture)
484 {
485 try
486 {
487 lock (_frames)
488 {
489 if (!_acceptFrames || _decodeBuffer is not { } buffer)
490 return;
491
492 FrameReady?.Invoke(
493 this,
494 new(
495 buffer.Pixels,
496 buffer.Width,
497 buffer.Height,
498 buffer.Stride,
499 0));
500 }
501 }
502 catch (Exception ex)
503 {
504 Volatile.Write(ref _lastError, ex);
505 }
506 }
507
508 private void CleanupFormat(ref IntPtr opaque)
509 {
510 // LibVLCSharp 3.9.7 passes cleanup straight to native code, unlike its
511 // format/lock/display shims. Its ref IntPtr is NOT our format user data.
512 // Never read/write it. This instance owns the single active vmem output.
513 lock (_frames)
514 {
515 _decodeBuffer?.Dispose();
516 _decodeBuffer = null;
517 }
518 }
519
521 public void Play()
522 {
523 lock (_control)
524 {
525 ThrowIfDisposed();
526 ++_playbackRevision;
527 _playRequested = true;
528 _player.Play();
529 }
530 }
531
533 public void Pause()
534 {
535 lock (_control)
536 {
537 ThrowIfDisposed();
538 ++_playbackRevision;
539 _playRequested = false;
540 _player.SetPause(true);
541 }
542 }
543
545 public void Stop()
546 {
547 lock (_control)
548 {
549 ThrowIfDisposed();
550 ++_playbackRevision;
551 _playRequested = false;
552 _player.Stop();
553 }
554 }
555
557 public void Seek(TimeSpan position)
558 {
559 lock (_control)
560 {
561 ThrowIfDisposed();
562 _player.Time = Math.Max(0, (long)position.TotalMilliseconds);
563 }
564 }
565
567 public void SetRate(double rate)
568 {
569 if (!double.IsFinite(rate) || rate <= 0)
570 throw new ArgumentOutOfRangeException(nameof(rate));
571
572 lock (_control)
573 {
574 ThrowIfDisposed();
575 _player.SetRate((float)rate);
576 }
577 }
578
579 private void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this);
580
581 private void ReleaseMedia()
582 {
583 _playRequested = false;
584 _player.Stop(); // Joins decoder callbacks before media/input/buffer ownership is released.
585
586 lock (_frames)
587 {
588 _decodeBuffer?.Dispose();
589 _decodeBuffer = null;
590 }
591
592 _parseCancellation?.Cancel();
593
594 if (_parseTask is not null)
595 {
596 try
597 {
598 _parseTask.GetAwaiter().GetResult();
599 }
600 catch (OperationCanceledException)
601 {
602 }
603 catch (Exception ex)
604 {
605 Volatile.Write(ref _lastError, ex);
606 }
607 }
608
609 _parseTask = null;
610 _parseCancellation?.Dispose();
611 _parseCancellation = null;
612 _player.Media = null;
613 _media?.Dispose();
614 _media = null;
615 _input?.Dispose();
616 _input = null;
617 _ownedStream?.Dispose();
618 _ownedStream = null;
619 }
620
622 public void Dispose()
623 {
624 lock (_control)
625 {
626 if (_disposed)
627 return;
628
629 _disposed = true;
630 ++_generation;
631
632 lock (_frames)
633 _acceptFrames = false;
634
635 ReleaseMedia();
636 _metadata.Reset();
637 _player.Playing -= OnStarted;
638 _player.Paused -= OnPaused;
639 _player.Stopped -= OnStopped;
640 _player.EndReached -= OnEnded;
641 _player.EncounteredError -= OnError;
642 _player.Dispose();
643 _vlc.Dispose();
644 }
645 }
646}
bool IsMuted
Mutes output without changing the retained volume.
int MaximumFramePixels
Maximum pixels (and aligned RGBA-equivalent storage) per decoded frame. Set before playback.
bool IsPlaying
Gets a value indicating whether the video is currently playing.
bool Loop
Gets or sets a value indicating whether the video should loop when it reaches the end.
void Stop()
Stops the video playback and resets the position.
EventHandler< VideoFrameReadyEventArgs >? FrameReady
bool CanSeek
Whether the current media supports seeking. Legacy backends retain their existing seek behavior.
float Volume
Audible output gain from zero to one. Legacy backends may not support setting it.
EventHandler< VideoStateChangedEventArgs >? StateChanged
bool HasAudio
Gets whether the video has an audio track. Consult IsMetadataReady before interpreting false.
VlcVideoPlayer(string[]? vlcArgs=null, int initialWidth=1280, int initialHeight=720)
Creates a native desktop player. Native libraries are supplied by the application.
void SetRate(double rate)
Sets the playback rate of the video.
void Open(Stream source, bool leaveOpen=false)
Opens a readable stream. Ownership transfers on success unless leaveOpen is true. Keep a borrowed str...
TimeSpan Position
Gets the current playback position in the video.
void Seek(TimeSpan position)
Seeks to the specified position in the video.
void Play()
Starts or resumes playback of the video.
Exception? LastError
The most recent native callback or playback failure, if any.
VideoMetadata Metadata
Gets an atomic snapshot of metadata availability and values for the current source.
void Open(Uri source)
Opens a video from the specified source URI.
TimeSpan Duration
Gets the total duration of the video.
bool IsMetadataReady
True only when metadata for the current source is available.
void Pause()
Pauses the video playback.
bool CanControlAudio
Whether this backend exposes independent volume and mute controls.
Defines the contract for a video player that can play, pause, stop, and seek video content.
VideoMetadataStatus
The availability of metadata for the active source.
@ Failed
Metadata discovery failed.
record VideoMetadata(VideoMetadataStatus Status, bool HasAudio, TimeSpan Duration)
An immutable metadata snapshot. Values are authoritative only when status is Ready.