/* static */ bool
FFVPXRuntimeLinker::Init()
{
  if (sLinkStatus) {
    return sLinkStatus == LinkStatus_SUCCEEDED;
  }

  MOZ_ASSERT(NS_IsMainThread());
  sLinkStatus = LinkStatus_FAILED;

  // We retrieve the path of the lgpllibs library as this is where mozavcodec
  // and mozavutil libs are located.
  PathString lgpllibsname = GetLibraryName(nullptr, "lgpllibs");
  if (lgpllibsname.IsEmpty()) {
    return false;
  }
  PathString path =
    GetLibraryFilePathname(lgpllibsname.get(),
                           (PRFuncPtr)&soundtouch::SoundTouch::getVersionId);
  if (path.IsEmpty()) {
    return false;
  }
  RefPtr<nsLocalFile> xulFile = new nsLocalFile(path);
  if (xulFile->NativePath().IsEmpty()) {
    return false;
  }

  nsCOMPtr<nsIFile> rootDir;
  if (NS_FAILED(xulFile->GetParent(getter_AddRefs(rootDir))) || !rootDir) {
    return false;
  }
  PathString rootPath = rootDir->NativePath();

  /* Get the platform-dependent library name of the module */
  PathString libname = GetLibraryName(rootPath.get(), "mozavutil");
  if (libname.IsEmpty()) {
    return false;
  }
  RefPtr<nsLocalFile> libFile = new nsLocalFile(libname);
  if (libFile->NativePath().IsEmpty()) {
    return false;
  }
  sFFVPXLib.mAVUtilLib = MozAVLink(libFile);
  libname = GetLibraryName(rootPath.get(), "mozavcodec");
  if (!libname.IsEmpty()) {
    libFile = new nsLocalFile(libname);
    if (!libFile->NativePath().IsEmpty()) {
      sFFVPXLib.mAVCodecLib = MozAVLink(libFile);
    }
  }
  if (sFFVPXLib.Link() == FFmpegLibWrapper::LinkResult::Success) {
    sLinkStatus = LinkStatus_SUCCEEDED;
    return true;
  }
  return false;
}
static PRLibrary*
MozAVLink(nsIFile* aFile)
{
  PRLibSpec lspec;
  PathString path = aFile->NativePath();
#ifdef XP_WIN
  lspec.type = PR_LibSpec_PathnameU;
  lspec.value.pathname_u = path.get();
#else
  lspec.type = PR_LibSpec_Pathname;
  lspec.value.pathname = path.get();
#endif
#ifdef MOZ_WIDGET_ANDROID
  PRLibrary* lib = PR_LoadLibraryWithFlags(lspec, PR_LD_NOW | PR_LD_GLOBAL);
#else
  PRLibrary* lib = PR_LoadLibraryWithFlags(lspec, PR_LD_NOW | PR_LD_LOCAL);
#endif
  if (!lib) {
    FFMPEG_LOG("unable to load library %s", aFile->HumanReadablePath().get());
  }
  return lib;
}