Skip to content

Extremely slow initialization under the pressure #580

@snechaev

Description

@snechaev

Environment

  • Package versions:
        <PackageReference Include="FFMpegCore" Version="5.2.0" />
        <PackageReference Include="Instances" Version="3.0.2" />
    
  • Net version: 9.0.305
  • Target framework: net8.0
  • OS: Win11
  • ffmpeg version: 7.1.1-full_build-www.gyan.dev

Steps

  • Paste the following code snippet into the empty console application. Avoid calling any members of FFMpegCore before this code to prevent static members initialization.

    In this code we emulate the "high" load immediately after the app start.

    using System.Diagnostics;
    using System.Reflection;
    using FFMpegCore;
    using FFMpegCore.Enums;
    
    var dllPath = Assembly.GetExecutingAssembly().Location;
    var dllDir = Path.GetDirectoryName(dllPath)!;
    var binDir = Path.Combine(dllDir, "ffmpeg", "Windows");
    
    GlobalFFOptions.Configure(options =>
    {
        options.BinaryFolder = binDir;
        options.UseCache = true;
    });
    
    var tcs = new TaskCompletionSource<bool>();
    var startSignal = tcs.Task;
    
    //var warmUp = VideoType.Mp4; // <-------------------- uncomment me!!!
    var tasks = Enumerable.Range(0, 20).Select(_ => Task.Run(async () =>
    {
        await startSignal;
        return VideoType.Mp4;
    })).ToList();
    
    var sw = Stopwatch.StartNew();
    tcs.SetResult(true);
    var res = await Task.WhenAll(tasks);
    sw.Stop();
    
    for (var index = 0; index < res.Length; index++)
    {
        var format = res[index];
        Console.WriteLine($"{index} - {format.Extension}");
    }
    Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms");
  • run app and check the time.

In my system this gives Elapsed: 17329ms

Uncomment the line var warmUp = VideoType.Mp4; and run again. I got Elapsed: 2ms

So, when we starting several ffmpeg-related tasks simultaneously, the initialization slows down drastically - x8600 slower.

Workaround

Perform manual initialization of the static members explicitly in the single-threaded mode before running any concurrent tasks. Call this from main thread.

  var warmUp = VideoType.Mp4; 

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions