001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.cscore;
006
007import edu.wpi.first.util.RuntimeLoader;
008import java.io.IOException;
009import java.util.concurrent.atomic.AtomicBoolean;
010import org.opencv.core.Core;
011
012/** OpenCV Native Loader. */
013public final class OpenCvLoader {
014  @SuppressWarnings("PMD.MutableStaticState")
015  static boolean libraryLoaded;
016
017  @SuppressWarnings("PMD.MutableStaticState")
018  static RuntimeLoader<Core> loader;
019
020  /** Sets whether JNI should be loaded in the static block. */
021  public static class Helper {
022    private static AtomicBoolean extractOnStaticLoad = new AtomicBoolean(true);
023
024    /**
025     * Returns true if the JNI should be loaded in the static block.
026     *
027     * @return True if the JNI should be loaded in the static block.
028     */
029    public static boolean getExtractOnStaticLoad() {
030      return extractOnStaticLoad.get();
031    }
032
033    /**
034     * Sets whether the JNI should be loaded in the static block.
035     *
036     * @param load Whether the JNI should be loaded in the static block.
037     */
038    public static void setExtractOnStaticLoad(boolean load) {
039      extractOnStaticLoad.set(load);
040    }
041
042    /** Utility class. */
043    private Helper() {}
044  }
045
046  static {
047    String opencvName = Core.NATIVE_LIBRARY_NAME;
048    if (Helper.getExtractOnStaticLoad()) {
049      try {
050        loader =
051            new RuntimeLoader<>(opencvName, RuntimeLoader.getDefaultExtractionRoot(), Core.class);
052        loader.loadLibraryHashed();
053      } catch (IOException ex) {
054        ex.printStackTrace();
055        System.exit(1);
056      }
057      libraryLoaded = true;
058    }
059  }
060
061  /**
062   * Forces a static load.
063   *
064   * @return a garbage value
065   */
066  public static int forceStaticLoad() {
067    return libraryLoaded ? 1 : 0;
068  }
069
070  /**
071   * Force load the library.
072   *
073   * @throws IOException if library load failed
074   */
075  public static synchronized void forceLoad() throws IOException {
076    if (libraryLoaded) {
077      return;
078    }
079    loader =
080        new RuntimeLoader<>(
081            Core.NATIVE_LIBRARY_NAME, RuntimeLoader.getDefaultExtractionRoot(), Core.class);
082    loader.loadLibrary();
083    libraryLoaded = true;
084  }
085
086  /** Utility class. */
087  private OpenCvLoader() {}
088}