/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#ifndef OPENCV_CUDAOPTFLOW_HPP
#define OPENCV_CUDAOPTFLOW_HPP

#ifndef __cplusplus
#  error cudaoptflow.hpp header must be compiled as C++
#endif

#include "opencv2/core/cuda.hpp"

/**
  @addtogroup cuda
  @{
    @defgroup cudaoptflow Optical Flow
  @}
 */

namespace cv { namespace cuda {

//! @addtogroup cudaoptflow
//! @{

//
// Interface
//

/** @brief Base interface for dense optical flow algorithms.
 */
class CV_EXPORTS_W DenseOpticalFlow : public Algorithm
{
public:
    /** @brief Calculates a dense optical flow.

    @param I0 first input image.
    @param I1 second input image of the same size and the same type as I0.
    @param flow computed flow image that has the same size as I0 and type CV_32FC2.
    @param stream Stream for the asynchronous version.
     */
    CV_WRAP virtual void calc(InputArray I0, InputArray I1, InputOutputArray flow, Stream& stream = Stream::Null()) = 0;
};

/** @brief Base interface for sparse optical flow algorithms.
 */
class CV_EXPORTS_W SparseOpticalFlow : public Algorithm
{
public:
    /** @brief Calculates a sparse optical flow.

    @param prevImg First input image.
    @param nextImg Second input image of the same size and the same type as prevImg.
    @param prevPts Vector of 2D points for which the flow needs to be found.
    @param nextPts Output vector of 2D points containing the calculated new positions of input features in the second image.
    @param status Output status vector. Each element of the vector is set to 1 if the
                  flow for the corresponding features has been found. Otherwise, it is set to 0.
    @param err Optional output vector that contains error response for each point (inverse confidence).
    @param stream Stream for the asynchronous version.
     */
    CV_WRAP virtual void calc(InputArray prevImg, InputArray nextImg,
                      InputArray prevPts, InputOutputArray nextPts,
                      OutputArray status,
                      OutputArray err = cv::noArray(),
                      Stream& stream = Stream::Null()) = 0;
};
/** @brief Base Interface for optical flow algorithms using NVIDIA Optical Flow SDK.
 */
class CV_EXPORTS_W NvidiaHWOpticalFlow : public Algorithm
{
public:
    /** @brief Calculates Optical Flow using NVIDIA Optical Flow SDK.

    * NVIDIA GPUs starting with Turing contain a dedicated hardware accelerator for computing optical flow vectors between pairs of images.
    * The optical flow hardware accelerator generates block-based optical flow vectors.
    * The size of the block depends on hardware in use, and can be queried using the function getGridSize().
    * The block-based flow vectors generated by the hardware can be converted to dense representation (i.e. per-pixel flow vectors) using upSampler() helper function, if needed.
    * The flow vectors are stored in CV_16SC2 format with x and y components of each flow vector in 16-bit signed fixed point representation S10.5.

    @param inputImage Input image.
    @param referenceImage Reference image of the same size and the same type as input image.
    @param flow A buffer consisting of inputImage.Size() / getGridSize() flow vectors in CV_16SC2 format.
    @param stream It is highly recommended that CUDA streams for pre and post processing of optical flow vectors should be set once per session in create() function as a part of optical flow session creation.
                  This parameter is left here for backward compatibility and may be removed in the future.
                  Default value is NULL stream;
    @param hint Hint buffer if client provides external hints. Must have same size as flow buffer.
                Caller can provide flow vectors as hints for optical flow calculation.
    @param cost Cost buffer contains numbers indicating the confidence associated with each of the generated flow vectors.
                Higher the cost, lower the confidence. Cost buffer is of type CV_32SC1.

    @note
    - Client must use critical sections around each calc() function if calling it from multiple threads.
    */
    CV_WRAP virtual void calc(
        InputArray inputImage,
        InputArray referenceImage,
        InputOutputArray flow,
        Stream& stream = Stream::Null(),
        InputArray hint = cv::noArray(),
        OutputArray cost = cv::noArray()) = 0;

    /** @brief Releases all buffers, contexts and device pointers.
    */
    CV_WRAP virtual void collectGarbage() = 0;

    /** @brief Returns grid size of output buffer as per the hardware's capability.
    */
    CV_WRAP virtual int getGridSize() const = 0;
};

//
// BroxOpticalFlow
//

/** @brief Class computing the optical flow for two images using Brox et al Optical Flow algorithm (@cite Brox2004).
 */
class CV_EXPORTS_W BroxOpticalFlow : public DenseOpticalFlow
{
public:
    CV_WRAP virtual double getFlowSmoothness() const = 0;
    CV_WRAP virtual void setFlowSmoothness(double alpha) = 0;

    CV_WRAP virtual double getGradientConstancyImportance() const = 0;
    CV_WRAP virtual void setGradientConstancyImportance(double gamma) = 0;

    CV_WRAP virtual double getPyramidScaleFactor() const = 0;
    CV_WRAP virtual void setPyramidScaleFactor(double scale_factor) = 0;

    //! number of lagged non-linearity iterations (inner loop)
    CV_WRAP virtual int getInnerIterations() const = 0;
    CV_WRAP virtual void setInnerIterations(int inner_iterations) = 0;

    //! number of warping iterations (number of pyramid levels)
    CV_WRAP virtual int getOuterIterations() const = 0;
    CV_WRAP virtual void setOuterIterations(int outer_iterations) = 0;

    //! number of linear system solver iterations
    CV_WRAP virtual int getSolverIterations() const = 0;
    CV_WRAP virtual void setSolverIterations(int solver_iterations) = 0;

    CV_WRAP static Ptr<BroxOpticalFlow> create(
            double alpha = 0.197,
            double gamma = 50.0,
            double scale_factor = 0.8,
            int inner_iterations = 5,
            int outer_iterations = 150,
            int solver_iterations = 10);
};

//
// PyrLKOpticalFlow
//

/** @brief Class used for calculating a sparse optical flow.

The class can calculate an optical flow for a sparse feature set using the
iterative Lucas-Kanade method with pyramids.

@sa calcOpticalFlowPyrLK

@note
   -   An example of the Lucas Kanade optical flow algorithm can be found at
        opencv_source_code/samples/gpu/pyrlk_optical_flow.cpp
 */
class CV_EXPORTS_W SparsePyrLKOpticalFlow : public SparseOpticalFlow
{
public:
    CV_WRAP virtual Size getWinSize() const = 0;
    CV_WRAP virtual void setWinSize(Size winSize) = 0;

    CV_WRAP virtual int getMaxLevel() const = 0;
    CV_WRAP virtual void setMaxLevel(int maxLevel) = 0;

    CV_WRAP virtual int getNumIters() const = 0;
    CV_WRAP virtual void setNumIters(int iters) = 0;

    CV_WRAP virtual bool getUseInitialFlow() const = 0;
    CV_WRAP virtual void setUseInitialFlow(bool useInitialFlow) = 0;

    CV_WRAP static Ptr<cuda::SparsePyrLKOpticalFlow> create(
            Size winSize = Size(21, 21),
            int maxLevel = 3,
            int iters = 30,
            bool useInitialFlow = false);
};

/** @brief Class used for calculating a dense optical flow.

The class can calculate an optical flow for a dense optical flow using the
iterative Lucas-Kanade method with pyramids.
 */
class CV_EXPORTS_W DensePyrLKOpticalFlow : public DenseOpticalFlow
{
public:
    CV_WRAP virtual Size getWinSize() const = 0;
    CV_WRAP virtual void setWinSize(Size winSize) = 0;

    CV_WRAP virtual int getMaxLevel() const = 0;
    CV_WRAP virtual void setMaxLevel(int maxLevel) = 0;

    CV_WRAP virtual int getNumIters() const = 0;
    CV_WRAP virtual void setNumIters(int iters) = 0;

    CV_WRAP virtual bool getUseInitialFlow() const = 0;
    CV_WRAP virtual void setUseInitialFlow(bool useInitialFlow) = 0;

    CV_WRAP static Ptr<DensePyrLKOpticalFlow> create(
            Size winSize = Size(13, 13),
            int maxLevel = 3,
            int iters = 30,
            bool useInitialFlow = false);
};

//
// FarnebackOpticalFlow
//

/** @brief Class computing a dense optical flow using the Gunnar Farneback's algorithm.
 */
class CV_EXPORTS_W FarnebackOpticalFlow : public DenseOpticalFlow
{
public:
    CV_WRAP virtual int getNumLevels() const = 0;
    CV_WRAP virtual void setNumLevels(int numLevels) = 0;

    CV_WRAP virtual double getPyrScale() const = 0;
    CV_WRAP virtual void setPyrScale(double pyrScale) = 0;

    CV_WRAP virtual bool getFastPyramids() const = 0;
    CV_WRAP virtual void setFastPyramids(bool fastPyramids) = 0;

    CV_WRAP virtual int getWinSize() const = 0;
    CV_WRAP virtual void setWinSize(int winSize) = 0;

    CV_WRAP virtual int getNumIters() const = 0;
    CV_WRAP virtual void setNumIters(int numIters) = 0;

    CV_WRAP virtual int getPolyN() const = 0;
    CV_WRAP virtual void setPolyN(int polyN) = 0;

    CV_WRAP virtual double getPolySigma() const = 0;
    CV_WRAP virtual void setPolySigma(double polySigma) = 0;

    CV_WRAP virtual int getFlags() const = 0;
    CV_WRAP virtual void setFlags(int flags) = 0;

    CV_WRAP static Ptr<cuda::FarnebackOpticalFlow> create(
            int numLevels = 5,
            double pyrScale = 0.5,
            bool fastPyramids = false,
            int winSize = 13,
            int numIters = 10,
            int polyN = 5,
            double polySigma = 1.1,
            int flags = 0);
};

//
// OpticalFlowDual_TVL1
//

/** @brief Implementation of the Zach, Pock and Bischof Dual TV-L1 Optical Flow method.
 *
 * @note C. Zach, T. Pock and H. Bischof, "A Duality Based Approach for Realtime TV-L1 Optical Flow".
 * @note Javier Sanchez, Enric Meinhardt-Llopis and Gabriele Facciolo. "TV-L1 Optical Flow Estimation".
 */
class CV_EXPORTS_W OpticalFlowDual_TVL1 : public DenseOpticalFlow
{
public:
    /**
     * Time step of the numerical scheme.
     */
    CV_WRAP virtual double getTau() const = 0;
    CV_WRAP virtual void setTau(double tau) = 0;

    /**
     * Weight parameter for the data term, attachment parameter.
     * This is the most relevant parameter, which determines the smoothness of the output.
     * The smaller this parameter is, the smoother the solutions we obtain.
     * It depends on the range of motions of the images, so its value should be adapted to each image sequence.
     */
    CV_WRAP virtual double getLambda() const = 0;
    CV_WRAP virtual void setLambda(double lambda) = 0;

    /**
     * Weight parameter for (u - v)^2, tightness parameter.
     * It serves as a link between the attachment and the regularization terms.
     * In theory, it should have a small value in order to maintain both parts in correspondence.
     * The method is stable for a large range of values of this parameter.
     */
    CV_WRAP virtual double getGamma() const = 0;
    CV_WRAP virtual void setGamma(double gamma) = 0;

    /**
     * parameter used for motion estimation. It adds a variable allowing for illumination variations
     * Set this parameter to 1. if you have varying illumination.
     * See: Chambolle et al, A First-Order Primal-Dual Algorithm for Convex Problems with Applications to Imaging
     * Journal of Mathematical imaging and vision, may 2011 Vol 40 issue 1, pp 120-145
     */
    CV_WRAP virtual double getTheta() const = 0;
    CV_WRAP virtual void setTheta(double theta) = 0;

    /**
     * Number of scales used to create the pyramid of images.
     */
    CV_WRAP virtual int getNumScales() const = 0;
    CV_WRAP virtual void setNumScales(int nscales) = 0;

    /**
     * Number of warpings per scale.
     * Represents the number of times that I1(x+u0) and grad( I1(x+u0) ) are computed per scale.
     * This is a parameter that assures the stability of the method.
     * It also affects the running time, so it is a compromise between speed and accuracy.
     */
    CV_WRAP virtual int getNumWarps() const = 0;
    CV_WRAP virtual void setNumWarps(int warps) = 0;

    /**
     * Stopping criterion threshold used in the numerical scheme, which is a trade-off between precision and running time.
     * A small value will yield more accurate solutions at the expense of a slower convergence.
     */
    CV_WRAP virtual double getEpsilon() const = 0;
    CV_WRAP virtual void setEpsilon(double epsilon) = 0;

    /**
     * Stopping criterion iterations number used in the numerical scheme.
     */
    CV_WRAP virtual int getNumIterations() const = 0;
    CV_WRAP virtual void setNumIterations(int iterations) = 0;

    CV_WRAP virtual double getScaleStep() const = 0;
    CV_WRAP virtual void setScaleStep(double scaleStep) = 0;

    CV_WRAP virtual bool getUseInitialFlow() const = 0;
    CV_WRAP virtual void setUseInitialFlow(bool useInitialFlow) = 0;

    CV_WRAP static Ptr<OpticalFlowDual_TVL1> create(
            double tau = 0.25,
            double lambda = 0.15,
            double theta = 0.3,
            int nscales = 5,
            int warps = 5,
            double epsilon = 0.01,
            int iterations = 300,
            double scaleStep = 0.8,
            double gamma = 0.0,
            bool useInitialFlow = false);
};

//
// NvidiaOpticalFlow
//

/** @brief Class for computing the optical flow vectors between two images using NVIDIA Optical Flow hardware and Optical Flow SDK 1.0.
@note
- A sample application demonstrating the use of NVIDIA Optical Flow can be found at
opencv_source_code/samples/gpu/nvidia_optical_flow.cpp
- An example application comparing accuracy and performance of NVIDIA Optical Flow with other optical flow algorithms in OpenCV can be found at
opencv_source_code/samples/gpu/optical_flow.cpp
*/

class CV_EXPORTS_W NvidiaOpticalFlow_1_0 : public NvidiaHWOpticalFlow
{
public:
    /**
    * Supported optical flow performance levels.
    */
    enum NVIDIA_OF_PERF_LEVEL
    {
        NV_OF_PERF_LEVEL_UNDEFINED,
        NV_OF_PERF_LEVEL_SLOW = 5,                   /**< Slow perf level results in lowest performance and best quality */
        NV_OF_PERF_LEVEL_MEDIUM = 10,                /**< Medium perf level results in low performance and medium quality */
        NV_OF_PERF_LEVEL_FAST = 20,                  /**< Fast perf level results in high performance and low quality */
        NV_OF_PERF_LEVEL_MAX
    };

    /** @brief The NVIDIA optical flow hardware generates flow vectors at granularity gridSize, which can be queried via function getGridSize().
    * Upsampler() helper function converts the hardware-generated flow vectors to dense representation (1 flow vector for each pixel)
    * using nearest neighbour upsampling method.

    @param flow Buffer of type CV_16FC2 containing flow vectors generated by calc().
    @param width Width of the input image in pixels for which these flow vectors were generated.
    @param height Height of the input image in pixels for which these flow vectors were generated.
    @param gridSize Granularity of the optical flow vectors returned by calc() function. Can be queried using getGridSize().
    @param upsampledFlow Buffer of type CV_32FC2, containing upsampled flow vectors, each flow vector for 1 pixel, in the pitch-linear layout.
    */
    CV_WRAP virtual void upSampler(InputArray flow, int width, int height,
        int gridSize, InputOutputArray upsampledFlow) = 0;

    /** @brief Instantiate NVIDIA Optical Flow

    @param width Width of input image in pixels.
    @param height Height of input image in pixels.
    @param perfPreset Optional parameter. Refer [NV OF SDK documentation](https://developer.nvidia.com/opticalflow-sdk) for details about presets.
                      Defaults to NV_OF_PERF_LEVEL_SLOW.
    @param enableTemporalHints Optional parameter. Flag to enable temporal hints. When set to true, the hardware uses the flow vectors
                               generated in previous call to calc() as internal hints for the current call to calc().
                               Useful when computing flow vectors between successive video frames. Defaults to false.
    @param enableExternalHints Optional Parameter. Flag to enable passing external hints buffer to calc(). Defaults to false.
    @param enableCostBuffer Optional Parameter. Flag to enable cost buffer output from calc(). Defaults to false.
    @param gpuId Optional parameter to select the GPU ID on which the optical flow should be computed. Useful in multi-GPU systems. Defaults to 0.
    @param inputStream Optical flow algorithm may optionally involve cuda preprocessing on the input buffers.
                       The input cuda stream can be used to pipeline and synchronize the cuda preprocessing tasks with OF HW engine.
                       If input stream is not set, the execute function will use default stream which is NULL stream;
    @param outputStream Optical flow algorithm may optionally involve cuda post processing on the output flow vectors.
                        The output cuda stream can be used to pipeline and synchronize the cuda post processing tasks with OF HW engine.
                        If output stream is not set, the execute function will use default stream which is NULL stream;
    */
    CV_WRAP static Ptr<NvidiaOpticalFlow_1_0> create(
        int width,
        int height,
        cv::cuda::NvidiaOpticalFlow_1_0::NVIDIA_OF_PERF_LEVEL perfPreset
        = cv::cuda::NvidiaOpticalFlow_1_0::NVIDIA_OF_PERF_LEVEL::NV_OF_PERF_LEVEL_SLOW,
        bool enableTemporalHints = false,
        bool enableExternalHints = false,
        bool enableCostBuffer = false,
        int gpuId = 0,
        Stream& inputStream = Stream::Null(),
        Stream& outputStream = Stream::Null());
};

//! @}

}} // namespace cv { namespace cuda {

#endif /* OPENCV_CUDAOPTFLOW_HPP */
