FFmpegBinariesHelper.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. namespace FFmpeg.AutoGen.Example
  5. {
  6. public class FFmpegBinariesHelper
  7. {
  8. private const string LD_LIBRARY_PATH = "LD_LIBRARY_PATH";
  9. public static void RegisterFFmpegBinaries()
  10. {
  11. string libraryPath = "";
  12. switch (Environment.OSVersion.Platform)
  13. {
  14. case PlatformID.Win32NT:
  15. case PlatformID.Win32S:
  16. case PlatformID.Win32Windows:
  17. string current = Environment.CurrentDirectory;
  18. string probe = Path.Combine(Environment.Is64BitProcess ? "x64" : "x86");
  19. while (current != null)
  20. {
  21. string ffmpegDirectory = Path.Combine(current, probe);
  22. if (Directory.Exists(ffmpegDirectory))
  23. {
  24. Console.WriteLine($"FFmpeg binaries found in: {ffmpegDirectory}");
  25. RegisterLibrariesSearchPath(ffmpegDirectory);
  26. return;
  27. }
  28. current = Directory.GetParent(current)?.FullName;
  29. }
  30. break;
  31. case PlatformID.Unix:
  32. libraryPath = "/usr/lib/x86_64-linux-gnu";
  33. RegisterLibrariesSearchPath(libraryPath);
  34. break;
  35. case PlatformID.MacOSX:
  36. libraryPath = Environment.GetEnvironmentVariable(LD_LIBRARY_PATH);
  37. RegisterLibrariesSearchPath(libraryPath);
  38. break;
  39. }
  40. }
  41. private static void RegisterLibrariesSearchPath(string path)
  42. {
  43. switch (Environment.OSVersion.Platform)
  44. {
  45. case PlatformID.Win32NT:
  46. case PlatformID.Win32S:
  47. case PlatformID.Win32Windows:
  48. NativeMethods.SetDllDirectory(path);
  49. break;
  50. case PlatformID.Unix:
  51. case PlatformID.MacOSX:
  52. string currentValue = Environment.GetEnvironmentVariable(LD_LIBRARY_PATH);
  53. if (string.IsNullOrWhiteSpace(currentValue) == false && currentValue.Contains(path) == false)
  54. {
  55. string newValue = currentValue + Path.PathSeparator + path;
  56. Environment.SetEnvironmentVariable(LD_LIBRARY_PATH, newValue);
  57. }
  58. break;
  59. }
  60. }
  61. internal static class NativeMethods
  62. {
  63. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  64. [return: MarshalAs(UnmanagedType.Bool)]
  65. internal static extern bool SetDllDirectory(string lpPathName);
  66. }
  67. }
  68. }