fft.cpp 11.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/*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) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
//    Peng Xiao, pengxiao@multicorewareinc.com
//
// 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 oclMaterials 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*/
#include <iomanip>
#include "precomp.hpp"

using namespace cv;
using namespace cv::ocl;
using namespace std;

52
#if !defined HAVE_CLAMDFFT
53
void cv::ocl::dft(const oclMat&, oclMat&, Size, int)
Niko's avatar
Niko committed
54 55 56
{
    CV_Error(CV_StsNotImplemented, "OpenCL DFT is not implemented");
}
57
namespace cv { namespace ocl {
58
    void fft_teardown();
59
}}
60
void cv::ocl::fft_teardown(){}
61
#else
62
#include "clAmdFft.h"
63 64 65
namespace cv
{
    namespace ocl
66
    {
67 68
        void fft_setup();
        void fft_teardown();
69 70 71 72 73 74 75 76 77
        enum FftType
        {
            C2R = 1, // complex to complex
            R2C = 2, // real to opencl HERMITIAN_INTERLEAVED
            C2C = 3  // opencl HERMITIAN_INTERLEAVED to real
        };
        struct FftPlan
        {
        protected:
78 79 80
            clAmdFftPlanHandle plHandle;
            FftPlan& operator=(const FftPlan&);
        public:
81
            FftPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type);
82 83 84
            ~FftPlan();
            inline clAmdFftPlanHandle getPlanHandle() { return plHandle; }

85 86 87 88
            const Size dft_size;
            const int src_step, dst_step;
            const int flags;
            const FftType type;
89 90 91 92 93 94 95 96 97 98 99 100
        };
        class PlanCache
        {
        protected:
            PlanCache();
            ~PlanCache();
            friend class auto_ptr<PlanCache>;
            static auto_ptr<PlanCache> planCache;

            bool started;
            vector<FftPlan *> planStore;
            clAmdFftSetupData *setupData;
101
        public:
102 103 104 105 106 107 108 109 110
            friend void fft_setup();
            friend void fft_teardown();

            static PlanCache* getPlanCache()
            {
                if( NULL == planCache.get())
                    planCache.reset(new PlanCache());
                return planCache.get();
            }
111 112 113
            // return a baked plan->
            // if there is one matched plan, return it
            // if not, bake a new one, put it into the planStore and return it.
114 115 116 117 118 119
            static FftPlan* getPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type);

            // remove a single plan from the store
            // return true if the plan is successfully removed
            // else
            static bool removePlan(clAmdFftPlanHandle );
120 121 122
        };
    }
}
123
auto_ptr<PlanCache> PlanCache::planCache;
124 125 126

void cv::ocl::fft_setup()
{
127 128
    PlanCache& pCache = *PlanCache::getPlanCache();
    if(pCache.started)
129 130 131
    {
        return;
    }
132 133 134
    pCache.setupData = new clAmdFftSetupData;
    openCLSafeCall(clAmdFftInitSetupData( pCache.setupData ));
    pCache.started = true;
135 136 137
}
void cv::ocl::fft_teardown()
{
138 139
    PlanCache& pCache = *PlanCache::getPlanCache();
    if(!pCache.started)
140 141 142
    {
        return;
    }
143 144
    delete pCache.setupData;
    for(size_t i = 0; i < pCache.planStore.size(); i ++)
145
    {
146
        delete pCache.planStore[i];
147
    }
148
    pCache.planStore.clear();
149
    openCLSafeCall( clAmdFftTeardown( ) );
150
    pCache.started = false;
151 152 153 154
}

// bake a new plan
cv::ocl::FftPlan::FftPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type)
155
    : plHandle(0), dft_size(_dft_size), src_step(_src_step), dst_step(_dst_step), flags(_flags), type(_type)
156
{
157
    fft_setup();
158 159 160

    bool is_1d_input	= (_dft_size.height == 1);
    int is_row_dft		= flags & DFT_ROWS;
161 162
    int is_scaled_dft   = flags & DFT_SCALE;
    int is_inverse		= flags & DFT_INVERSE;
163

164
    //clAmdFftResultLocation	place;
165 166
    clAmdFftLayout			inLayout;
    clAmdFftLayout			outLayout;
167
    clAmdFftDim				dim = is_1d_input || is_row_dft ? CLFFT_1D : CLFFT_2D;
168

169
    size_t batchSize		 = is_row_dft ? dft_size.height : 1;
170 171
    size_t clLengthsIn[ 3 ]  = {1, 1, 1};
    size_t clStridesIn[ 3 ]  = {1, 1, 1};
172
    //size_t clLengthsOut[ 3 ] = {1, 1, 1};
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
    size_t clStridesOut[ 3 ] = {1, 1, 1};
    clLengthsIn[0]			 = dft_size.width;
    clLengthsIn[1]			 = is_row_dft ? 1 : dft_size.height;
    clStridesIn[0]			 = 1;
    clStridesOut[0]			 = 1;

    switch(_type)
    {
    case C2C:
        inLayout        = CLFFT_COMPLEX_INTERLEAVED;
        outLayout       = CLFFT_COMPLEX_INTERLEAVED;
        clStridesIn[1]  = src_step / sizeof(std::complex<float>);
        clStridesOut[1] = clStridesIn[1];
        break;
    case R2C:
        inLayout        = CLFFT_REAL;
        outLayout       = CLFFT_HERMITIAN_INTERLEAVED;
        clStridesIn[1]  = src_step / sizeof(float);
        clStridesOut[1] = dst_step / sizeof(std::complex<float>);
        break;
    case C2R:
        inLayout        = CLFFT_HERMITIAN_INTERLEAVED;
        outLayout       = CLFFT_REAL;
        clStridesIn[1]  = src_step / sizeof(std::complex<float>);
        clStridesOut[1] = dst_step / sizeof(float);
        break;
    default:
        //std::runtime_error("does not support this convertion!");
        cout << "Does not support this convertion!" << endl;
        throw exception();
        break;
    }

    clStridesIn[2]  = is_row_dft ? clStridesIn[1]  : dft_size.width * clStridesIn[1];
    clStridesOut[2] = is_row_dft ? clStridesOut[1] : dft_size.width * clStridesOut[1];

    openCLSafeCall( clAmdFftCreateDefaultPlan( &plHandle, Context::getContext()->impl->clContext, dim, clLengthsIn ) );

    openCLSafeCall( clAmdFftSetResultLocation( plHandle, CLFFT_OUTOFPLACE ) );
    openCLSafeCall( clAmdFftSetLayout( plHandle, inLayout, outLayout ) );
    openCLSafeCall( clAmdFftSetPlanBatchSize( plHandle, batchSize ) );

    openCLSafeCall( clAmdFftSetPlanInStride  ( plHandle, dim, clStridesIn ) );
    openCLSafeCall( clAmdFftSetPlanOutStride ( plHandle, dim, clStridesOut ) );
217 218 219 220 221 222
    openCLSafeCall( clAmdFftSetPlanDistance  ( plHandle, clStridesIn[ dim ], clStridesOut[ dim ]) );

    float scale_ = is_scaled_dft ? 1.f / _dft_size.area() : 1.f;
    openCLSafeCall( clAmdFftSetPlanScale  ( plHandle, is_inverse ? CLFFT_BACKWARD : CLFFT_FORWARD, scale_ ) );

    //ready to bake
223 224 225 226 227 228 229
    openCLSafeCall( clAmdFftBakePlan( plHandle, 1, &(Context::getContext()->impl->clCmdQueue), NULL, NULL ) );
}
cv::ocl::FftPlan::~FftPlan()
{
    openCLSafeCall( clAmdFftDestroyPlan( &plHandle ) );
}

230 231 232 233 234 235 236 237 238 239 240 241 242
cv::ocl::PlanCache::PlanCache()
    : started(false),
      planStore(vector<cv::ocl::FftPlan *>()),
      setupData(NULL)
{
}

cv::ocl::PlanCache::~PlanCache()
{
    fft_teardown();
}

FftPlan* cv::ocl::PlanCache::getPlan(Size _dft_size, int _src_step, int _dst_step, int _flags, FftType _type)
243
{
244 245
    PlanCache& pCache = *PlanCache::getPlanCache();
    vector<FftPlan *>& pStore = pCache.planStore;
246
    // go through search
247
    for(size_t i = 0; i < pStore.size(); i ++)
248
    {
249
        FftPlan *plan = pStore[i];
250
        if(
251
            plan->dft_size.width == _dft_size.width &&
252 253 254 255 256
            plan->dft_size.height == _dft_size.height &&
            plan->flags == _flags &&
            plan->src_step == _src_step &&
            plan->dst_step == _dst_step &&
            plan->type == _type
257
            )
258
        {
259
            return plan;
260 261 262 263
        }
    }
    // no baked plan is found
    FftPlan *newPlan = new FftPlan(_dft_size, _src_step, _dst_step, _flags, _type);
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
    pStore.push_back(newPlan);
    return newPlan;
}

bool cv::ocl::PlanCache::removePlan(clAmdFftPlanHandle plHandle)
{
    PlanCache& pCache = *PlanCache::getPlanCache();
    vector<FftPlan *>& pStore = pCache.planStore;
    for(size_t i = 0; i < pStore.size(); i ++)
    {
        if(pStore[i]->getPlanHandle() == plHandle)
        {
            pStore.erase(pStore.begin() + i);
            delete pStore[i];
            return true;
        }
    }
    return false;
282 283
}

284
void cv::ocl::dft(const oclMat &src, oclMat &dst, Size dft_size, int flags)
285
{
286
    if(dft_size == Size(0, 0))
287 288 289 290 291 292
    {
        dft_size = src.size();
    }
    // check if the given dft size is of optimal dft size
    CV_Assert(dft_size.area() == getOptimalDFTSize(dft_size.area()));

293 294 295
    // the two flags are not compatible
    CV_Assert( !((flags & DFT_SCALE) && (flags & DFT_ROWS)) );

296 297 298
    // similar assertions with cuda module
    CV_Assert(src.type() == CV_32F || src.type() == CV_32FC2);

299 300 301
    //bool is_1d_input	= (src.rows == 1);
    //int is_row_dft		= flags & DFT_ROWS;
    //int is_scaled_dft		= flags & DFT_SCALE;
302 303 304 305
    int is_inverse			= flags & DFT_INVERSE;
    bool is_complex_input	= src.channels() == 2;
    bool is_complex_output	= !(flags & DFT_REAL_OUTPUT);

306

307 308 309 310 311 312 313 314 315 316
    // We don't support real-to-real transform
    CV_Assert(is_complex_input || is_complex_output);
    FftType type = (FftType)(is_complex_input << 0 | is_complex_output << 1);

    switch(type)
    {
    case C2C:
        dst.create(src.rows, src.cols, CV_32FC2);
        break;
    case R2C:
317
        dst.create(src.rows, src.cols / 2 + 1, CV_32FC2);
318 319 320 321 322 323 324 325 326 327 328
        break;
    case C2R:
        CV_Assert(dft_size.width / 2 + 1 == src.cols && dft_size.height == src.rows);
        dst.create(src.rows, dft_size.width, CV_32FC1);
        break;
    default:
        //std::runtime_error("does not support this convertion!");
        cout << "Does not support this convertion!" << endl;
        throw exception();
        break;
    }
329
    clAmdFftPlanHandle plHandle = PlanCache::getPlan(dft_size, src.step, dst.step, flags, type)->getPlanHandle();
330 331

    //get the buffersize
332
    size_t buffersize = 0;
333 334
    openCLSafeCall( clAmdFftGetTmpBufSize(plHandle, &buffersize ) );

335
    //allocate the intermediate buffer
336
    // TODO, bind this with the current FftPlan
337
    cl_mem clMedBuffer = NULL;
338 339 340 341 342 343
    if (buffersize)
    {
        cl_int medstatus;
        clMedBuffer = clCreateBuffer ( src.clCxt->impl->clContext, CL_MEM_READ_WRITE, buffersize, 0, &medstatus);
        openCLSafeCall( medstatus );
    }
344
    openCLSafeCall( clAmdFftEnqueueTransform( plHandle,
345 346 347 348 349
        is_inverse ? CLFFT_BACKWARD : CLFFT_FORWARD,
        1,
        &src.clCxt->impl->clCmdQueue,
        0, NULL, NULL,
        (cl_mem *)&src.data, (cl_mem *)&dst.data, clMedBuffer ) );
350 351 352 353 354
    openCLSafeCall( clFinish(src.clCxt->impl->clCmdQueue) );
    if(clMedBuffer)
    {
        openCLFree(clMedBuffer);
    }
355
    //fft_teardown();
356 357 358
}

#endif