FFmpegBinariesHelper.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. var libraryPath = "";
  12. switch (Environment.OSVersion.Platform)
  13. {
  14. case PlatformID.Win32NT:
  15. case PlatformID.Win32S:
  16. case PlatformID.Win32Windows:
  17. var current = Environment.CurrentDirectory;
  18. var probe = Path.Combine(Environment.Is64BitProcess ? "x64" : "x86");
  19. while (current != null)
  20. {
  21. var 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. 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. [DllImport("kernel32", SetLastError = true)]
  62. private static extern bool SetDllDirectory(string lpPathName);
  63. }
  64. }