radek-k / FFMediaToolkit

FFMediaToolkit is a cross-platform video decoder/encoder library for .NET that uses FFmpeg native libraries. It supports video frames extraction, reading stream metadata and creating videos from bitmaps in any format supported by FFmpeg.
MIT License
352 stars 56 forks source link

CallbackOnCollectedDelegate #94

Closed Lua12138 closed 2 years ago

Lua12138 commented 2 years ago

I call the following code through multiple threads:

Task.Run(()=>{
            var options = new MediaOptions();
            options.ShouldLoadStreamsOfType(AVMediaType.AVMEDIA_TYPE_VIDEO);
            options.StreamsToLoad = MediaMode.Video;
            options.DecoderOptions.Add("flags", "low_delay");
            options.DemuxerOptions = new ContainerOptions()
            {
                FlagNoBuffer = true
            };
            var stream = MediaFile.Open(new MyCustomStream(...), options); // real time stream
            while (stream.Video.TryGetNextFrame(out ImageData bitmap)) // <-- this line throws the exception
            {
                doUpdateImage(this.mScreen, bitmap.ToBitmap());
            }
});

In the single-threaded case, this is not a problem. When running from multiple threads at the same time, exceptions like this are thrown

Managed Debugging Assistant 'CallbackOnCollectedDelegate' 
  Message=Managed Debugging Assistant 'CallbackOnCollectedDelegate' : 'A callback was made on a garbage collected delegate of type 'FFmpeg.AutoGen!FFmpeg.AutoGen.avio_alloc_context_read_packet::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.'

Is this due to my misuse, or is FFMediaToolkit not capable of being used in a multi-threaded environment?

ptrace commented 2 years ago

I am also experiencing issues in a multithreaded application