ocl.cpp 213 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
/*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) 2013, OpenCV Foundation, 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 OpenCV Foundation 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 "precomp.hpp"
43
#include <list>
44
#include <map>
45
#include <deque>
46
#include <set>
47 48 49
#include <string>
#include <sstream>
#include <iostream> // std::cerr
50
#include <fstream>
51
#if !(defined _MSC_VER) || (defined _MSC_VER && _MSC_VER > 1700)
52
#include <inttypes.h>
53
#endif
54

55 56
#include <opencv2/core/utils/configuration.private.hpp>

57 58
#include <opencv2/core/utils/logger.hpp>

59
#include "opencv2/core/ocl_genbase.hpp"
60
#include "opencl_kernels_core.hpp"
61

62 63 64 65 66 67 68 69
#include "opencv2/core/utils/lock.private.hpp"
#include "opencv2/core/utils/filesystem.hpp"
#include "opencv2/core/utils/filesystem.private.hpp"

#define CV_OPENCL_ALWAYS_SHOW_BUILD_LOG          0

#define CV_OPENCL_SHOW_RUN_KERNELS               0
#define CV_OPENCL_TRACE_CHECK                    0
70

71
#define CV_OPENCL_VALIDATE_BINARY_PROGRAMS       1
72

73 74
#define CV_OPENCL_SHOW_SVM_ERROR_LOG             1
#define CV_OPENCL_SHOW_SVM_LOG                   0
75

76 77 78 79 80 81 82 83 84
#include "opencv2/core/bufferpool.hpp"
#ifndef LOG_BUFFER_POOL
# if 0
#   define LOG_BUFFER_POOL printf
# else
#   define LOG_BUFFER_POOL(...)
# endif
#endif

85 86 87 88 89 90 91 92 93 94 95 96 97 98
#if CV_OPENCL_SHOW_SVM_LOG
// TODO add timestamp logging
#define CV_OPENCL_SVM_TRACE_P printf("line %d (ocl.cpp): ", __LINE__); printf
#else
#define CV_OPENCL_SVM_TRACE_P(...)
#endif

#if CV_OPENCL_SHOW_SVM_ERROR_LOG
// TODO add timestamp logging
#define CV_OPENCL_SVM_TRACE_ERROR_P printf("Error on line %d (ocl.cpp): ", __LINE__); printf
#else
#define CV_OPENCL_SVM_TRACE_ERROR_P(...)
#endif

Ilya Lavrenov's avatar
Ilya Lavrenov committed
99
#include "opencv2/core/opencl/runtime/opencl_clamdblas.hpp"
Ilya Lavrenov's avatar
Ilya Lavrenov committed
100
#include "opencv2/core/opencl/runtime/opencl_clamdfft.hpp"
Ilya Lavrenov's avatar
Ilya Lavrenov committed
101

102 103 104
#ifdef HAVE_OPENCL
#include "opencv2/core/opencl/runtime/opencl_core.hpp"
#else
105 106 107 108 109 110 111 112 113 114 115
#if defined(_MSC_VER)
    #pragma warning(push)
    #pragma warning(disable : 4100)
    #pragma warning(disable : 4702)
#elif defined(__clang__)
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Wunused-parameter"
#elif defined(__GNUC__)
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
116
// TODO FIXIT: This file can't be build without OPENCL
117
#include "ocl_deprecated.hpp"
118
#endif // HAVE_OPENCL
119

120 121 122 123 124 125
#ifdef HAVE_OPENCL_SVM
#include "opencv2/core/opencl/runtime/opencl_svm_20.hpp"
#include "opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp"
#include "opencv2/core/opencl/opencl_svm.hpp"
#endif

126 127
#include "umatrix.hpp"

128 129
namespace cv { namespace ocl {

130 131 132 133 134 135
#define IMPLEMENT_REFCOUNTABLE() \
    void addref() { CV_XADD(&refcount, 1); } \
    void release() { if( CV_XADD(&refcount, -1) == 1 && !cv::__termination) delete this; } \
    int refcount

#ifndef HAVE_OPENCL
136
#define CV_OPENCL_NO_SUPPORT() CV_Error(cv::Error::OpenCLApiCallError, "OpenCV build without OpenCL support")
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
namespace {
struct DummyImpl
{
    DummyImpl() { CV_OPENCL_NO_SUPPORT(); }
    ~DummyImpl() { /* do not throw in desctructors */ }
    IMPLEMENT_REFCOUNTABLE();
};
} // namespace

// TODO Replace to empty body (without HAVE_OPENCL)
#define CV_OCL_TRACE_CHECK_RESULT(status, message) /* nothing */
#define CV_OCL_API_ERROR_MSG(check_result, msg) cv::String()
#define CV_OCL_CHECK_RESULT(check_result, msg) (void)check_result
#define CV_OCL_CHECK_(expr, check_result) expr; (void)check_result
#define CV_OCL_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_CHECK_RESULT(__cl_result, #expr); } while (0)
#define CV_OCL_DBG_CHECK_RESULT(check_result, msg) (void)check_result
#define CV_OCL_DBG_CHECK_(expr, check_result) expr; (void)check_result
#define CV_OCL_DBG_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_CHECK_RESULT(__cl_result, #expr); } while (0)

156 157
static const bool CV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS = false;

158 159
#else // HAVE_OPENCL

160
#ifndef _DEBUG
161 162 163 164 165 166
static bool isRaiseError()
{
    static bool initialized = false;
    static bool value = false;
    if (!initialized)
    {
167
        value = cv::utils::getConfigurationParameterBool("OPENCV_OPENCL_RAISE_ERROR", false);
168 169 170 171
        initialized = true;
    }
    return value;
}
172 173
#endif

174 175 176 177 178 179 180 181 182
#if CV_OPENCL_TRACE_CHECK
static inline
void traceOpenCLCheck(cl_int status, const char* message)
{
    std::cout << "OpenCV(OpenCL:" << status << "): " << message << std::endl << std::flush;
}
#define CV_OCL_TRACE_CHECK_RESULT(status, message) traceOpenCLCheck(status, message)
#else
#define CV_OCL_TRACE_CHECK_RESULT(status, message) /* nothing */
183 184
#endif

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 217 218 219 220
#define CV_OCL_API_ERROR_MSG(check_result, msg) \
    cv::format("OpenCL error %s (%d) during call: %s", getOpenCLErrorString(check_result), check_result, msg)

#define CV_OCL_CHECK_RESULT(check_result, msg) \
    do { \
        CV_OCL_TRACE_CHECK_RESULT(check_result, msg); \
        if (check_result != CL_SUCCESS) \
        { \
            if (0) { const char* msg_ = (msg); (void)msg_; /* ensure const char* type (cv::String without c_str()) */ } \
            cv::String error_msg = CV_OCL_API_ERROR_MSG(check_result, msg); \
            CV_Error(Error::OpenCLApiCallError, error_msg); \
        } \
    } while (0)

#define CV_OCL_CHECK_(expr, check_result) do { expr; CV_OCL_CHECK_RESULT(check_result, #expr); } while (0)

#define CV_OCL_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_CHECK_RESULT(__cl_result, #expr); } while (0)

#ifdef _DEBUG
#define CV_OCL_DBG_CHECK_RESULT(check_result, msg) CV_OCL_CHECK_RESULT(check_result, msg)
#define CV_OCL_DBG_CHECK(expr) CV_OCL_CHECK(expr)
#define CV_OCL_DBG_CHECK_(expr, check_result) CV_OCL_CHECK_(expr, check_result)
#else
#define CV_OCL_DBG_CHECK_RESULT(check_result, msg) \
    do { \
        CV_OCL_TRACE_CHECK_RESULT(check_result, msg); \
        if (check_result != CL_SUCCESS && isRaiseError()) \
        { \
            if (0) { const char* msg_ = (msg); (void)msg_; /* ensure const char* type (cv::String without c_str()) */ } \
            cv::String error_msg = CV_OCL_API_ERROR_MSG(check_result, msg); \
            CV_Error(Error::OpenCLApiCallError, error_msg); \
        } \
    } while (0)
#define CV_OCL_DBG_CHECK_(expr, check_result) do { expr; CV_OCL_DBG_CHECK_RESULT(check_result, #expr); } while (0)
#define CV_OCL_DBG_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_DBG_CHECK_RESULT(__cl_result, #expr); } while (0)
#endif
221

222 223 224 225

static const bool CV_OPENCL_CACHE_ENABLE = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_ENABLE", true);
static const bool CV_OPENCL_CACHE_WRITE = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_WRITE", true);
static const bool CV_OPENCL_CACHE_LOCK_ENABLE = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_LOCK_ENABLE", true);
226
static const bool CV_OPENCL_CACHE_CLEANUP = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_CLEANUP", true);
227 228 229 230 231

#if CV_OPENCL_VALIDATE_BINARY_PROGRAMS
static const bool CV_OPENCL_VALIDATE_BINARY_PROGRAMS_VALUE = utils::getConfigurationParameterBool("OPENCV_OPENCL_VALIDATE_BINARY_PROGRAMS", false);
#endif

232 233 234 235 236 237 238 239 240
// Option to disable calls clEnqueueReadBufferRect / clEnqueueWriteBufferRect / clEnqueueCopyBufferRect
static const bool CV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS = utils::getConfigurationParameterBool("OPENCV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS",
#ifdef __APPLE__
        true
#else
        false
#endif
);

241
#endif // HAVE_OPENCL
242

243 244
struct UMat2D
{
245
    UMat2D(const UMat& m)
246
    {
247 248
        offset = (int)m.offset;
        step = (int)m.step;
249 250 251
        rows = m.rows;
        cols = m.cols;
    }
252 253
    int offset;
    int step;
254 255 256 257 258 259
    int rows;
    int cols;
};

struct UMat3D
{
260
    UMat3D(const UMat& m)
261
    {
262 263 264 265
        offset = (int)m.offset;
        step = (int)m.step.p[1];
        slicestep = (int)m.step.p[0];
        slices = (int)m.size.p[0];
266 267 268
        rows = m.size.p[1];
        cols = m.size.p[2];
    }
269 270 271
    int offset;
    int slicestep;
    int step;
272 273 274 275 276
    int slices;
    int rows;
    int cols;
};

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
// Computes 64-bit "cyclic redundancy check" sum, as specified in ECMA-182
static uint64 crc64( const uchar* data, size_t size, uint64 crc0=0 )
{
    static uint64 table[256];
    static bool initialized = false;

    if( !initialized )
    {
        for( int i = 0; i < 256; i++ )
        {
            uint64 c = i;
            for( int j = 0; j < 8; j++ )
                c = ((c & 1) ? CV_BIG_UINT(0xc96c5795d7870f42) : 0) ^ (c >> 1);
            table[i] = c;
        }
        initialized = true;
    }

    uint64 crc = ~crc0;
    for( size_t idx = 0; idx < size; idx++ )
        crc = table[(uchar)crc ^ data[idx]] ^ (crc >> 8);

    return ~crc;
}

302
#if defined HAVE_OPENCL && OPENCV_HAVE_FILESYSTEM_SUPPORT
303 304 305 306 307 308 309 310
struct OpenCLBinaryCacheConfigurator
{
    cv::String cache_path_;
    cv::String cache_lock_filename_;
    cv::Ptr<utils::fs::FileLock> cache_lock_;

    typedef std::map<std::string, std::string> ContextCacheType;
    ContextCacheType prepared_contexts_;
311
    Mutex mutex_prepared_contexts_;
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412

    OpenCLBinaryCacheConfigurator()
    {
        CV_LOG_DEBUG(NULL, "Initializing OpenCL cache configuration...");
        if (!CV_OPENCL_CACHE_ENABLE)
        {
            CV_LOG_INFO(NULL, "OpenCL cache is disabled");
            return;
        }
        cache_path_ = utils::fs::getCacheDirectory("opencl_cache", "OPENCV_OPENCL_CACHE_DIR");
        if (cache_path_.empty())
        {
            CV_LOG_INFO(NULL, "Specify OPENCV_OPENCL_CACHE_DIR configuration parameter to enable OpenCL cache");
        }
        do
        {
            try
            {
                if (cache_path_.empty())
                    break;
                if (cache_path_ == "disabled")
                    break;
                if (!utils::fs::createDirectories(cache_path_))
                {
                    CV_LOG_DEBUG(NULL, "Can't use OpenCL cache directory: " << cache_path_);
                    clear();
                    break;
                }

                if (CV_OPENCL_CACHE_LOCK_ENABLE)
                {
                    cache_lock_filename_ = cache_path_ + ".lock";
                    if (!utils::fs::exists(cache_lock_filename_))
                    {
                        CV_LOG_DEBUG(NULL, "Creating lock file... (" << cache_lock_filename_ << ")");
                        std::ofstream lock_filename(cache_lock_filename_.c_str(), std::ios::out);
                        if (!lock_filename.is_open())
                        {
                            CV_LOG_WARNING(NULL, "Can't create lock file for OpenCL program cache: " << cache_lock_filename_);
                            break;
                        }
                    }

                    try
                    {
                        cache_lock_ = makePtr<utils::fs::FileLock>(cache_lock_filename_.c_str());
                        CV_LOG_VERBOSE(NULL, 0, "Checking cache lock... (" << cache_lock_filename_ << ")");
                        {
                            utils::shared_lock_guard<utils::fs::FileLock> lock(*cache_lock_);
                        }
                        CV_LOG_VERBOSE(NULL, 0, "Checking cache lock... Done!");
                    }
                    catch (const cv::Exception& e)
                    {
                        CV_LOG_WARNING(NULL, "Can't create OpenCL program cache lock: " << cache_lock_filename_ << std::endl << e.what());
                    }
                    catch (...)
                    {
                        CV_LOG_WARNING(NULL, "Can't create OpenCL program cache lock: " << cache_lock_filename_);
                    }
                }
                else
                {
                    if (CV_OPENCL_CACHE_WRITE)
                    {
                        CV_LOG_WARNING(NULL, "OpenCL cache lock is disabled while cache write is allowed "
                                "(not safe for multiprocess environment)");
                    }
                    else
                    {
                        CV_LOG_INFO(NULL, "OpenCL cache lock is disabled");
                    }
                }
            }
            catch (const cv::Exception& e)
            {
                CV_LOG_WARNING(NULL, "Can't prepare OpenCL program cache: " << cache_path_ << std::endl << e.what());
                clear();
            }
        } while (0);
        if (!cache_path_.empty())
        {
            if (cache_lock_.empty() && CV_OPENCL_CACHE_LOCK_ENABLE)
            {
                CV_LOG_WARNING(NULL, "Initialized OpenCL cache directory, but interprocess synchronization lock is not available. "
                        "Consider to disable OpenCL cache: OPENCV_OPENCL_CACHE_DIR=disabled");
            }
            else
            {
                CV_LOG_INFO(NULL, "Successfully initialized OpenCL cache directory: " << cache_path_);
            }
        }
    }

    void clear()
    {
        cache_path_.clear();
        cache_lock_filename_.clear();
        cache_lock_.release();
    }

413 414
    std::string prepareCacheDirectoryForContext(const std::string& ctx_prefix,
            const std::string& cleanup_prefix)
415 416 417 418
    {
        if (cache_path_.empty())
            return std::string();

419 420 421 422 423
        AutoLock lock(mutex_prepared_contexts_);

        ContextCacheType::iterator found_it = prepared_contexts_.find(ctx_prefix);
        if (found_it != prepared_contexts_.end())
            return found_it->second;
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450

        CV_LOG_INFO(NULL, "Preparing OpenCL cache configuration for context: " << ctx_prefix);

        std::string target_directory = cache_path_ + ctx_prefix + "/";
        bool result = utils::fs::isDirectory(target_directory);
        if (!result)
        {
            try
            {
                CV_LOG_VERBOSE(NULL, 0, "Creating directory: " << target_directory);
                if (utils::fs::createDirectories(target_directory))
                {
                    result = true;
                }
                else
                {
                    CV_LOG_WARNING(NULL, "Can't create directory: " << target_directory);
                }
            }
            catch (const cv::Exception& e)
            {
                CV_LOG_ERROR(NULL, "Can't create OpenCL program cache directory for context: " << target_directory << std::endl << e.what());
            }
        }
        target_directory = result ? target_directory : std::string();
        prepared_contexts_.insert(std::pair<std::string, std::string>(ctx_prefix, target_directory));

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
        if (result && CV_OPENCL_CACHE_CLEANUP && CV_OPENCL_CACHE_WRITE && !cleanup_prefix.empty())
        {
            try
            {
                std::vector<String> entries;
                utils::fs::glob_relative(cache_path_, cleanup_prefix + "*", entries, false, true);
                std::vector<String> remove_entries;
                for (size_t i = 0; i < entries.size(); i++)
                {
                    const String& name = entries[i];
                    if (0 == name.find(cleanup_prefix))
                    {
                        if (0 == name.find(ctx_prefix))
                            continue; // skip current
                        remove_entries.push_back(name);
                    }
                }
                if (!remove_entries.empty())
                {
                    CV_LOG_WARNING(NULL, (remove_entries.size() == 1
                            ? "Detected OpenCL cache directory for other version of OpenCL device."
                            : "Detected OpenCL cache directories for other versions of OpenCL device.")
                            << " We assume that these directories are obsolete after OpenCL runtime/drivers upgrade.");
                    CV_LOG_WARNING(NULL, "Trying to remove these directories...");
                    for (size_t i = 0; i < remove_entries.size(); i++)
                    {
                        CV_LOG_WARNING(NULL, "- " << remove_entries[i]);
                    }
479
                    CV_LOG_WARNING(NULL, "Note: You can disable this behavior via this option: OPENCV_OPENCL_CACHE_CLEANUP=0");
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

                    for (size_t i = 0; i < remove_entries.size(); i++)
                    {
                        const String& name = remove_entries[i];
                        cv::String path = utils::fs::join(cache_path_, name);
                        try
                        {
                            utils::fs::remove_all(path);
                            CV_LOG_WARNING(NULL, "Removed: " << path);
                        }
                        catch (const cv::Exception& e)
                        {
                            CV_LOG_ERROR(NULL, "Exception during removal of obsolete OpenCL cache directory: " << path << std::endl << e.what());
                        }
                    }
                }
            }
            catch (...)
            {
                CV_LOG_WARNING(NULL, "Can't check for obsolete OpenCL cache directories");
            }
        }
502

503
        CV_LOG_VERBOSE(NULL, 1, "  Result: " << (target_directory.empty() ? std::string("Failed") : target_directory));
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619
        return target_directory;
    }

    static OpenCLBinaryCacheConfigurator& getSingletonInstance()
    {
        CV_SINGLETON_LAZY_INIT_REF(OpenCLBinaryCacheConfigurator, new OpenCLBinaryCacheConfigurator());
    }
};
class BinaryProgramFile
{
    enum { MAX_ENTRIES = 64 };

    typedef unsigned int uint32_t;

    struct CV_DECL_ALIGNED(4) FileHeader
    {
        uint32_t sourceSignatureSize;
        //char sourceSignature[];
    };

    struct CV_DECL_ALIGNED(4) FileTable
    {
        uint32_t numberOfEntries;
        //uint32_t firstEntryOffset[];
    };

    struct CV_DECL_ALIGNED(4) FileEntry
    {
        uint32_t nextEntryFileOffset; // 0 for the last entry in chain
        uint32_t keySize;
        uint32_t dataSize;
        //char key[];
        //char data[];
    };

    const std::string fileName_;
    const char* const sourceSignature_;
    const size_t sourceSignatureSize_;

    std::fstream f;

    uint32_t entryOffsets[MAX_ENTRIES];

    uint32_t getHash(const std::string& options)
    {
        uint64 hash = crc64((const uchar*)options.c_str(), options.size(), 0);
        return hash & (MAX_ENTRIES - 1);
    }

    inline size_t getFileSize()
    {
        size_t pos = (size_t)f.tellg();
        f.seekg(0, std::fstream::end);
        size_t fileSize = (size_t)f.tellg();
        f.seekg(pos, std::fstream::beg);
        return fileSize;
    }
    inline uint32_t readUInt32()
    {
        uint32_t res = 0;
        f.read((char*)&res, sizeof(uint32_t));
        CV_Assert(!f.fail());
        return res;
    }
    inline void writeUInt32(const uint32_t value)
    {
        uint32_t v = value;
        f.write((char*)&v, sizeof(uint32_t));
        CV_Assert(!f.fail());
    }

    inline void seekReadAbsolute(size_t pos)
    {
        f.seekg(pos, std::fstream::beg);
        CV_Assert(!f.fail());
    }
    inline void seekReadRelative(size_t pos)
    {
        f.seekg(pos, std::fstream::cur);
        CV_Assert(!f.fail());
    }

    inline void seekWriteAbsolute(size_t pos)
    {
        f.seekp(pos, std::fstream::beg);
        CV_Assert(!f.fail());
    }

    void clearFile()
    {
        f.close();
        if (0 != remove(fileName_.c_str()))
            CV_LOG_ERROR(NULL, "Can't remove: " << fileName_);
        return;
    }

public:
    BinaryProgramFile(const std::string& fileName, const char* sourceSignature)
        : fileName_(fileName), sourceSignature_(sourceSignature), sourceSignatureSize_(sourceSignature_ ? strlen(sourceSignature_) : 0)
    {
        CV_StaticAssert(sizeof(uint32_t) == 4, "");
        CV_Assert(sourceSignature_ != NULL);
        CV_Assert(sourceSignatureSize_ > 0);
        memset(entryOffsets, 0, sizeof(entryOffsets));

        f.rdbuf()->pubsetbuf(0, 0); // disable buffering
        f.open(fileName_.c_str(), std::ios::in|std::ios::out|std::ios::binary);
        if(f.is_open() && getFileSize() > 0)
        {
            bool isValid = false;
            try
            {
                uint32_t fileSourceSignatureSize = readUInt32();
                if (fileSourceSignatureSize == sourceSignatureSize_)
                {
                    cv::AutoBuffer<char> fileSourceSignature(fileSourceSignatureSize + 1);
620
                    f.read(fileSourceSignature.data(), fileSourceSignatureSize);
621 622 623 624
                    if (f.eof())
                    {
                        CV_LOG_ERROR(NULL, "Unexpected EOF");
                    }
625
                    else if (memcmp(sourceSignature, fileSourceSignature.data(), fileSourceSignatureSize) == 0)
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
                    {
                        isValid = true;
                    }
                }
                if (!isValid)
                {
                    CV_LOG_ERROR(NULL, "Source code signature/hash mismatch (program source code has been changed/updated)");
                }
            }
            catch (const cv::Exception& e)
            {
                CV_LOG_ERROR(NULL, "Can't open binary program file: " << fileName << " : " << e.what());
            }
            catch (...)
            {
                CV_LOG_ERROR(NULL, "Can't open binary program file: " << fileName << " : Unknown error");
            }
            if (!isValid)
            {
                clearFile();
            }
            else
            {
                seekReadAbsolute(0);
            }
        }
    }

    bool read(const std::string& key, std::vector<char>& buf)
    {
        if (!f.is_open())
            return false;

        size_t fileSize = getFileSize();
        if (fileSize == 0)
        {
            CV_LOG_ERROR(NULL, "Invalid file (empty): " << fileName_);
            clearFile();
            return false;
        }
        seekReadAbsolute(0);

        // bypass FileHeader
        uint32_t fileSourceSignatureSize = readUInt32();
        CV_Assert(fileSourceSignatureSize > 0);
        seekReadRelative(fileSourceSignatureSize);

        uint32_t numberOfEntries = readUInt32();
        CV_Assert(numberOfEntries > 0);
        if (numberOfEntries != MAX_ENTRIES)
        {
            CV_LOG_ERROR(NULL, "Invalid file: " << fileName_);
            clearFile();
            return false;
        }
        f.read((char*)&entryOffsets[0], sizeof(entryOffsets));
        CV_Assert(!f.fail());

        uint32_t entryNum = getHash(key);

        uint32_t entryOffset = entryOffsets[entryNum];
        FileEntry entry;
        while (entryOffset > 0)
        {
            seekReadAbsolute(entryOffset);
            //CV_StaticAssert(sizeof(entry) == sizeof(uint32_t) * 3, "");
            f.read((char*)&entry, sizeof(entry));
            CV_Assert(!f.fail());
            cv::AutoBuffer<char> fileKey(entry.keySize + 1);
            if (key.size() == entry.keySize)
            {
                if (entry.keySize > 0)
                {
699
                    f.read(fileKey.data(), entry.keySize);
700 701
                    CV_Assert(!f.fail());
                }
702
                if (memcmp(fileKey.data(), key.c_str(), entry.keySize) == 0)
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
                {
                    buf.resize(entry.dataSize);
                    f.read(&buf[0], entry.dataSize);
                    CV_Assert(!f.fail());
                    seekReadAbsolute(0);
                    CV_LOG_VERBOSE(NULL, 0, "Read...");
                    return true;
                }
            }
            if (entry.nextEntryFileOffset == 0)
                break;
            entryOffset = entry.nextEntryFileOffset;
        }
        return false;
    }

    bool write(const std::string& key, std::vector<char>& buf)
    {
        if (!f.is_open())
        {
            f.open(fileName_.c_str(), std::ios::in|std::ios::out|std::ios::binary);
            if (!f.is_open())
            {
                f.open(fileName_.c_str(), std::ios::out|std::ios::binary);
                if (!f.is_open())
                {
                    CV_LOG_ERROR(NULL, "Can't create file: " << fileName_);
                    return false;
                }
            }
        }

        size_t fileSize = getFileSize();
        if (fileSize == 0)
        {
            // Write header
            seekWriteAbsolute(0);
            writeUInt32((uint32_t)sourceSignatureSize_);
            f.write(sourceSignature_, sourceSignatureSize_);
            CV_Assert(!f.fail());

            writeUInt32(MAX_ENTRIES);
            memset(entryOffsets, 0, sizeof(entryOffsets));
            f.write((char*)entryOffsets, sizeof(entryOffsets));
            CV_Assert(!f.fail());
            f.flush();
            CV_Assert(!f.fail());
            f.close();
            f.open(fileName_.c_str(), std::ios::in|std::ios::out|std::ios::binary);
            CV_Assert(f.is_open());
            fileSize = getFileSize();
        }
        seekReadAbsolute(0);

        // bypass FileHeader
        uint32_t fileSourceSignatureSize = readUInt32();
        CV_Assert(fileSourceSignatureSize == sourceSignatureSize_);
        seekReadRelative(fileSourceSignatureSize);

        uint32_t numberOfEntries = readUInt32();
        CV_Assert(numberOfEntries > 0);
        if (numberOfEntries != MAX_ENTRIES)
        {
            CV_LOG_ERROR(NULL, "Invalid file: " << fileName_);
            clearFile();
            return false;
        }
        size_t tableEntriesOffset = (size_t)f.tellg();
        f.read((char*)&entryOffsets[0], sizeof(entryOffsets));
        CV_Assert(!f.fail());

        uint32_t entryNum = getHash(key);

        uint32_t entryOffset = entryOffsets[entryNum];
        FileEntry entry;
        while (entryOffset > 0)
        {
            seekReadAbsolute(entryOffset);
            //CV_StaticAssert(sizeof(entry) == sizeof(uint32_t) * 3, "");
            f.read((char*)&entry, sizeof(entry));
            CV_Assert(!f.fail());
            cv::AutoBuffer<char> fileKey(entry.keySize + 1);
            if (key.size() == entry.keySize)
            {
                if (entry.keySize > 0)
                {
789
                    f.read(fileKey.data(), entry.keySize);
790 791
                    CV_Assert(!f.fail());
                }
792
                if (0 == memcmp(fileKey.data(), key.c_str(), entry.keySize))
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
                {
                    // duplicate
                    CV_LOG_VERBOSE(NULL, 0, "Duplicate key ignored: " << fileName_);
                    return false;
                }
            }
            if (entry.nextEntryFileOffset == 0)
                break;
            entryOffset = entry.nextEntryFileOffset;
        }
        seekReadAbsolute(0);
        if (entryOffset > 0)
        {
            seekWriteAbsolute(entryOffset);
            entry.nextEntryFileOffset = (uint32_t)fileSize;
            f.write((char*)&entry, sizeof(entry));
            CV_Assert(!f.fail());
        }
        else
        {
            entryOffsets[entryNum] = (uint32_t)fileSize;
            seekWriteAbsolute(tableEntriesOffset);
            f.write((char*)entryOffsets, sizeof(entryOffsets));
            CV_Assert(!f.fail());
        }
        seekWriteAbsolute(fileSize);
        entry.nextEntryFileOffset = 0;
        entry.dataSize = (uint32_t)buf.size();
        entry.keySize = (uint32_t)key.size();
        f.write((char*)&entry, sizeof(entry));
        CV_Assert(!f.fail());
        f.write(key.c_str(), entry.keySize);
        CV_Assert(!f.fail());
        f.write(&buf[0], entry.dataSize);
        CV_Assert(!f.fail());
        f.flush();
        CV_Assert(!f.fail());
        CV_LOG_VERBOSE(NULL, 0, "Write... (" << buf.size() << " bytes)");
        return true;
    }
};
#endif // OPENCV_HAVE_FILESYSTEM_SUPPORT


837 838 839
// true if we have initialized OpenCL subsystem with available platforms
static bool g_isOpenCVActivated = false;

840 841
bool haveOpenCL()
{
842
    CV_TRACE_FUNCTION();
843 844 845 846
#ifdef HAVE_OPENCL
    static bool g_isOpenCLInitialized = false;
    static bool g_isOpenCLAvailable = false;

Ilya Lavrenov's avatar
Ilya Lavrenov committed
847
    if (!g_isOpenCLInitialized)
848
    {
849 850 851 852 853 854 855 856 857 858 859
        CV_TRACE_REGION("Init_OpenCL_Runtime");
        const char* envPath = getenv("OPENCV_OPENCL_RUNTIME");
        if (envPath)
        {
            if (cv::String(envPath) == "disabled")
            {
                g_isOpenCLAvailable = false;
                g_isOpenCLInitialized = true;
            }
        }
        CV_LOG_INFO(NULL, "Initialize OpenCL runtime...");
Ilya Lavrenov's avatar
Ilya Lavrenov committed
860
        try
861
        {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
862 863
            cl_uint n = 0;
            g_isOpenCLAvailable = ::clGetPlatformIDs(0, NULL, &n) == CL_SUCCESS;
864
            g_isOpenCVActivated = n > 0;
865
        }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
866 867 868
        catch (...)
        {
            g_isOpenCLAvailable = false;
869
        }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
870
        g_isOpenCLInitialized = true;
871 872
    }
    return g_isOpenCLAvailable;
873 874 875
#else
    return false;
#endif
876 877 878 879
}

bool useOpenCL()
{
880
    CoreTLSData* data = getCoreTlsData().get();
881
    if( data->useOpenCL < 0 )
882
    {
883
        CV_TRY
884
        {
885
            data->useOpenCL = (int)(haveOpenCL() && Device::getDefault().ptr() && Device::getDefault().available()) ? 1 : 0;
886
        }
887
        CV_CATCH_ALL
888 889 890 891
        {
            data->useOpenCL = 0;
        }
    }
892 893 894
    return data->useOpenCL > 0;
}

895 896 897 898 899 900 901 902 903
#ifdef HAVE_OPENCL
bool isOpenCLActivated()
{
    if (!g_isOpenCVActivated)
        return false; // prevent unnecessary OpenCL activation via useOpenCL()->haveOpenCL() calls
    return useOpenCL();
}
#endif

904 905
void setUseOpenCL(bool flag)
{
906 907 908 909
    CV_TRACE_FUNCTION();

    CoreTLSData* data = getCoreTlsData().get();
    if (!flag)
910
    {
911 912 913 914 915
        data->useOpenCL = 0;
    }
    else if( haveOpenCL() )
    {
        data->useOpenCL = (Device::getDefault().ptr() != NULL) ? 1 : 0;
916 917 918
    }
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
919 920 921 922 923 924 925
#ifdef HAVE_CLAMDBLAS

class AmdBlasHelper
{
public:
    static AmdBlasHelper & getInstance()
    {
926
        CV_SINGLETON_LAZY_INIT_REF(AmdBlasHelper, new AmdBlasHelper())
Ilya Lavrenov's avatar
Ilya Lavrenov committed
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    }

    bool isAvailable() const
    {
        return g_isAmdBlasAvailable;
    }

    ~AmdBlasHelper()
    {
        try
        {
            clAmdBlasTeardown();
        }
        catch (...) { }
    }

protected:
    AmdBlasHelper()
    {
        if (!g_isAmdBlasInitialized)
        {
948
            AutoLock lock(getInitializationMutex());
Ilya Lavrenov's avatar
Ilya Lavrenov committed
949

950
            if (!g_isAmdBlasInitialized)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
951
            {
952
                if (haveOpenCL())
Ilya Lavrenov's avatar
Ilya Lavrenov committed
953
                {
954 955 956 957 958 959 960 961
                    try
                    {
                        g_isAmdBlasAvailable = clAmdBlasSetup() == clAmdBlasSuccess;
                    }
                    catch (...)
                    {
                        g_isAmdBlasAvailable = false;
                    }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
962
                }
963
                else
Ilya Lavrenov's avatar
Ilya Lavrenov committed
964 965
                    g_isAmdBlasAvailable = false;

966 967
                g_isAmdBlasInitialized = true;
            }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
        }
    }

private:
    static bool g_isAmdBlasInitialized;
    static bool g_isAmdBlasAvailable;
};

bool AmdBlasHelper::g_isAmdBlasAvailable = false;
bool AmdBlasHelper::g_isAmdBlasInitialized = false;

bool haveAmdBlas()
{
    return AmdBlasHelper::getInstance().isAvailable();
}

#else

bool haveAmdBlas()
{
    return false;
}

#endif

Ilya Lavrenov's avatar
Ilya Lavrenov committed
993 994 995 996 997 998 999
#ifdef HAVE_CLAMDFFT

class AmdFftHelper
{
public:
    static AmdFftHelper & getInstance()
    {
1000
        CV_SINGLETON_LAZY_INIT_REF(AmdFftHelper, new AmdFftHelper())
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
    }

    bool isAvailable() const
    {
        return g_isAmdFftAvailable;
    }

    ~AmdFftHelper()
    {
        try
        {
//            clAmdFftTeardown();
        }
        catch (...) { }
    }

protected:
    AmdFftHelper()
    {
        if (!g_isAmdFftInitialized)
        {
1022
            AutoLock lock(getInitializationMutex());
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1023

1024
            if (!g_isAmdFftInitialized)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1025
            {
1026
                if (haveOpenCL())
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1027
                {
1028 1029 1030 1031
                    try
                    {
                        cl_uint major, minor, patch;
                        CV_Assert(clAmdFftInitSetupData(&setupData) == CLFFT_SUCCESS);
1032

1033 1034 1035 1036 1037 1038 1039 1040
                        // it throws exception in case AmdFft binaries are not found
                        CV_Assert(clAmdFftGetVersion(&major, &minor, &patch) == CLFFT_SUCCESS);
                        g_isAmdFftAvailable = true;
                    }
                    catch (const Exception &)
                    {
                        g_isAmdFftAvailable = false;
                    }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1041
                }
1042
                else
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1043 1044
                    g_isAmdFftAvailable = false;

1045 1046
                g_isAmdFftInitialized = true;
            }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
        }
    }

private:
    static clAmdFftSetupData setupData;
    static bool g_isAmdFftInitialized;
    static bool g_isAmdFftAvailable;
};

clAmdFftSetupData AmdFftHelper::setupData;
bool AmdFftHelper::g_isAmdFftAvailable = false;
bool AmdFftHelper::g_isAmdFftInitialized = false;

bool haveAmdFft()
{
    return AmdFftHelper::getInstance().isAvailable();
}

#else

bool haveAmdFft()
{
    return false;
}

#endif

1074 1075 1076 1077 1078 1079 1080 1081 1082
bool haveSVM()
{
#ifdef HAVE_OPENCL_SVM
    return true;
#else
    return false;
#endif
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
1083
void finish()
1084 1085 1086 1087
{
    Queue::getDefault().finish();
}

1088 1089
/////////////////////////////////////////// Platform /////////////////////////////////////////////

1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106
struct Platform::Impl
{
    Impl()
    {
        refcount = 1;
        handle = 0;
        initialized = false;
    }

    ~Impl() {}

    void init()
    {
        if( !initialized )
        {
            //cl_uint num_entries
            cl_uint n = 0;
1107
            if( clGetPlatformIDs(1, &handle, &n) != CL_SUCCESS || n == 0 )
1108 1109 1110 1111 1112
                handle = 0;
            if( handle != 0 )
            {
                char buf[1000];
                size_t len = 0;
1113
                CV_OCL_DBG_CHECK(clGetPlatformInfo(handle, CL_PLATFORM_VENDOR, sizeof(buf), buf, &len));
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
                buf[len] = '\0';
                vendor = String(buf);
            }

            initialized = true;
        }
    }

    IMPLEMENT_REFCOUNTABLE();

    cl_platform_id handle;
    String vendor;
    bool initialized;
};

Platform::Platform()
{
    p = 0;
}

Platform::~Platform()
{
    if(p)
        p->release();
}

Platform::Platform(const Platform& pl)
{
    p = (Impl*)pl.p;
    if(p)
        p->addref();
}

Platform& Platform::operator = (const Platform& pl)
{
    Impl* newp = (Impl*)pl.p;
    if(newp)
        newp->addref();
    if(p)
        p->release();
    p = newp;
    return *this;
}

void* Platform::ptr() const
{
    return p ? p->handle : 0;
}

Platform& Platform::getDefault()
{
    static Platform p;
    if( !p.p )
    {
        p.p = new Impl;
        p.p->init();
    }
    return p;
}

1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
/////////////////////////////////////// Device ////////////////////////////////////////////

// deviceVersion has format
//   OpenCL<space><major_version.minor_version><space><vendor-specific information>
// by specification
//   http://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clGetDeviceInfo.html
//   http://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetDeviceInfo.html
static void parseDeviceVersion(const String &deviceVersion, int &major, int &minor)
{
    major = minor = 0;
    if (10 >= deviceVersion.length())
        return;
    const char *pstr = deviceVersion.c_str();
    if (0 != strncmp(pstr, "OpenCL ", 7))
        return;
    size_t ppos = deviceVersion.find('.', 7);
    if (String::npos == ppos)
        return;
    String temp = deviceVersion.substr(7, ppos - 7);
    major = atoi(temp.c_str());
    temp = deviceVersion.substr(ppos + 1);
    minor = atoi(temp.c_str());
}
1197 1198 1199 1200 1201 1202

struct Device::Impl
{
    Impl(void* d)
    {
        handle = (cl_device_id)d;
1203
        refcount = 1;
1204 1205 1206

        name_ = getStrProp(CL_DEVICE_NAME);
        version_ = getStrProp(CL_DEVICE_VERSION);
1207
        extensions_ = getStrProp(CL_DEVICE_EXTENSIONS);
1208 1209 1210 1211 1212 1213
        doubleFPConfig_ = getProp<cl_device_fp_config, int>(CL_DEVICE_DOUBLE_FP_CONFIG);
        hostUnifiedMemory_ = getBoolProp(CL_DEVICE_HOST_UNIFIED_MEMORY);
        maxComputeUnits_ = getProp<cl_uint, int>(CL_DEVICE_MAX_COMPUTE_UNITS);
        maxWorkGroupSize_ = getProp<size_t, size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE);
        type_ = getProp<cl_device_type, int>(CL_DEVICE_TYPE);
        driverVersion_ = getStrProp(CL_DRIVER_VERSION);
1214
        addressBits_ = getProp<cl_uint, int>(CL_DEVICE_ADDRESS_BITS);
1215 1216 1217

        String deviceVersion_ = getStrProp(CL_DEVICE_VERSION);
        parseDeviceVersion(deviceVersion_, deviceVersionMajor_, deviceVersionMinor_);
1218

1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
        size_t pos = 0;
        while (pos < extensions_.size())
        {
            size_t pos2 = extensions_.find(' ', pos);
            if (pos2 == String::npos)
                pos2 = extensions_.size();
            if (pos2 > pos)
            {
                std::string extensionName = extensions_.substr(pos, pos2 - pos);
                extensions_set_.insert(extensionName);
            }
            pos = pos2 + 1;
        }

1233 1234
        intelSubgroupsSupport_ = isExtensionSupported("cl_intel_subgroups");

1235 1236 1237 1238
        vendorName_ = getStrProp(CL_DEVICE_VENDOR);
        if (vendorName_ == "Advanced Micro Devices, Inc." ||
            vendorName_ == "AMD")
            vendorID_ = VENDOR_AMD;
1239
        else if (vendorName_ == "Intel(R) Corporation" || vendorName_ == "Intel" || strstr(name_.c_str(), "Iris") != 0)
1240 1241 1242
            vendorID_ = VENDOR_INTEL;
        else if (vendorName_ == "NVIDIA Corporation")
            vendorID_ = VENDOR_NVIDIA;
1243
        else
1244
            vendorID_ = UNKNOWN_VENDOR;
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255

#if 0
        if (isExtensionSupported("cl_khr_spir"))
        {
#ifndef CL_DEVICE_SPIR_VERSIONS
#define CL_DEVICE_SPIR_VERSIONS                     0x40E0
#endif
            cv::String spir_versions = getStrProp(CL_DEVICE_SPIR_VERSIONS);
            std::cout << spir_versions << std::endl;
        }
#endif
1256 1257 1258 1259 1260 1261 1262 1263
    }

    template<typename _TpCL, typename _TpOut>
    _TpOut getProp(cl_device_info prop) const
    {
        _TpCL temp=_TpCL();
        size_t sz = 0;

1264
        return clGetDeviceInfo(handle, prop, sizeof(temp), &temp, &sz) == CL_SUCCESS &&
1265 1266 1267
            sz == sizeof(temp) ? _TpOut(temp) : _TpOut();
    }

1268 1269 1270 1271 1272
    bool getBoolProp(cl_device_info prop) const
    {
        cl_bool temp = CL_FALSE;
        size_t sz = 0;

1273
        return clGetDeviceInfo(handle, prop, sizeof(temp), &temp, &sz) == CL_SUCCESS &&
1274 1275 1276
            sz == sizeof(temp) ? temp != 0 : false;
    }

1277 1278
    String getStrProp(cl_device_info prop) const
    {
1279
        char buf[4096];
1280
        size_t sz=0;
1281
        return clGetDeviceInfo(handle, prop, sizeof(buf)-16, buf, &sz) == CL_SUCCESS &&
1282 1283 1284
            sz < sizeof(buf) ? String(buf) : String();
    }

1285
    bool isExtensionSupported(const std::string& extensionName) const
1286
    {
1287
        return extensions_set_.count(extensionName) > 0;
1288 1289 1290
    }


1291
    IMPLEMENT_REFCOUNTABLE();
1292

1293
    cl_device_id handle;
1294 1295 1296

    String name_;
    String version_;
1297
    std::string extensions_;
1298 1299 1300 1301 1302
    int doubleFPConfig_;
    bool hostUnifiedMemory_;
    int maxComputeUnits_;
    size_t maxWorkGroupSize_;
    int type_;
1303
    int addressBits_;
1304 1305
    int deviceVersionMajor_;
    int deviceVersionMinor_;
1306
    String driverVersion_;
1307 1308
    String vendorName_;
    int vendorID_;
1309
    bool intelSubgroupsSupport_;
1310 1311

    std::set<std::string> extensions_set_;
1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362
};


Device::Device()
{
    p = 0;
}

Device::Device(void* d)
{
    p = 0;
    set(d);
}

Device::Device(const Device& d)
{
    p = d.p;
    if(p)
        p->addref();
}

Device& Device::operator = (const Device& d)
{
    Impl* newp = (Impl*)d.p;
    if(newp)
        newp->addref();
    if(p)
        p->release();
    p = newp;
    return *this;
}

Device::~Device()
{
    if(p)
        p->release();
}

void Device::set(void* d)
{
    if(p)
        p->release();
    p = new Impl(d);
}

void* Device::ptr() const
{
    return p ? p->handle : 0;
}

String Device::name() const
1363
{ return p ? p->name_ : String(); }
1364 1365

String Device::extensions() const
1366 1367 1368 1369
{ return p ? String(p->extensions_) : String(); }

bool Device::isExtensionSupported(const String& extensionName) const
{ return p ? p->isExtensionSupported(extensionName) : false; }
1370

Konstantin Matskevich's avatar
Konstantin Matskevich committed
1371
String Device::version() const
1372
{ return p ? p->version_ : String(); }
Konstantin Matskevich's avatar
Konstantin Matskevich committed
1373

1374 1375 1376 1377 1378
String Device::vendorName() const
{ return p ? p->vendorName_ : String(); }

int Device::vendorID() const
{ return p ? p->vendorID_ : 0; }
1379 1380 1381 1382 1383

String Device::OpenCL_C_Version() const
{ return p ? p->getStrProp(CL_DEVICE_OPENCL_C_VERSION) : String(); }

String Device::OpenCLVersion() const
1384
{ return p ? p->getStrProp(CL_DEVICE_VERSION) : String(); }
1385

1386 1387 1388 1389 1390
int Device::deviceVersionMajor() const
{ return p ? p->deviceVersionMajor_ : 0; }

int Device::deviceVersionMinor() const
{ return p ? p->deviceVersionMinor_ : 0; }
1391

1392
String Device::driverVersion() const
1393
{ return p ? p->driverVersion_ : String(); }
1394 1395

int Device::type() const
1396
{ return p ? p->type_ : 0; }
1397 1398

int Device::addressBits() const
1399
{ return p ? p->addressBits_ : 0; }
1400 1401

bool Device::available() const
1402
{ return p ? p->getBoolProp(CL_DEVICE_AVAILABLE) : false; }
1403 1404

bool Device::compilerAvailable() const
1405
{ return p ? p->getBoolProp(CL_DEVICE_COMPILER_AVAILABLE) : false; }
1406 1407

bool Device::linkerAvailable() const
1408
#ifdef CL_VERSION_1_2
1409
{ return p ? p->getBoolProp(CL_DEVICE_LINKER_AVAILABLE) : false; }
1410 1411 1412
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
1413 1414

int Device::doubleFPConfig() const
1415
{ return p ? p->doubleFPConfig_ : 0; }
1416 1417 1418 1419 1420

int Device::singleFPConfig() const
{ return p ? p->getProp<cl_device_fp_config, int>(CL_DEVICE_SINGLE_FP_CONFIG) : 0; }

int Device::halfFPConfig() const
1421
#ifdef CL_VERSION_1_2
1422
{ return p ? p->getProp<cl_device_fp_config, int>(CL_DEVICE_HALF_FP_CONFIG) : 0; }
1423 1424 1425
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
1426 1427

bool Device::endianLittle() const
1428
{ return p ? p->getBoolProp(CL_DEVICE_ENDIAN_LITTLE) : false; }
1429 1430

bool Device::errorCorrectionSupport() const
1431
{ return p ? p->getBoolProp(CL_DEVICE_ERROR_CORRECTION_SUPPORT) : false; }
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454

int Device::executionCapabilities() const
{ return p ? p->getProp<cl_device_exec_capabilities, int>(CL_DEVICE_EXECUTION_CAPABILITIES) : 0; }

size_t Device::globalMemCacheSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_GLOBAL_MEM_CACHE_SIZE) : 0; }

int Device::globalMemCacheType() const
{ return p ? p->getProp<cl_device_mem_cache_type, int>(CL_DEVICE_GLOBAL_MEM_CACHE_TYPE) : 0; }

int Device::globalMemCacheLineSize() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE) : 0; }

size_t Device::globalMemSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_GLOBAL_MEM_SIZE) : 0; }

size_t Device::localMemSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_LOCAL_MEM_SIZE) : 0; }

int Device::localMemType() const
{ return p ? p->getProp<cl_device_local_mem_type, int>(CL_DEVICE_LOCAL_MEM_TYPE) : 0; }

bool Device::hostUnifiedMemory() const
1455
{ return p ? p->hostUnifiedMemory_ : false; }
1456 1457

bool Device::imageSupport() const
1458
{ return p ? p->getBoolProp(CL_DEVICE_IMAGE_SUPPORT) : false; }
1459

1460 1461
bool Device::imageFromBufferSupport() const
{
1462
    return p ? p->isExtensionSupported("cl_khr_image2d_from_buffer") : false;
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
}

uint Device::imagePitchAlignment() const
{
#ifdef CL_DEVICE_IMAGE_PITCH_ALIGNMENT
    return p ? p->getProp<cl_uint, uint>(CL_DEVICE_IMAGE_PITCH_ALIGNMENT) : 0;
#else
    return 0;
#endif
}

uint Device::imageBaseAddressAlignment() const
{
#ifdef CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT
    return p ? p->getProp<cl_uint, uint>(CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT) : 0;
#else
    return 0;
#endif
}

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
size_t Device::image2DMaxWidth() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE2D_MAX_WIDTH) : 0; }

size_t Device::image2DMaxHeight() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE2D_MAX_HEIGHT) : 0; }

size_t Device::image3DMaxWidth() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_WIDTH) : 0; }

size_t Device::image3DMaxHeight() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_HEIGHT) : 0; }

size_t Device::image3DMaxDepth() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_DEPTH) : 0; }

size_t Device::imageMaxBufferSize() const
1499
#ifdef CL_VERSION_1_2
1500
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE_MAX_BUFFER_SIZE) : 0; }
1501 1502 1503
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
1504 1505

size_t Device::imageMaxArraySize() const
1506
#ifdef CL_VERSION_1_2
1507
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE_MAX_ARRAY_SIZE) : 0; }
1508 1509 1510
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
1511

1512 1513 1514
bool Device::intelSubgroupsSupport() const
{ return p ? p->intelSubgroupsSupport_ : false; }

1515 1516 1517 1518
int Device::maxClockFrequency() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_CLOCK_FREQUENCY) : 0; }

int Device::maxComputeUnits() const
1519
{ return p ? p->maxComputeUnits_ : 0; }
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

int Device::maxConstantArgs() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_CONSTANT_ARGS) : 0; }

size_t Device::maxConstantBufferSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE) : 0; }

size_t Device::maxMemAllocSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_MEM_ALLOC_SIZE) : 0; }

size_t Device::maxParameterSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_PARAMETER_SIZE) : 0; }

int Device::maxReadImageArgs() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_READ_IMAGE_ARGS) : 0; }

int Device::maxWriteImageArgs() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_WRITE_IMAGE_ARGS) : 0; }

int Device::maxSamplers() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_SAMPLERS) : 0; }

size_t Device::maxWorkGroupSize() const
1543
{ return p ? p->maxWorkGroupSize_ : 0; }
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553

int Device::maxWorkItemDims() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS) : 0; }

void Device::maxWorkItemSizes(size_t* sizes) const
{
    if(p)
    {
        const int MAX_DIMS = 32;
        size_t retsz = 0;
1554 1555
        CV_OCL_DBG_CHECK(clGetDeviceInfo(p->handle, CL_DEVICE_MAX_WORK_ITEM_SIZES,
                MAX_DIMS*sizeof(sizes[0]), &sizes[0], &retsz));
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604
    }
}

int Device::memBaseAddrAlign() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MEM_BASE_ADDR_ALIGN) : 0; }

int Device::nativeVectorWidthChar() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR) : 0; }

int Device::nativeVectorWidthShort() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT) : 0; }

int Device::nativeVectorWidthInt() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_INT) : 0; }

int Device::nativeVectorWidthLong() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG) : 0; }

int Device::nativeVectorWidthFloat() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT) : 0; }

int Device::nativeVectorWidthDouble() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE) : 0; }

int Device::nativeVectorWidthHalf() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF) : 0; }

int Device::preferredVectorWidthChar() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR) : 0; }

int Device::preferredVectorWidthShort() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT) : 0; }

int Device::preferredVectorWidthInt() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT) : 0; }

int Device::preferredVectorWidthLong() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG) : 0; }

int Device::preferredVectorWidthFloat() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT) : 0; }

int Device::preferredVectorWidthDouble() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE) : 0; }

int Device::preferredVectorWidthHalf() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF) : 0; }

size_t Device::printfBufferSize() const
1605
#ifdef CL_VERSION_1_2
1606
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_PRINTF_BUFFER_SIZE) : 0; }
1607 1608 1609 1610
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif

1611 1612 1613 1614 1615 1616

size_t Device::profilingTimerResolution() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_PROFILING_TIMER_RESOLUTION) : 0; }

const Device& Device::getDefault()
{
Ilya Lavrenov's avatar
Ilya Lavrenov committed
1617
    const Context& ctx = Context::getDefault();
1618
    int idx = getCoreTlsData().get()->device;
1619 1620
    const Device& device = ctx.device(idx);
    return device;
1621 1622
}

1623
////////////////////////////////////// Context ///////////////////////////////////////////////////
1624

1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
template <typename Functor, typename ObjectType>
inline cl_int getStringInfo(Functor f, ObjectType obj, cl_uint name, std::string& param)
{
    ::size_t required;
    cl_int err = f(obj, name, 0, NULL, &required);
    if (err != CL_SUCCESS)
        return err;

    param.clear();
    if (required > 0)
    {
Alexander Alekhin's avatar
Alexander Alekhin committed
1636
        AutoBuffer<char> buf(required + 1);
1637
        char* ptr = buf.data(); // cleanup is not needed
Alexander Alekhin's avatar
Alexander Alekhin committed
1638
        err = f(obj, name, required, ptr, NULL);
1639 1640
        if (err != CL_SUCCESS)
            return err;
Alexander Alekhin's avatar
Alexander Alekhin committed
1641
        param = ptr;
1642 1643 1644
    }

    return CL_SUCCESS;
1645
}
1646

1647 1648
static void split(const std::string &s, char delim, std::vector<std::string> &elems)
{
Alexander Alekhin's avatar
Alexander Alekhin committed
1649 1650 1651 1652
    elems.clear();
    if (s.size() == 0)
        return;
    std::istringstream ss(s);
1653
    std::string item;
Alexander Alekhin's avatar
Alexander Alekhin committed
1654 1655 1656
    while (!ss.eof())
    {
        std::getline(ss, item, delim);
1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
        elems.push_back(item);
    }
}

// Layout: <Platform>:<CPU|GPU|ACCELERATOR|nothing=GPU/CPU>:<deviceName>
// Sample: AMD:GPU:
// Sample: AMD:GPU:Tahiti
// Sample: :GPU|CPU: = '' = ':' = '::'
static bool parseOpenCLDeviceConfiguration(const std::string& configurationStr,
        std::string& platform, std::vector<std::string>& deviceTypes, std::string& deviceNameOrID)
{
Alexander Alekhin's avatar
Alexander Alekhin committed
1668 1669 1670
    std::vector<std::string> parts;
    split(configurationStr, ':', parts);
    if (parts.size() > 3)
1671
    {
Alexander Alekhin's avatar
Alexander Alekhin committed
1672 1673 1674 1675 1676 1677 1678 1679
        std::cerr << "ERROR: Invalid configuration string for OpenCL device" << std::endl;
        return false;
    }
    if (parts.size() > 2)
        deviceNameOrID = parts[2];
    if (parts.size() > 1)
    {
        split(parts[1], '|', deviceTypes);
1680
    }
Alexander Alekhin's avatar
Alexander Alekhin committed
1681
    if (parts.size() > 0)
1682
    {
Alexander Alekhin's avatar
Alexander Alekhin committed
1683
        platform = parts[0];
1684 1685 1686 1687
    }
    return true;
}

1688
#ifdef WINRT
1689 1690 1691 1692 1693
static cl_device_id selectOpenCLDevice()
{
    return NULL;
}
#else
1694 1695 1696 1697 1698
// std::tolower is int->int
static char char_tolower(char ch)
{
    return (char)std::tolower((int)ch);
}
1699 1700
static cl_device_id selectOpenCLDevice()
{
1701
    std::string platform, deviceName;
1702
    std::vector<std::string> deviceTypes;
1703

1704
    const char* configuration = getenv("OPENCV_OPENCL_DEVICE");
1705 1706 1707 1708
    if (configuration &&
            (strcmp(configuration, "disabled") == 0 ||
             !parseOpenCLDeviceConfiguration(std::string(configuration), platform, deviceTypes, deviceName)
            ))
1709
        return NULL;
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

    bool isID = false;
    int deviceID = -1;
    if (deviceName.length() == 1)
    // We limit ID range to 0..9, because we want to write:
    // - '2500' to mean i5-2500
    // - '8350' to mean AMD FX-8350
    // - '650' to mean GeForce 650
    // To extend ID range change condition to '> 0'
    {
        isID = true;
        for (size_t i = 0; i < deviceName.length(); i++)
        {
            if (!isdigit(deviceName[i]))
            {
                isID = false;
                break;
            }
        }
        if (isID)
        {
            deviceID = atoi(deviceName.c_str());
1732 1733
            if (deviceID < 0)
                return NULL;
1734 1735 1736 1737
        }
    }

    std::vector<cl_platform_id> platforms;
Alexander Alekhin's avatar
Alexander Alekhin committed
1738 1739
    {
        cl_uint numPlatforms = 0;
1740
        CV_OCL_DBG_CHECK(clGetPlatformIDs(0, NULL, &numPlatforms));
1741

Alexander Alekhin's avatar
Alexander Alekhin committed
1742 1743 1744
        if (numPlatforms == 0)
            return NULL;
        platforms.resize((size_t)numPlatforms);
1745
        CV_OCL_DBG_CHECK(clGetPlatformIDs(numPlatforms, &platforms[0], &numPlatforms));
Alexander Alekhin's avatar
Alexander Alekhin committed
1746 1747
        platforms.resize(numPlatforms);
    }
1748 1749 1750 1751 1752 1753 1754

    int selectedPlatform = -1;
    if (platform.length() > 0)
    {
        for (size_t i = 0; i < platforms.size(); i++)
        {
            std::string name;
1755
            CV_OCL_DBG_CHECK(getStringInfo(clGetPlatformInfo, platforms[i], CL_PLATFORM_NAME, name));
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
            if (name.find(platform) != std::string::npos)
            {
                selectedPlatform = (int)i;
                break;
            }
        }
        if (selectedPlatform == -1)
        {
            std::cerr << "ERROR: Can't find OpenCL platform by name: " << platform << std::endl;
            goto not_found;
        }
    }
    if (deviceTypes.size() == 0)
    {
        if (!isID)
        {
            deviceTypes.push_back("GPU");
1773 1774
            if (configuration)
                deviceTypes.push_back("CPU");
1775 1776 1777 1778 1779 1780 1781
        }
        else
            deviceTypes.push_back("ALL");
    }
    for (size_t t = 0; t < deviceTypes.size(); t++)
    {
        int deviceType = 0;
1782
        std::string tempStrDeviceType = deviceTypes[t];
1783
        std::transform(tempStrDeviceType.begin(), tempStrDeviceType.end(), tempStrDeviceType.begin(), char_tolower);
1784 1785

        if (tempStrDeviceType == "gpu" || tempStrDeviceType == "dgpu" || tempStrDeviceType == "igpu")
1786
            deviceType = Device::TYPE_GPU;
1787
        else if (tempStrDeviceType == "cpu")
1788
            deviceType = Device::TYPE_CPU;
1789
        else if (tempStrDeviceType == "accelerator")
1790
            deviceType = Device::TYPE_ACCELERATOR;
1791
        else if (tempStrDeviceType == "all")
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804
            deviceType = Device::TYPE_ALL;
        else
        {
            std::cerr << "ERROR: Unsupported device type for OpenCL device (GPU, CPU, ACCELERATOR): " << deviceTypes[t] << std::endl;
            goto not_found;
        }

        std::vector<cl_device_id> devices; // TODO Use clReleaseDevice to cleanup
        for (int i = selectedPlatform >= 0 ? selectedPlatform : 0;
                (selectedPlatform >= 0 ? i == selectedPlatform : true) && (i < (int)platforms.size());
                i++)
        {
            cl_uint count = 0;
1805
            cl_int status = clGetDeviceIDs(platforms[i], deviceType, 0, NULL, &count);
1806 1807 1808 1809
            if (!(status == CL_SUCCESS || status == CL_DEVICE_NOT_FOUND))
            {
                CV_OCL_DBG_CHECK_RESULT(status, "clGetDeviceIDs get count");
            }
1810 1811 1812 1813 1814
            if (count == 0)
                continue;
            size_t base = devices.size();
            devices.resize(base + count);
            status = clGetDeviceIDs(platforms[i], deviceType, count, &devices[base], &count);
1815 1816 1817 1818
            if (!(status == CL_SUCCESS || status == CL_DEVICE_NOT_FOUND))
            {
                CV_OCL_DBG_CHECK_RESULT(status, "clGetDeviceIDs get IDs");
            }
1819 1820 1821 1822 1823 1824 1825
        }

        for (size_t i = (isID ? deviceID : 0);
             (isID ? (i == (size_t)deviceID) : true) && (i < devices.size());
             i++)
        {
            std::string name;
1826
            CV_OCL_DBG_CHECK(getStringInfo(clGetDeviceInfo, devices[i], CL_DEVICE_NAME, name));
1827
            cl_bool useGPU = true;
1828
            if(tempStrDeviceType == "dgpu" || tempStrDeviceType == "igpu")
1829 1830
            {
                cl_bool isIGPU = CL_FALSE;
1831
                CV_OCL_DBG_CHECK(clGetDeviceInfo(devices[i], CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(isIGPU), &isIGPU, NULL));
1832
                useGPU = tempStrDeviceType == "dgpu" ? !isIGPU : isIGPU;
1833 1834
            }
            if ( (isID || name.find(deviceName) != std::string::npos) && useGPU)
1835 1836 1837 1838 1839 1840
            {
                // TODO check for OpenCL 1.1
                return devices[i];
            }
        }
    }
1841

1842
not_found:
1843 1844 1845
    if (!configuration)
        return NULL; // suppress messages on stderr

1846
    std::cerr << "ERROR: Requested OpenCL device not found, check configuration: " << configuration << std::endl
1847 1848 1849 1850
            << "    Platform: " << (platform.length() == 0 ? "any" : platform) << std::endl
            << "    Device types: ";
    for (size_t t = 0; t < deviceTypes.size(); t++)
        std::cerr << deviceTypes[t] << " ";
1851

1852 1853 1854
    std::cerr << std::endl << "    Device name: " << (deviceName.length() == 0 ? "any" : deviceName) << std::endl;
    return NULL;
}
1855
#endif
1856

1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873
#ifdef HAVE_OPENCL_SVM
namespace svm {

enum AllocatorFlags { // don't use first 16 bits
        OPENCL_SVM_COARSE_GRAIN_BUFFER = 1 << 16, // clSVMAlloc + SVM map/unmap
        OPENCL_SVM_FINE_GRAIN_BUFFER = 2 << 16, // clSVMAlloc
        OPENCL_SVM_FINE_GRAIN_SYSTEM = 3 << 16, // direct access
        OPENCL_SVM_BUFFER_MASK = 3 << 16,
        OPENCL_SVM_BUFFER_MAP = 4 << 16
};

static bool checkForceSVMUmatUsage()
{
    static bool initialized = false;
    static bool force = false;
    if (!initialized)
    {
1874
        force = utils::getConfigurationParameterBool("OPENCV_OPENCL_SVM_FORCE_UMAT_USAGE", false);
1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
        initialized = true;
    }
    return force;
}
static bool checkDisableSVMUMatUsage()
{
    static bool initialized = false;
    static bool force = false;
    if (!initialized)
    {
1885
        force = utils::getConfigurationParameterBool("OPENCV_OPENCL_SVM_DISABLE_UMAT_USAGE", false);
1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
        initialized = true;
    }
    return force;
}
static bool checkDisableSVM()
{
    static bool initialized = false;
    static bool force = false;
    if (!initialized)
    {
1896
        force = utils::getConfigurationParameterBool("OPENCV_OPENCL_SVM_DISABLE", false);
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
        initialized = true;
    }
    return force;
}
// see SVMCapabilities
static unsigned int getSVMCapabilitiesMask()
{
    static bool initialized = false;
    static unsigned int mask = 0;
    if (!initialized)
    {
        const char* envValue = getenv("OPENCV_OPENCL_SVM_CAPABILITIES_MASK");
        if (envValue == NULL)
        {
            return ~0U; // all bits 1
        }
        mask = atoi(envValue);
        initialized = true;
    }
    return mask;
}
} // namespace
#endif

1921
#ifdef HAVE_OPENCL
1922 1923 1924 1925 1926 1927
static size_t getProgramCountLimit()
{
    static bool initialized = false;
    static size_t count = 0;
    if (!initialized)
    {
1928
        count = utils::getConfigurationParameterSizeT("OPENCV_OPENCL_PROGRAM_CACHE", 0);
1929 1930 1931 1932
        initialized = true;
    }
    return count;
}
1933
#endif
1934

Ilya Lavrenov's avatar
Ilya Lavrenov committed
1935
struct Context::Impl
1936
{
1937 1938 1939
    static Context::Impl* get(Context& context) { return context.p; }

    void __init()
1940 1941 1942
    {
        refcount = 1;
        handle = 0;
1943 1944 1945 1946 1947 1948 1949 1950
#ifdef HAVE_OPENCL_SVM
        svmInitialized = false;
#endif
    }

    Impl()
    {
        __init();
1951 1952
    }

1953 1954 1955 1956 1957 1958 1959 1960 1961 1962
    void setDefault()
    {
        CV_Assert(handle == NULL);

        cl_device_id d = selectOpenCLDevice();

        if (d == NULL)
            return;

        cl_platform_id pl = NULL;
1963
        CV_OCL_DBG_CHECK(clGetDeviceInfo(d, CL_DEVICE_PLATFORM, sizeof(cl_platform_id), &pl, NULL));
1964 1965 1966 1967 1968 1969 1970 1971

        cl_context_properties prop[] =
        {
            CL_CONTEXT_PLATFORM, (cl_context_properties)pl,
            0
        };

        // !!! in the current implementation force the number of devices to 1 !!!
1972 1973
        cl_uint nd = 1;
        cl_int status;
1974 1975

        handle = clCreateContext(prop, nd, &d, 0, 0, &status);
1976
        CV_OCL_DBG_CHECK_RESULT(status, "clCreateContext");
1977 1978

        bool ok = handle != 0 && status == CL_SUCCESS;
1979 1980 1981 1982 1983 1984 1985 1986 1987
        if( ok )
        {
            devices.resize(nd);
            devices[0].set(d);
        }
        else
            handle = NULL;
    }

1988 1989
    Impl(int dtype0)
    {
1990
        __init();
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001

        cl_int retval = 0;
        cl_platform_id pl = (cl_platform_id)Platform::getDefault().ptr();
        cl_context_properties prop[] =
        {
            CL_CONTEXT_PLATFORM, (cl_context_properties)pl,
            0
        };

        cl_uint i, nd0 = 0, nd = 0;
        int dtype = dtype0 & 15;
2002
        CV_OCL_DBG_CHECK(clGetDeviceIDs(pl, dtype, 0, 0, &nd0));
2003

2004
        AutoBuffer<void*> dlistbuf(nd0*2+1);
2005
        cl_device_id* dlist = (cl_device_id*)dlistbuf.data();
2006
        cl_device_id* dlist_new = dlist + nd0;
2007
        CV_OCL_DBG_CHECK(clGetDeviceIDs(pl, dtype, nd0, dlist, &nd0));
2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032
        String name0;

        for(i = 0; i < nd0; i++)
        {
            Device d(dlist[i]);
            if( !d.available() || !d.compilerAvailable() )
                continue;
            if( dtype0 == Device::TYPE_DGPU && d.hostUnifiedMemory() )
                continue;
            if( dtype0 == Device::TYPE_IGPU && !d.hostUnifiedMemory() )
                continue;
            String name = d.name();
            if( nd != 0 && name != name0 )
                continue;
            name0 = name;
            dlist_new[nd++] = dlist[i];
        }

        if(nd == 0)
            return;

        // !!! in the current implementation force the number of devices to 1 !!!
        nd = 1;

        handle = clCreateContext(prop, nd, dlist_new, 0, 0, &retval);
2033
        CV_OCL_DBG_CHECK_RESULT(retval, "clCreateContext");
2034
        bool ok = handle != 0 && retval == CL_SUCCESS;
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
        if( ok )
        {
            devices.resize(nd);
            for( i = 0; i < nd; i++ )
                devices[i].set(dlist_new[i]);
        }
    }

    ~Impl()
    {
        if(handle)
2046
        {
2047
            CV_OCL_DBG_CHECK(clReleaseContext(handle));
2048 2049
            handle = NULL;
        }
2050 2051 2052
        devices.clear();
    }

2053
    Program getProg(const ProgramSource& src, const String& buildflags, String& errmsg);
2054

2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071
    void unloadProg(Program& prog)
    {
        cv::AutoLock lock(program_cache_mutex);
        for (CacheList::iterator i = cacheList.begin(); i != cacheList.end(); ++i)
        {
              phash_t::iterator it = phash.find(*i);
              if (it != phash.end())
              {
                  if (it->second.ptr() == prog.ptr())
                  {
                      phash.erase(*i);
                      cacheList.erase(i);
                      return;
                  }
              }
        }
    }
2072

2073
    std::string& getPrefixString()
2074 2075 2076
    {
        if (prefix.empty())
        {
2077 2078
            cv::AutoLock lock(program_cache_mutex);
            if (prefix.empty())
2079
            {
2080 2081 2082 2083 2084 2085 2086 2087
                CV_Assert(!devices.empty());
                const Device& d = devices[0];
                int bits = d.addressBits();
                if (bits > 0 && bits != 64)
                    prefix = cv::format("%d-bit--", bits);
                prefix += d.vendorName() + "--" + d.name() + "--" + d.driverVersion();
                // sanitize chars
                for (size_t i = 0; i < prefix.size(); i++)
2088
                {
2089 2090 2091 2092 2093
                    char c = prefix[i];
                    if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-'))
                    {
                        prefix[i] = '_';
                    }
2094 2095 2096 2097 2098 2099
                }
            }
        }
        return prefix;
    }

2100 2101 2102 2103
    std::string& getPrefixBase()
    {
        if (prefix_base.empty())
        {
2104 2105
            cv::AutoLock lock(program_cache_mutex);
            if (prefix_base.empty())
2106
            {
2107 2108 2109 2110 2111 2112 2113
                const Device& d = devices[0];
                int bits = d.addressBits();
                if (bits > 0 && bits != 64)
                    prefix_base = cv::format("%d-bit--", bits);
                prefix_base += d.vendorName() + "--" + d.name() + "--";
                // sanitize chars
                for (size_t i = 0; i < prefix_base.size(); i++)
2114
                {
2115 2116 2117 2118 2119
                    char c = prefix_base[i];
                    if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-'))
                    {
                        prefix_base[i] = '_';
                    }
2120 2121 2122 2123 2124 2125
                }
            }
        }
        return prefix_base;
    }

2126 2127 2128 2129 2130
    IMPLEMENT_REFCOUNTABLE();

    cl_context handle;
    std::vector<Device> devices;

2131
    std::string prefix;
2132
    std::string prefix_base;
2133

2134 2135
    cv::Mutex program_cache_mutex;
    typedef std::map<std::string, Program> phash_t;
2136
    phash_t phash;
2137 2138
    typedef std::list<cv::String> CacheList;
    CacheList cacheList;
2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179

#ifdef HAVE_OPENCL_SVM
    bool svmInitialized;
    bool svmAvailable;
    bool svmEnabled;
    svm::SVMCapabilities svmCapabilities;
    svm::SVMFunctions svmFunctions;

    void svmInit()
    {
        CV_Assert(handle != NULL);
        const Device& device = devices[0];
        cl_device_svm_capabilities deviceCaps = 0;
        CV_Assert(((void)0, CL_DEVICE_SVM_CAPABILITIES == CL_DEVICE_SVM_CAPABILITIES_AMD)); // Check assumption
        cl_int status = clGetDeviceInfo((cl_device_id)device.ptr(), CL_DEVICE_SVM_CAPABILITIES, sizeof(deviceCaps), &deviceCaps, NULL);
        if (status != CL_SUCCESS)
        {
            CV_OPENCL_SVM_TRACE_ERROR_P("CL_DEVICE_SVM_CAPABILITIES via clGetDeviceInfo failed: %d\n", status);
            goto noSVM;
        }
        CV_OPENCL_SVM_TRACE_P("CL_DEVICE_SVM_CAPABILITIES returned: 0x%x\n", (int)deviceCaps);
        CV_Assert(((void)0, CL_DEVICE_SVM_COARSE_GRAIN_BUFFER == CL_DEVICE_SVM_COARSE_GRAIN_BUFFER_AMD)); // Check assumption
        svmCapabilities.value_ =
                ((deviceCaps & CL_DEVICE_SVM_COARSE_GRAIN_BUFFER) ? svm::SVMCapabilities::SVM_COARSE_GRAIN_BUFFER : 0) |
                ((deviceCaps & CL_DEVICE_SVM_FINE_GRAIN_BUFFER) ? svm::SVMCapabilities::SVM_FINE_GRAIN_BUFFER : 0) |
                ((deviceCaps & CL_DEVICE_SVM_FINE_GRAIN_SYSTEM) ? svm::SVMCapabilities::SVM_FINE_GRAIN_SYSTEM : 0) |
                ((deviceCaps & CL_DEVICE_SVM_ATOMICS) ? svm::SVMCapabilities::SVM_ATOMICS : 0);
        svmCapabilities.value_ &= svm::getSVMCapabilitiesMask();
        if (svmCapabilities.value_ == 0)
        {
            CV_OPENCL_SVM_TRACE_ERROR_P("svmCapabilities is empty\n");
            goto noSVM;
        }
        try
        {
            // Try OpenCL 2.0
            CV_OPENCL_SVM_TRACE_P("Try SVM from OpenCL 2.0 ...\n");
            void* ptr = clSVMAlloc(handle, CL_MEM_READ_WRITE, 100, 0);
            if (!ptr)
            {
                CV_OPENCL_SVM_TRACE_ERROR_P("clSVMAlloc returned NULL...\n");
2180
                CV_Error(Error::StsBadArg, "clSVMAlloc returned NULL");
2181 2182 2183 2184 2185 2186 2187 2188
            }
            try
            {
                bool error = false;
                cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
                if (CL_SUCCESS != clEnqueueSVMMap(q, CL_TRUE, CL_MAP_WRITE, ptr, 100, 0, NULL, NULL))
                {
                    CV_OPENCL_SVM_TRACE_ERROR_P("clEnqueueSVMMap failed...\n");
2189
                    CV_Error(Error::StsBadArg, "clEnqueueSVMMap FAILED");
2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
                }
                clFinish(q);
                try
                {
                    ((int*)ptr)[0] = 100;
                }
                catch (...)
                {
                    CV_OPENCL_SVM_TRACE_ERROR_P("SVM buffer access test FAILED\n");
                    error = true;
                }
                if (CL_SUCCESS != clEnqueueSVMUnmap(q, ptr, 0, NULL, NULL))
                {
                    CV_OPENCL_SVM_TRACE_ERROR_P("clEnqueueSVMUnmap failed...\n");
2204
                    CV_Error(Error::StsBadArg, "clEnqueueSVMUnmap FAILED");
2205 2206 2207 2208
                }
                clFinish(q);
                if (error)
                {
2209
                    CV_Error(Error::StsBadArg, "OpenCL SVM buffer access test was FAILED");
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241
                }
            }
            catch (...)
            {
                CV_OPENCL_SVM_TRACE_ERROR_P("OpenCL SVM buffer access test was FAILED\n");
                clSVMFree(handle, ptr);
                throw;
            }
            clSVMFree(handle, ptr);
            svmFunctions.fn_clSVMAlloc = clSVMAlloc;
            svmFunctions.fn_clSVMFree = clSVMFree;
            svmFunctions.fn_clSetKernelArgSVMPointer = clSetKernelArgSVMPointer;
            //svmFunctions.fn_clSetKernelExecInfo = clSetKernelExecInfo;
            //svmFunctions.fn_clEnqueueSVMFree = clEnqueueSVMFree;
            svmFunctions.fn_clEnqueueSVMMemcpy = clEnqueueSVMMemcpy;
            svmFunctions.fn_clEnqueueSVMMemFill = clEnqueueSVMMemFill;
            svmFunctions.fn_clEnqueueSVMMap = clEnqueueSVMMap;
            svmFunctions.fn_clEnqueueSVMUnmap = clEnqueueSVMUnmap;
        }
        catch (...)
        {
            CV_OPENCL_SVM_TRACE_P("clSVMAlloc failed, trying HSA extension...\n");
            try
            {
                // Try HSA extension
                String extensions = device.extensions();
                if (extensions.find("cl_amd_svm") == String::npos)
                {
                    CV_OPENCL_SVM_TRACE_P("Device extension doesn't have cl_amd_svm: %s\n", extensions.c_str());
                    goto noSVM;
                }
                cl_platform_id p = NULL;
2242
                CV_OCL_CHECK(status = clGetDeviceInfo((cl_device_id)device.ptr(), CL_DEVICE_PLATFORM, sizeof(cl_platform_id), &p, NULL));
2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275
                svmFunctions.fn_clSVMAlloc = (clSVMAllocAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSVMAllocAMD");
                svmFunctions.fn_clSVMFree = (clSVMFreeAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSVMFreeAMD");
                svmFunctions.fn_clSetKernelArgSVMPointer = (clSetKernelArgSVMPointerAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSetKernelArgSVMPointerAMD");
                //svmFunctions.fn_clSetKernelExecInfo = (clSetKernelExecInfoAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSetKernelExecInfoAMD");
                //svmFunctions.fn_clEnqueueSVMFree = (clEnqueueSVMFreeAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMFreeAMD");
                svmFunctions.fn_clEnqueueSVMMemcpy = (clEnqueueSVMMemcpyAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMMemcpyAMD");
                svmFunctions.fn_clEnqueueSVMMemFill = (clEnqueueSVMMemFillAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMMemFillAMD");
                svmFunctions.fn_clEnqueueSVMMap = (clEnqueueSVMMapAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMMapAMD");
                svmFunctions.fn_clEnqueueSVMUnmap = (clEnqueueSVMUnmapAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMUnmapAMD");
                CV_Assert(svmFunctions.isValid());
            }
            catch (...)
            {
                CV_OPENCL_SVM_TRACE_P("Something is totally wrong\n");
                goto noSVM;
            }
        }

        svmAvailable = true;
        svmEnabled = !svm::checkDisableSVM();
        svmInitialized = true;
        CV_OPENCL_SVM_TRACE_P("OpenCV OpenCL SVM support initialized\n");
        return;
    noSVM:
        CV_OPENCL_SVM_TRACE_P("OpenCL SVM is not detected\n");
        svmAvailable = false;
        svmEnabled = false;
        svmCapabilities.value_ = 0;
        svmInitialized = true;
        svmFunctions.fn_clSVMAlloc = NULL;
        return;
    }
#endif
2276 2277

    friend class Program;
2278 2279 2280
};


Ilya Lavrenov's avatar
Ilya Lavrenov committed
2281
Context::Context()
2282 2283 2284 2285
{
    p = 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2286
Context::Context(int dtype)
2287 2288 2289 2290 2291
{
    p = 0;
    create(dtype);
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2292
bool Context::create()
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306
{
    if( !haveOpenCL() )
        return false;
    if(p)
        p->release();
    p = new Impl();
    if(!p->handle)
    {
        delete p;
        p = 0;
    }
    return p != 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2307
bool Context::create(int dtype0)
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321
{
    if( !haveOpenCL() )
        return false;
    if(p)
        p->release();
    p = new Impl(dtype0);
    if(!p->handle)
    {
        delete p;
        p = 0;
    }
    return p != 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2322
Context::~Context()
2323
{
2324 2325 2326 2327 2328
    if (p)
    {
        p->release();
        p = NULL;
    }
2329 2330
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2331
Context::Context(const Context& c)
2332 2333 2334 2335 2336 2337
{
    p = (Impl*)c.p;
    if(p)
        p->addref();
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2338
Context& Context::operator = (const Context& c)
2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
{
    Impl* newp = (Impl*)c.p;
    if(newp)
        newp->addref();
    if(p)
        p->release();
    p = newp;
    return *this;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2349
void* Context::ptr() const
2350
{
2351
    return p == NULL ? NULL : p->handle;
2352 2353
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2354
size_t Context::ndevices() const
2355 2356 2357 2358
{
    return p ? p->devices.size() : 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2359
const Device& Context::device(size_t idx) const
2360 2361 2362 2363 2364
{
    static Device dummy;
    return !p || idx >= p->devices.size() ? dummy : p->devices[idx];
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2365
Context& Context::getDefault(bool initialize)
2366
{
2367 2368
    static Context* ctx = new Context();
    if(!ctx->p && haveOpenCL())
2369
    {
2370 2371
        if (!ctx->p)
            ctx->p = new Impl();
2372 2373
        if (initialize)
        {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2374
            // do not create new Context right away.
2375
            // First, try to retrieve existing context of the same type.
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2376
            // In its turn, Platform::getContext() may call Context::create()
2377
            // if there is no such context.
2378 2379
            if (ctx->p->handle == NULL)
                ctx->p->setDefault();
2380
        }
2381 2382
    }

2383
    return *ctx;
2384 2385
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2386
Program Context::getProg(const ProgramSource& prog,
2387 2388 2389 2390 2391
                         const String& buildopts, String& errmsg)
{
    return p ? p->getProg(prog, buildopts, errmsg) : Program();
}

2392 2393 2394 2395 2396
void Context::unloadProg(Program& prog)
{
    if (p)
        p->unloadProg(prog);
}
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414

#ifdef HAVE_OPENCL_SVM
bool Context::useSVM() const
{
    Context::Impl* i = p;
    CV_Assert(i);
    if (!i->svmInitialized)
        i->svmInit();
    return i->svmEnabled;
}
void Context::setUseSVM(bool enabled)
{
    Context::Impl* i = p;
    CV_Assert(i);
    if (!i->svmInitialized)
        i->svmInit();
    if (enabled && !i->svmAvailable)
    {
2415
        CV_Error(Error::StsError, "OpenCL Shared Virtual Memory (SVM) is not supported by OpenCL device");
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459
    }
    i->svmEnabled = enabled;
}
#else
bool Context::useSVM() const { return false; }
void Context::setUseSVM(bool enabled) { CV_Assert(!enabled); }
#endif

#ifdef HAVE_OPENCL_SVM
namespace svm {

const SVMCapabilities getSVMCapabilitites(const ocl::Context& context)
{
    Context::Impl* i = context.p;
    CV_Assert(i);
    if (!i->svmInitialized)
        i->svmInit();
    return i->svmCapabilities;
}

CV_EXPORTS const SVMFunctions* getSVMFunctions(const ocl::Context& context)
{
    Context::Impl* i = context.p;
    CV_Assert(i);
    CV_Assert(i->svmInitialized); // getSVMCapabilitites() must be called first
    CV_Assert(i->svmFunctions.fn_clSVMAlloc != NULL);
    return &i->svmFunctions;
}

CV_EXPORTS bool useSVM(UMatUsageFlags usageFlags)
{
    if (checkForceSVMUmatUsage())
        return true;
    if (checkDisableSVMUMatUsage())
        return false;
    if ((usageFlags & USAGE_ALLOCATE_SHARED_MEMORY) != 0)
        return true;
    return false; // don't use SVM by default
}

} // namespace cv::ocl::svm
#endif // HAVE_OPENCL_SVM


2460 2461 2462 2463
static void get_platform_name(cl_platform_id id, String& name)
{
    // get platform name string length
    size_t sz = 0;
2464
    CV_OCL_CHECK(clGetPlatformInfo(id, CL_PLATFORM_NAME, 0, 0, &sz));
2465 2466 2467

    // get platform name string
    AutoBuffer<char> buf(sz + 1);
2468
    CV_OCL_CHECK(clGetPlatformInfo(id, CL_PLATFORM_NAME, sz, buf.data(), 0));
2469 2470 2471 2472

    // just in case, ensure trailing zero for ASCIIZ string
    buf[sz] = 0;

2473
    name = buf.data();
2474 2475 2476 2477 2478 2479 2480 2481 2482
}

/*
// Attaches OpenCL context to OpenCV
*/
void attachContext(const String& platformName, void* platformID, void* context, void* deviceID)
{
    cl_uint cnt = 0;

2483
    CV_OCL_CHECK(clGetPlatformIDs(0, 0, &cnt));
2484 2485

    if (cnt == 0)
2486
        CV_Error(cv::Error::OpenCLApiCallError, "no OpenCL platform available!");
2487 2488 2489

    std::vector<cl_platform_id> platforms(cnt);

2490
    CV_OCL_CHECK(clGetPlatformIDs(cnt, &platforms[0], 0));
2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507

    bool platformAvailable = false;

    // check if external platformName contained in list of available platforms in OpenCV
    for (unsigned int i = 0; i < cnt; i++)
    {
        String availablePlatformName;
        get_platform_name(platforms[i], availablePlatformName);
        // external platform is found in the list of available platforms
        if (platformName == availablePlatformName)
        {
            platformAvailable = true;
            break;
        }
    }

    if (!platformAvailable)
2508
        CV_Error(cv::Error::OpenCLApiCallError, "No matched platforms available!");
2509 2510 2511 2512 2513

    // check if platformID corresponds to platformName
    String actualPlatformName;
    get_platform_name((cl_platform_id)platformID, actualPlatformName);
    if (platformName != actualPlatformName)
2514
        CV_Error(cv::Error::OpenCLApiCallError, "No matched platforms available!");
2515 2516 2517 2518 2519 2520 2521

    // do not initialize OpenCL context
    Context ctx = Context::getDefault(false);

    // attach supplied context to OpenCV
    initializeContextFromHandle(ctx, platformID, context, deviceID);

2522
    CV_OCL_CHECK(clRetainContext((cl_context)context));
2523 2524 2525 2526 2527 2528 2529 2530 2531

    // clear command queue, if any
    getCoreTlsData().get()->oclQueue.finish();
    Queue q;
    getCoreTlsData().get()->oclQueue = q;

    return;
} // attachContext()

2532

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2533
void initializeContextFromHandle(Context& ctx, void* platform, void* _context, void* _device)
2534 2535 2536 2537 2538
{
    cl_context context = (cl_context)_context;
    cl_device_id device = (cl_device_id)_device;

    // cleanup old context
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2539
    Context::Impl * impl = ctx.p;
2540 2541
    if (impl->handle)
    {
2542
        CV_OCL_DBG_CHECK(clReleaseContext(impl->handle));
2543 2544 2545 2546 2547 2548 2549 2550
    }
    impl->devices.clear();

    impl->handle = context;
    impl->devices.resize(1);
    impl->devices[0].set(device);

    Platform& p = Platform::getDefault();
2551
    Platform::Impl* pImpl = p.p;
2552 2553 2554
    pImpl->handle = (cl_platform_id)platform;
}

2555
/////////////////////////////////////////// Queue /////////////////////////////////////////////
2556

2557 2558
struct Queue::Impl
{
2559
    inline void __init()
2560 2561
    {
        refcount = 1;
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
        handle = 0;
        isProfilingQueue_ = false;
    }

    Impl(cl_command_queue q)
    {
        __init();
        handle = q;

        cl_command_queue_properties props = 0;
2572
        CV_OCL_CHECK(clGetCommandQueueInfo(handle, CL_QUEUE_PROPERTIES, sizeof(cl_command_queue_properties), &props, NULL));
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586
        isProfilingQueue_ = !!(props & CL_QUEUE_PROFILING_ENABLE);
    }

    Impl(cl_command_queue q, bool isProfilingQueue)
    {
        __init();
        handle = q;
        isProfilingQueue_ = isProfilingQueue;
    }

    Impl(const Context& c, const Device& d, bool withProfiling = false)
    {
        __init();

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2587
        const Context* pc = &c;
2588 2589 2590
        cl_context ch = (cl_context)pc->ptr();
        if( !ch )
        {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2591
            pc = &Context::getDefault();
2592 2593 2594 2595 2596 2597
            ch = (cl_context)pc->ptr();
        }
        cl_device_id dh = (cl_device_id)d.ptr();
        if( !dh )
            dh = (cl_device_id)pc->device(0).ptr();
        cl_int retval = 0;
2598
        cl_command_queue_properties props = withProfiling ? CL_QUEUE_PROFILING_ENABLE : 0;
2599
        CV_OCL_DBG_CHECK_(handle = clCreateCommandQueue(ch, dh, props, &retval), retval);
2600
        isProfilingQueue_ = withProfiling;
2601 2602 2603 2604
    }

    ~Impl()
    {
2605 2606 2607
#ifdef _WIN32
        if (!cv::__termination)
#endif
2608
        {
2609 2610
            if(handle)
            {
2611 2612
                CV_OCL_DBG_CHECK(clFinish(handle));
                CV_OCL_DBG_CHECK(clReleaseCommandQueue(handle));
2613
                handle = NULL;
2614
            }
2615 2616 2617
        }
    }

2618 2619 2620 2621 2622 2623 2624 2625 2626
    const cv::ocl::Queue& getProfilingQueue(const cv::ocl::Queue& self)
    {
        if (isProfilingQueue_)
            return self;

        if (profiling_queue_.ptr())
            return profiling_queue_;

        cl_context ctx = 0;
2627
        CV_OCL_CHECK(clGetCommandQueueInfo(handle, CL_QUEUE_CONTEXT, sizeof(cl_context), &ctx, NULL));
2628 2629

        cl_device_id device = 0;
2630
        CV_OCL_CHECK(clGetCommandQueueInfo(handle, CL_QUEUE_DEVICE, sizeof(cl_device_id), &device, NULL));
2631 2632 2633 2634

        cl_int result = CL_SUCCESS;
        cl_command_queue_properties props = CL_QUEUE_PROFILING_ENABLE;
        cl_command_queue q = clCreateCommandQueue(ctx, device, props, &result);
2635
        CV_OCL_DBG_CHECK_RESULT(result, "clCreateCommandQueue(with CL_QUEUE_PROFILING_ENABLE)");
2636 2637 2638 2639 2640 2641 2642 2643

        Queue queue;
        queue.p = new Impl(q, true);
        profiling_queue_ = queue;

        return profiling_queue_;
    }

2644 2645 2646
    IMPLEMENT_REFCOUNTABLE();

    cl_command_queue handle;
2647 2648
    bool isProfilingQueue_;
    cv::ocl::Queue profiling_queue_;
2649 2650 2651 2652 2653 2654 2655
};

Queue::Queue()
{
    p = 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2656
Queue::Queue(const Context& c, const Device& d)
2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685
{
    p = 0;
    create(c, d);
}

Queue::Queue(const Queue& q)
{
    p = q.p;
    if(p)
        p->addref();
}

Queue& Queue::operator = (const Queue& q)
{
    Impl* newp = (Impl*)q.p;
    if(newp)
        newp->addref();
    if(p)
        p->release();
    p = newp;
    return *this;
}

Queue::~Queue()
{
    if(p)
        p->release();
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2686
bool Queue::create(const Context& c, const Device& d)
2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
{
    if(p)
        p->release();
    p = new Impl(c, d);
    return p->handle != 0;
}

void Queue::finish()
{
    if(p && p->handle)
2697
    {
2698
        CV_OCL_DBG_CHECK(clFinish(p->handle));
2699
    }
2700 2701
}

2702 2703 2704 2705 2706 2707
const Queue& Queue::getProfilingQueue() const
{
    CV_Assert(p);
    return p->getProfilingQueue(*this);
}

2708 2709 2710 2711 2712 2713 2714
void* Queue::ptr() const
{
    return p ? p->handle : 0;
}

Queue& Queue::getDefault()
{
2715
    Queue& q = getCoreTlsData().get()->oclQueue;
2716
    if( !q.p && haveOpenCL() )
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2717
        q.create(Context::getDefault());
2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728
    return q;
}

static cl_command_queue getQueue(const Queue& q)
{
    cl_command_queue qq = (cl_command_queue)q.ptr();
    if(!qq)
        qq = (cl_command_queue)Queue::getDefault().ptr();
    return qq;
}

2729 2730
/////////////////////////////////////////// KernelArg /////////////////////////////////////////////

2731
KernelArg::KernelArg()
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2732
    : flags(0), m(0), obj(0), sz(0), wscale(1), iwscale(1)
2733 2734 2735
{
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2736 2737
KernelArg::KernelArg(int _flags, UMat* _m, int _wscale, int _iwscale, const void* _obj, size_t _sz)
    : flags(_flags), m(_m), obj(_obj), sz(_sz), wscale(_wscale), iwscale(_iwscale)
2738
{
2739
    CV_Assert(_flags == LOCAL || _flags == CONSTANT || _m != NULL);
2740 2741 2742 2743 2744
}

KernelArg KernelArg::Constant(const Mat& m)
{
    CV_Assert(m.isContinuous());
2745
    return KernelArg(CONSTANT, 0, 0, 0, m.ptr(), m.total()*m.elemSize());
2746 2747
}

2748
/////////////////////////////////////////// Kernel /////////////////////////////////////////////
2749 2750 2751

struct Kernel::Impl
{
2752
    Impl(const char* kname, const Program& prog) :
2753
        refcount(1), handle(NULL), isInProgress(false), nu(0)
2754 2755 2756
    {
        cl_program ph = (cl_program)prog.ptr();
        cl_int retval = 0;
2757
        name = kname;
2758 2759 2760 2761 2762
        if (ph)
        {
            handle = clCreateKernel(ph, kname, &retval);
            CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clCreateKernel('%s')", kname).c_str());
        }
2763 2764
        for( int i = 0; i < MAX_ARRS; i++ )
            u[i] = 0;
2765
        haveTempDstUMats = false;
2766 2767 2768 2769 2770 2771 2772 2773
    }

    void cleanupUMats()
    {
        for( int i = 0; i < MAX_ARRS; i++ )
            if( u[i] )
            {
                if( CV_XADD(&u[i]->urefcount, -1) == 1 )
2774 2775
                {
                    u[i]->flags |= UMatData::ASYNC_CLEANUP;
2776
                    u[i]->currAllocator->deallocate(u[i]);
2777
                }
2778 2779 2780
                u[i] = 0;
            }
        nu = 0;
2781
        haveTempDstUMats = false;
2782 2783
    }

2784
    void addUMat(const UMat& m, bool dst)
2785 2786 2787 2788 2789
    {
        CV_Assert(nu < MAX_ARRS && m.u && m.u->urefcount > 0);
        u[nu] = m.u;
        CV_XADD(&m.u->urefcount, 1);
        nu++;
2790 2791
        if(dst && m.u->tempUMat())
            haveTempDstUMats = true;
2792
    }
2793

2794 2795 2796 2797 2798
    void addImage(const Image2D& image)
    {
        images.push_back(image);
    }

2799
    void finit(cl_event e)
2800
    {
2801
        CV_UNUSED(e);
2802
        cleanupUMats();
2803
        images.clear();
2804
        isInProgress = false;
2805 2806 2807
        release();
    }

2808 2809 2810
    bool run(int dims, size_t _globalsize[], size_t _localsize[],
            bool sync, int64* timeNS, const Queue& q);

2811 2812 2813
    ~Impl()
    {
        if(handle)
2814 2815 2816
        {
            CV_OCL_DBG_CHECK(clReleaseKernel(handle));
        }
2817 2818 2819 2820
    }

    IMPLEMENT_REFCOUNTABLE();

2821
    cv::String name;
2822
    cl_kernel handle;
2823 2824
    enum { MAX_ARRS = 16 };
    UMatData* u[MAX_ARRS];
2825
    bool isInProgress;
2826
    int nu;
2827
    std::list<Image2D> images;
2828
    bool haveTempDstUMats;
2829 2830
};

2831 2832 2833
}} // namespace cv::ocl

extern "C" {
2834

2835
static void CL_CALLBACK oclCleanupCallback(cl_event e, cl_int, void *p)
2836
{
2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852
    try
    {
        ((cv::ocl::Kernel::Impl*)p)->finit(e);
    }
    catch (const cv::Exception& exc)
    {
        CV_LOG_ERROR(NULL, "OCL: Unexpected OpenCV exception in OpenCL callback: " << exc.what());
    }
    catch (const std::exception& exc)
    {
        CV_LOG_ERROR(NULL, "OCL: Unexpected C++ exception in OpenCL callback: " << exc.what());
    }
    catch (...)
    {
        CV_LOG_ERROR(NULL, "OCL: Unexpected unknown C++ exception in OpenCL callback");
    }
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869
}

}

namespace cv { namespace ocl {

Kernel::Kernel()
{
    p = 0;
}

Kernel::Kernel(const char* kname, const Program& prog)
{
    p = 0;
    create(kname, prog);
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2870
Kernel::Kernel(const char* kname, const ProgramSource& src,
2871
               const String& buildopts, String* errmsg)
2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
{
    p = 0;
    create(kname, src, buildopts, errmsg);
}

Kernel::Kernel(const Kernel& k)
{
    p = k.p;
    if(p)
        p->addref();
}

Kernel& Kernel::operator = (const Kernel& k)
{
    Impl* newp = (Impl*)k.p;
    if(newp)
        newp->addref();
    if(p)
        p->release();
    p = newp;
    return *this;
}

Kernel::~Kernel()
{
    if(p)
        p->release();
}

bool Kernel::create(const char* kname, const Program& prog)
{
    if(p)
        p->release();
    p = new Impl(kname, prog);
    if(p->handle == 0)
    {
        p->release();
        p = 0;
    }
2911 2912 2913
#ifdef CV_OPENCL_RUN_ASSERT // check kernel compilation fails
    CV_Assert(p);
#endif
2914 2915 2916
    return p != 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2917
bool Kernel::create(const char* kname, const ProgramSource& src,
2918
                    const String& buildopts, String* errmsg)
2919 2920 2921 2922 2923 2924
{
    if(p)
    {
        p->release();
        p = 0;
    }
2925 2926
    String tempmsg;
    if( !errmsg ) errmsg = &tempmsg;
2927
    const Program prog = Context::getDefault().getProg(src, buildopts, *errmsg);
2928 2929 2930 2931 2932 2933 2934 2935
    return create(kname, prog);
}

void* Kernel::ptr() const
{
    return p ? p->handle : 0;
}

2936
bool Kernel::empty() const
2937
{
2938 2939 2940 2941 2942
    return ptr() == 0;
}

int Kernel::set(int i, const void* value, size_t sz)
{
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2943 2944
    if (!p || !p->handle)
        return -1;
2945 2946
    if (i < 0)
        return i;
2947 2948
    if( i == 0 )
        p->cleanupUMats();
2949 2950

    cl_int retval = clSetKernelArg(p->handle, (cl_uint)i, sz, value);
2951
    CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clSetKernelArg('%s', arg_index=%d, size=%d, value=%p)", p->name.c_str(), (int)i, (int)sz, (void*)value).c_str());
2952
    if (retval != CL_SUCCESS)
2953 2954
        return -1;
    return i+1;
2955 2956
}

2957 2958
int Kernel::set(int i, const Image2D& image2D)
{
2959
    p->addImage(image2D);
2960 2961 2962 2963
    cl_mem h = (cl_mem)image2D.ptr();
    return set(i, &h, sizeof(h));
}

2964
int Kernel::set(int i, const UMat& m)
2965
{
2966
    return set(i, KernelArg(KernelArg::READ_WRITE, (UMat*)&m));
2967 2968
}

2969
int Kernel::set(int i, const KernelArg& arg)
2970
{
2971 2972
    if( !p || !p->handle )
        return -1;
2973 2974
    if (i < 0)
        return i;
2975 2976
    if( i == 0 )
        p->cleanupUMats();
2977
    cl_int status = 0;
2978 2979
    if( arg.m )
    {
2980 2981
        int accessFlags = ((arg.flags & KernelArg::READ_ONLY) ? ACCESS_READ : 0) +
                          ((arg.flags & KernelArg::WRITE_ONLY) ? ACCESS_WRITE : 0);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
2982
        bool ptronly = (arg.flags & KernelArg::PTR_ONLY) != 0;
2983 2984
        cl_mem h = (cl_mem)arg.m->handle(accessFlags);

Ilya Lavrenov's avatar
Ilya Lavrenov committed
2985 2986 2987 2988 2989 2990 2991
        if (!h)
        {
            p->release();
            p = 0;
            return -1;
        }

2992 2993 2994 2995 2996 2997 2998 2999
#ifdef HAVE_OPENCL_SVM
        if ((arg.m->u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
        {
            const Context& ctx = Context::getDefault();
            const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
            uchar*& svmDataPtr = (uchar*&)arg.m->u->handle;
            CV_OPENCL_SVM_TRACE_P("clSetKernelArgSVMPointer: %p\n", svmDataPtr);
#if 1 // TODO
3000
            status = svmFns->fn_clSetKernelArgSVMPointer(p->handle, (cl_uint)i, svmDataPtr);
3001
#else
3002
            status = svmFns->fn_clSetKernelArgSVMPointer(p->handle, (cl_uint)i, &svmDataPtr);
3003
#endif
3004
            CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArgSVMPointer('%s', arg_index=%d, ptr=%p)", p->name.c_str(), (int)i, (void*)svmDataPtr).c_str());
3005 3006 3007 3008
        }
        else
#endif
        {
3009 3010
            status = clSetKernelArg(p->handle, (cl_uint)i, sizeof(h), &h);
            CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, cl_mem=%p)", p->name.c_str(), (int)i, (void*)h).c_str());
3011 3012
        }

Ilya Lavrenov's avatar
Ilya Lavrenov committed
3013
        if (ptronly)
3014 3015 3016
        {
            i++;
        }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
3017
        else if( arg.m->dims <= 2 )
3018
        {
3019
            UMat2D u2d(*arg.m);
3020 3021 3022 3023
            status = clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u2d.step), &u2d.step);
            CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, step_value=%d)", p->name.c_str(), (int)(i+1), (int)u2d.step).c_str());
            status = clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u2d.offset), &u2d.offset);
            CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, offset_value=%d)", p->name.c_str(), (int)(i+2), (int)u2d.offset).c_str());
3024 3025 3026 3027
            i += 3;

            if( !(arg.flags & KernelArg::NO_SIZE) )
            {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
3028
                int cols = u2d.cols*arg.wscale/arg.iwscale;
3029 3030 3031 3032
                status = clSetKernelArg(p->handle, (cl_uint)i, sizeof(u2d.rows), &u2d.rows);
                CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, rows_value=%d)", p->name.c_str(), (int)i, (int)u2d.rows).c_str());
                status = clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(cols), &cols);
                CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, cols_value=%d)", p->name.c_str(), (int)(i+1), (int)cols).c_str());
3033 3034
                i += 2;
            }
3035 3036 3037
        }
        else
        {
3038
            UMat3D u3d(*arg.m);
3039 3040 3041 3042 3043 3044
            status = clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u3d.slicestep), &u3d.slicestep);
            CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, slicestep_value=%d)", p->name.c_str(), (int)(i+1), (int)u3d.slicestep).c_str());
            status = clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u3d.step), &u3d.step);
            CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, step_value=%d)", p->name.c_str(), (int)(i+2), (int)u3d.step).c_str());
            status = clSetKernelArg(p->handle, (cl_uint)(i+3), sizeof(u3d.offset), &u3d.offset);
            CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, offset_value=%d)", p->name.c_str(), (int)(i+3), (int)u3d.offset).c_str());
3045 3046 3047
            i += 4;
            if( !(arg.flags & KernelArg::NO_SIZE) )
            {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
3048
                int cols = u3d.cols*arg.wscale/arg.iwscale;
3049 3050 3051 3052 3053 3054
                status = clSetKernelArg(p->handle, (cl_uint)i, sizeof(u3d.slices), &u3d.slices);
                CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, slices_value=%d)", p->name.c_str(), (int)i, (int)u3d.slices).c_str());
                status = clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u3d.rows), &u3d.rows);
                CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, rows_value=%d)", p->name.c_str(), (int)(i+1), (int)u3d.rows).c_str());
                status = clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u3d.cols), &cols);
                CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, cols_value=%d)", p->name.c_str(), (int)(i+2), (int)cols).c_str());
3055 3056
                i += 3;
            }
3057
        }
3058
        p->addUMat(*arg.m, (accessFlags & ACCESS_WRITE) != 0);
3059
        return i;
3060
    }
3061 3062
    status = clSetKernelArg(p->handle, (cl_uint)i, arg.sz, arg.obj);
    CV_OCL_DBG_CHECK_RESULT(status, cv::format("clSetKernelArg('%s', arg_index=%d, size=%d, obj=%p)", p->name.c_str(), (int)i, (int)arg.sz, (void*)arg.obj).c_str());
3063
    return i+1;
3064 3065
}

3066
bool Kernel::run(int dims, size_t _globalsize[], size_t _localsize[],
3067
                 bool sync, const Queue& q)
3068
{
3069
    if (!p)
3070
        return false;
3071

3072
    size_t globalsize[CV_MAX_DIM] = {1,1,1};
3073
    size_t total = 1;
3074
    CV_Assert(_globalsize != NULL);
3075 3076
    for (int i = 0; i < dims; i++)
    {
3077
        size_t val = _localsize ? _localsize[i] :
Ilya Lavrenov's avatar
Ilya Lavrenov committed
3078
            dims == 1 ? 64 : dims == 2 ? (i == 0 ? 256 : 8) : dims == 3 ? (8>>(int)(i>0)) : 1;
3079
        CV_Assert( val > 0 );
3080
        total *= _globalsize[i];
3081 3082 3083
        if (_globalsize[i] == 1)
            val = 1;
        globalsize[i] = divUp(_globalsize[i], (unsigned int)val) * val;
3084
    }
3085
    CV_Assert(total > 0);
3086 3087 3088 3089 3090 3091 3092 3093

    return p->run(dims, globalsize, _localsize, sync, NULL, q);
}


bool Kernel::Impl::run(int dims, size_t globalsize[], size_t localsize[],
        bool sync, int64* timeNS, const Queue& q)
{
3094
    CV_INSTRUMENT_REGION_OPENCL_RUN(name.c_str());
3095 3096 3097 3098 3099 3100 3101 3102

    if (!handle || isInProgress)
        return false;

    cl_command_queue qq = getQueue(q);
    if (haveTempDstUMats)
        sync = true;
    if (timeNS)
3103
        sync = true;
3104
    cl_event asyncEvent = 0;
3105 3106 3107
    cl_int retval = clEnqueueNDRangeKernel(qq, handle, (cl_uint)dims,
                                           NULL, globalsize, localsize, 0, 0,
                                           (sync && !timeNS) ? 0 : &asyncEvent);
3108
#if !CV_OPENCL_SHOW_RUN_KERNELS
3109
    if (retval != CL_SUCCESS)
3110
#endif
3111
    {
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124
        cv::String msg = cv::format("clEnqueueNDRangeKernel('%s', dims=%d, globalsize=%dx%dx%d, localsize=%s) sync=%s", name.c_str(), (int)dims,
                        globalsize[0], (dims > 1 ? globalsize[1] : 1), (dims > 2 ? globalsize[2] : 1),
                        (localsize ? cv::format("%dx%dx%d", localsize[0], (dims > 1 ? localsize[1] : 1), (dims > 2 ? localsize[2] : 1)) : cv::String("NULL")).c_str(),
                        sync ? "true" : "false"
                        );
        if (retval != CL_SUCCESS)
        {
            msg = CV_OCL_API_ERROR_MSG(retval, msg.c_str());
        }
#if CV_OPENCL_TRACE_CHECK
        CV_OCL_TRACE_CHECK_RESULT(retval, msg.c_str());
#else
        printf("%s\n", msg.c_str());
3125 3126
        fflush(stdout);
#endif
3127
    }
3128
    if (sync || retval != CL_SUCCESS)
3129
    {
3130
        CV_OCL_DBG_CHECK(clFinish(qq));
3131 3132 3133 3134
        if (timeNS)
        {
            if (retval == CL_SUCCESS)
            {
3135
                CV_OCL_DBG_CHECK(clWaitForEvents(1, &asyncEvent));
3136
                cl_ulong startTime, stopTime;
3137 3138
                CV_OCL_CHECK(clGetEventProfilingInfo(asyncEvent, CL_PROFILING_COMMAND_START, sizeof(startTime), &startTime, NULL));
                CV_OCL_CHECK(clGetEventProfilingInfo(asyncEvent, CL_PROFILING_COMMAND_END, sizeof(stopTime), &stopTime, NULL));
3139 3140 3141 3142 3143 3144 3145 3146
                *timeNS = (int64)(stopTime - startTime);
            }
            else
            {
                *timeNS = -1;
            }
        }
        cleanupUMats();
3147 3148 3149
    }
    else
    {
3150 3151
        addref();
        isInProgress = true;
3152
        CV_OCL_CHECK(clSetEventCallback(asyncEvent, CL_COMPLETE, oclCleanupCallback, this));
3153
    }
3154
    if (asyncEvent)
3155
        CV_OCL_DBG_CHECK(clReleaseEvent(asyncEvent));
3156
    return retval == CL_SUCCESS;
3157 3158
}

3159
bool Kernel::runTask(bool sync, const Queue& q)
3160
{
3161
    if(!p || !p->handle || p->isInProgress)
3162 3163
        return false;

3164
    cl_command_queue qq = getQueue(q);
3165 3166
    cl_event asyncEvent = 0;
    cl_int retval = clEnqueueTask(qq, p->handle, 0, 0, sync ? 0 : &asyncEvent);
3167 3168
    CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clEnqueueTask('%s') sync=%s", p->name.c_str(), sync ? "true" : "false").c_str());
    if (sync || retval != CL_SUCCESS)
3169
    {
3170
        CV_OCL_DBG_CHECK(clFinish(qq));
3171
        p->cleanupUMats();
3172 3173 3174 3175
    }
    else
    {
        p->addref();
3176
        p->isInProgress = true;
3177
        CV_OCL_CHECK(clSetEventCallback(asyncEvent, CL_COMPLETE, oclCleanupCallback, p));
3178
    }
3179
    if (asyncEvent)
3180
        CV_OCL_DBG_CHECK(clReleaseEvent(asyncEvent));
3181
    return retval == CL_SUCCESS;
3182 3183
}

3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
int64 Kernel::runProfiling(int dims, size_t globalsize[], size_t localsize[], const Queue& q_)
{
    CV_Assert(p && p->handle && !p->isInProgress);
    Queue q = q_.ptr() ? q_ : Queue::getDefault();
    CV_Assert(q.ptr());
    q.finish(); // call clFinish() on base queue
    Queue profilingQueue = q.getProfilingQueue();
    int64 timeNs = -1;
    bool res = p->run(dims, globalsize, localsize, true, &timeNs, profilingQueue);
    return res ? timeNs : -1;
}
3195 3196 3197

size_t Kernel::workGroupSize() const
{
3198
    if(!p || !p->handle)
3199 3200 3201
        return 0;
    size_t val = 0, retsz = 0;
    cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
3202 3203 3204
    cl_int status = clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_WORK_GROUP_SIZE, sizeof(val), &val, &retsz);
    CV_OCL_CHECK_RESULT(status, "clGetKernelWorkGroupInfo(CL_KERNEL_WORK_GROUP_SIZE)");
    return status == CL_SUCCESS ? val : 0;
3205 3206
}

Konstantin Matskevich's avatar
Konstantin Matskevich committed
3207 3208
size_t Kernel::preferedWorkGroupSizeMultiple() const
{
3209
    if(!p || !p->handle)
Konstantin Matskevich's avatar
Konstantin Matskevich committed
3210 3211 3212
        return 0;
    size_t val = 0, retsz = 0;
    cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
3213 3214 3215
    cl_int status = clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(val), &val, &retsz);
    CV_OCL_CHECK_RESULT(status, "clGetKernelWorkGroupInfo(CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE)");
    return status == CL_SUCCESS ? val : 0;
Konstantin Matskevich's avatar
Konstantin Matskevich committed
3216 3217
}

3218 3219
bool Kernel::compileWorkGroupSize(size_t wsz[]) const
{
3220
    if(!p || !p->handle || !wsz)
3221 3222 3223
        return 0;
    size_t retsz = 0;
    cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
3224 3225 3226
    cl_int status = clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_COMPILE_WORK_GROUP_SIZE, sizeof(wsz[0])*3, wsz, &retsz);
    CV_OCL_CHECK_RESULT(status, "clGetKernelWorkGroupInfo(CL_KERNEL_COMPILE_WORK_GROUP_SIZE)");
    return status == CL_SUCCESS;
3227 3228 3229 3230
}

size_t Kernel::localMemSize() const
{
3231
    if(!p || !p->handle)
3232 3233 3234 3235
        return 0;
    size_t retsz = 0;
    cl_ulong val = 0;
    cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
3236 3237 3238
    cl_int status = clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_LOCAL_MEM_SIZE, sizeof(val), &val, &retsz);
    CV_OCL_CHECK_RESULT(status, "clGetKernelWorkGroupInfo(CL_KERNEL_LOCAL_MEM_SIZE)");
    return status == CL_SUCCESS ? (size_t)val : 0;
3239 3240
}

3241 3242 3243 3244 3245 3246


///////////////////////////////////////// ProgramSource ///////////////////////////////////////////////

struct ProgramSource::Impl
{
3247 3248 3249 3250 3251 3252 3253 3254 3255
    IMPLEMENT_REFCOUNTABLE();

    enum KIND {
        PROGRAM_SOURCE_CODE = 0,
        PROGRAM_BINARIES,
        PROGRAM_SPIR,
        PROGRAM_SPIRV
    } kind_;

3256 3257
    Impl(const String& src)
    {
3258 3259
        init(PROGRAM_SOURCE_CODE, cv::String(), cv::String());
        initFromSource(src, cv::String());
3260 3261 3262
    }
    Impl(const String& module, const String& name, const String& codeStr, const String& codeHash)
    {
3263 3264
        init(PROGRAM_SOURCE_CODE, module, name);
        initFromSource(codeStr, codeHash);
3265
    }
3266 3267 3268

    /// reset fields
    void init(enum KIND kind, const String& module, const String& name)
3269 3270
    {
        refcount = 1;
3271
        kind_ = kind;
3272 3273 3274
        module_ = module;
        name_ = name;

3275 3276
        sourceAddr_ = NULL;
        sourceSize_ = 0;
3277
        isHashUpdated = false;
3278 3279 3280 3281 3282 3283 3284
    }

    void initFromSource(const String& codeStr, const String& codeHash)
    {
        codeStr_ = codeStr;
        sourceHash_ = codeHash;
        if (sourceHash_.empty())
3285 3286
        {
            updateHash();
3287 3288 3289 3290
        }
        else
        {
            isHashUpdated = true;
3291 3292 3293
        }
    }

3294
    void updateHash(const char* hashStr = NULL)
3295
    {
3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322
        if (hashStr)
        {
            sourceHash_ = cv::String(hashStr);
            isHashUpdated = true;
            return;
        }
        uint64 hash = 0;
        switch (kind_)
        {
        case PROGRAM_SOURCE_CODE:
            if (sourceAddr_)
            {
                CV_Assert(codeStr_.empty());
                hash = crc64(sourceAddr_, sourceSize_); // static storage
            }
            else
            {
                CV_Assert(!codeStr_.empty());
                hash = crc64((uchar*)codeStr_.c_str(), codeStr_.size());
            }
            break;
        case PROGRAM_BINARIES:
        case PROGRAM_SPIR:
        case PROGRAM_SPIRV:
            hash = crc64(sourceAddr_, sourceSize_);
            break;
        default:
3323
            CV_Error(Error::StsInternal, "Internal error");
3324 3325
        }
        sourceHash_ = cv::format("%08llx", hash);
3326 3327 3328
        isHashUpdated = true;
    }

3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369
    Impl(enum KIND kind,
            const String& module, const String& name,
            const unsigned char* binary, const size_t size,
            const cv::String& buildOptions = cv::String())
    {
        init(kind, module, name);

        sourceAddr_ = binary;
        sourceSize_ = size;

        buildOptions_ = buildOptions;
    }

    static ProgramSource fromSourceWithStaticLifetime(const String& module, const String& name,
            const char* sourceCodeStaticStr, const char* hashStaticStr,
            const cv::String& buildOptions)
    {
        ProgramSource result;
        result.p = new Impl(PROGRAM_SOURCE_CODE, module, name,
                (const unsigned char*)sourceCodeStaticStr, strlen(sourceCodeStaticStr), buildOptions);
        result.p->updateHash(hashStaticStr);
        return result;
    }

    static ProgramSource fromBinary(const String& module, const String& name,
            const unsigned char* binary, const size_t size,
            const cv::String& buildOptions)
    {
        ProgramSource result;
        result.p = new Impl(PROGRAM_BINARIES, module, name, binary, size, buildOptions);
        return result;
    }

    static ProgramSource fromSPIR(const String& module, const String& name,
            const unsigned char* binary, const size_t size,
            const cv::String& buildOptions)
    {
        ProgramSource result;
        result.p = new Impl(PROGRAM_SPIR, module, name, binary, size, buildOptions);
        return result;
    }
3370 3371 3372

    String module_;
    String name_;
3373

3374
    // TODO std::vector<ProgramSource> includes_;
3375 3376 3377 3378
    String codeStr_; // PROGRAM_SOURCE_CODE only

    const unsigned char* sourceAddr_;
    size_t sourceSize_;
3379

3380 3381 3382
    cv::String buildOptions_;

    String sourceHash_;
3383
    bool isHashUpdated;
3384 3385 3386 3387

    friend struct Program::Impl;
    friend struct internal::ProgramEntry;
    friend struct Context::Impl;
3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437
};


ProgramSource::ProgramSource()
{
    p = 0;
}

ProgramSource::ProgramSource(const String& module, const String& name, const String& codeStr, const String& codeHash)
{
    p = new Impl(module, name, codeStr, codeHash);
}

ProgramSource::ProgramSource(const char* prog)
{
    p = new Impl(prog);
}

ProgramSource::ProgramSource(const String& prog)
{
    p = new Impl(prog);
}

ProgramSource::~ProgramSource()
{
    if(p)
        p->release();
}

ProgramSource::ProgramSource(const ProgramSource& prog)
{
    p = prog.p;
    if(p)
        p->addref();
}

ProgramSource& ProgramSource::operator = (const ProgramSource& prog)
{
    Impl* newp = (Impl*)prog.p;
    if(newp)
        newp->addref();
    if(p)
        p->release();
    p = newp;
    return *this;
}

const String& ProgramSource::source() const
{
    CV_Assert(p);
3438 3439
    CV_Assert(p->kind_ == Impl::PROGRAM_SOURCE_CODE);
    CV_Assert(p->sourceAddr_ == NULL); // method returns reference - can't construct temporary object
3440 3441 3442 3443 3444
    return p->codeStr_;
}

ProgramSource::hash_t ProgramSource::hash() const
{
3445
    CV_Error(Error::StsNotImplemented, "Removed method: ProgramSource::hash()");
3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463
}

ProgramSource ProgramSource::fromBinary(const String& module, const String& name,
        const unsigned char* binary, const size_t size,
        const cv::String& buildOptions)
{
    CV_Assert(binary);
    CV_Assert(size > 0);
    return Impl::fromBinary(module, name, binary, size, buildOptions);
}

ProgramSource ProgramSource::fromSPIR(const String& module, const String& name,
        const unsigned char* binary, const size_t size,
        const cv::String& buildOptions)
{
    CV_Assert(binary);
    CV_Assert(size > 0);
    return Impl::fromBinary(module, name, binary, size, buildOptions);
3464 3465 3466 3467 3468 3469 3470 3471 3472 3473
}


internal::ProgramEntry::operator ProgramSource&() const
{
    if (this->pProgramSource == NULL)
    {
        cv::AutoLock lock(cv::getInitializationMutex());
        if (this->pProgramSource == NULL)
        {
3474 3475 3476
            ProgramSource ps = ProgramSource::Impl::fromSourceWithStaticLifetime(this->module, this->name, this->programCode, this->programHash, cv::String());
            ProgramSource* ptr = new ProgramSource(ps);
            const_cast<ProgramEntry*>(this)->pProgramSource = ptr;
3477 3478 3479 3480 3481 3482 3483
        }
    }
    return *this->pProgramSource;
}



3484
/////////////////////////////////////////// Program /////////////////////////////////////////////
3485

3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499
#ifdef HAVE_OPENCL

static
cv::String joinBuildOptions(const cv::String& a, const cv::String& b)
{
    if (b.empty())
        return a;
    if (a.empty())
        return b;
    if (b[0] == ' ')
        return a + b;
    return a + (cv::String(" ") + b);
}

3500 3501
struct Program::Impl
{
3502 3503
    IMPLEMENT_REFCOUNTABLE();

3504
    Impl(const ProgramSource& src,
3505
         const String& _buildflags, String& errmsg) :
3506 3507 3508
         refcount(1),
         handle(NULL),
         buildflags(_buildflags)
3509
    {
3510 3511 3512 3513
        const ProgramSource::Impl* src_ = src.getImpl();
        CV_Assert(src_);
        sourceModule_ = src_->module_;
        sourceName_ = src_->name_;
3514 3515
        const Context ctx = Context::getDefault();
        Device device = ctx.device(0);
3516 3517
        if (ctx.ptr() == NULL || device.ptr() == NULL)
            return;
3518 3519 3520 3521 3522 3523 3524 3525
        buildflags = joinBuildOptions(buildflags, src_->buildOptions_);
        if (src.getImpl()->kind_ == ProgramSource::Impl::PROGRAM_SOURCE_CODE)
        {
            if (device.isAMD())
                buildflags = joinBuildOptions(buildflags, " -D AMD_DEVICE");
            else if (device.isIntel())
                buildflags = joinBuildOptions(buildflags, " -D INTEL_DEVICE");
        }
3526
        compile(ctx, src_, errmsg);
3527 3528
    }

3529
    bool compile(const Context& ctx, const ProgramSource::Impl* src_, String& errmsg)
3530
    {
3531
        CV_Assert(ctx.getImpl());
3532 3533 3534 3535 3536 3537 3538 3539
        CV_Assert(src_);

        // We don't cache OpenCL binaries
        if (src_->kind_ == ProgramSource::Impl::PROGRAM_BINARIES)
        {
            bool isLoaded = createFromBinary(ctx, src_->sourceAddr_, src_->sourceSize_, errmsg);
            return isLoaded;
        }
3540
        return compileWithCache(ctx, src_, errmsg);
3541 3542
    }

3543
    bool compileWithCache(const Context& ctx, const ProgramSource::Impl* src_, String& errmsg)
3544 3545 3546 3547 3548 3549
    {
        CV_Assert(ctx.getImpl());
        CV_Assert(src_);
        CV_Assert(src_->kind_ != ProgramSource::Impl::PROGRAM_BINARIES);

#if OPENCV_HAVE_FILESYSTEM_SUPPORT
3550
        OpenCLBinaryCacheConfigurator& config = OpenCLBinaryCacheConfigurator::getSingletonInstance();
3551 3552 3553 3554
        const std::string base_dir = config.prepareCacheDirectoryForContext(
                ctx.getImpl()->getPrefixString(),
                ctx.getImpl()->getPrefixBase()
        );
3555 3556 3557 3558 3559 3560 3561 3562
        const String& hash_str = src_->sourceHash_;
        cv::String fname;
        if (!base_dir.empty() && !src_->module_.empty() && !src_->name_.empty())
        {
            CV_Assert(!hash_str.empty());
            fname = src_->module_ + "--" + src_->name_ + "_" + hash_str + ".bin";
            fname = utils::fs::join(base_dir, fname);
        }
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
        const cv::Ptr<utils::fs::FileLock> fileLock = config.cache_lock_; // can be empty
        if (!fname.empty() && CV_OPENCL_CACHE_ENABLE)
        {
            try
            {
                std::vector<char> binaryBuf;
                bool res = false;
                {
                    cv::utils::optional_shared_lock_guard<cv::utils::fs::FileLock> lock_fs(fileLock.get());
                    BinaryProgramFile file(fname, hash_str.c_str());
                    res = file.read(buildflags, binaryBuf);
                }
                if (res)
                {
                    CV_Assert(!binaryBuf.empty());
                    bool isLoaded = createFromBinary(ctx, binaryBuf, errmsg);
                    if (isLoaded)
                        return true;
                }
            }
            catch (const cv::Exception& e)
            {
                CV_UNUSED(e);
                CV_LOG_VERBOSE(NULL, 0, "Can't load OpenCL binary: " + fname << std::endl << e.what());
            }
            catch (...)
            {
                CV_LOG_VERBOSE(NULL, 0, "Can't load OpenCL binary: " + fname);
            }
        }
#endif // OPENCV_HAVE_FILESYSTEM_SUPPORT
3594
        CV_Assert(handle == NULL);
3595
        if (src_->kind_ == ProgramSource::Impl::PROGRAM_SOURCE_CODE)
3596
        {
3597
            if (!buildFromSources(ctx, src_, errmsg))
3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614
            {
                return false;
            }
        }
        else if (src_->kind_ == ProgramSource::Impl::PROGRAM_SPIR)
        {
            buildflags = joinBuildOptions(buildflags, " -x spir");
            if ((cv::String(" ") + buildflags).find(" -spir-std=") == cv::String::npos)
            {
                buildflags = joinBuildOptions(buildflags, " -spir-std=1.2");
            }
            bool isLoaded = createFromBinary(ctx, src_->sourceAddr_, src_->sourceSize_, errmsg);
            if (!isLoaded)
                return false;
        }
        else if (src_->kind_ == ProgramSource::Impl::PROGRAM_SPIRV)
        {
3615
            CV_Error(Error::StsNotImplemented, "OpenCL: SPIR-V is not supported");
3616 3617 3618
        }
        else
        {
3619
            CV_Error(Error::StsInternal, "Internal error");
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671
        }
        CV_Assert(handle != NULL);
#if OPENCV_HAVE_FILESYSTEM_SUPPORT
        if (!fname.empty() && CV_OPENCL_CACHE_WRITE)
        {
            try
            {
                std::vector<char> binaryBuf;
                getProgramBinary(binaryBuf);
                {
                    cv::utils::optional_lock_guard<cv::utils::fs::FileLock> lock_fs(fileLock.get());
                    BinaryProgramFile file(fname, hash_str.c_str());
                    file.write(buildflags, binaryBuf);
                }
            }
            catch (const cv::Exception& e)
            {
                CV_LOG_WARNING(NULL, "Can't save OpenCL binary into cache: " + fname << std::endl << e.what());
            }
            catch (...)
            {
                CV_LOG_WARNING(NULL, "Can't save OpenCL binary into cache: " + fname);
            }
        }
#endif // OPENCV_HAVE_FILESYSTEM_SUPPORT
#if CV_OPENCL_VALIDATE_BINARY_PROGRAMS
        if (CV_OPENCL_VALIDATE_BINARY_PROGRAMS_VALUE)
        {
            std::vector<char> binaryBuf;
            getProgramBinary(binaryBuf);
            if (!binaryBuf.empty())
            {
                CV_OCL_DBG_CHECK(clReleaseProgram(handle));
                handle = NULL;
                createFromBinary(ctx, binaryBuf, errmsg);
            }
        }
#endif
        return handle != NULL;
    }

    void dumpBuildLog_(cl_int result, const cl_device_id* deviceList, String& errmsg)
    {
        AutoBuffer<char, 4096> buffer; buffer[0] = 0;

        size_t retsz = 0;
        cl_int log_retval = clGetProgramBuildInfo(handle, deviceList[0],
                                                  CL_PROGRAM_BUILD_LOG, 0, 0, &retsz);
        if (log_retval == CL_SUCCESS && retsz > 1)
        {
            buffer.resize(retsz + 16);
            log_retval = clGetProgramBuildInfo(handle, deviceList[0],
3672
                                               CL_PROGRAM_BUILD_LOG, retsz+1, buffer.data(), &retsz);
3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685
            if (log_retval == CL_SUCCESS)
            {
                if (retsz < buffer.size())
                    buffer[retsz] = 0;
                else
                    buffer[buffer.size() - 1] = 0;
            }
            else
            {
                buffer[0] = 0;
            }
        }

3686
        errmsg = String(buffer.data());
3687
        printf("OpenCL program build log: %s/%s\nStatus %d: %s\n%s\n%s\n",
3688
                sourceModule_.c_str(), sourceName_.c_str(),
3689 3690 3691 3692 3693
                result, getOpenCLErrorString(result),
                buildflags.c_str(), errmsg.c_str());
        fflush(stdout);
    }

3694
    bool buildFromSources(const Context& ctx, const ProgramSource::Impl* src_, String& errmsg)
3695
    {
3696 3697
        CV_Assert(src_);
        CV_Assert(src_->kind_ == ProgramSource::Impl::PROGRAM_SOURCE_CODE);
3698
        CV_Assert(handle == NULL);
3699
        CV_INSTRUMENT_REGION_OPENCL_COMPILE(cv::format("Build OpenCL program: %s/%s %s options: %s",
3700
                sourceModule_.c_str(), sourceName_.c_str(),
3701
                src_->sourceHash_.c_str(), buildflags.c_str()).c_str());
3702

3703
        CV_LOG_VERBOSE(NULL, 0, "Compile... " << sourceModule_.c_str() << "/" << sourceName_.c_str());
3704 3705 3706 3707 3708

        const char* srcptr = src_->sourceAddr_ ? ((const char*)src_->sourceAddr_) : src_->codeStr_.c_str();
        size_t srclen = src_->sourceAddr_ ? src_->sourceSize_ : src_->codeStr_.size();
        CV_Assert(srcptr != NULL);
        CV_Assert(srclen > 0);
3709

3710 3711 3712
        cl_int retval = 0;

        handle = clCreateProgramWithSource((cl_context)ctx.ptr(), 1, &srcptr, &srclen, &retval);
3713
        CV_OCL_DBG_CHECK_RESULT(retval, "clCreateProgramWithSource");
3714
        CV_Assert(handle || retval != CL_SUCCESS);
3715
        if (handle && retval == CL_SUCCESS)
3716
        {
3717 3718
            size_t n = ctx.ndevices();
            AutoBuffer<cl_device_id, 4> deviceListBuf(n + 1);
3719
            cl_device_id* deviceList = deviceListBuf.data();
3720 3721 3722 3723 3724 3725
            for (size_t i = 0; i < n; i++)
            {
                deviceList[i] = (cl_device_id)(ctx.device(i).ptr());
            }

            retval = clBuildProgram(handle, (cl_uint)n, deviceList, buildflags.c_str(), 0, 0);
3726
            CV_OCL_TRACE_CHECK_RESULT(/*don't throw: retval*/CL_SUCCESS, cv::format("clBuildProgram(source: %s)", buildflags.c_str()).c_str());
3727
#if !CV_OPENCL_ALWAYS_SHOW_BUILD_LOG
3728
            if (retval != CL_SUCCESS)
3729
#endif
3730
            {
3731
                dumpBuildLog_(retval, deviceList, errmsg);
3732 3733 3734

                // don't remove "retval != CL_SUCCESS" condition here:
                // it would break CV_OPENCL_ALWAYS_SHOW_BUILD_LOG mode
3735
                if (retval != CL_SUCCESS && handle)
3736
                {
3737
                    CV_OCL_DBG_CHECK(clReleaseProgram(handle));
3738 3739
                    handle = NULL;
                }
3740
            }
3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754
#if CV_OPENCL_VALIDATE_BINARY_PROGRAMS
            if (handle && CV_OPENCL_VALIDATE_BINARY_PROGRAMS_VALUE)
            {
                CV_LOG_INFO(NULL, "OpenCL: query kernel names (build from sources)...");
                size_t retsz = 0;
                char kernels_buffer[4096] = {0};
                cl_int result = clGetProgramInfo(handle, CL_PROGRAM_KERNEL_NAMES, sizeof(kernels_buffer), &kernels_buffer[0], &retsz);
                if (retsz < sizeof(kernels_buffer))
                    kernels_buffer[retsz] = 0;
                else
                    kernels_buffer[0] = 0;
                CV_LOG_INFO(NULL, result << ": Kernels='" << kernels_buffer << "'");
            }
#endif
3755

3756
        }
3757
        return handle != NULL;
3758 3759
    }

3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770
    void getProgramBinary(std::vector<char>& buf)
    {
        CV_Assert(handle);
        size_t sz = 0;
        CV_OCL_CHECK(clGetProgramInfo(handle, CL_PROGRAM_BINARY_SIZES, sizeof(sz), &sz, NULL));
        buf.resize(sz);
        uchar* ptr = (uchar*)&buf[0];
        CV_OCL_CHECK(clGetProgramInfo(handle, CL_PROGRAM_BINARIES, sizeof(ptr), &ptr, NULL));
    }

    bool createFromBinary(const Context& ctx, const std::vector<char>& buf, String& errmsg)
3771 3772 3773 3774 3775
    {
        return createFromBinary(ctx, (const unsigned char*)&buf[0], buf.size(), errmsg);
    }

    bool createFromBinary(const Context& ctx, const unsigned char* binaryAddr, const size_t binarySize, String& errmsg)
3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787
    {
        CV_Assert(handle == NULL);
        CV_INSTRUMENT_REGION_OPENCL_COMPILE("Load OpenCL program");
        CV_LOG_VERBOSE(NULL, 0, "Load from binary... " << src.getImpl()->module_.c_str() << "/" << src.getImpl()->name_.c_str());

        CV_Assert(binarySize > 0);

        size_t ndevices = (int)ctx.ndevices();
        AutoBuffer<cl_device_id> devices_(ndevices);
        AutoBuffer<const uchar*> binaryPtrs_(ndevices);
        AutoBuffer<size_t> binarySizes_(ndevices);

3788 3789 3790
        cl_device_id* devices = devices_.data();
        const uchar** binaryPtrs = binaryPtrs_.data();
        size_t* binarySizes = binarySizes_.data();
3791 3792 3793
        for (size_t i = 0; i < ndevices; i++)
        {
            devices[i] = (cl_device_id)ctx.device(i).ptr();
3794
            binaryPtrs[i] = binaryAddr;
3795 3796 3797 3798
            binarySizes[i] = binarySize;
        }

        cl_int result = 0;
3799
        handle = clCreateProgramWithBinary((cl_context)ctx.ptr(), (cl_uint)ndevices, devices_.data(),
3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811
                                           binarySizes, binaryPtrs, NULL, &result);
        if (result != CL_SUCCESS)
        {
            CV_LOG_ERROR(NULL, CV_OCL_API_ERROR_MSG(result, "clCreateProgramWithBinary"));
            if (handle)
            {
                CV_OCL_DBG_CHECK(clReleaseProgram(handle));
                handle = NULL;
            }
        }
        if (!handle)
        {
3812
            return false;
3813
        }
3814
        // call clBuildProgram()
3815
        {
3816
            result = clBuildProgram(handle, (cl_uint)ndevices, devices_.data(), buildflags.c_str(), 0, 0);
3817
            CV_OCL_DBG_CHECK_RESULT(result, cv::format("clBuildProgram(binary: %s/%s)", sourceModule_.c_str(), sourceName_.c_str()).c_str());
3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828
            if (result != CL_SUCCESS)
            {
                dumpBuildLog_(result, devices, errmsg);
                if (handle)
                {
                    CV_OCL_DBG_CHECK(clReleaseProgram(handle));
                    handle = NULL;
                }
                return false;
            }
        }
3829
        // check build status
3830
        {
3831 3832
            cl_build_status build_status = CL_BUILD_NONE;
            size_t retsz = 0;
3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
            CV_OCL_DBG_CHECK(result = clGetProgramBuildInfo(handle, devices[0], CL_PROGRAM_BUILD_STATUS,
                    sizeof(build_status), &build_status, &retsz));
            if (result == CL_SUCCESS)
            {
                if (build_status == CL_BUILD_SUCCESS)
                {
                    return true;
                }
                else
                {
                    CV_LOG_WARNING(NULL, "clGetProgramBuildInfo() returns " << build_status);
                    return false;
                }
            }
            else
            {
                CV_LOG_ERROR(NULL, CV_OCL_API_ERROR_MSG(result, "clGetProgramBuildInfo()"));
                if (handle)
                {
                    CV_OCL_DBG_CHECK(clReleaseProgram(handle));
                    handle = NULL;
                }
            }
        }
#if CV_OPENCL_VALIDATE_BINARY_PROGRAMS
        if (handle && CV_OPENCL_VALIDATE_BINARY_PROGRAMS_VALUE)
        {
            CV_LOG_INFO(NULL, "OpenCL: query kernel names (binary)...");
3861
            size_t retsz = 0;
3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873
            char kernels_buffer[4096] = {0};
            result = clGetProgramInfo(handle, CL_PROGRAM_KERNEL_NAMES, sizeof(kernels_buffer), &kernels_buffer[0], &retsz);
            if (retsz < sizeof(kernels_buffer))
                kernels_buffer[retsz] = 0;
            else
                kernels_buffer[0] = 0;
            CV_LOG_INFO(NULL, result << ": Kernels='" << kernels_buffer << "'");
        }
#endif
        return handle != NULL;
    }

3874 3875 3876
    ~Impl()
    {
        if( handle )
3877
        {
3878 3879 3880 3881 3882 3883
#ifdef _WIN32
            if (!cv::__termination)
#endif
            {
                clReleaseProgram(handle);
            }
3884 3885
            handle = NULL;
        }
3886 3887 3888
    }

    cl_program handle;
3889 3890 3891 3892

    String buildflags;
    String sourceModule_;
    String sourceName_;
3893 3894
};

3895 3896 3897 3898
#else // HAVE_OPENCL
struct Program::Impl : public DummyImpl {};
#endif // HAVE_OPENCL

3899 3900 3901

Program::Program() { p = 0; }

Ilya Lavrenov's avatar
Ilya Lavrenov committed
3902
Program::Program(const ProgramSource& src,
3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932
        const String& buildflags, String& errmsg)
{
    p = 0;
    create(src, buildflags, errmsg);
}

Program::Program(const Program& prog)
{
    p = prog.p;
    if(p)
        p->addref();
}

Program& Program::operator = (const Program& prog)
{
    Impl* newp = (Impl*)prog.p;
    if(newp)
        newp->addref();
    if(p)
        p->release();
    p = newp;
    return *this;
}

Program::~Program()
{
    if(p)
        p->release();
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
3933
bool Program::create(const ProgramSource& src,
3934 3935 3936
            const String& buildflags, String& errmsg)
{
    if(p)
3937
    {
3938
        p->release();
3939 3940 3941
        p = NULL;
    }
#ifdef HAVE_OPENCL
3942 3943 3944 3945 3946 3947 3948
    p = new Impl(src, buildflags, errmsg);
    if(!p->handle)
    {
        p->release();
        p = 0;
    }
    return p != 0;
3949 3950 3951
#else
    CV_OPENCL_NO_SUPPORT();
#endif
3952 3953
}

3954
void* Program::ptr() const
3955
{
3956
#ifdef HAVE_OPENCL
3957
    return p ? p->handle : 0;
3958 3959 3960
#else
    CV_OPENCL_NO_SUPPORT();
#endif
3961 3962
}

3963 3964
#ifndef OPENCV_REMOVE_DEPRECATED_API
const ProgramSource& Program::source() const
3965
{
3966
    CV_Error(Error::StsNotImplemented, "Removed API");
3967 3968 3969 3970
}

bool Program::read(const String& bin, const String& buildflags)
{
3971
    CV_UNUSED(bin); CV_UNUSED(buildflags);
3972
    CV_Error(Error::StsNotImplemented, "Removed API");
3973 3974 3975 3976
}

bool Program::write(String& bin) const
{
3977
    CV_UNUSED(bin);
3978
    CV_Error(Error::StsNotImplemented, "Removed API");
3979 3980 3981 3982
}

String Program::getPrefix() const
{
3983
#ifdef HAVE_OPENCL
3984 3985
    if(!p)
        return String();
3986 3987 3988
    Context::Impl* ctx_ = Context::getDefault().getImpl();
    CV_Assert(ctx_);
    return cv::format("opencl=%s\nbuildflags=%s", ctx_->getPrefixString().c_str(), p->buildflags.c_str());
3989 3990 3991
#else
    CV_OPENCL_NO_SUPPORT();
#endif
3992 3993 3994 3995
}

String Program::getPrefix(const String& buildflags)
{
3996
#ifdef HAVE_OPENCL
3997 3998 3999
        Context::Impl* ctx_ = Context::getDefault().getImpl();
        CV_Assert(ctx_);
        return cv::format("opencl=%s\nbuildflags=%s", ctx_->getPrefixString().c_str(), buildflags.c_str());
4000 4001 4002
#else
    CV_OPENCL_NO_SUPPORT();
#endif
4003
}
4004
#endif
4005

4006 4007 4008
void Program::getBinary(std::vector<char>& binary) const
{
#ifdef HAVE_OPENCL
4009
    CV_Assert(p && "Empty program");
4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023
    p->getProgramBinary(binary);
#else
    binary.clear();
    CV_OPENCL_NO_SUPPORT();
#endif
}

Program Context::Impl::getProg(const ProgramSource& src,
                               const String& buildflags, String& errmsg)
{
#ifdef HAVE_OPENCL
    size_t limit = getProgramCountLimit();
    const ProgramSource::Impl* src_ = src.getImpl();
    CV_Assert(src_);
4024 4025 4026 4027
    String key = cv::format("module=%s name=%s codehash=%s\nopencl=%s\nbuildflags=%s",
            src_->module_.c_str(), src_->name_.c_str(), src_->sourceHash_.c_str(),
            getPrefixString().c_str(),
            buildflags.c_str());
4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075
    {
        cv::AutoLock lock(program_cache_mutex);
        phash_t::iterator it = phash.find(key);
        if (it != phash.end())
        {
            // TODO LRU cache
            CacheList::iterator i = std::find(cacheList.begin(), cacheList.end(), key);
            if (i != cacheList.end() && i != cacheList.begin())
            {
                cacheList.erase(i);
                cacheList.push_front(key);
            }
            return it->second;
        }
        { // cleanup program cache
            size_t sz = phash.size();
            if (limit > 0 && sz >= limit)
            {
                static bool warningFlag = false;
                if (!warningFlag)
                {
                    printf("\nWARNING: OpenCV-OpenCL:\n"
                        "    In-memory cache for OpenCL programs is full, older programs will be unloaded.\n"
                        "    You can change cache size via OPENCV_OPENCL_PROGRAM_CACHE environment variable\n\n");
                    warningFlag = true;
                }
                while (!cacheList.empty())
                {
                    size_t c = phash.erase(cacheList.back());
                    cacheList.pop_back();
                    if (c != 0)
                        break;
                }
            }
        }
    }
    Program prog(src, buildflags, errmsg);
    // Cache result of build failures too (to prevent unnecessary compiler invocations)
    {
        cv::AutoLock lock(program_cache_mutex);
        phash.insert(std::pair<std::string, Program>(key, prog));
        cacheList.push_front(key);
    }
    return prog;
#else
    CV_OPENCL_NO_SUPPORT();
#endif
}
4076

4077

4078
//////////////////////////////////////////// OpenCLAllocator //////////////////////////////////////////////////
4079

4080
template<typename T>
4081 4082 4083 4084 4085
class OpenCLBufferPool
{
protected:
    ~OpenCLBufferPool() { }
public:
4086 4087
    virtual T allocate(size_t size) = 0;
    virtual void release(T buffer) = 0;
4088 4089
};

4090 4091
template <typename Derived, typename BufferEntry, typename T>
class OpenCLBufferPoolBaseImpl : public BufferPoolController, public OpenCLBufferPool<T>
4092
{
4093 4094
private:
    inline Derived& derived() { return *static_cast<Derived*>(this); }
4095 4096 4097 4098 4099 4100
protected:
    Mutex mutex_;

    size_t currentReservedSize;
    size_t maxReservedSize;

4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
    std::list<BufferEntry> allocatedEntries_; // Allocated and used entries
    std::list<BufferEntry> reservedEntries_; // LRU order. Allocated, but not used entries

    // synchronized
    bool _findAndRemoveEntryFromAllocatedList(CV_OUT BufferEntry& entry, T buffer)
    {
        typename std::list<BufferEntry>::iterator i = allocatedEntries_.begin();
        for (; i != allocatedEntries_.end(); ++i)
        {
            BufferEntry& e = *i;
            if (e.clBuffer_ == buffer)
            {
                entry = e;
                allocatedEntries_.erase(i);
                return true;
            }
        }
        return false;
    }
4120 4121 4122 4123 4124 4125

    // synchronized
    bool _findAndRemoveEntryFromReservedList(CV_OUT BufferEntry& entry, const size_t size)
    {
        if (reservedEntries_.empty())
            return false;
4126 4127 4128
        typename std::list<BufferEntry>::iterator i = reservedEntries_.begin();
        typename std::list<BufferEntry>::iterator result_pos = reservedEntries_.end();
        BufferEntry result;
4129 4130 4131 4132 4133 4134 4135
        size_t minDiff = (size_t)(-1);
        for (; i != reservedEntries_.end(); ++i)
        {
            BufferEntry& e = *i;
            if (e.capacity_ >= size)
            {
                size_t diff = e.capacity_ - size;
4136
                if (diff < std::max((size_t)4096, size / 8) && (result_pos == reservedEntries_.end() || diff < minDiff))
4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151
                {
                    minDiff = diff;
                    result_pos = i;
                    result = e;
                    if (diff == 0)
                        break;
                }
            }
        }
        if (result_pos != reservedEntries_.end())
        {
            //CV_DbgAssert(result == *result_pos);
            reservedEntries_.erase(result_pos);
            entry = result;
            currentReservedSize -= entry.capacity_;
4152
            allocatedEntries_.push_back(entry);
4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166
            return true;
        }
        return false;
    }

    // synchronized
    void _checkSizeOfReservedEntries()
    {
        while (currentReservedSize > maxReservedSize)
        {
            CV_DbgAssert(!reservedEntries_.empty());
            const BufferEntry& entry = reservedEntries_.back();
            CV_DbgAssert(currentReservedSize >= entry.capacity_);
            currentReservedSize -= entry.capacity_;
4167
            derived()._releaseBufferEntry(entry);
4168 4169 4170 4171 4172 4173 4174
            reservedEntries_.pop_back();
        }
    }

    inline size_t _allocationGranularity(size_t size)
    {
        // heuristic values
4175 4176
        if (size < 1024*1024)
            return 4096;  // don't work with buffers smaller than 4Kb (hidden allocation overhead issue)
4177 4178 4179 4180 4181 4182 4183
        else if (size < 16*1024*1024)
            return 64*1024;
        else
            return 1024*1024;
    }

public:
4184 4185 4186
    OpenCLBufferPoolBaseImpl()
        : currentReservedSize(0),
          maxReservedSize(0)
4187
    {
4188
        // nothing
4189
    }
4190
    virtual ~OpenCLBufferPoolBaseImpl()
4191 4192 4193 4194 4195
    {
        freeAllReservedBuffers();
        CV_Assert(reservedEntries_.empty());
    }
public:
4196
    virtual T allocate(size_t size) CV_OVERRIDE
4197
    {
4198 4199 4200
        AutoLock locker(mutex_);
        BufferEntry entry;
        if (maxReservedSize > 0 && _findAndRemoveEntryFromReservedList(entry, size))
4201
        {
4202 4203 4204 4205 4206 4207
            CV_DbgAssert(size <= entry.capacity_);
            LOG_BUFFER_POOL("Reuse reserved buffer: %p\n", entry.clBuffer_);
        }
        else
        {
            derived()._allocateBufferEntry(entry, size);
4208 4209 4210
        }
        return entry.clBuffer_;
    }
4211
    virtual void release(T buffer) CV_OVERRIDE
4212
    {
4213 4214 4215
        AutoLock locker(mutex_);
        BufferEntry entry;
        CV_Assert(_findAndRemoveEntryFromAllocatedList(entry, buffer));
4216 4217
        if (maxReservedSize == 0 || entry.capacity_ > maxReservedSize / 8)
        {
4218
            derived()._releaseBufferEntry(entry);
4219 4220 4221 4222 4223 4224 4225 4226 4227
        }
        else
        {
            reservedEntries_.push_front(entry);
            currentReservedSize += entry.capacity_;
            _checkSizeOfReservedEntries();
        }
    }

4228 4229 4230
    virtual size_t getReservedSize() const CV_OVERRIDE { return currentReservedSize; }
    virtual size_t getMaxReservedSize() const CV_OVERRIDE { return maxReservedSize; }
    virtual void setMaxReservedSize(size_t size) CV_OVERRIDE
4231 4232 4233 4234 4235 4236
    {
        AutoLock locker(mutex_);
        size_t oldMaxReservedSize = maxReservedSize;
        maxReservedSize = size;
        if (maxReservedSize < oldMaxReservedSize)
        {
4237
            typename std::list<BufferEntry>::iterator i = reservedEntries_.begin();
4238 4239 4240 4241 4242 4243 4244
            for (; i != reservedEntries_.end();)
            {
                const BufferEntry& entry = *i;
                if (entry.capacity_ > maxReservedSize / 8)
                {
                    CV_DbgAssert(currentReservedSize >= entry.capacity_);
                    currentReservedSize -= entry.capacity_;
4245
                    derived()._releaseBufferEntry(entry);
4246 4247 4248 4249 4250 4251 4252 4253
                    i = reservedEntries_.erase(i);
                    continue;
                }
                ++i;
            }
            _checkSizeOfReservedEntries();
        }
    }
4254
    virtual void freeAllReservedBuffers() CV_OVERRIDE
4255 4256
    {
        AutoLock locker(mutex_);
4257
        typename std::list<BufferEntry>::const_iterator i = reservedEntries_.begin();
4258 4259 4260
        for (; i != reservedEntries_.end(); ++i)
        {
            const BufferEntry& entry = *i;
4261
            derived()._releaseBufferEntry(entry);
4262 4263
        }
        reservedEntries_.clear();
4264
        currentReservedSize = 0;
4265 4266 4267
    }
};

4268 4269 4270 4271 4272 4273 4274
struct CLBufferEntry
{
    cl_mem clBuffer_;
    size_t capacity_;
    CLBufferEntry() : clBuffer_((cl_mem)NULL), capacity_(0) { }
};

4275
class OpenCLBufferPoolImpl CV_FINAL : public OpenCLBufferPoolBaseImpl<OpenCLBufferPoolImpl, CLBufferEntry, cl_mem>
4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292
{
public:
    typedef struct CLBufferEntry BufferEntry;
protected:
    int createFlags_;
public:
    OpenCLBufferPoolImpl(int createFlags = 0)
        : createFlags_(createFlags)
    {
    }

    void _allocateBufferEntry(BufferEntry& entry, size_t size)
    {
        CV_DbgAssert(entry.clBuffer_ == NULL);
        entry.capacity_ = alignSize(size, (int)_allocationGranularity(size));
        Context& ctx = Context::getDefault();
        cl_int retval = CL_SUCCESS;
4293 4294
        entry.clBuffer_ = clCreateBuffer((cl_context)ctx.ptr(), CL_MEM_READ_WRITE|createFlags_, entry.capacity_, 0, &retval);
        CV_OCL_CHECK_RESULT(retval, cv::format("clCreateBuffer(capacity=%lld) => %p", (long long int)entry.capacity_, (void*)entry.clBuffer_).c_str());
4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310
        CV_Assert(entry.clBuffer_ != NULL);
        if(retval == CL_SUCCESS)
        {
            CV_IMPL_ADD(CV_IMPL_OCL);
        }
        LOG_BUFFER_POOL("OpenCL allocate %lld (0x%llx) bytes: %p\n",
                (long long)entry.capacity_, (long long)entry.capacity_, entry.clBuffer_);
        allocatedEntries_.push_back(entry);
    }

    void _releaseBufferEntry(const BufferEntry& entry)
    {
        CV_Assert(entry.capacity_ != 0);
        CV_Assert(entry.clBuffer_ != NULL);
        LOG_BUFFER_POOL("OpenCL release buffer: %p, %lld (0x%llx) bytes\n",
                entry.clBuffer_, (long long)entry.capacity_, (long long)entry.capacity_);
4311
        CV_OCL_DBG_CHECK(clReleaseMemObject(entry.clBuffer_));
4312 4313 4314 4315 4316 4317 4318 4319 4320 4321
    }
};

#ifdef HAVE_OPENCL_SVM
struct CLSVMBufferEntry
{
    void* clBuffer_;
    size_t capacity_;
    CLSVMBufferEntry() : clBuffer_(NULL), capacity_(0) { }
};
4322
class OpenCLSVMBufferPoolImpl CV_FINAL : public OpenCLBufferPoolBaseImpl<OpenCLSVMBufferPoolImpl, CLSVMBufferEntry, void*>
4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374
{
public:
    typedef struct CLSVMBufferEntry BufferEntry;
public:
    OpenCLSVMBufferPoolImpl()
    {
    }

    void _allocateBufferEntry(BufferEntry& entry, size_t size)
    {
        CV_DbgAssert(entry.clBuffer_ == NULL);
        entry.capacity_ = alignSize(size, (int)_allocationGranularity(size));

        Context& ctx = Context::getDefault();
        const svm::SVMCapabilities svmCaps = svm::getSVMCapabilitites(ctx);
        bool isFineGrainBuffer = svmCaps.isSupportFineGrainBuffer();
        cl_svm_mem_flags memFlags = CL_MEM_READ_WRITE |
                (isFineGrainBuffer ? CL_MEM_SVM_FINE_GRAIN_BUFFER : 0);

        const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
        CV_DbgAssert(svmFns->isValid());

        CV_OPENCL_SVM_TRACE_P("clSVMAlloc: %d\n", (int)entry.capacity_);
        void *buf = svmFns->fn_clSVMAlloc((cl_context)ctx.ptr(), memFlags, entry.capacity_, 0);
        CV_Assert(buf);

        entry.clBuffer_ = buf;
        {
            CV_IMPL_ADD(CV_IMPL_OCL);
        }
        LOG_BUFFER_POOL("OpenCL SVM allocate %lld (0x%llx) bytes: %p\n",
                (long long)entry.capacity_, (long long)entry.capacity_, entry.clBuffer_);
        allocatedEntries_.push_back(entry);
    }

    void _releaseBufferEntry(const BufferEntry& entry)
    {
        CV_Assert(entry.capacity_ != 0);
        CV_Assert(entry.clBuffer_ != NULL);
        LOG_BUFFER_POOL("OpenCL release SVM buffer: %p, %lld (0x%llx) bytes\n",
                entry.clBuffer_, (long long)entry.capacity_, (long long)entry.capacity_);
        Context& ctx = Context::getDefault();
        const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
        CV_DbgAssert(svmFns->isValid());
        CV_OPENCL_SVM_TRACE_P("clSVMFree: %p\n",  entry.clBuffer_);
        svmFns->fn_clSVMFree((cl_context)ctx.ptr(), entry.clBuffer_);
    }
};
#endif



4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423
template <bool readAccess, bool writeAccess>
class AlignedDataPtr
{
protected:
    const size_t size_;
    uchar* const originPtr_;
    const size_t alignment_;
    uchar* ptr_;
    uchar* allocatedPtr_;

public:
    AlignedDataPtr(uchar* ptr, size_t size, size_t alignment)
        : size_(size), originPtr_(ptr), alignment_(alignment), ptr_(ptr), allocatedPtr_(NULL)
    {
        CV_DbgAssert((alignment & (alignment - 1)) == 0); // check for 2^n
        if (((size_t)ptr_ & (alignment - 1)) != 0)
        {
            allocatedPtr_ = new uchar[size_ + alignment - 1];
            ptr_ = (uchar*)(((uintptr_t)allocatedPtr_ + (alignment - 1)) & ~(alignment - 1));
            if (readAccess)
            {
                memcpy(ptr_, originPtr_, size_);
            }
        }
    }

    uchar* getAlignedPtr() const
    {
        CV_DbgAssert(((size_t)ptr_ & (alignment_ - 1)) == 0);
        return ptr_;
    }

    ~AlignedDataPtr()
    {
        if (allocatedPtr_)
        {
            if (writeAccess)
            {
                memcpy(originPtr_, ptr_, size_);
            }
            delete[] allocatedPtr_;
            allocatedPtr_ = NULL;
        }
        ptr_ = NULL;
    }
private:
    AlignedDataPtr(const AlignedDataPtr&); // disabled
    AlignedDataPtr& operator=(const AlignedDataPtr&); // disabled
};
4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438

template <bool readAccess, bool writeAccess>
class AlignedDataPtr2D
{
protected:
    const size_t size_;
    uchar* const originPtr_;
    const size_t alignment_;
    uchar* ptr_;
    uchar* allocatedPtr_;
    size_t rows_;
    size_t cols_;
    size_t step_;

public:
4439
    AlignedDataPtr2D(uchar* ptr, size_t rows, size_t cols, size_t step, size_t alignment, size_t extrabytes=0)
4440 4441 4442
        : size_(rows*step), originPtr_(ptr), alignment_(alignment), ptr_(ptr), allocatedPtr_(NULL), rows_(rows), cols_(cols), step_(step)
    {
        CV_DbgAssert((alignment & (alignment - 1)) == 0); // check for 2^n
4443
        if (ptr == 0 || ((size_t)ptr_ & (alignment - 1)) != 0)
4444
        {
4445
            allocatedPtr_ = new uchar[size_ + extrabytes + alignment - 1];
4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478
            ptr_ = (uchar*)(((uintptr_t)allocatedPtr_ + (alignment - 1)) & ~(alignment - 1));
            if (readAccess)
            {
                for (size_t i = 0; i < rows_; i++)
                    memcpy(ptr_ + i*step_, originPtr_ + i*step_, cols_);
            }
        }
    }

    uchar* getAlignedPtr() const
    {
        CV_DbgAssert(((size_t)ptr_ & (alignment_ - 1)) == 0);
        return ptr_;
    }

    ~AlignedDataPtr2D()
    {
        if (allocatedPtr_)
        {
            if (writeAccess)
            {
                for (size_t i = 0; i < rows_; i++)
                    memcpy(originPtr_ + i*step_, ptr_ + i*step_, cols_);
            }
            delete[] allocatedPtr_;
            allocatedPtr_ = NULL;
        }
        ptr_ = NULL;
    }
private:
    AlignedDataPtr2D(const AlignedDataPtr2D&); // disabled
    AlignedDataPtr2D& operator=(const AlignedDataPtr2D&); // disabled
};
4479 4480 4481 4482

#ifndef CV_OPENCL_DATA_PTR_ALIGNMENT
#define CV_OPENCL_DATA_PTR_ALIGNMENT 16
#endif
4483

4484
class OpenCLAllocator CV_FINAL : public MatAllocator
4485
{
4486
    mutable OpenCLBufferPoolImpl bufferPool;
4487 4488 4489 4490 4491
    mutable OpenCLBufferPoolImpl bufferPoolHostPtr;
#ifdef  HAVE_OPENCL_SVM
    mutable OpenCLSVMBufferPoolImpl bufferPoolSVM;
#endif

4492 4493
    enum AllocatorFlags
    {
4494 4495 4496 4497 4498
        ALLOCATOR_FLAGS_BUFFER_POOL_USED = 1 << 0,
        ALLOCATOR_FLAGS_BUFFER_POOL_HOST_PTR_USED = 1 << 1
#ifdef HAVE_OPENCL_SVM
        ,ALLOCATOR_FLAGS_BUFFER_POOL_SVM_USED = 1 << 2
#endif
4499
    };
4500
public:
4501 4502 4503 4504 4505 4506
    OpenCLAllocator()
        : bufferPool(0),
          bufferPoolHostPtr(CL_MEM_ALLOC_HOST_PTR)
    {
        size_t defaultPoolSize, poolSize;
        defaultPoolSize = ocl::Device::getDefault().isIntel() ? 1 << 27 : 0;
4507
        poolSize = utils::getConfigurationParameterSizeT("OPENCV_OPENCL_BUFFERPOOL_LIMIT", defaultPoolSize);
4508
        bufferPool.setMaxReservedSize(poolSize);
4509
        poolSize = utils::getConfigurationParameterSizeT("OPENCV_OPENCL_HOST_PTR_BUFFERPOOL_LIMIT", defaultPoolSize);
4510 4511
        bufferPoolHostPtr.setMaxReservedSize(poolSize);
#ifdef HAVE_OPENCL_SVM
4512
        poolSize = utils::getConfigurationParameterSizeT("OPENCV_OPENCL_SVM_BUFFERPOOL_LIMIT", defaultPoolSize);
4513 4514 4515
        bufferPoolSVM.setMaxReservedSize(poolSize);
#endif

4516
        matStdAllocator = Mat::getDefaultAllocator();
4517
    }
4518 4519 4520 4521
    ~OpenCLAllocator()
    {
        flushCleanupQueue();
    }
4522

4523 4524
    UMatData* defaultAllocate(int dims, const int* sizes, int type, void* data, size_t* step,
            int flags, UMatUsageFlags usageFlags) const
4525
    {
4526
        UMatData* u = matStdAllocator->allocate(dims, sizes, type, data, step, flags, usageFlags);
4527 4528 4529
        return u;
    }

4530
    void getBestFlags(const Context& ctx, int /*flags*/, UMatUsageFlags usageFlags, int& createFlags, int& flags0) const
4531 4532
    {
        const Device& dev = ctx.device(0);
4533 4534 4535
        createFlags = 0;
        if ((usageFlags & USAGE_ALLOCATE_HOST_MEMORY) != 0)
            createFlags |= CL_MEM_ALLOC_HOST_PTR;
4536 4537 4538 4539 4540 4541 4542

        if( dev.hostUnifiedMemory() )
            flags0 = 0;
        else
            flags0 = UMatData::COPY_ON_MAP;
    }

4543
    UMatData* allocate(int dims, const int* sizes, int type,
4544
                       void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const CV_OVERRIDE
4545 4546
    {
        if(!useOpenCL())
4547
            return defaultAllocate(dims, sizes, type, data, step, flags, usageFlags);
4548
        CV_Assert(data == 0);
4549 4550 4551 4552 4553 4554 4555 4556
        size_t total = CV_ELEM_SIZE(type);
        for( int i = dims-1; i >= 0; i-- )
        {
            if( step )
                step[i] = total;
            total *= sizes[i];
        }

Ilya Lavrenov's avatar
Ilya Lavrenov committed
4557
        Context& ctx = Context::getDefault();
4558
        flushCleanupQueue();
4559

4560
        int createFlags = 0, flags0 = 0;
4561
        getBestFlags(ctx, flags, usageFlags, createFlags, flags0);
4562

4563 4564
        void* handle = NULL;
        int allocatorFlags = 0;
4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578

#ifdef HAVE_OPENCL_SVM
        const svm::SVMCapabilities svmCaps = svm::getSVMCapabilitites(ctx);
        if (ctx.useSVM() && svm::useSVM(usageFlags) && !svmCaps.isNoSVMSupport())
        {
            allocatorFlags = ALLOCATOR_FLAGS_BUFFER_POOL_SVM_USED;
            handle = bufferPoolSVM.allocate(total);

            // this property is constant, so single buffer pool can be used here
            bool isFineGrainBuffer = svmCaps.isSupportFineGrainBuffer();
            allocatorFlags |= isFineGrainBuffer ? svm::OPENCL_SVM_FINE_GRAIN_BUFFER : svm::OPENCL_SVM_COARSE_GRAIN_BUFFER;
        }
        else
#endif
4579 4580 4581
        if (createFlags == 0)
        {
            allocatorFlags = ALLOCATOR_FLAGS_BUFFER_POOL_USED;
4582 4583 4584 4585 4586 4587
            handle = bufferPool.allocate(total);
        }
        else if (createFlags == CL_MEM_ALLOC_HOST_PTR)
        {
            allocatorFlags = ALLOCATOR_FLAGS_BUFFER_POOL_HOST_PTR_USED;
            handle = bufferPoolHostPtr.allocate(total);
4588 4589 4590
        }
        else
        {
4591
            CV_Assert(handle != NULL); // Unsupported, throw
4592
        }
4593 4594 4595 4596

        if (!handle)
            return defaultAllocate(dims, sizes, type, data, step, flags, usageFlags);

4597 4598 4599 4600 4601
        UMatData* u = new UMatData(this);
        u->data = 0;
        u->size = total;
        u->handle = handle;
        u->flags = flags0;
4602 4603
        u->allocatorFlags_ = allocatorFlags;
        CV_DbgAssert(!u->tempUMat()); // for bufferPool.release() consistency in deallocate()
4604
        u->markHostCopyObsolete(true);
4605 4606 4607
        return u;
    }

4608
    bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const CV_OVERRIDE
4609 4610 4611 4612
    {
        if(!u)
            return false;

4613 4614
        flushCleanupQueue();

4615 4616 4617 4618 4619
        UMatDataAutoLock lock(u);

        if(u->handle == 0)
        {
            CV_Assert(u->origdata != 0);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
4620
            Context& ctx = Context::getDefault();
4621
            int createFlags = 0, flags0 = 0;
4622
            getBestFlags(ctx, accessFlags, usageFlags, createFlags, flags0);
4623 4624

            cl_context ctx_handle = (cl_context)ctx.ptr();
4625 4626 4627 4628 4629 4630 4631 4632 4633
            int allocatorFlags = 0;
            int tempUMatFlags = 0;
            void* handle = NULL;
            cl_int retval = CL_SUCCESS;

#ifdef HAVE_OPENCL_SVM
            svm::SVMCapabilities svmCaps = svm::getSVMCapabilitites(ctx);
            bool useSVM = ctx.useSVM() && svm::useSVM(usageFlags);
            if (useSVM && svmCaps.isSupportFineGrainSystem())
4634
            {
4635 4636 4637 4638 4639 4640 4641 4642 4643 4644
                allocatorFlags = svm::OPENCL_SVM_FINE_GRAIN_SYSTEM;
                tempUMatFlags = UMatData::TEMP_UMAT;
                handle = u->origdata;
                CV_OPENCL_SVM_TRACE_P("Use fine grain system: %d (%p)\n", (int)u->size, handle);
            }
            else if (useSVM && (svmCaps.isSupportFineGrainBuffer() || svmCaps.isSupportCoarseGrainBuffer()))
            {
                if (!(accessFlags & ACCESS_FAST)) // memcpy used
                {
                    bool isFineGrainBuffer = svmCaps.isSupportFineGrainBuffer();
4645

4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663
                    cl_svm_mem_flags memFlags = createFlags |
                            (isFineGrainBuffer ? CL_MEM_SVM_FINE_GRAIN_BUFFER : 0);

                    const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
                    CV_DbgAssert(svmFns->isValid());

                    CV_OPENCL_SVM_TRACE_P("clSVMAlloc + copy: %d\n", (int)u->size);
                    handle = svmFns->fn_clSVMAlloc((cl_context)ctx.ptr(), memFlags, u->size, 0);
                    CV_Assert(handle);

                    cl_command_queue q = NULL;
                    if (!isFineGrainBuffer)
                    {
                        q = (cl_command_queue)Queue::getDefault().ptr();
                        CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", handle, (int)u->size);
                        cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_TRUE, CL_MAP_WRITE,
                                handle, u->size,
                                0, NULL, NULL);
4664
                        CV_OCL_CHECK_RESULT(status, "clEnqueueSVMMap()");
4665 4666 4667 4668 4669 4670 4671

                    }
                    memcpy(handle, u->origdata, u->size);
                    if (!isFineGrainBuffer)
                    {
                        CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", handle);
                        cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, handle, 0, NULL, NULL);
4672
                        CV_OCL_CHECK_RESULT(status, "clEnqueueSVMUnmap()");
4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683
                    }

                    tempUMatFlags = UMatData::TEMP_UMAT | UMatData::TEMP_COPIED_UMAT;
                    allocatorFlags |= isFineGrainBuffer ? svm::OPENCL_SVM_FINE_GRAIN_BUFFER
                                                : svm::OPENCL_SVM_COARSE_GRAIN_BUFFER;
                }
            }
            else
#endif
            {
                tempUMatFlags = UMatData::TEMP_UMAT;
4684 4685 4686
                if (u->origdata == cv::alignPtr(u->origdata, 4)  // There are OpenCL runtime issues for less aligned data
                    && !(u->originalUMatData && u->originalUMatData->handle)  // Avoid sharing of host memory between OpenCL buffers
                )
4687 4688 4689
                {
                    handle = clCreateBuffer(ctx_handle, CL_MEM_USE_HOST_PTR|createFlags,
                                            u->size, u->origdata, &retval);
4690 4691
                    CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clCreateBuffer(CL_MEM_USE_HOST_PTR|createFlags, sz=%lld, origdata=%p) => %p",
                            (long long int)u->size, u->origdata, (void*)handle).c_str());
4692
                }
4693 4694 4695 4696
                if((!handle || retval < 0) && !(accessFlags & ACCESS_FAST))
                {
                    handle = clCreateBuffer(ctx_handle, CL_MEM_COPY_HOST_PTR|CL_MEM_READ_WRITE|createFlags,
                                               u->size, u->origdata, &retval);
4697 4698
                    CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clCreateBuffer(CL_MEM_COPY_HOST_PTR|CL_MEM_READ_WRITE|createFlags, sz=%lld, origdata=%p) => %p",
                            (long long int)u->size, u->origdata, (void*)handle).c_str());
4699 4700
                    tempUMatFlags |= UMatData::TEMP_COPIED_UMAT;
                }
4701
            }
4702
            CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clCreateBuffer() => %p", (void*)handle).c_str());
4703
            if(!handle || retval != CL_SUCCESS)
4704
                return false;
4705
            u->handle = handle;
4706 4707 4708
            u->prevAllocator = u->currAllocator;
            u->currAllocator = this;
            u->flags |= tempUMatFlags;
4709
            u->allocatorFlags_ = allocatorFlags;
4710 4711 4712 4713 4714 4715
        }
        if(accessFlags & ACCESS_WRITE)
            u->markHostCopyObsolete(true);
        return true;
    }

4716
    /*void sync(UMatData* u) const
4717 4718
    {
        cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
4719 4720
        UMatDataAutoLock lock(u);

4721
        if( u->hostCopyObsolete() && u->handle && u->refcount > 0 && u->origdata)
4722
        {
4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736
            if( u->tempCopiedUMat() )
            {
                clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
                                    u->size, u->origdata, 0, 0, 0);
            }
            else
            {
                cl_int retval = 0;
                void* data = clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE,
                                                (CL_MAP_READ | CL_MAP_WRITE),
                                                0, u->size, 0, 0, 0, &retval);
                clEnqueueUnmapMemObject(q, (cl_mem)u->handle, data, 0, 0, 0);
                clFinish(q);
            }
4737 4738 4739 4740 4741 4742 4743
            u->markHostCopyObsolete(false);
        }
        else if( u->copyOnMap() && u->deviceCopyObsolete() && u->data )
        {
            clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
                                 u->size, u->data, 0, 0, 0);
        }
4744
    }*/
4745

4746
    void deallocate(UMatData* u) const CV_OVERRIDE
4747 4748 4749 4750
    {
        if(!u)
            return;

4751 4752
        CV_Assert(u->urefcount == 0);
        CV_Assert(u->refcount == 0 && "UMat deallocation error: some derived Mat is still alive");
4753

4754
        CV_Assert(u->handle != 0);
4755
        CV_Assert(u->mapcount == 0);
4756 4757 4758 4759 4760 4761 4762 4763 4764

        if (u->flags & UMatData::ASYNC_CLEANUP)
            addToCleanupQueue(u);
        else
            deallocate_(u);
    }

    void deallocate_(UMatData* u) const
    {
4765 4766
        if(u->tempUMat())
        {
4767
            CV_Assert(u->origdata);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
4768
//            UMatDataAutoLock lock(u);
4769

4770
            if (u->hostCopyObsolete())
4771
            {
4772 4773
#ifdef HAVE_OPENCL_SVM
                if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
4774
                {
4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792
                    Context& ctx = Context::getDefault();
                    const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
                    CV_DbgAssert(svmFns->isValid());

                    if( u->tempCopiedUMat() )
                    {
                        CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
                                (u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER);
                        bool isFineGrainBuffer = (u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER;
                        cl_command_queue q = NULL;
                        if (!isFineGrainBuffer)
                        {
                            CV_DbgAssert(((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0));
                            q = (cl_command_queue)Queue::getDefault().ptr();
                            CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
                            cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_READ,
                                    u->handle, u->size,
                                    0, NULL, NULL);
4793
                            CV_OCL_CHECK_RESULT(status, "clEnqueueSVMMap()");
4794 4795 4796 4797 4798 4799 4800
                        }
                        clFinish(q);
                        memcpy(u->origdata, u->handle, u->size);
                        if (!isFineGrainBuffer)
                        {
                            CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
                            cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle, 0, NULL, NULL);
4801
                            CV_OCL_CHECK_RESULT(status, "clEnqueueSVMUnmap()");
4802 4803 4804 4805 4806 4807 4808
                        }
                    }
                    else
                    {
                        CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM);
                        // nothing
                    }
4809 4810
                }
                else
4811 4812 4813 4814 4815 4816
#endif
                {
                    cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
                    if( u->tempCopiedUMat() )
                    {
                        AlignedDataPtr<false, true> alignedPtr(u->origdata, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT);
4817 4818
                        CV_OCL_CHECK(clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
                                            u->size, alignedPtr.getAlignedPtr(), 0, 0, 0));
4819 4820 4821
                    }
                    else
                    {
4822
                        cl_int retval = 0;
4823 4824 4825
                        if (u->tempUMat())
                        {
                            CV_Assert(u->mapcount == 0);
4826
                            flushCleanupQueue(); // workaround for CL_OUT_OF_RESOURCES problem (#9960)
4827 4828 4829
                            void* data = clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE,
                                (CL_MAP_READ | CL_MAP_WRITE),
                                0, u->size, 0, 0, 0, &retval);
4830
                            CV_OCL_CHECK_RESULT(retval, cv::format("clEnqueueMapBuffer(handle=%p, sz=%lld) => %p", (void*)u->handle, (long long int)u->size, data).c_str());
4831 4832 4833 4834 4835
                            CV_Assert(u->origdata == data);
                            if (u->originalUMatData)
                            {
                                CV_Assert(u->originalUMatData->data == data);
                            }
4836 4837
                            retval = clEnqueueUnmapMemObject(q, (cl_mem)u->handle, data, 0, 0, 0);
                            CV_OCL_CHECK_RESULT(retval, cv::format("clEnqueueUnmapMemObject(handle=%p, data=%p, [sz=%lld])", (void*)u->handle, data, (long long int)u->size).c_str());
4838
                            CV_OCL_DBG_CHECK(clFinish(q));
4839
                        }
4840 4841 4842 4843
                    }
                }
                u->markHostCopyObsolete(false);
            }
4844 4845 4846 4847
            else
            {
                // nothing
            }
4848 4849 4850 4851
#ifdef HAVE_OPENCL_SVM
            if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
            {
                if( u->tempCopiedUMat() )
4852
                {
4853 4854 4855 4856 4857 4858
                    Context& ctx = Context::getDefault();
                    const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
                    CV_DbgAssert(svmFns->isValid());

                    CV_OPENCL_SVM_TRACE_P("clSVMFree: %p\n", u->handle);
                    svmFns->fn_clSVMFree((cl_context)ctx.ptr(), u->handle);
4859
                }
4860
            }
4861 4862 4863
            else
#endif
            {
4864 4865
                cl_int retval = clReleaseMemObject((cl_mem)u->handle);
                CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clReleaseMemObject(ptr=%p)", (void*)u->handle).c_str());
4866
            }
4867
            u->handle = 0;
4868
            u->markDeviceCopyObsolete(true);
4869
            u->currAllocator = u->prevAllocator;
4870 4871
            u->prevAllocator = NULL;
            if(u->data && u->copyOnMap() && u->data != u->origdata)
4872 4873
                fastFree(u->data);
            u->data = u->origdata;
4874 4875
            u->currAllocator->deallocate(u);
            u = NULL;
4876 4877 4878
        }
        else
        {
4879 4880
            CV_Assert(u->origdata == NULL);
            if(u->data && u->copyOnMap() && u->data != u->origdata)
4881
            {
4882
                fastFree(u->data);
4883
                u->data = 0;
4884
                u->markHostCopyObsolete(true);
4885
            }
4886 4887
            if (u->allocatorFlags_ & ALLOCATOR_FLAGS_BUFFER_POOL_USED)
            {
4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912
                bufferPool.release((cl_mem)u->handle);
            }
            else if (u->allocatorFlags_ & ALLOCATOR_FLAGS_BUFFER_POOL_HOST_PTR_USED)
            {
                bufferPoolHostPtr.release((cl_mem)u->handle);
            }
#ifdef HAVE_OPENCL_SVM
            else if (u->allocatorFlags_ & ALLOCATOR_FLAGS_BUFFER_POOL_SVM_USED)
            {
                if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
                {
                    //nothing
                }
                else if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
                        (u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
                {
                    Context& ctx = Context::getDefault();
                    const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
                    CV_DbgAssert(svmFns->isValid());
                    cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();

                    if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) != 0)
                    {
                        CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
                        cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle, 0, NULL, NULL);
4913
                        CV_OCL_CHECK_RESULT(status, "clEnqueueSVMUnmap()");
4914 4915 4916
                    }
                }
                bufferPoolSVM.release((void*)u->handle);
4917
            }
4918
#endif
4919 4920
            else
            {
4921
                CV_OCL_DBG_CHECK(clReleaseMemObject((cl_mem)u->handle));
4922
            }
4923
            u->handle = 0;
4924
            u->markDeviceCopyObsolete(true);
4925
            delete u;
4926
            u = NULL;
4927
        }
4928
        CV_Assert(u == NULL);
4929 4930
    }

4931
    // synchronized call (external UMatDataAutoLock, see UMat::getMat)
4932
    void map(UMatData* u, int accessFlags) const CV_OVERRIDE
4933
    {
4934
        CV_Assert(u && u->handle);
4935 4936 4937 4938 4939 4940 4941 4942 4943

        if(accessFlags & ACCESS_WRITE)
            u->markDeviceCopyObsolete(true);

        cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();

        {
            if( !u->copyOnMap() )
            {
4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961
                // TODO
                // because there can be other map requests for the same UMat with different access flags,
                // we use the universal (read-write) access mode.
#ifdef HAVE_OPENCL_SVM
                if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
                {
                    if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
                    {
                        Context& ctx = Context::getDefault();
                        const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
                        CV_DbgAssert(svmFns->isValid());

                        if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0)
                        {
                            CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
                            cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_READ | CL_MAP_WRITE,
                                    u->handle, u->size,
                                    0, NULL, NULL);
4962
                            CV_OCL_CHECK_RESULT(status, "clEnqueueSVMMap()");
4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973
                            u->allocatorFlags_ |= svm::OPENCL_SVM_BUFFER_MAP;
                        }
                    }
                    clFinish(q);
                    u->data = (uchar*)u->handle;
                    u->markHostCopyObsolete(false);
                    u->markDeviceMemMapped(true);
                    return;
                }
#endif

4974 4975 4976 4977 4978 4979 4980 4981
                cl_int retval = CL_SUCCESS;
                if (!u->deviceMemMapped())
                {
                    CV_Assert(u->refcount == 1);
                    CV_Assert(u->mapcount++ == 0);
                    u->data = (uchar*)clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE,
                                                         (CL_MAP_READ | CL_MAP_WRITE),
                                                         0, u->size, 0, 0, 0, &retval);
4982
                    CV_OCL_DBG_CHECK_RESULT(retval, cv::format("clEnqueueMapBuffer(handle=%p, sz=%lld) => %p", (void*)u->handle, (long long int)u->size, u->data).c_str());
4983 4984
                }
                if (u->data && retval == CL_SUCCESS)
4985 4986
                {
                    u->markHostCopyObsolete(false);
4987
                    u->markDeviceMemMapped(true);
4988 4989 4990
                    return;
                }

4991
                // TODO Is it really a good idea and was it tested well?
4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004
                // if map failed, switch to copy-on-map mode for the particular buffer
                u->flags |= UMatData::COPY_ON_MAP;
            }

            if(!u->data)
            {
                u->data = (uchar*)fastMalloc(u->size);
                u->markHostCopyObsolete(true);
            }
        }

        if( (accessFlags & ACCESS_READ) != 0 && u->hostCopyObsolete() )
        {
5005
            AlignedDataPtr<false, true> alignedPtr(u->data, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT);
5006 5007 5008
#ifdef HAVE_OPENCL_SVM
            CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == 0);
#endif
5009 5010 5011 5012
            cl_int retval = clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE,
                    0, u->size, alignedPtr.getAlignedPtr(), 0, 0, 0);
            CV_OCL_CHECK_RESULT(retval, cv::format("clEnqueueReadBuffer(q, handle=%p, CL_TRUE, 0, sz=%lld, data=%p, 0, 0, 0)",
                    (void*)u->handle, (long long int)u->size, alignedPtr.getAlignedPtr()).c_str());
5013 5014 5015 5016
            u->markHostCopyObsolete(false);
        }
    }

5017
    void unmap(UMatData* u) const CV_OVERRIDE
5018 5019 5020 5021
    {
        if(!u)
            return;

5022

5023 5024 5025 5026 5027
        CV_Assert(u->handle != 0);

        UMatDataAutoLock autolock(u);

        cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
5028
        cl_int retval = 0;
5029
        if( !u->copyOnMap() && u->deviceMemMapped() )
5030
        {
5031
            CV_Assert(u->data != NULL);
5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045
#ifdef HAVE_OPENCL_SVM
            if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
            {
                if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
                {
                    Context& ctx = Context::getDefault();
                    const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
                    CV_DbgAssert(svmFns->isValid());

                    CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) != 0);
                    {
                        CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
                        cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle,
                                0, NULL, NULL);
5046
                        CV_OCL_CHECK_RESULT(status, "clEnqueueSVMUnmap()");
5047 5048 5049 5050
                        clFinish(q);
                        u->allocatorFlags_ &= ~svm::OPENCL_SVM_BUFFER_MAP;
                    }
                }
5051 5052
                if (u->refcount == 0)
                    u->data = 0;
5053
                u->markDeviceCopyObsolete(false);
5054
                u->markHostCopyObsolete(true);
5055 5056 5057
                return;
            }
#endif
5058
            if (u->refcount == 0)
5059 5060
            {
                CV_Assert(u->mapcount-- == 1);
5061 5062
                retval = clEnqueueUnmapMemObject(q, (cl_mem)u->handle, u->data, 0, 0, 0);
                CV_OCL_CHECK_RESULT(retval, cv::format("clEnqueueUnmapMemObject(handle=%p, data=%p, [sz=%lld])", (void*)u->handle, u->data, (long long int)u->size).c_str());
5063 5064 5065
                if (Device::getDefault().isAMD())
                {
                    // required for multithreaded applications (see stitching test)
5066
                    CV_OCL_DBG_CHECK(clFinish(q));
5067 5068
                }
                u->markDeviceMemMapped(false);
5069
                u->data = 0;
5070 5071 5072
                u->markDeviceCopyObsolete(false);
                u->markHostCopyObsolete(true);
            }
5073 5074 5075
        }
        else if( u->copyOnMap() && u->deviceCopyObsolete() )
        {
5076
            AlignedDataPtr<true, false> alignedPtr(u->data, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT);
5077 5078 5079
#ifdef HAVE_OPENCL_SVM
            CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == 0);
#endif
5080 5081 5082 5083
            retval = clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE,
                                0, u->size, alignedPtr.getAlignedPtr(), 0, 0, 0);
            CV_OCL_CHECK_RESULT(retval, cv::format("clEnqueueWriteBuffer(q, handle=%p, CL_TRUE, 0, sz=%lld, data=%p, 0, 0, 0)",
                    (void*)u->handle, (long long int)u->size, alignedPtr.getAlignedPtr()).c_str());
5084 5085
            u->markDeviceCopyObsolete(false);
            u->markHostCopyObsolete(true);
5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101
        }
    }

    bool checkContinuous(int dims, const size_t sz[],
                         const size_t srcofs[], const size_t srcstep[],
                         const size_t dstofs[], const size_t dststep[],
                         size_t& total, size_t new_sz[],
                         size_t& srcrawofs, size_t new_srcofs[], size_t new_srcstep[],
                         size_t& dstrawofs, size_t new_dstofs[], size_t new_dststep[]) const
    {
        bool iscontinuous = true;
        srcrawofs = srcofs ? srcofs[dims-1] : 0;
        dstrawofs = dstofs ? dstofs[dims-1] : 0;
        total = sz[dims-1];
        for( int i = dims-2; i >= 0; i-- )
        {
5102
            if( i >= 0 && (total != srcstep[i] || total != dststep[i]) )
5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164
                iscontinuous = false;
            total *= sz[i];
            if( srcofs )
                srcrawofs += srcofs[i]*srcstep[i];
            if( dstofs )
                dstrawofs += dstofs[i]*dststep[i];
        }

        if( !iscontinuous )
        {
            // OpenCL uses {x, y, z} order while OpenCV uses {z, y, x} order.
            if( dims == 2 )
            {
                new_sz[0] = sz[1]; new_sz[1] = sz[0]; new_sz[2] = 1;
                // we assume that new_... arrays are initialized by caller
                // with 0's, so there is no else branch
                if( srcofs )
                {
                    new_srcofs[0] = srcofs[1];
                    new_srcofs[1] = srcofs[0];
                    new_srcofs[2] = 0;
                }

                if( dstofs )
                {
                    new_dstofs[0] = dstofs[1];
                    new_dstofs[1] = dstofs[0];
                    new_dstofs[2] = 0;
                }

                new_srcstep[0] = srcstep[0]; new_srcstep[1] = 0;
                new_dststep[0] = dststep[0]; new_dststep[1] = 0;
            }
            else
            {
                // we could check for dims == 3 here,
                // but from user perspective this one is more informative
                CV_Assert(dims <= 3);
                new_sz[0] = sz[2]; new_sz[1] = sz[1]; new_sz[2] = sz[0];
                if( srcofs )
                {
                    new_srcofs[0] = srcofs[2];
                    new_srcofs[1] = srcofs[1];
                    new_srcofs[2] = srcofs[0];
                }

                if( dstofs )
                {
                    new_dstofs[0] = dstofs[2];
                    new_dstofs[1] = dstofs[1];
                    new_dstofs[2] = dstofs[0];
                }

                new_srcstep[0] = srcstep[1]; new_srcstep[1] = srcstep[0];
                new_dststep[0] = dststep[1]; new_dststep[1] = dststep[0];
            }
        }
        return iscontinuous;
    }

    void download(UMatData* u, void* dstptr, int dims, const size_t sz[],
                  const size_t srcofs[], const size_t srcstep[],
5165
                  const size_t dststep[]) const CV_OVERRIDE
5166 5167 5168 5169 5170 5171 5172
    {
        if(!u)
            return;
        UMatDataAutoLock autolock(u);

        if( u->data && !u->hostCopyObsolete() )
        {
5173
            Mat::getDefaultAllocator()->download(u, dstptr, dims, sz, srcofs, srcstep, dststep);
5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187
            return;
        }
        CV_Assert( u->handle != 0 );

        cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();

        size_t total = 0, new_sz[] = {0, 0, 0};
        size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0};
        size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0};

        bool iscontinuous = checkContinuous(dims, sz, srcofs, srcstep, 0, dststep,
                                            total, new_sz,
                                            srcrawofs, new_srcofs, new_srcstep,
                                            dstrawofs, new_dstofs, new_dststep);
5188

5189 5190
#ifdef HAVE_OPENCL_SVM
        if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
5191
        {
5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203
            CV_DbgAssert(u->data == NULL || u->data == u->handle);
            Context& ctx = Context::getDefault();
            const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
            CV_DbgAssert(svmFns->isValid());

            CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0);
            if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
            {
                CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
                cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_READ,
                        u->handle, u->size,
                        0, NULL, NULL);
5204
                CV_OCL_CHECK_RESULT(status, "clEnqueueSVMMap()");
5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241
            }
            clFinish(q);
            if( iscontinuous )
            {
                memcpy(dstptr, (uchar*)u->handle + srcrawofs, total);
            }
            else
            {
                // This code is from MatAllocator::download()
                int isz[CV_MAX_DIM];
                uchar* srcptr = (uchar*)u->handle;
                for( int i = 0; i < dims; i++ )
                {
                    CV_Assert( sz[i] <= (size_t)INT_MAX );
                    if( sz[i] == 0 )
                    return;
                    if( srcofs )
                    srcptr += srcofs[i]*(i <= dims-2 ? srcstep[i] : 1);
                    isz[i] = (int)sz[i];
                }

                Mat src(dims, isz, CV_8U, srcptr, srcstep);
                Mat dst(dims, isz, CV_8U, dstptr, dststep);

                const Mat* arrays[] = { &src, &dst };
                uchar* ptrs[2];
                NAryMatIterator it(arrays, ptrs, 2);
                size_t j, planesz = it.size;

                for( j = 0; j < it.nplanes; j++, ++it )
                    memcpy(ptrs[1], ptrs[0], planesz);
            }
            if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
            {
                CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
                cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle,
                        0, NULL, NULL);
5242
                CV_OCL_CHECK_RESULT(status, "clEnqueueSVMUnmap()");
5243 5244
                clFinish(q);
            }
5245 5246
        }
        else
5247
#endif
5248
        {
5249 5250
            if( iscontinuous )
            {
5251
                AlignedDataPtr<false, true> alignedPtr((uchar*)dstptr, total, CV_OPENCL_DATA_PTR_ALIGNMENT);
5252 5253
                CV_OCL_CHECK(clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE,
                    srcrawofs, total, alignedPtr.getAlignedPtr(), 0, 0, 0));
5254
            }
5255
            else if (CV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS)
5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271
            {
                const size_t padding = CV_OPENCL_DATA_PTR_ALIGNMENT;
                size_t new_srcrawofs = srcrawofs & ~(padding-1);
                size_t membuf_ofs = srcrawofs - new_srcrawofs;
                AlignedDataPtr2D<false, false> alignedPtr(0, new_sz[1], new_srcstep[0], new_srcstep[0],
                                                          CV_OPENCL_DATA_PTR_ALIGNMENT, padding*2);
                uchar* ptr = alignedPtr.getAlignedPtr();

                CV_Assert(new_srcstep[0] >= new_sz[0]);
                total = alignSize(new_srcstep[0]*new_sz[1] + membuf_ofs, padding);
                total = std::min(total, u->size - new_srcrawofs);
                CV_OCL_CHECK(clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE,
                                                 new_srcrawofs, total, ptr, 0, 0, 0));
                for( size_t i = 0; i < new_sz[1]; i++ )
                    memcpy( (uchar*)dstptr + i*new_dststep[0], ptr + i*new_srcstep[0] + membuf_ofs, new_sz[0]);
            }
5272 5273
            else
            {
5274 5275 5276
                AlignedDataPtr2D<false, true> alignedPtr((uchar*)dstptr, new_sz[1], new_sz[0], new_dststep[0], CV_OPENCL_DATA_PTR_ALIGNMENT);
                uchar* ptr = alignedPtr.getAlignedPtr();

5277
                CV_OCL_CHECK(clEnqueueReadBufferRect(q, (cl_mem)u->handle, CL_TRUE,
5278 5279 5280
                    new_srcofs, new_dstofs, new_sz,
                    new_srcstep[0], 0,
                    new_dststep[0], 0,
5281
                    ptr, 0, 0, 0));
5282
            }
5283 5284 5285 5286 5287
        }
    }

    void upload(UMatData* u, const void* srcptr, int dims, const size_t sz[],
                const size_t dstofs[], const size_t dststep[],
5288
                const size_t srcstep[]) const CV_OVERRIDE
5289 5290 5291 5292 5293
    {
        if(!u)
            return;

        // there should be no user-visible CPU copies of the UMat which we are going to copy to
5294
        CV_Assert(u->refcount == 0 || u->tempUMat());
5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311

        size_t total = 0, new_sz[] = {0, 0, 0};
        size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0};
        size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0};

        bool iscontinuous = checkContinuous(dims, sz, 0, srcstep, dstofs, dststep,
                                            total, new_sz,
                                            srcrawofs, new_srcofs, new_srcstep,
                                            dstrawofs, new_dstofs, new_dststep);

        UMatDataAutoLock autolock(u);

        // if there is cached CPU copy of the GPU matrix,
        // we could use it as a destination.
        // we can do it in 2 cases:
        //    1. we overwrite the whole content
        //    2. we overwrite part of the matrix, but the GPU copy is out-of-date
5312
        if( u->data && (u->hostCopyObsolete() < u->deviceCopyObsolete() || total == u->size))
5313
        {
5314
            Mat::getDefaultAllocator()->upload(u, srcptr, dims, sz, dstofs, dststep, srcstep);
5315 5316 5317 5318 5319 5320 5321 5322
            u->markHostCopyObsolete(false);
            u->markDeviceCopyObsolete(true);
            return;
        }

        CV_Assert( u->handle != 0 );
        cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();

5323 5324
#ifdef HAVE_OPENCL_SVM
        if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
5325
        {
5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337
            CV_DbgAssert(u->data == NULL || u->data == u->handle);
            Context& ctx = Context::getDefault();
            const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
            CV_DbgAssert(svmFns->isValid());

            CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0);
            if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
            {
                CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
                cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_WRITE,
                        u->handle, u->size,
                        0, NULL, NULL);
5338
                CV_OCL_CHECK_RESULT(status, "clEnqueueSVMMap()");
5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375
            }
            clFinish(q);
            if( iscontinuous )
            {
                memcpy((uchar*)u->handle + dstrawofs, srcptr, total);
            }
            else
            {
                // This code is from MatAllocator::upload()
                int isz[CV_MAX_DIM];
                uchar* dstptr = (uchar*)u->handle;
                for( int i = 0; i < dims; i++ )
                {
                    CV_Assert( sz[i] <= (size_t)INT_MAX );
                    if( sz[i] == 0 )
                    return;
                    if( dstofs )
                    dstptr += dstofs[i]*(i <= dims-2 ? dststep[i] : 1);
                    isz[i] = (int)sz[i];
                }

                Mat src(dims, isz, CV_8U, (void*)srcptr, srcstep);
                Mat dst(dims, isz, CV_8U, dstptr, dststep);

                const Mat* arrays[] = { &src, &dst };
                uchar* ptrs[2];
                NAryMatIterator it(arrays, ptrs, 2);
                size_t j, planesz = it.size;

                for( j = 0; j < it.nplanes; j++, ++it )
                    memcpy(ptrs[1], ptrs[0], planesz);
            }
            if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
            {
                CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
                cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle,
                        0, NULL, NULL);
5376
                CV_OCL_CHECK_RESULT(status, "clEnqueueSVMUnmap()");
5377 5378
                clFinish(q);
            }
5379 5380
        }
        else
5381
#endif
5382
        {
5383 5384
            if( iscontinuous )
            {
5385
                AlignedDataPtr<true, false> alignedPtr((uchar*)srcptr, total, CV_OPENCL_DATA_PTR_ALIGNMENT);
5386 5387 5388 5389
                cl_int retval = clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE,
                    dstrawofs, total, alignedPtr.getAlignedPtr(), 0, 0, 0);
                CV_OCL_CHECK_RESULT(retval, cv::format("clEnqueueWriteBuffer(q, handle=%p, CL_TRUE, offset=%lld, sz=%lld, data=%p, 0, 0, 0)",
                        (void*)u->handle, (long long int)dstrawofs, (long long int)u->size, alignedPtr.getAlignedPtr()).c_str());
5390
            }
5391
            else if (CV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS)
5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412
            {
                const size_t padding = CV_OPENCL_DATA_PTR_ALIGNMENT;
                size_t new_dstrawofs = dstrawofs & ~(padding-1);
                size_t membuf_ofs = dstrawofs - new_dstrawofs;
                AlignedDataPtr2D<false, false> alignedPtr(0, new_sz[1], new_dststep[0], new_dststep[0],
                                                          CV_OPENCL_DATA_PTR_ALIGNMENT, padding*2);
                uchar* ptr = alignedPtr.getAlignedPtr();

                CV_Assert(new_dststep[0] >= new_sz[0] && new_srcstep[0] >= new_sz[0]);
                total = alignSize(new_dststep[0]*new_sz[1] + membuf_ofs, padding);
                total = std::min(total, u->size - new_dstrawofs);
                /*printf("new_sz0=%d, new_sz1=%d, membuf_ofs=%d, total=%d (%08x), new_dstrawofs=%d (%08x)\n",
                       (int)new_sz[0], (int)new_sz[1], (int)membuf_ofs,
                       (int)total, (int)total, (int)new_dstrawofs, (int)new_dstrawofs);*/
                CV_OCL_CHECK(clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE,
                                                 new_dstrawofs, total, ptr, 0, 0, 0));
                for( size_t i = 0; i < new_sz[1]; i++ )
                    memcpy( ptr + i*new_dststep[0] + membuf_ofs, (uchar*)srcptr + i*new_srcstep[0], new_sz[0]);
                CV_OCL_CHECK(clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE,
                                                 new_dstrawofs, total, ptr, 0, 0, 0));
            }
5413 5414
            else
            {
5415
                AlignedDataPtr2D<true, false> alignedPtr((uchar*)srcptr, new_sz[1], new_sz[0], new_srcstep[0], CV_OPENCL_DATA_PTR_ALIGNMENT);
5416 5417
                uchar* ptr = alignedPtr.getAlignedPtr();

5418
                CV_OCL_CHECK(clEnqueueWriteBufferRect(q, (cl_mem)u->handle, CL_TRUE,
5419 5420 5421
                    new_dstofs, new_srcofs, new_sz,
                    new_dststep[0], 0,
                    new_srcstep[0], 0,
5422
                    ptr, 0, 0, 0));
5423
            }
5424 5425
        }
        u->markHostCopyObsolete(true);
5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436
#ifdef HAVE_OPENCL_SVM
        if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
                (u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
        {
            // nothing
        }
        else
#endif
        {
            u->markHostCopyObsolete(true);
        }
5437 5438 5439 5440 5441
        u->markDeviceCopyObsolete(false);
    }

    void copy(UMatData* src, UMatData* dst, int dims, const size_t sz[],
              const size_t srcofs[], const size_t srcstep[],
5442
              const size_t dstofs[], const size_t dststep[], bool _sync) const CV_OVERRIDE
5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455
    {
        if(!src || !dst)
            return;

        size_t total = 0, new_sz[] = {0, 0, 0};
        size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0};
        size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0};

        bool iscontinuous = checkContinuous(dims, sz, srcofs, srcstep, dstofs, dststep,
                                            total, new_sz,
                                            srcrawofs, new_srcofs, new_srcstep,
                                            dstrawofs, new_dstofs, new_dststep);

5456
        UMatDataAutoLock src_autolock(src, dst);
5457

5458
        if( !src->handle || (src->data && src->hostCopyObsolete() < src->deviceCopyObsolete()) )
5459 5460 5461 5462
        {
            upload(dst, src->data + srcrawofs, dims, sz, dstofs, dststep, srcstep);
            return;
        }
5463
        if( !dst->handle || (dst->data && dst->hostCopyObsolete() < dst->deviceCopyObsolete()) )
5464 5465 5466
        {
            download(src, dst->data + dstrawofs, dims, sz, srcofs, srcstep, dststep);
            dst->markHostCopyObsolete(false);
5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477
#ifdef HAVE_OPENCL_SVM
            if ((dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
                    (dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
            {
                // nothing
            }
            else
#endif
            {
                dst->markDeviceCopyObsolete(true);
            }
5478 5479 5480 5481 5482 5483 5484
            return;
        }

        // there should be no user-visible CPU copies of the UMat which we are going to copy to
        CV_Assert(dst->refcount == 0);
        cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();

5485 5486 5487 5488
        cl_int retval = CL_SUCCESS;
#ifdef HAVE_OPENCL_SVM
        if ((src->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0 ||
                (dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
5489
        {
5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503
            if ((src->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0 &&
                            (dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
            {
                Context& ctx = Context::getDefault();
                const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
                CV_DbgAssert(svmFns->isValid());

                if( iscontinuous )
                {
                    CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMemcpy: %p <-- %p (%d)\n",
                            (uchar*)dst->handle + dstrawofs, (uchar*)src->handle + srcrawofs, (int)total);
                    cl_int status = svmFns->fn_clEnqueueSVMMemcpy(q, CL_TRUE,
                            (uchar*)dst->handle + dstrawofs, (uchar*)src->handle + srcrawofs,
                            total, 0, NULL, NULL);
5504
                    CV_OCL_CHECK_RESULT(status, "clEnqueueSVMMemcpy()");
5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554
                }
                else
                {
                    clFinish(q);
                    // This code is from MatAllocator::download()/upload()
                    int isz[CV_MAX_DIM];
                    uchar* srcptr = (uchar*)src->handle;
                    for( int i = 0; i < dims; i++ )
                    {
                        CV_Assert( sz[i] <= (size_t)INT_MAX );
                        if( sz[i] == 0 )
                        return;
                        if( srcofs )
                        srcptr += srcofs[i]*(i <= dims-2 ? srcstep[i] : 1);
                        isz[i] = (int)sz[i];
                    }
                    Mat m_src(dims, isz, CV_8U, srcptr, srcstep);

                    uchar* dstptr = (uchar*)dst->handle;
                    for( int i = 0; i < dims; i++ )
                    {
                        if( dstofs )
                        dstptr += dstofs[i]*(i <= dims-2 ? dststep[i] : 1);
                    }
                    Mat m_dst(dims, isz, CV_8U, dstptr, dststep);

                    const Mat* arrays[] = { &m_src, &m_dst };
                    uchar* ptrs[2];
                    NAryMatIterator it(arrays, ptrs, 2);
                    size_t j, planesz = it.size;

                    for( j = 0; j < it.nplanes; j++, ++it )
                        memcpy(ptrs[1], ptrs[0], planesz);
                }
            }
            else
            {
                if ((src->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
                {
                    map(src, ACCESS_READ);
                    upload(dst, src->data + srcrawofs, dims, sz, dstofs, dststep, srcstep);
                    unmap(src);
                }
                else
                {
                    map(dst, ACCESS_WRITE);
                    download(src, dst->data + dstrawofs, dims, sz, srcofs, srcstep, dststep);
                    unmap(dst);
                }
            }
5555 5556
        }
        else
5557
#endif
5558
        {
5559 5560
            if( iscontinuous )
            {
5561 5562 5563 5564
                retval = clEnqueueCopyBuffer(q, (cl_mem)src->handle, (cl_mem)dst->handle,
                                               srcrawofs, dstrawofs, total, 0, 0, 0);
                CV_OCL_CHECK_RESULT(retval, cv::format("clEnqueueCopyBuffer(q, src=%p, dst=%p, src_offset=%lld, dst_offset=%lld, sz=%lld, 0, 0, 0)",
                        (void*)src->handle, (void*)dst->handle, (long long int)srcrawofs, (long long int)dstrawofs, (long long int)total).c_str());
5565
            }
5566
            else if (CV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS)
5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598
            {
                const size_t padding = CV_OPENCL_DATA_PTR_ALIGNMENT;
                size_t new_srcrawofs = srcrawofs & ~(padding-1);
                size_t srcmembuf_ofs = srcrawofs - new_srcrawofs;
                size_t new_dstrawofs = dstrawofs & ~(padding-1);
                size_t dstmembuf_ofs = dstrawofs - new_dstrawofs;

                AlignedDataPtr2D<false, false> srcBuf(0, new_sz[1], new_srcstep[0], new_srcstep[0],
                                                      CV_OPENCL_DATA_PTR_ALIGNMENT, padding*2);
                AlignedDataPtr2D<false, false> dstBuf(0, new_sz[1], new_dststep[0], new_dststep[0],
                                                      CV_OPENCL_DATA_PTR_ALIGNMENT, padding*2);
                uchar* srcptr = srcBuf.getAlignedPtr();
                uchar* dstptr = dstBuf.getAlignedPtr();

                CV_Assert(new_dststep[0] >= new_sz[0] && new_srcstep[0] >= new_sz[0]);

                size_t src_total = alignSize(new_srcstep[0]*new_sz[1] + srcmembuf_ofs, padding);
                src_total = std::min(src_total, src->size - new_srcrawofs);
                size_t dst_total = alignSize(new_dststep[0]*new_sz[1] + dstmembuf_ofs, padding);
                dst_total = std::min(dst_total, dst->size - new_dstrawofs);

                CV_OCL_CHECK(clEnqueueReadBuffer(q, (cl_mem)src->handle, CL_TRUE,
                                                 new_srcrawofs, src_total, srcptr, 0, 0, 0));
                CV_OCL_CHECK(clEnqueueReadBuffer(q, (cl_mem)dst->handle, CL_TRUE,
                                                 new_dstrawofs, dst_total, dstptr, 0, 0, 0));

                for( size_t i = 0; i < new_sz[1]; i++ )
                    memcpy( dstptr + dstmembuf_ofs + i*new_dststep[0],
                            srcptr + srcmembuf_ofs + i*new_srcstep[0], new_sz[0]);
                CV_OCL_CHECK(clEnqueueWriteBuffer(q, (cl_mem)dst->handle, CL_TRUE,
                                                  new_dstrawofs, dst_total, dstptr, 0, 0, 0));
            }
5599 5600
            else
            {
5601
                CV_OCL_CHECK(retval = clEnqueueCopyBufferRect(q, (cl_mem)src->handle, (cl_mem)dst->handle,
5602
                                                   new_srcofs, new_dstofs, new_sz,
5603 5604
                                                   new_srcstep[0], 0,
                                                   new_dststep[0], 0,
5605
                                                   0, 0, 0));
5606
            }
5607
        }
5608
        if (retval == CL_SUCCESS)
5609 5610 5611
        {
            CV_IMPL_ADD(CV_IMPL_OCL)
        }
5612

5613 5614
#ifdef HAVE_OPENCL_SVM
        if ((dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
5615
            (dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
5616 5617 5618 5619 5620 5621 5622 5623
        {
            // nothing
        }
        else
#endif
        {
            dst->markHostCopyObsolete(true);
        }
5624 5625
        dst->markDeviceCopyObsolete(false);

5626
        if( _sync )
5627
        {
5628
            CV_OCL_DBG_CHECK(clFinish(q));
5629
        }
5630
    }
5631

5632
    BufferPoolController* getBufferPoolController(const char* id) const CV_OVERRIDE {
5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644
#ifdef HAVE_OPENCL_SVM
        if ((svm::checkForceSVMUmatUsage() && (id == NULL || strcmp(id, "OCL") == 0)) || (id != NULL && strcmp(id, "SVM") == 0))
        {
            return &bufferPoolSVM;
        }
#endif
        if (id != NULL && strcmp(id, "HOST_ALLOC") == 0)
        {
            return &bufferPoolHostPtr;
        }
        if (id != NULL && strcmp(id, "OCL") != 0)
        {
5645
            CV_Error(cv::Error::StsBadArg, "getBufferPoolController(): unknown BufferPool ID\n");
5646 5647 5648
        }
        return &bufferPool;
    }
5649

5650
    MatAllocator* matStdAllocator;
5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677

    mutable cv::Mutex cleanupQueueMutex;
    mutable std::deque<UMatData*> cleanupQueue;

    void flushCleanupQueue() const
    {
        if (!cleanupQueue.empty())
        {
            std::deque<UMatData*> q;
            {
                cv::AutoLock lock(cleanupQueueMutex);
                q.swap(cleanupQueue);
            }
            for (std::deque<UMatData*>::const_iterator i = q.begin(); i != q.end(); ++i)
            {
                deallocate_(*i);
            }
        }
    }
    void addToCleanupQueue(UMatData* u) const
    {
        //TODO: Validation check: CV_Assert(!u->tempUMat());
        {
            cv::AutoLock lock(cleanupQueueMutex);
            cleanupQueue.push_back(u);
        }
    }
5678 5679
};

5680 5681 5682 5683 5684 5685
static OpenCLAllocator* getOpenCLAllocator_() // call once guarantee
{
    static OpenCLAllocator* g_allocator = new OpenCLAllocator(); // avoid destrutor call (using of this object is too wide)
    g_isOpenCVActivated = true;
    return g_allocator;
}
5686 5687
MatAllocator* getOpenCLAllocator()
{
5688
    CV_SINGLETON_LAZY_INIT(MatAllocator, getOpenCLAllocator_())
5689 5690
}

5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726
}} // namespace cv::ocl


namespace cv {

// three funcs below are implemented in umatrix.cpp
void setSize( UMat& m, int _dims, const int* _sz, const size_t* _steps,
              bool autoSteps = false );
void finalizeHdr(UMat& m);

} // namespace cv


namespace cv { namespace ocl {

/*
// Convert OpenCL buffer memory to UMat
*/
void convertFromBuffer(void* cl_mem_buffer, size_t step, int rows, int cols, int type, UMat& dst)
{
    int d = 2;
    int sizes[] = { rows, cols };

    CV_Assert(0 <= d && d <= CV_MAX_DIM);

    dst.release();

    dst.flags      = (type & Mat::TYPE_MASK) | Mat::MAGIC_VAL;
    dst.usageFlags = USAGE_DEFAULT;

    setSize(dst, d, sizes, 0, true);
    dst.offset = 0;

    cl_mem             memobj = (cl_mem)cl_mem_buffer;
    cl_mem_object_type mem_type = 0;

5727
    CV_OCL_CHECK(clGetMemObjectInfo(memobj, CL_MEM_TYPE, sizeof(cl_mem_object_type), &mem_type, 0));
5728 5729 5730 5731

    CV_Assert(CL_MEM_OBJECT_BUFFER == mem_type);

    size_t total = 0;
5732
    CV_OCL_CHECK(clGetMemObjectInfo(memobj, CL_MEM_SIZE, sizeof(size_t), &total, 0));
5733

5734
    CV_OCL_CHECK(clRetainMemObject(memobj));
5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763

    CV_Assert((int)step >= cols * CV_ELEM_SIZE(type));
    CV_Assert(total >= rows * step);

    // attach clBuffer to UMatData
    dst.u = new UMatData(getOpenCLAllocator());
    dst.u->data            = 0;
    dst.u->allocatorFlags_ = 0; // not allocated from any OpenCV buffer pool
    dst.u->flags           = 0;
    dst.u->handle          = cl_mem_buffer;
    dst.u->origdata        = 0;
    dst.u->prevAllocator   = 0;
    dst.u->size            = total;

    finalizeHdr(dst);
    dst.addref();

    return;
} // convertFromBuffer()


/*
// Convert OpenCL image2d_t memory to UMat
*/
void convertFromImage(void* cl_mem_image, UMat& dst)
{
    cl_mem             clImage = (cl_mem)cl_mem_image;
    cl_mem_object_type mem_type = 0;

5764
    CV_OCL_CHECK(clGetMemObjectInfo(clImage, CL_MEM_TYPE, sizeof(cl_mem_object_type), &mem_type, 0));
5765 5766 5767 5768

    CV_Assert(CL_MEM_OBJECT_IMAGE2D == mem_type);

    cl_image_format fmt = { 0, 0 };
5769
    CV_OCL_CHECK(clGetImageInfo(clImage, CL_IMAGE_FORMAT, sizeof(cl_image_format), &fmt, 0));
5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815

    int depth = CV_8U;
    switch (fmt.image_channel_data_type)
    {
    case CL_UNORM_INT8:
    case CL_UNSIGNED_INT8:
        depth = CV_8U;
        break;

    case CL_SNORM_INT8:
    case CL_SIGNED_INT8:
        depth = CV_8S;
        break;

    case CL_UNORM_INT16:
    case CL_UNSIGNED_INT16:
        depth = CV_16U;
        break;

    case CL_SNORM_INT16:
    case CL_SIGNED_INT16:
        depth = CV_16S;
        break;

    case CL_SIGNED_INT32:
        depth = CV_32S;
        break;

    case CL_FLOAT:
        depth = CV_32F;
        break;

    default:
        CV_Error(cv::Error::OpenCLApiCallError, "Not supported image_channel_data_type");
    }

    int type = CV_8UC1;
    switch (fmt.image_channel_order)
    {
    case CL_R:
        type = CV_MAKE_TYPE(depth, 1);
        break;

    case CL_RGBA:
    case CL_BGRA:
    case CL_ARGB:
5816
        type = CV_MAKE_TYPE(depth, 4);
5817 5818 5819 5820 5821 5822 5823 5824
        break;

    default:
        CV_Error(cv::Error::OpenCLApiCallError, "Not supported image_channel_order");
        break;
    }

    size_t step = 0;
5825
    CV_OCL_CHECK(clGetImageInfo(clImage, CL_IMAGE_ROW_PITCH, sizeof(size_t), &step, 0));
5826 5827

    size_t w = 0;
5828
    CV_OCL_CHECK(clGetImageInfo(clImage, CL_IMAGE_WIDTH, sizeof(size_t), &w, 0));
5829 5830

    size_t h = 0;
5831
    CV_OCL_CHECK(clGetImageInfo(clImage, CL_IMAGE_HEIGHT, sizeof(size_t), &h, 0));
5832 5833 5834 5835 5836 5837 5838 5839 5840 5841

    dst.create((int)h, (int)w, type);

    cl_mem clBuffer = (cl_mem)dst.handle(ACCESS_READ);

    cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();

    size_t offset = 0;
    size_t src_origin[3] = { 0, 0, 0 };
    size_t region[3] = { w, h, 1 };
5842
    CV_OCL_CHECK(clEnqueueCopyImageToBuffer(q, clImage, clBuffer, src_origin, region, offset, 0, NULL, NULL));
5843

5844
    CV_OCL_CHECK(clFinish(q));
5845 5846 5847 5848 5849

    return;
} // convertFromImage()


5850
///////////////////////////////////////////// Utility functions /////////////////////////////////////////////////
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5851

5852
static void getDevices(std::vector<cl_device_id>& devices, cl_platform_id platform)
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5853 5854
{
    cl_uint numDevices = 0;
5855
    CV_OCL_DBG_CHECK(clGetDeviceIDs(platform, (cl_device_type)Device::TYPE_ALL, 0, NULL, &numDevices));
5856

Konstantin Matskevich's avatar
Konstantin Matskevich committed
5857
    if (numDevices == 0)
5858 5859
    {
        devices.clear();
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5860
        return;
5861 5862
    }

Konstantin Matskevich's avatar
Konstantin Matskevich committed
5863
    devices.resize((size_t)numDevices);
5864
    CV_OCL_DBG_CHECK(clGetDeviceIDs(platform, (cl_device_type)Device::TYPE_ALL, numDevices, &devices[0], &numDevices));
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5865 5866
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5867
struct PlatformInfo::Impl
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5868 5869 5870
{
    Impl(void* id)
    {
5871
        refcount = 1;
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5872 5873 5874 5875
        handle = *(cl_platform_id*)id;
        getDevices(devices, handle);
    }

5876
    String getStrProp(cl_platform_info prop) const
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5877 5878 5879
    {
        char buf[1024];
        size_t sz=0;
5880
        return clGetPlatformInfo(handle, prop, sizeof(buf)-16, buf, &sz) == CL_SUCCESS &&
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5881 5882 5883 5884 5885 5886 5887 5888
            sz < sizeof(buf) ? String(buf) : String();
    }

    IMPLEMENT_REFCOUNTABLE();
    std::vector<cl_device_id> devices;
    cl_platform_id handle;
};

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5889
PlatformInfo::PlatformInfo()
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5890 5891 5892 5893
{
    p = 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5894
PlatformInfo::PlatformInfo(void* platform_id)
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5895 5896 5897 5898
{
    p = new Impl(platform_id);
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5899
PlatformInfo::~PlatformInfo()
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5900 5901 5902 5903 5904
{
    if(p)
        p->release();
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5905
PlatformInfo::PlatformInfo(const PlatformInfo& i)
5906 5907 5908
{
    if (i.p)
        i.p->addref();
5909
    p = i.p;
5910 5911
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5912
PlatformInfo& PlatformInfo::operator =(const PlatformInfo& i)
5913
{
5914
    if (i.p != p)
5915 5916 5917
    {
        if (i.p)
            i.p->addref();
5918 5919 5920
        if (p)
            p->release();
        p = i.p;
5921 5922 5923 5924
    }
    return *this;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5925
int PlatformInfo::deviceNumber() const
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5926 5927 5928 5929
{
    return p ? (int)p->devices.size() : 0;
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5930
void PlatformInfo::getDevice(Device& device, int d) const
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5931
{
5932
    CV_Assert(p && d < (int)p->devices.size() );
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5933 5934 5935 5936
    if(p)
        device.set(p->devices[d]);
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5937
String PlatformInfo::name() const
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5938 5939 5940 5941
{
    return p ? p->getStrProp(CL_PLATFORM_NAME) : String();
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5942
String PlatformInfo::vendor() const
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5943 5944 5945 5946
{
    return p ? p->getStrProp(CL_PLATFORM_VENDOR) : String();
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5947
String PlatformInfo::version() const
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5948 5949 5950 5951 5952 5953 5954
{
    return p ? p->getStrProp(CL_PLATFORM_VERSION) : String();
}

static void getPlatforms(std::vector<cl_platform_id>& platforms)
{
    cl_uint numPlatforms = 0;
5955
    CV_OCL_DBG_CHECK(clGetPlatformIDs(0, NULL, &numPlatforms));
5956

Konstantin Matskevich's avatar
Konstantin Matskevich committed
5957
    if (numPlatforms == 0)
5958 5959
    {
        platforms.clear();
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5960
        return;
5961 5962
    }

Konstantin Matskevich's avatar
Konstantin Matskevich committed
5963
    platforms.resize((size_t)numPlatforms);
5964
    CV_OCL_DBG_CHECK(clGetPlatformIDs(numPlatforms, &platforms[0], &numPlatforms));
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5965 5966
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
5967
void getPlatfomsInfo(std::vector<PlatformInfo>& platformsInfo)
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5968 5969 5970
{
    std::vector<cl_platform_id> platforms;
    getPlatforms(platforms);
5971

Konstantin Matskevich's avatar
Konstantin Matskevich committed
5972
    for (size_t i = 0; i < platforms.size(); i++)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
5973
        platformsInfo.push_back( PlatformInfo((void*)&platforms[i]) );
Konstantin Matskevich's avatar
Konstantin Matskevich committed
5974 5975
}

5976
const char* typeToStr(int type)
5977 5978 5979
{
    static const char* tab[]=
    {
Ilya Lavrenov's avatar
Ilya Lavrenov committed
5980 5981 5982 5983 5984 5985 5986 5987
        "uchar", "uchar2", "uchar3", "uchar4", 0, 0, 0, "uchar8", 0, 0, 0, 0, 0, 0, 0, "uchar16",
        "char", "char2", "char3", "char4", 0, 0, 0, "char8", 0, 0, 0, 0, 0, 0, 0, "char16",
        "ushort", "ushort2", "ushort3", "ushort4",0, 0, 0, "ushort8", 0, 0, 0, 0, 0, 0, 0, "ushort16",
        "short", "short2", "short3", "short4", 0, 0, 0, "short8", 0, 0, 0, 0, 0, 0, 0, "short16",
        "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
        "float", "float2", "float3", "float4", 0, 0, 0, "float8", 0, 0, 0, 0, 0, 0, 0, "float16",
        "double", "double2", "double3", "double4", 0, 0, 0, "double8", 0, 0, 0, 0, 0, 0, 0, "double16",
        "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?"
5988
    };
5989
    int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
5990
    return cn > 16 ? "?" : tab[depth*16 + cn-1];
5991 5992
}

5993
const char* memopTypeToStr(int type)
5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010
{
    static const char* tab[] =
    {
        "uchar", "uchar2", "uchar3", "uchar4", 0, 0, 0, "uchar8", 0, 0, 0, 0, 0, 0, 0, "uchar16",
        "char", "char2", "char3", "char4", 0, 0, 0, "char8", 0, 0, 0, 0, 0, 0, 0, "char16",
        "ushort", "ushort2", "ushort3", "ushort4",0, 0, 0, "ushort8", 0, 0, 0, 0, 0, 0, 0, "ushort16",
        "short", "short2", "short3", "short4", 0, 0, 0, "short8", 0, 0, 0, 0, 0, 0, 0, "short16",
        "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
        "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
        "ulong", "ulong2", "ulong3", "ulong4", 0, 0, 0, "ulong8", 0, 0, 0, 0, 0, 0, 0, "ulong16",
        "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?"
    };
    int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type);
    return cn > 16 ? "?" : tab[depth*16 + cn-1];
}

const char* vecopTypeToStr(int type)
6011
{
6012
    static const char* tab[] =
6013
    {
6014 6015 6016 6017
        "uchar", "short", "uchar3", "int", 0, 0, 0, "int2", 0, 0, 0, 0, 0, 0, 0, "int4",
        "char", "short", "char3", "int", 0, 0, 0, "int2", 0, 0, 0, 0, 0, 0, 0, "int4",
        "ushort", "int", "ushort3", "int2",0, 0, 0, "int4", 0, 0, 0, 0, 0, 0, 0, "int8",
        "short", "int", "short3", "int2", 0, 0, 0, "int4", 0, 0, 0, 0, 0, 0, 0, "int8",
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6018 6019 6020 6021
        "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
        "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
        "ulong", "ulong2", "ulong3", "ulong4", 0, 0, 0, "ulong8", 0, 0, 0, 0, 0, 0, 0, "ulong16",
        "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?"
6022
    };
6023
    int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type);
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6024
    return cn > 16 ? "?" : tab[depth*16 + cn-1];
6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042
}

const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf)
{
    if( sdepth == ddepth )
        return "noconvert";
    const char *typestr = typeToStr(CV_MAKETYPE(ddepth, cn));
    if( ddepth >= CV_32F ||
        (ddepth == CV_32S && sdepth < CV_32S) ||
        (ddepth == CV_16S && sdepth <= CV_8S) ||
        (ddepth == CV_16U && sdepth == CV_8U))
    {
        sprintf(buf, "convert_%s", typestr);
    }
    else if( sdepth >= CV_32F )
        sprintf(buf, "convert_%s%s_rte", typestr, (ddepth < CV_32S ? "_sat" : ""));
    else
        sprintf(buf, "convert_%s_sat", typestr);
6043

6044 6045 6046
    return buf;
}

6047 6048
const char* getOpenCLErrorString(int errorCode)
{
6049 6050
#define CV_OCL_CODE(id) case id: return #id
#define CV_OCL_CODE_(id, name) case id: return #name
6051 6052
    switch (errorCode)
    {
6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123
    CV_OCL_CODE(CL_SUCCESS);
    CV_OCL_CODE(CL_DEVICE_NOT_FOUND);
    CV_OCL_CODE(CL_DEVICE_NOT_AVAILABLE);
    CV_OCL_CODE(CL_COMPILER_NOT_AVAILABLE);
    CV_OCL_CODE(CL_MEM_OBJECT_ALLOCATION_FAILURE);
    CV_OCL_CODE(CL_OUT_OF_RESOURCES);
    CV_OCL_CODE(CL_OUT_OF_HOST_MEMORY);
    CV_OCL_CODE(CL_PROFILING_INFO_NOT_AVAILABLE);
    CV_OCL_CODE(CL_MEM_COPY_OVERLAP);
    CV_OCL_CODE(CL_IMAGE_FORMAT_MISMATCH);
    CV_OCL_CODE(CL_IMAGE_FORMAT_NOT_SUPPORTED);
    CV_OCL_CODE(CL_BUILD_PROGRAM_FAILURE);
    CV_OCL_CODE(CL_MAP_FAILURE);
    CV_OCL_CODE(CL_MISALIGNED_SUB_BUFFER_OFFSET);
    CV_OCL_CODE(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST);
    CV_OCL_CODE(CL_COMPILE_PROGRAM_FAILURE);
    CV_OCL_CODE(CL_LINKER_NOT_AVAILABLE);
    CV_OCL_CODE(CL_LINK_PROGRAM_FAILURE);
    CV_OCL_CODE(CL_DEVICE_PARTITION_FAILED);
    CV_OCL_CODE(CL_KERNEL_ARG_INFO_NOT_AVAILABLE);
    CV_OCL_CODE(CL_INVALID_VALUE);
    CV_OCL_CODE(CL_INVALID_DEVICE_TYPE);
    CV_OCL_CODE(CL_INVALID_PLATFORM);
    CV_OCL_CODE(CL_INVALID_DEVICE);
    CV_OCL_CODE(CL_INVALID_CONTEXT);
    CV_OCL_CODE(CL_INVALID_QUEUE_PROPERTIES);
    CV_OCL_CODE(CL_INVALID_COMMAND_QUEUE);
    CV_OCL_CODE(CL_INVALID_HOST_PTR);
    CV_OCL_CODE(CL_INVALID_MEM_OBJECT);
    CV_OCL_CODE(CL_INVALID_IMAGE_FORMAT_DESCRIPTOR);
    CV_OCL_CODE(CL_INVALID_IMAGE_SIZE);
    CV_OCL_CODE(CL_INVALID_SAMPLER);
    CV_OCL_CODE(CL_INVALID_BINARY);
    CV_OCL_CODE(CL_INVALID_BUILD_OPTIONS);
    CV_OCL_CODE(CL_INVALID_PROGRAM);
    CV_OCL_CODE(CL_INVALID_PROGRAM_EXECUTABLE);
    CV_OCL_CODE(CL_INVALID_KERNEL_NAME);
    CV_OCL_CODE(CL_INVALID_KERNEL_DEFINITION);
    CV_OCL_CODE(CL_INVALID_KERNEL);
    CV_OCL_CODE(CL_INVALID_ARG_INDEX);
    CV_OCL_CODE(CL_INVALID_ARG_VALUE);
    CV_OCL_CODE(CL_INVALID_ARG_SIZE);
    CV_OCL_CODE(CL_INVALID_KERNEL_ARGS);
    CV_OCL_CODE(CL_INVALID_WORK_DIMENSION);
    CV_OCL_CODE(CL_INVALID_WORK_GROUP_SIZE);
    CV_OCL_CODE(CL_INVALID_WORK_ITEM_SIZE);
    CV_OCL_CODE(CL_INVALID_GLOBAL_OFFSET);
    CV_OCL_CODE(CL_INVALID_EVENT_WAIT_LIST);
    CV_OCL_CODE(CL_INVALID_EVENT);
    CV_OCL_CODE(CL_INVALID_OPERATION);
    CV_OCL_CODE(CL_INVALID_GL_OBJECT);
    CV_OCL_CODE(CL_INVALID_BUFFER_SIZE);
    CV_OCL_CODE(CL_INVALID_MIP_LEVEL);
    CV_OCL_CODE(CL_INVALID_GLOBAL_WORK_SIZE);
    // OpenCL 1.1
    CV_OCL_CODE(CL_INVALID_PROPERTY);
    // OpenCL 1.2
    CV_OCL_CODE(CL_INVALID_IMAGE_DESCRIPTOR);
    CV_OCL_CODE(CL_INVALID_COMPILER_OPTIONS);
    CV_OCL_CODE(CL_INVALID_LINKER_OPTIONS);
    CV_OCL_CODE(CL_INVALID_DEVICE_PARTITION_COUNT);
    // OpenCL 2.0
    CV_OCL_CODE_(-69, CL_INVALID_PIPE_SIZE);
    CV_OCL_CODE_(-70, CL_INVALID_DEVICE_QUEUE);
    // Extensions
    CV_OCL_CODE_(-1000, CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR);
    CV_OCL_CODE_(-1001, CL_PLATFORM_NOT_FOUND_KHR);
    CV_OCL_CODE_(-1002, CL_INVALID_D3D10_DEVICE_KHR);
    CV_OCL_CODE_(-1003, CL_INVALID_D3D10_RESOURCE_KHR);
    CV_OCL_CODE_(-1004, CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR);
    CV_OCL_CODE_(-1005, CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR);
6124 6125
    default: return "Unknown OpenCL error";
    }
6126 6127
#undef CV_OCL_CODE
#undef CV_OCL_CODE_
6128 6129
}

6130 6131 6132 6133
template <typename T>
static std::string kerToStr(const Mat & k)
{
    int width = k.cols - 1, depth = k.depth();
6134
    const T * const data = k.ptr<T>();
6135 6136 6137 6138 6139 6140 6141

    std::ostringstream stream;
    stream.precision(10);

    if (depth <= CV_8S)
    {
        for (int i = 0; i < width; ++i)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6142 6143
            stream << "DIG(" << (int)data[i] << ")";
        stream << "DIG(" << (int)data[width] << ")";
6144 6145 6146 6147 6148
    }
    else if (depth == CV_32F)
    {
        stream.setf(std::ios_base::showpoint);
        for (int i = 0; i < width; ++i)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6149 6150
            stream << "DIG(" << data[i] << "f)";
        stream << "DIG(" << data[width] << "f)";
6151 6152 6153 6154
    }
    else
    {
        for (int i = 0; i < width; ++i)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6155 6156
            stream << "DIG(" << data[i] << ")";
        stream << "DIG(" << data[width] << ")";
6157 6158 6159 6160 6161
    }

    return stream.str();
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
6162
String kernelToStr(InputArray _kernel, int ddepth, const char * name)
6163 6164 6165 6166 6167 6168 6169 6170 6171 6172
{
    Mat kernel = _kernel.getMat().reshape(1, 1);

    int depth = kernel.depth();
    if (ddepth < 0)
        ddepth = depth;

    if (ddepth != depth)
        kernel.convertTo(kernel, ddepth);

6173 6174
    typedef std::string (* func_t)(const Mat &);
    static const func_t funcs[] = { kerToStr<uchar>, kerToStr<char>, kerToStr<ushort>, kerToStr<short>,
6175
                                    kerToStr<int>, kerToStr<float>, kerToStr<double>, 0 };
6176
    const func_t func = funcs[ddepth];
6177 6178
    CV_Assert(func != 0);

Ilya Lavrenov's avatar
Ilya Lavrenov committed
6179
    return cv::format(" -D %s=%s", name ? name : "COEFF", func(kernel).c_str());
6180 6181
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
6182 6183 6184 6185 6186 6187 6188
#define PROCESS_SRC(src) \
    do \
    { \
        if (!src.empty()) \
        { \
            CV_Assert(src.isMat() || src.isUMat()); \
            Size csize = src.size(); \
6189 6190 6191 6192 6193 6194
            int ctype = src.type(), ccn = CV_MAT_CN(ctype), cdepth = CV_MAT_DEPTH(ctype), \
                ckercn = vectorWidths[cdepth], cwidth = ccn * csize.width; \
            if (cwidth < ckercn || ckercn <= 0) \
                return 1; \
            cols.push_back(cwidth); \
            if (strat == OCL_VECTOR_OWN && ctype != ref_type) \
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6195 6196 6197
                return 1; \
            offsets.push_back(src.offset()); \
            steps.push_back(src.step()); \
6198
            dividers.push_back(ckercn * CV_ELEM_SIZE1(ctype)); \
6199
            kercns.push_back(ckercn); \
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6200 6201 6202 6203 6204 6205
        } \
    } \
    while ((void)0, 0)

int predictOptimalVectorWidth(InputArray src1, InputArray src2, InputArray src3,
                              InputArray src4, InputArray src5, InputArray src6,
6206 6207
                              InputArray src7, InputArray src8, InputArray src9,
                              OclVectorStrategy strat)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6208 6209 6210 6211 6212 6213
{
    const ocl::Device & d = ocl::Device::getDefault();

    int vectorWidths[] = { d.preferredVectorWidthChar(), d.preferredVectorWidthChar(),
        d.preferredVectorWidthShort(), d.preferredVectorWidthShort(),
        d.preferredVectorWidthInt(), d.preferredVectorWidthFloat(),
6214
        d.preferredVectorWidthDouble(), -1 };
6215 6216 6217

    // if the device says don't use vectors
    if (vectorWidths[0] == 1)
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6218 6219
    {
        // it's heuristic
6220 6221
        vectorWidths[CV_8U] = vectorWidths[CV_8S] = 4;
        vectorWidths[CV_16U] = vectorWidths[CV_16S] = 2;
6222
        vectorWidths[CV_32S] = vectorWidths[CV_32F] = vectorWidths[CV_64F] = 1;
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6223
    }
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6224

6225 6226 6227
    return checkOptimalVectorWidth(vectorWidths, src1, src2, src3, src4, src5, src6, src7, src8, src9, strat);
}

6228
int checkOptimalVectorWidth(const int *vectorWidths,
6229 6230 6231 6232 6233
                            InputArray src1, InputArray src2, InputArray src3,
                            InputArray src4, InputArray src5, InputArray src6,
                            InputArray src7, InputArray src8, InputArray src9,
                            OclVectorStrategy strat)
{
6234 6235
    CV_Assert(vectorWidths);

6236 6237
    int ref_type = src1.type();

Ilya Lavrenov's avatar
Ilya Lavrenov committed
6238
    std::vector<size_t> offsets, steps, cols;
6239
    std::vector<int> dividers, kercns;
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252
    PROCESS_SRC(src1);
    PROCESS_SRC(src2);
    PROCESS_SRC(src3);
    PROCESS_SRC(src4);
    PROCESS_SRC(src5);
    PROCESS_SRC(src6);
    PROCESS_SRC(src7);
    PROCESS_SRC(src8);
    PROCESS_SRC(src9);

    size_t size = offsets.size();

    for (size_t i = 0; i < size; ++i)
6253 6254
        while (offsets[i] % dividers[i] != 0 || steps[i] % dividers[i] != 0 || cols[i] % kercns[i] != 0)
            dividers[i] >>= 1, kercns[i] >>= 1;
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6255 6256

    // default strategy
6257
    int kercn = *std::min_element(kercns.begin(), kercns.end());
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6258

Ilya Lavrenov's avatar
Ilya Lavrenov committed
6259
    return kercn;
Ilya Lavrenov's avatar
Ilya Lavrenov committed
6260 6261
}

6262 6263 6264 6265 6266 6267 6268
int predictOptimalVectorWidthMax(InputArray src1, InputArray src2, InputArray src3,
                                 InputArray src4, InputArray src5, InputArray src6,
                                 InputArray src7, InputArray src8, InputArray src9)
{
    return predictOptimalVectorWidth(src1, src2, src3, src4, src5, src6, src7, src8, src9, OCL_VECTOR_MAX);
}

Ilya Lavrenov's avatar
Ilya Lavrenov committed
6269 6270
#undef PROCESS_SRC

6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288

// TODO Make this as a method of OpenCL "BuildOptions" class
void buildOptionsAddMatrixDescription(String& buildOptions, const String& name, InputArray _m)
{
    if (!buildOptions.empty())
        buildOptions += " ";
    int type = _m.type(), depth = CV_MAT_DEPTH(type);
    buildOptions += format(
            "-D %s_T=%s -D %s_T1=%s -D %s_CN=%d -D %s_TSIZE=%d -D %s_T1SIZE=%d -D %s_DEPTH=%d",
            name.c_str(), ocl::typeToStr(type),
            name.c_str(), ocl::typeToStr(CV_MAKE_TYPE(depth, 1)),
            name.c_str(), (int)CV_MAT_CN(type),
            name.c_str(), (int)CV_ELEM_SIZE(type),
            name.c_str(), (int)CV_ELEM_SIZE1(type),
            name.c_str(), (int)depth
            );
}

6289 6290 6291

struct Image2D::Impl
{
6292
    Impl(const UMat &src, bool norm, bool alias)
6293
    {
6294 6295
        handle = 0;
        refcount = 1;
6296
        init(src, norm, alias);
6297
    }
6298

6299 6300 6301 6302 6303
    ~Impl()
    {
        if (handle)
            clReleaseMemObject(handle);
    }
6304

6305
    static cl_image_format getImageFormat(int depth, int cn, bool norm)
6306 6307
    {
        cl_image_format format;
6308 6309
        static const int channelTypes[] = { CL_UNSIGNED_INT8, CL_SIGNED_INT8, CL_UNSIGNED_INT16,
                                       CL_SIGNED_INT16, CL_SIGNED_INT32, CL_FLOAT, -1, -1 };
6310 6311
        static const int channelTypesNorm[] = { CL_UNORM_INT8, CL_SNORM_INT8, CL_UNORM_INT16,
                                                CL_SNORM_INT16, -1, -1, -1, -1 };
6312 6313
        static const int channelOrders[] = { -1, CL_R, CL_RG, -1, CL_RGBA };

6314 6315
        int channelType = norm ? channelTypesNorm[depth] : channelTypes[depth];
        int channelOrder = channelOrders[cn];
6316 6317
        format.image_channel_data_type = (cl_channel_type)channelType;
        format.image_channel_order = (cl_channel_order)channelOrder;
6318 6319 6320 6321 6322
        return format;
    }

    static bool isFormatSupported(cl_image_format format)
    {
6323 6324 6325
        if (!haveOpenCL())
            CV_Error(Error::OpenCLApiCallError, "OpenCL runtime not found!");

6326 6327 6328 6329 6330 6331
        cl_context context = (cl_context)Context::getDefault().ptr();
        // Figure out how many formats are supported by this context.
        cl_uint numFormats = 0;
        cl_int err = clGetSupportedImageFormats(context, CL_MEM_READ_WRITE,
                                                CL_MEM_OBJECT_IMAGE2D, numFormats,
                                                NULL, &numFormats);
6332
        CV_OCL_DBG_CHECK_RESULT(err, "clGetSupportedImageFormats(CL_MEM_OBJECT_IMAGE2D, NULL)");
6333 6334 6335
        AutoBuffer<cl_image_format> formats(numFormats);
        err = clGetSupportedImageFormats(context, CL_MEM_READ_WRITE,
                                         CL_MEM_OBJECT_IMAGE2D, numFormats,
6336
                                         formats.data(), NULL);
6337
        CV_OCL_DBG_CHECK_RESULT(err, "clGetSupportedImageFormats(CL_MEM_OBJECT_IMAGE2D, formats)");
6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349
        for (cl_uint i = 0; i < numFormats; ++i)
        {
            if (!memcmp(&formats[i], &format, sizeof(format)))
            {
                return true;
            }
        }
        return false;
    }

    void init(const UMat &src, bool norm, bool alias)
    {
6350 6351 6352 6353
        if (!haveOpenCL())
            CV_Error(Error::OpenCLApiCallError, "OpenCL runtime not found!");

        CV_Assert(!src.empty());
6354 6355 6356 6357 6358 6359 6360 6361
        CV_Assert(ocl::Device::getDefault().imageSupport());

        int err, depth = src.depth(), cn = src.channels();
        CV_Assert(cn <= 4);
        cl_image_format format = getImageFormat(depth, cn, norm);

        if (!isFormatSupported(format))
            CV_Error(Error::OpenCLApiCallError, "Image format is not supported");
6362

6363 6364 6365
        if (alias && !src.handle(ACCESS_RW))
            CV_Error(Error::OpenCLApiCallError, "Incorrect UMat, handle is null");

Ilya Lavrenov's avatar
Ilya Lavrenov committed
6366
        cl_context context = (cl_context)Context::getDefault().ptr();
6367
        cl_command_queue queue = (cl_command_queue)Queue::getDefault().ptr();
6368 6369

#ifdef CL_VERSION_1_2
6370 6371 6372 6373
        // this enables backwards portability to
        // run on OpenCL 1.1 platform if library binaries are compiled with OpenCL 1.2 support
        const Device & d = ocl::Device::getDefault();
        int minor = d.deviceVersionMinor(), major = d.deviceVersionMajor();
6374
        CV_Assert(!alias || canCreateAlias(src));
6375
        if (1 < major || (1 == major && 2 <= minor))
6376 6377 6378 6379 6380 6381 6382
        {
            cl_image_desc desc;
            desc.image_type       = CL_MEM_OBJECT_IMAGE2D;
            desc.image_width      = src.cols;
            desc.image_height     = src.rows;
            desc.image_depth      = 0;
            desc.image_array_size = 1;
6383
            desc.image_row_pitch  = alias ? src.step[0] : 0;
6384
            desc.image_slice_pitch = 0;
6385
            desc.buffer           = alias ? (cl_mem)src.handle(ACCESS_RW) : 0;
6386 6387
            desc.num_mip_levels   = 0;
            desc.num_samples      = 0;
6388
            handle = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &err);
6389 6390 6391 6392
        }
        else
#endif
        {
6393
            CV_SUPPRESS_DEPRECATED_START
6394
            CV_Assert(!alias);  // This is an OpenCL 1.2 extension
6395
            handle = clCreateImage2D(context, CL_MEM_READ_WRITE, &format, src.cols, src.rows, 0, NULL, &err);
6396
            CV_SUPPRESS_DEPRECATED_END
6397
        }
6398
        CV_OCL_DBG_CHECK_RESULT(err, "clCreateImage()");
6399

6400
        size_t origin[] = { 0, 0, 0 };
6401
        size_t region[] = { static_cast<size_t>(src.cols), static_cast<size_t>(src.rows), 1 };
6402 6403

        cl_mem devData;
6404
        if (!alias && !src.isContinuous())
6405
        {
6406
            devData = clCreateBuffer(context, CL_MEM_READ_ONLY, src.cols * src.rows * src.elemSize(), NULL, &err);
6407 6408 6409
            CV_OCL_CHECK_RESULT(err, cv::format("clCreateBuffer(CL_MEM_READ_ONLY, sz=%lld) => %p",
                    (long long int)(src.cols * src.rows * src.elemSize()), (void*)devData
                ).c_str());
6410

6411
            const size_t roi[3] = {static_cast<size_t>(src.cols) * src.elemSize(), static_cast<size_t>(src.rows), 1};
6412 6413 6414
            CV_OCL_CHECK(clEnqueueCopyBufferRect(queue, (cl_mem)src.handle(ACCESS_READ), devData, origin, origin,
                roi, src.step, 0, src.cols * src.elemSize(), 0, 0, NULL, NULL));
            CV_OCL_DBG_CHECK(clFlush(queue));
6415 6416
        }
        else
6417
        {
6418
            devData = (cl_mem)src.handle(ACCESS_READ);
6419
        }
6420
        CV_Assert(devData != NULL);
6421

6422
        if (!alias)
6423
        {
6424
            CV_OCL_CHECK(clEnqueueCopyBufferToImage(queue, devData, handle, 0, origin, region, 0, NULL, 0));
6425 6426
            if (!src.isContinuous())
            {
6427 6428
                CV_OCL_DBG_CHECK(clFlush(queue));
                CV_OCL_DBG_CHECK(clReleaseMemObject(devData));
6429
            }
6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441
        }
    }

    IMPLEMENT_REFCOUNTABLE();

    cl_mem handle;
};

Image2D::Image2D()
{
    p = NULL;
}
6442

6443
Image2D::Image2D(const UMat &src, bool norm, bool alias)
6444
{
6445 6446 6447 6448 6449 6450 6451
    p = new Impl(src, norm, alias);
}

bool Image2D::canCreateAlias(const UMat &m)
{
    bool ret = false;
    const Device & d = ocl::Device::getDefault();
6452
    if (d.imageFromBufferSupport() && !m.empty())
6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473
    {
        // This is the required pitch alignment in pixels
        uint pitchAlign = d.imagePitchAlignment();
        if (pitchAlign && !(m.step % (pitchAlign * m.elemSize())))
        {
            // We don't currently handle the case where the buffer was created
            // with CL_MEM_USE_HOST_PTR
            if (!m.u->tempUMat())
            {
                ret = true;
            }
        }
    }
    return ret;
}

bool Image2D::isFormatSupported(int depth, int cn, bool norm)
{
    cl_image_format format = Impl::getImageFormat(depth, cn, norm);

    return Impl::isFormatSupported(format);
6474
}
6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495

Image2D::Image2D(const Image2D & i)
{
    p = i.p;
    if (p)
        p->addref();
}

Image2D & Image2D::operator = (const Image2D & i)
{
    if (i.p != p)
    {
        if (i.p)
            i.p->addref();
        if (p)
            p->release();
        p = i.p;
    }
    return *this;
}

6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506
Image2D::~Image2D()
{
    if (p)
        p->release();
}

void* Image2D::ptr() const
{
    return p ? p->handle : 0;
}

6507 6508 6509 6510 6511 6512
bool internal::isOpenCLForced()
{
    static bool initialized = false;
    static bool value = false;
    if (!initialized)
    {
6513
        value = utils::getConfigurationParameterBool("OPENCV_OPENCL_FORCE", false);
6514 6515 6516 6517 6518
        initialized = true;
    }
    return value;
}

6519
bool internal::isPerformanceCheckBypassed()
6520 6521 6522 6523 6524
{
    static bool initialized = false;
    static bool value = false;
    if (!initialized)
    {
6525
        value = utils::getConfigurationParameterBool("OPENCV_OPENCL_PERF_CHECK_BYPASS", false);
6526 6527 6528 6529 6530
        initialized = true;
    }
    return value;
}

6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548
bool internal::isCLBuffer(UMat& u)
{
    void* h = u.handle(ACCESS_RW);
    if (!h)
        return true;
    CV_DbgAssert(u.u->currAllocator == getOpenCLAllocator());
#if 1
    if ((u.u->allocatorFlags_ & 0xffff0000) != 0) // OpenCL SVM flags are stored here
        return false;
#else
    cl_mem_object_type type = 0;
    cl_int ret = clGetMemObjectInfo((cl_mem)h, CL_MEM_TYPE, sizeof(type), &type, NULL);
    if (ret != CL_SUCCESS || type != CL_MEM_OBJECT_BUFFER)
        return false;
#endif
    return true;
}

6549 6550 6551 6552 6553 6554 6555 6556 6557
struct Timer::Impl
{
    const Queue queue;

    Impl(const Queue& q)
        : queue(q)
    {
    }

Wu Zhiwen's avatar
Wu Zhiwen committed
6558
    ~Impl(){}
6559 6560 6561 6562

    void start()
    {
#ifdef HAVE_OPENCL
6563
        CV_OCL_DBG_CHECK(clFinish((cl_command_queue)queue.ptr()));
Wu Zhiwen's avatar
Wu Zhiwen committed
6564
        timer.start();
6565 6566 6567 6568 6569 6570
#endif
    }

    void stop()
    {
#ifdef HAVE_OPENCL
6571
        CV_OCL_DBG_CHECK(clFinish((cl_command_queue)queue.ptr()));
Wu Zhiwen's avatar
Wu Zhiwen committed
6572
        timer.stop();
6573 6574 6575
#endif
    }

6576
    uint64 durationNS() const
6577 6578
    {
#ifdef HAVE_OPENCL
6579
        return (uint64)(timer.getTimeSec() * 1e9);
6580 6581 6582 6583 6584
#else
        return 0;
#endif
    }

Wu Zhiwen's avatar
Wu Zhiwen committed
6585
    TickMeter timer;
6586 6587
};

6588 6589
Timer::Timer(const Queue& q) : p(new Impl(q)) { }
Timer::~Timer() { delete p; }
6590 6591 6592

void Timer::start()
{
6593 6594
    CV_Assert(p);
    p->start();
6595 6596 6597 6598
}

void Timer::stop()
{
6599 6600
    CV_Assert(p);
    p->stop();
6601 6602
}

6603 6604 6605 6606 6607
uint64 Timer::durationNS() const
{
    CV_Assert(p);
    return p->durationNS();
}
6608

6609 6610 6611 6612 6613 6614 6615 6616 6617
#ifndef HAVE_OPENCL
#if defined(_MSC_VER)
    #pragma warning(pop)
#elif defined(__clang__)
    #pragma clang diagnostic pop
#elif defined(__GNUC__)
    #pragma GCC diagnostic pop
#endif
#endif
6618
}} // namespace