Skip to content

Commit 1ad638f

Browse files
committed
Media: Internally keep a reference to the last set Media
libvlc_media_player_get_media increments the ref count of the media, which may easily cause a memory leak, as this is very unusual behavior for C# property getter to have these types of consequences. Users don't have the reflex to dispose every Media returned by the getter property. Holding a ref internally in the mediaplayer prevents from incrementing the native ref count of the media object. https://code.videolan.org/videolan/LibVLCSharp/-/issues/442
1 parent d6b4e2b commit 1ad638f

File tree

1 file changed

+20
-8
lines changed

1 file changed

+20
-8
lines changed

src/LibVLCSharp/Shared/MediaPlayer.cs

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,6 @@ readonly struct Native
3434
internal static extern void LibVLCMediaPlayerSetMedia(IntPtr mediaPlayer, IntPtr media);
3535

3636

37-
[DllImport(Constants.LibraryName, CallingConvention = CallingConvention.Cdecl,
38-
EntryPoint = "libvlc_media_player_get_media")]
39-
internal static extern IntPtr LibVLCMediaPlayerGetMedia(IntPtr mediaPlayer);
40-
41-
4237
[DllImport(Constants.LibraryName, CallingConvention = CallingConvention.Cdecl,
4338
EntryPoint = "libvlc_media_player_event_manager")]
4439
internal static extern IntPtr LibVLCMediaPlayerEventManager(IntPtr mediaPlayer);
@@ -623,8 +618,11 @@ public MediaPlayer(Media media)
623618
: base(() => Native.LibVLCMediaPlayerNewFromMedia(media.NativeReference), Native.LibVLCMediaPlayerRelease)
624619
{
625620
_gcHandle = GCHandle.Alloc(this);
621+
_media = media;
626622
}
627623

624+
Media? _media;
625+
628626
/// <summary>
629627
/// Get the media used by the media_player.
630628
/// Set the media that will be used by the media_player.
@@ -635,10 +633,19 @@ public Media? Media
635633
{
636634
get
637635
{
638-
var mediaPtr = Native.LibVLCMediaPlayerGetMedia(NativeReference);
639-
return mediaPtr == IntPtr.Zero ? null : new Media(mediaPtr);
636+
return _media;
637+
}
638+
set
639+
{
640+
if(_media?.NativeReference != IntPtr.Zero)
641+
{
642+
_media?.Dispose();
643+
_media = null;
644+
}
645+
646+
_media = value;
647+
Native.LibVLCMediaPlayerSetMedia(NativeReference, value?.NativeReference ?? IntPtr.Zero);
640648
}
641-
set => Native.LibVLCMediaPlayerSetMedia(NativeReference, value?.NativeReference ?? IntPtr.Zero);
642649
}
643650

644651
/// <summary>
@@ -2408,6 +2415,11 @@ protected override void Dispose(bool disposing)
24082415
{
24092416
if (_gcHandle.IsAllocated)
24102417
_gcHandle.Free();
2418+
if (_media?.NativeReference != IntPtr.Zero)
2419+
{
2420+
_media?.Dispose();
2421+
_media = null;
2422+
}
24112423
}
24122424

24132425
base.Dispose(disposing);

0 commit comments

Comments
 (0)