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.vision;
006
007import edu.wpi.first.cameraserver.CameraServerSharedStore;
008import edu.wpi.first.cscore.CvSink;
009import edu.wpi.first.cscore.VideoSource;
010import org.opencv.core.Mat;
011
012/**
013 * A vision runner is a convenient wrapper object to make it easy to run vision pipelines from robot
014 * code. The easiest way to use this is to run it in a {@link VisionThread} and use the listener to
015 * take snapshots of the pipeline's outputs.
016 *
017 * @see VisionPipeline
018 * @see VisionThread
019 * @see <a href="package-summary.html">vision</a>
020 */
021public class VisionRunner<P extends VisionPipeline> {
022  private final CvSink m_cvSink = new CvSink("VisionRunner CvSink");
023  private final P m_pipeline;
024  private final Mat m_image = new Mat();
025  private final Listener<? super P> m_listener;
026  private volatile boolean m_enabled = true;
027
028  /**
029   * Listener interface for a callback that should run after a pipeline has processed its input.
030   *
031   * @param <P> the type of the pipeline this listener is for
032   */
033  @FunctionalInterface
034  public interface Listener<P extends VisionPipeline> {
035    /**
036     * Called when the pipeline has run. This shouldn't take much time to run because it will delay
037     * later calls to the pipeline's {@link VisionPipeline#process process} method. Copying the
038     * outputs and code that uses the copies should be <i>synchronized</i> on the same mutex to
039     * prevent multiple threads from reading and writing to the same memory at the same time.
040     *
041     * @param pipeline the vision pipeline that ran
042     */
043    void copyPipelineOutputs(P pipeline);
044  }
045
046  /**
047   * Creates a new vision runner. It will take images from the {@code videoSource}, send them to the
048   * {@code pipeline}, and call the {@code listener} when the pipeline has finished to alert user
049   * code when it is safe to access the pipeline's outputs.
050   *
051   * @param videoSource the video source to use to supply images for the pipeline
052   * @param pipeline the vision pipeline to run
053   * @param listener a function to call after the pipeline has finished running
054   */
055  public VisionRunner(VideoSource videoSource, P pipeline, Listener<? super P> listener) {
056    this.m_pipeline = pipeline;
057    this.m_listener = listener;
058    m_cvSink.setSource(videoSource);
059  }
060
061  /**
062   * Runs the pipeline one time, giving it the next image from the video source specified in the
063   * constructor. This will block until the source either has an image or throws an error. If the
064   * source successfully supplied a frame, the pipeline's image input will be set, the pipeline will
065   * run, and the listener specified in the constructor will be called to notify it that the
066   * pipeline ran.
067   *
068   * <p>This method is exposed to allow teams to add additional functionality or have their own ways
069   * to run the pipeline. Most teams, however, should just use {@link #runForever} in its own thread
070   * using a {@link VisionThread}.
071   */
072  public void runOnce() {
073    Long id = CameraServerSharedStore.getCameraServerShared().getRobotMainThreadId();
074
075    if (id != null && Thread.currentThread().getId() == id) {
076      throw new IllegalStateException(
077          "VisionRunner.runOnce() cannot be called from the main robot thread");
078    }
079    runOnceInternal();
080  }
081
082  private void runOnceInternal() {
083    long frameTime = m_cvSink.grabFrame(m_image);
084    if (frameTime == 0) {
085      // There was an error, report it
086      String error = m_cvSink.getError();
087      CameraServerSharedStore.getCameraServerShared().reportDriverStationError(error);
088    } else {
089      // No errors, process the image
090      m_pipeline.process(m_image);
091      m_listener.copyPipelineOutputs(m_pipeline);
092    }
093  }
094
095  /**
096   * A convenience method that calls {@link #runOnce()} in an infinite loop. This must be run in a
097   * dedicated thread, and cannot be used in the main robot thread because it will freeze the robot
098   * program.
099   *
100   * <p><strong>Do not call this method directly from the main thread.</strong>
101   *
102   * @throws IllegalStateException if this is called from the main robot thread
103   * @see VisionThread
104   */
105  public void runForever() {
106    Long id = CameraServerSharedStore.getCameraServerShared().getRobotMainThreadId();
107
108    if (id != null && Thread.currentThread().getId() == id) {
109      throw new IllegalStateException(
110          "VisionRunner.runForever() cannot be called from the main robot thread");
111    }
112    while (m_enabled && !Thread.interrupted()) {
113      runOnceInternal();
114    }
115  }
116
117  /** Stop a RunForever() loop. */
118  public void stop() {
119    m_enabled = false;
120  }
121}