FFmpegBinariesHelper.cs 3.3 KB

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