1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Third party copyrights are property of their respective owners.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
23 // * Redistribution's in binary form must reproduce the above copyright notice,
24 // this list of conditions and the following disclaimer in the documentation
25 // and/or other materials provided with the distribution.
27 // * The name of the copyright holders may not be used to endorse or promote products
28 // derived from this software without specific prior written permission.
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
43 #include "precomp.hpp"
44 #include "opencv2/core/gpumat.hpp"
47 #if defined(HAVE_CUDA)
48 #include <cuda_runtime.h>
51 #define CUDART_MINIMUM_REQUIRED_VERSION 4020
52 #define NPP_MINIMUM_REQUIRED_VERSION 4200
54 #if (CUDART_VERSION < CUDART_MINIMUM_REQUIRED_VERSION)
55 #error "Insufficient Cuda Runtime library version, please update it."
58 #if (NPP_VERSION_MAJOR * 1000 + NPP_VERSION_MINOR * 100 + NPP_VERSION_BUILD < NPP_MINIMUM_REQUIRED_VERSION)
59 #error "Insufficient NPP version, please update it."
63 #ifdef DYNAMIC_CUDA_SUPPORT
65 #include <sys/types.h>
71 # include <android/log.h>
73 # define LOG_TAG "OpenCV::CUDA"
74 # define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__))
75 # define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__))
76 # define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__))
81 using namespace cv::gpu;
83 #define throw_nogpu CV_Error(CV_GpuNotSupported, "The library is compiled without CUDA support")
85 #include "opencv2/dynamicuda/dynamicuda.hpp"
87 #ifdef DYNAMIC_CUDA_SUPPORT
89 typedef GpuFuncTable* (*GpuFactoryType)();
90 typedef DeviceInfoFuncTable* (*DeviceInfoFactoryType)();
92 static GpuFactoryType gpuFactory = NULL;
93 static DeviceInfoFactoryType deviceInfoFactory = NULL;
95 # if defined(__linux__) || defined(__APPLE__) || defined (ANDROID)
97 static const std::string getCudaSupportLibName()
100 if(0 != dladdr((void *)getCudaSupportLibName, &dl_info))
102 LOGD("Library name: %s", dl_info.dli_fname);
103 LOGD("Library base address: %p", dl_info.dli_fbase);
105 const char* libName=dl_info.dli_fname;
106 while( ((*libName)=='/') || ((*libName)=='.') )
110 FILE* file = fopen("/proc/self/smaps", "rt");
114 while (fgets(lineBuf, sizeof lineBuf, file) != NULL)
116 //verify that line ends with library name
117 int lineLength = strlen(lineBuf);
118 int libNameLength = strlen(libName);
121 for(int i = lineLength - 1; i >= 0 && isspace(lineBuf[i]); --i)
127 if (0 != strncmp(lineBuf + lineLength - libNameLength, libName, libNameLength))
129 //the line does not contain the library name
133 //extract path from smaps line
134 char* pathBegin = strchr(lineBuf, '/');
137 LOGE("Strange error: could not find path beginning in lin \"%s\"", lineBuf);
141 char* pathEnd = strrchr(pathBegin, '/');
144 LOGD("Libraries folder found: %s", pathBegin);
147 return std::string(pathBegin) + "/libopencv_core_cuda.so";
150 LOGE("Could not find library path");
154 LOGE("Could not read /proc/self/smaps");
159 LOGE("Could not get library name and base address");
166 static const std::string getCudaSupportLibName()
168 return "libopencv_core_cuda.so";
172 static bool loadCudaSupportLib()
175 const std::string name = getCudaSupportLibName();
176 handle = dlopen(name.c_str(), RTLD_LAZY);
180 deviceInfoFactory = (DeviceInfoFactoryType)dlsym(handle, "deviceInfoFactory");
181 if (!deviceInfoFactory)
187 gpuFactory = (GpuFactoryType)dlsym(handle, "gpuFactory");
198 # error "Dynamic CUDA support is not implemented for this platform!"
203 static GpuFuncTable* gpuFuncTable()
205 #ifdef DYNAMIC_CUDA_SUPPORT
206 static EmptyFuncTable stub;
207 static GpuFuncTable* libFuncTable = loadCudaSupportLib() ? gpuFactory(): (GpuFuncTable*)&stub;
208 static GpuFuncTable *funcTable = libFuncTable ? libFuncTable : (GpuFuncTable*)&stub;
211 static CudaFuncTable impl;
212 static GpuFuncTable* funcTable = &impl;
214 static EmptyFuncTable stub;
215 static GpuFuncTable* funcTable = &stub;
221 static DeviceInfoFuncTable* deviceInfoFuncTable()
223 #ifdef DYNAMIC_CUDA_SUPPORT
224 static EmptyDeviceInfoFuncTable stub;
225 static DeviceInfoFuncTable* libFuncTable = loadCudaSupportLib() ? deviceInfoFactory(): (DeviceInfoFuncTable*)&stub;
226 static DeviceInfoFuncTable* funcTable = libFuncTable ? libFuncTable : (DeviceInfoFuncTable*)&stub;
229 static CudaDeviceInfoFuncTable impl;
230 static DeviceInfoFuncTable* funcTable = &impl;
232 static EmptyDeviceInfoFuncTable stub;
233 static DeviceInfoFuncTable* funcTable = &stub;
240 //////////////////////////////// Initialization & Info ////////////////////////
242 int cv::gpu::getCudaEnabledDeviceCount() { return deviceInfoFuncTable()->getCudaEnabledDeviceCount(); }
244 void cv::gpu::setDevice(int device) { deviceInfoFuncTable()->setDevice(device); }
245 int cv::gpu::getDevice() { return deviceInfoFuncTable()->getDevice(); }
247 void cv::gpu::resetDevice() { deviceInfoFuncTable()->resetDevice(); }
249 bool cv::gpu::deviceSupports(FeatureSet feature_set) { return deviceInfoFuncTable()->deviceSupports(feature_set); }
251 bool cv::gpu::TargetArchs::builtWith(FeatureSet feature_set) { return deviceInfoFuncTable()->builtWith(feature_set); }
252 bool cv::gpu::TargetArchs::has(int major, int minor) { return deviceInfoFuncTable()->has(major, minor); }
253 bool cv::gpu::TargetArchs::hasPtx(int major, int minor) { return deviceInfoFuncTable()->hasPtx(major, minor); }
254 bool cv::gpu::TargetArchs::hasBin(int major, int minor) { return deviceInfoFuncTable()->hasBin(major, minor); }
255 bool cv::gpu::TargetArchs::hasEqualOrLessPtx(int major, int minor) { return deviceInfoFuncTable()->hasEqualOrLessPtx(major, minor); }
256 bool cv::gpu::TargetArchs::hasEqualOrGreater(int major, int minor) { return deviceInfoFuncTable()->hasEqualOrGreater(major, minor); }
257 bool cv::gpu::TargetArchs::hasEqualOrGreaterPtx(int major, int minor) { return deviceInfoFuncTable()->hasEqualOrGreaterPtx(major, minor); }
258 bool cv::gpu::TargetArchs::hasEqualOrGreaterBin(int major, int minor) { return deviceInfoFuncTable()->hasEqualOrGreaterBin(major, minor); }
260 size_t cv::gpu::DeviceInfo::sharedMemPerBlock() const { return deviceInfoFuncTable()->sharedMemPerBlock(); }
261 void cv::gpu::DeviceInfo::queryMemory(size_t& total_memory, size_t& free_memory) const { deviceInfoFuncTable()->queryMemory(total_memory, free_memory); }
262 size_t cv::gpu::DeviceInfo::freeMemory() const { return deviceInfoFuncTable()->freeMemory(); }
263 size_t cv::gpu::DeviceInfo::totalMemory() const { return deviceInfoFuncTable()->totalMemory(); }
264 bool cv::gpu::DeviceInfo::supports(FeatureSet feature_set) const { return deviceInfoFuncTable()->supports(feature_set); }
265 bool cv::gpu::DeviceInfo::isCompatible() const { return deviceInfoFuncTable()->isCompatible(); }
266 int cv::gpu::DeviceInfo::deviceID() const { return deviceInfoFuncTable()->deviceID(); };
267 int cv::gpu::DeviceInfo::majorVersion() const { return deviceInfoFuncTable()->majorVersion(); }
268 int cv::gpu::DeviceInfo::minorVersion() const { return deviceInfoFuncTable()->minorVersion(); }
269 std::string cv::gpu::DeviceInfo::name() const { return deviceInfoFuncTable()->name(); }
270 int cv::gpu::DeviceInfo::multiProcessorCount() const { return deviceInfoFuncTable()->multiProcessorCount(); }
271 void cv::gpu::DeviceInfo::query() { deviceInfoFuncTable()->query(); }
273 void cv::gpu::printCudaDeviceInfo(int device) { deviceInfoFuncTable()->printCudaDeviceInfo(device); }
274 void cv::gpu::printShortCudaDeviceInfo(int device) { deviceInfoFuncTable()->printShortCudaDeviceInfo(device); }
276 namespace cv { namespace gpu
278 CV_EXPORTS void copyWithMask(const cv::gpu::GpuMat&, cv::gpu::GpuMat&, const cv::gpu::GpuMat&, cudaStream_t);
279 CV_EXPORTS void convertTo(const cv::gpu::GpuMat&, cv::gpu::GpuMat&);
280 CV_EXPORTS void convertTo(const cv::gpu::GpuMat&, cv::gpu::GpuMat&, double, double, cudaStream_t = 0);
281 CV_EXPORTS void setTo(cv::gpu::GpuMat&, cv::Scalar, cudaStream_t);
282 CV_EXPORTS void setTo(cv::gpu::GpuMat&, cv::Scalar, const cv::gpu::GpuMat&, cudaStream_t);
283 CV_EXPORTS void setTo(cv::gpu::GpuMat&, cv::Scalar);
284 CV_EXPORTS void setTo(cv::gpu::GpuMat&, cv::Scalar, const cv::gpu::GpuMat&);
287 //////////////////////////////// GpuMat ///////////////////////////////
289 cv::gpu::GpuMat::GpuMat(const GpuMat& m)
290 : flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend)
293 CV_XADD(refcount, 1);
296 cv::gpu::GpuMat::GpuMat(int rows_, int cols_, int type_, void* data_, size_t step_) :
297 flags(Mat::MAGIC_VAL + (type_ & TYPE_MASK)), rows(rows_), cols(cols_),
298 step(step_), data((uchar*)data_), refcount(0),
299 datastart((uchar*)data_), dataend((uchar*)data_)
301 size_t minstep = cols * elemSize();
303 if (step == Mat::AUTO_STEP)
306 flags |= Mat::CONTINUOUS_FLAG;
313 CV_DbgAssert(step >= minstep);
315 flags |= step == minstep ? Mat::CONTINUOUS_FLAG : 0;
317 dataend += step * (rows - 1) + minstep;
320 cv::gpu::GpuMat::GpuMat(Size size_, int type_, void* data_, size_t step_) :
321 flags(Mat::MAGIC_VAL + (type_ & TYPE_MASK)), rows(size_.height), cols(size_.width),
322 step(step_), data((uchar*)data_), refcount(0),
323 datastart((uchar*)data_), dataend((uchar*)data_)
325 size_t minstep = cols * elemSize();
327 if (step == Mat::AUTO_STEP)
330 flags |= Mat::CONTINUOUS_FLAG;
337 CV_DbgAssert(step >= minstep);
339 flags |= step == minstep ? Mat::CONTINUOUS_FLAG : 0;
341 dataend += step * (rows - 1) + minstep;
344 cv::gpu::GpuMat::GpuMat(const GpuMat& m, Range _rowRange, Range _colRange)
347 step = m.step; refcount = m.refcount;
348 data = m.data; datastart = m.datastart; dataend = m.dataend;
350 if (_rowRange == Range::all())
354 CV_Assert(0 <= _rowRange.start && _rowRange.start <= _rowRange.end && _rowRange.end <= m.rows);
356 rows = _rowRange.size();
357 data += step*_rowRange.start;
360 if (_colRange == Range::all())
364 CV_Assert(0 <= _colRange.start && _colRange.start <= _colRange.end && _colRange.end <= m.cols);
366 cols = _colRange.size();
367 data += _colRange.start*elemSize();
368 flags &= cols < m.cols ? ~Mat::CONTINUOUS_FLAG : -1;
372 flags |= Mat::CONTINUOUS_FLAG;
375 CV_XADD(refcount, 1);
377 if (rows <= 0 || cols <= 0)
381 cv::gpu::GpuMat::GpuMat(const GpuMat& m, Rect roi) :
382 flags(m.flags), rows(roi.height), cols(roi.width),
383 step(m.step), data(m.data + roi.y*step), refcount(m.refcount),
384 datastart(m.datastart), dataend(m.dataend)
386 flags &= roi.width < m.cols ? ~Mat::CONTINUOUS_FLAG : -1;
387 data += roi.x * elemSize();
389 CV_Assert(0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows);
392 CV_XADD(refcount, 1);
394 if (rows <= 0 || cols <= 0)
398 cv::gpu::GpuMat::GpuMat(const Mat& m) :
399 flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0)
404 GpuMat& cv::gpu::GpuMat::operator = (const GpuMat& m)
415 void cv::gpu::GpuMat::swap(GpuMat& b)
417 std::swap(flags, b.flags);
418 std::swap(rows, b.rows);
419 std::swap(cols, b.cols);
420 std::swap(step, b.step);
421 std::swap(data, b.data);
422 std::swap(datastart, b.datastart);
423 std::swap(dataend, b.dataend);
424 std::swap(refcount, b.refcount);
427 void cv::gpu::GpuMat::locateROI(Size& wholeSize, Point& ofs) const
429 size_t esz = elemSize();
430 ptrdiff_t delta1 = data - datastart;
431 ptrdiff_t delta2 = dataend - datastart;
433 CV_DbgAssert(step > 0);
439 ofs.y = static_cast<int>(delta1 / step);
440 ofs.x = static_cast<int>((delta1 - step * ofs.y) / esz);
442 CV_DbgAssert(data == datastart + ofs.y * step + ofs.x * esz);
445 size_t minstep = (ofs.x + cols) * esz;
447 wholeSize.height = std::max(static_cast<int>((delta2 - minstep) / step + 1), ofs.y + rows);
448 wholeSize.width = std::max(static_cast<int>((delta2 - step * (wholeSize.height - 1)) / esz), ofs.x + cols);
451 GpuMat& cv::gpu::GpuMat::adjustROI(int dtop, int dbottom, int dleft, int dright)
455 locateROI(wholeSize, ofs);
457 size_t esz = elemSize();
459 int row1 = std::max(ofs.y - dtop, 0);
460 int row2 = std::min(ofs.y + rows + dbottom, wholeSize.height);
462 int col1 = std::max(ofs.x - dleft, 0);
463 int col2 = std::min(ofs.x + cols + dright, wholeSize.width);
465 data += (row1 - ofs.y) * step + (col1 - ofs.x) * esz;
469 if (esz * cols == step || rows == 1)
470 flags |= Mat::CONTINUOUS_FLAG;
472 flags &= ~Mat::CONTINUOUS_FLAG;
477 GpuMat cv::gpu::GpuMat::reshape(int new_cn, int new_rows) const
485 int total_width = cols * cn;
487 if ((new_cn > total_width || total_width % new_cn != 0) && new_rows == 0)
488 new_rows = rows * total_width / new_cn;
490 if (new_rows != 0 && new_rows != rows)
492 int total_size = total_width * rows;
495 CV_Error(CV_BadStep, "The matrix is not continuous, thus its number of rows can not be changed");
497 if ((unsigned)new_rows > (unsigned)total_size)
498 CV_Error(CV_StsOutOfRange, "Bad new number of rows");
500 total_width = total_size / new_rows;
502 if (total_width * new_rows != total_size)
503 CV_Error(CV_StsBadArg, "The total number of matrix elements is not divisible by the new number of rows");
506 hdr.step = total_width * elemSize1();
509 int new_width = total_width / new_cn;
511 if (new_width * new_cn != total_width)
512 CV_Error(CV_BadNumChannels, "The total width is not divisible by the new number of channels");
514 hdr.cols = new_width;
515 hdr.flags = (hdr.flags & ~CV_MAT_CN_MASK) | ((new_cn - 1) << CV_CN_SHIFT);
520 cv::Mat::Mat(const GpuMat& m) : flags(0), dims(0), rows(0), cols(0), data(0), refcount(0), datastart(0), dataend(0), datalimit(0), allocator(0), size(&rows)
525 void cv::gpu::createContinuous(int rows, int cols, int type, GpuMat& m)
527 int area = rows * cols;
528 if (m.empty() || m.type() != type || !m.isContinuous() || m.size().area() < area)
529 m.create(1, area, type);
533 m.step = m.elemSize() * cols;
534 m.flags |= Mat::CONTINUOUS_FLAG;
537 void cv::gpu::ensureSizeIsEnough(int rows, int cols, int type, GpuMat& m)
539 if (m.empty() || m.type() != type || m.data != m.datastart)
540 m.create(rows, cols, type);
543 const size_t esz = m.elemSize();
544 const ptrdiff_t delta2 = m.dataend - m.datastart;
546 const size_t minstep = m.cols * esz;
549 wholeSize.height = std::max(static_cast<int>((delta2 - minstep) / m.step + 1), m.rows);
550 wholeSize.width = std::max(static_cast<int>((delta2 - m.step * (wholeSize.height - 1)) / esz), m.cols);
552 if (wholeSize.height < rows || wholeSize.width < cols)
553 m.create(rows, cols, type);
562 GpuMat cv::gpu::allocMatFromBuf(int rows, int cols, int type, GpuMat &mat)
564 if (!mat.empty() && mat.type() == type && mat.rows >= rows && mat.cols >= cols)
565 return mat(Rect(0, 0, cols, rows));
566 return mat = GpuMat(rows, cols, type);
569 void cv::gpu::GpuMat::upload(const Mat& m)
571 CV_DbgAssert(!m.empty());
573 create(m.size(), m.type());
575 gpuFuncTable()->copy(m, *this);
578 void cv::gpu::GpuMat::download(Mat& m) const
580 CV_DbgAssert(!empty());
582 m.create(size(), type());
584 gpuFuncTable()->copy(*this, m);
587 void cv::gpu::GpuMat::copyTo(GpuMat& m) const
589 CV_DbgAssert(!empty());
591 m.create(size(), type());
593 gpuFuncTable()->copy(*this, m);
596 void cv::gpu::GpuMat::copyTo(GpuMat& mat, const GpuMat& mask) const
602 mat.create(size(), type());
604 gpuFuncTable()->copyWithMask(*this, mat, mask);
608 void cv::gpu::GpuMat::convertTo(GpuMat& dst, int rtype, double alpha, double beta) const
610 bool noScale = fabs(alpha - 1) < numeric_limits<double>::epsilon() && fabs(beta) < numeric_limits<double>::epsilon();
615 rtype = CV_MAKETYPE(CV_MAT_DEPTH(rtype), channels());
617 int sdepth = depth();
618 int ddepth = CV_MAT_DEPTH(rtype);
619 if (sdepth == ddepth && noScale)
626 const GpuMat* psrc = this;
627 if (sdepth != ddepth && psrc == &dst)
633 dst.create(size(), rtype);
636 cv::gpu::convertTo(*psrc, dst);
638 cv::gpu::convertTo(*psrc, dst, alpha, beta);
641 GpuMat& cv::gpu::GpuMat::setTo(Scalar s, const GpuMat& mask)
643 CV_Assert(mask.empty() || mask.type() == CV_8UC1);
644 CV_DbgAssert(!empty());
646 gpu::setTo(*this, s, mask);
651 void cv::gpu::GpuMat::create(int _rows, int _cols, int _type)
655 if (rows == _rows && cols == _cols && type() == _type && data)
661 CV_DbgAssert(_rows >= 0 && _cols >= 0);
663 if (_rows > 0 && _cols > 0)
665 flags = Mat::MAGIC_VAL + _type;
669 size_t esz = elemSize();
672 gpuFuncTable()->mallocPitch(&devPtr, &step, esz * cols, rows);
674 // Single row must be continuous
678 if (esz * cols == step)
679 flags |= Mat::CONTINUOUS_FLAG;
681 int64 _nettosize = static_cast<int64>(step) * rows;
682 size_t nettosize = static_cast<size_t>(_nettosize);
684 datastart = data = static_cast<uchar*>(devPtr);
685 dataend = data + nettosize;
687 refcount = static_cast<int*>(fastMalloc(sizeof(*refcount)));
692 void cv::gpu::GpuMat::release()
694 if (refcount && CV_XADD(refcount, -1) == 1)
698 gpuFuncTable()->free(datastart);
701 data = datastart = dataend = 0;
702 step = rows = cols = 0;
706 namespace cv { namespace gpu
708 void convertTo(const GpuMat& src, GpuMat& dst)
710 gpuFuncTable()->convert(src, dst);
713 void convertTo(const GpuMat& src, GpuMat& dst, double alpha, double beta, cudaStream_t stream)
715 gpuFuncTable()->convert(src, dst, alpha, beta, stream);
718 void setTo(GpuMat& src, Scalar s, cudaStream_t stream)
720 gpuFuncTable()->setTo(src, s, cv::gpu::GpuMat(), stream);
723 void setTo(GpuMat& src, Scalar s, const GpuMat& mask, cudaStream_t stream)
725 gpuFuncTable()->setTo(src, s, mask, stream);
728 void setTo(GpuMat& src, Scalar s)
733 void setTo(GpuMat& src, Scalar s, const GpuMat& mask)
735 setTo(src, s, mask, 0);
739 ////////////////////////////////////////////////////////////////////////
742 void cv::gpu::error(const char *error_string, const char *file, const int line, const char *func)
744 int code = CV_GpuApiCallError;
746 if (uncaught_exception())
748 const char* errorStr = cvErrorStr(code);
749 const char* function = func ? func : "unknown function";
751 cerr << "OpenCV Error: " << errorStr << "(" << error_string << ") in " << function << ", file " << file << ", line " << line;
755 cv::error( cv::Exception(code, error_string, func, file, line) );