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 // Copyright (C) 2015, Itseez Inc., all rights reserved.
16 // Third party copyrights are property of their respective owners.
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
21 // * Redistribution's of source code must retain the above copyright notice,
22 // this list of conditions and the following disclaimer.
24 // * Redistribution's in binary form must reproduce the above copyright notice,
25 // this list of conditions and the following disclaimer in the documentation
26 // and/or other materials provided with the distribution.
28 // * The name of the copyright holders may not be used to endorse or promote products
29 // derived from this software without specific prior written permission.
31 // This software is provided by the copyright holders and contributors "as is" and
32 // any express or implied warranties, including, but not limited to, the implied
33 // warranties of merchantability and fitness for a particular purpose are disclaimed.
34 // In no event shall the Intel Corporation or contributors be liable for any direct,
35 // indirect, incidental, special, exemplary, or consequential damages
36 // (including, but not limited to, procurement of substitute goods or services;
37 // loss of use, data, or profits; or business interruption) however caused
38 // and on any theory of liability, whether in contract, strict liability,
39 // or tort (including negligence or otherwise) arising in any way out of
40 // the use of this software, even if advised of the possibility of such damage.
44 #include "precomp.hpp"
47 #include <opencv2/core/utils/configuration.private.hpp>
48 #include <opencv2/core/utils/trace.private.hpp>
52 static Mutex* __initialization_mutex = NULL;
53 Mutex& getInitializationMutex()
55 if (__initialization_mutex == NULL)
56 __initialization_mutex = new Mutex();
57 return *__initialization_mutex;
59 // force initialization (single-threaded environment)
60 Mutex* __initialization_mutex_initializer = &getInitializationMutex();
66 # pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
70 #if defined __ANDROID__ || defined __linux__ || defined __FreeBSD__ || defined __HAIKU__
74 #if defined __ANDROID__ || defined __linux__
75 # include <linux/auxvec.h>
79 #if defined __ANDROID__ && defined HAVE_CPUFEATURES
80 # include <cpu-features.h>
84 # if defined __PPC64__ && defined __linux__
85 # include "sys/auxv.h"
89 # ifndef PPC_FEATURE2_ARCH_2_07
90 # define PPC_FEATURE2_ARCH_2_07 0x80000000
95 #if defined _WIN32 || defined WINCE
96 #ifndef _WIN32_WINNT // This is needed for the declaration of TryEnterCriticalSection in winbase.h with Visual Studio 2005 (and older?)
97 #define _WIN32_WINNT 0x0400 // http://msdn.microsoft.com/en-us/library/ms686857(VS.85).aspx
100 #if (_WIN32_WINNT >= 0x0602)
101 #include <synchapi.h>
111 #elif defined _M_IX86
112 static void __cpuid(int* cpuid_data, int)
129 static void __cpuidex(int* cpuid_data, int, int)
149 #include <wrl/client.h>
150 #ifndef __cplusplus_winrt
151 #include <windows.storage.h>
152 #pragma comment(lib, "runtimeobject.lib")
155 std::wstring GetTempPathWinRT()
157 #ifdef __cplusplus_winrt
158 return std::wstring(Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data());
160 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> appdataFactory;
161 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> appdataRef;
162 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> storagefolderRef;
163 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageItem> storageitemRef;
165 HSTRING_HEADER hstrHead;
167 if (FAILED(WindowsCreateStringReference(RuntimeClass_Windows_Storage_ApplicationData,
168 (UINT32)wcslen(RuntimeClass_Windows_Storage_ApplicationData), &hstrHead, &str)))
170 if (FAILED(RoGetActivationFactory(str, IID_PPV_ARGS(appdataFactory.ReleaseAndGetAddressOf()))))
172 if (FAILED(appdataFactory->get_Current(appdataRef.ReleaseAndGetAddressOf())))
174 if (FAILED(appdataRef->get_TemporaryFolder(storagefolderRef.ReleaseAndGetAddressOf())))
176 if (FAILED(storagefolderRef.As(&storageitemRef)))
179 if (FAILED(storageitemRef->get_Path(&str)))
181 wstr = WindowsGetStringRawBuffer(str, NULL);
182 WindowsDeleteString(str);
187 std::wstring GetTempFileNameWinRT(std::wstring prefix)
192 wchar_t* mask = L"%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x";
193 swprintf(&guidStr[0], sizeof(guidStr)/sizeof(wchar_t), mask,
194 g.Data1, g.Data2, g.Data3, UINT(g.Data4[0]), UINT(g.Data4[1]),
195 UINT(g.Data4[2]), UINT(g.Data4[3]), UINT(g.Data4[4]),
196 UINT(g.Data4[5]), UINT(g.Data4[6]), UINT(g.Data4[7]));
198 return prefix.append(std::wstring(guidStr));
204 #include <sys/time.h>
207 #if defined __MACH__ && defined __APPLE__
208 #include <mach/mach.h>
209 #include <mach/mach_time.h>
218 #if defined __linux__ || defined __APPLE__ || defined __EMSCRIPTEN__ || defined __FreeBSD__ || defined __GLIBC__ || defined __HAIKU__
221 #include <sys/types.h>
222 #if defined __ANDROID__
223 #include <sys/sysconf.h>
228 # include <android/log.h>
234 Exception::Exception() { code = 0; line = 0; }
236 Exception::Exception(int _code, const String& _err, const String& _func, const String& _file, int _line)
237 : code(_code), err(_err), func(_func), file(_file), line(_line)
242 Exception::~Exception() throw() {}
245 \return the error description and the context as a text string.
247 const char* Exception::what() const throw() { return msg.c_str(); }
249 void Exception::formatMessage()
251 if( func.size() > 0 )
252 msg = format("%s:%d: error: (%d) %s in function %s\n", file.c_str(), line, code, err.c_str(), func.c_str());
254 msg = format("%s:%d: error: (%d) %s\n", file.c_str(), line, code, err.c_str());
257 static const char* g_hwFeatureNames[CV_HARDWARE_MAX_FEATURE] = { NULL };
259 static const char* getHWFeatureName(int id)
261 return (id < CV_HARDWARE_MAX_FEATURE) ? g_hwFeatureNames[id] : NULL;
263 static const char* getHWFeatureNameSafe(int id)
265 const char* name = getHWFeatureName(id);
266 return name ? name : "Unknown feature";
271 enum { MAX_FEATURE = CV_HARDWARE_MAX_FEATURE };
273 HWFeatures(bool run_initialize = false)
275 memset( have, 0, sizeof(have[0]) * MAX_FEATURE );
280 static void initializeNames()
282 for (int i = 0; i < CV_HARDWARE_MAX_FEATURE; i++)
284 g_hwFeatureNames[i] = 0;
286 g_hwFeatureNames[CPU_MMX] = "MMX";
287 g_hwFeatureNames[CPU_SSE] = "SSE";
288 g_hwFeatureNames[CPU_SSE2] = "SSE2";
289 g_hwFeatureNames[CPU_SSE3] = "SSE3";
290 g_hwFeatureNames[CPU_SSSE3] = "SSSE3";
291 g_hwFeatureNames[CPU_SSE4_1] = "SSE4.1";
292 g_hwFeatureNames[CPU_SSE4_2] = "SSE4.2";
293 g_hwFeatureNames[CPU_POPCNT] = "POPCNT";
294 g_hwFeatureNames[CPU_FP16] = "FP16";
295 g_hwFeatureNames[CPU_AVX] = "AVX";
296 g_hwFeatureNames[CPU_AVX2] = "AVX2";
297 g_hwFeatureNames[CPU_FMA3] = "FMA3";
299 g_hwFeatureNames[CPU_AVX_512F] = "AVX512F";
300 g_hwFeatureNames[CPU_AVX_512BW] = "AVX512BW";
301 g_hwFeatureNames[CPU_AVX_512CD] = "AVX512CD";
302 g_hwFeatureNames[CPU_AVX_512DQ] = "AVX512DQ";
303 g_hwFeatureNames[CPU_AVX_512ER] = "AVX512ER";
304 g_hwFeatureNames[CPU_AVX_512IFMA] = "AVX512IFMA";
305 g_hwFeatureNames[CPU_AVX_512PF] = "AVX512PF";
306 g_hwFeatureNames[CPU_AVX_512VBMI] = "AVX512VBMI";
307 g_hwFeatureNames[CPU_AVX_512VL] = "AVX512VL";
309 g_hwFeatureNames[CPU_NEON] = "NEON";
311 g_hwFeatureNames[CPU_VSX] = "VSX";
313 g_hwFeatureNames[CPU_AVX512_SKX] = "AVX512-SKX";
316 void initialize(void)
319 if (getenv("OPENCV_DUMP_CONFIG"))
321 fprintf(stderr, "\nOpenCV build configuration is:\n%s\n",
322 cv::getBuildInformation().c_str());
328 int cpuid_data[4] = { 0, 0, 0, 0 };
329 int cpuid_data_ex[4] = { 0, 0, 0, 0 };
331 #if defined _MSC_VER && (defined _M_IX86 || defined _M_X64)
332 #define OPENCV_HAVE_X86_CPUID 1
333 __cpuid(cpuid_data, 1);
334 #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__)
335 #define OPENCV_HAVE_X86_CPUID 1
341 :[eax]"=a"(cpuid_data[0]),[ebx]"=b"(cpuid_data[1]),[ecx]"=c"(cpuid_data[2]),[edx]"=d"(cpuid_data[3])
352 : "=a"(cpuid_data[0]), "=c"(cpuid_data[2]), "=d"(cpuid_data[3])
359 #ifdef OPENCV_HAVE_X86_CPUID
360 int x86_family = (cpuid_data[0] >> 8) & 15;
361 if( x86_family >= 6 )
363 have[CV_CPU_MMX] = (cpuid_data[3] & (1<<23)) != 0;
364 have[CV_CPU_SSE] = (cpuid_data[3] & (1<<25)) != 0;
365 have[CV_CPU_SSE2] = (cpuid_data[3] & (1<<26)) != 0;
366 have[CV_CPU_SSE3] = (cpuid_data[2] & (1<<0)) != 0;
367 have[CV_CPU_SSSE3] = (cpuid_data[2] & (1<<9)) != 0;
368 have[CV_CPU_FMA3] = (cpuid_data[2] & (1<<12)) != 0;
369 have[CV_CPU_SSE4_1] = (cpuid_data[2] & (1<<19)) != 0;
370 have[CV_CPU_SSE4_2] = (cpuid_data[2] & (1<<20)) != 0;
371 have[CV_CPU_POPCNT] = (cpuid_data[2] & (1<<23)) != 0;
372 have[CV_CPU_AVX] = (cpuid_data[2] & (1<<28)) != 0;
373 have[CV_CPU_FP16] = (cpuid_data[2] & (1<<29)) != 0;
375 // make the second call to the cpuid command in order to get
376 // information about extended features like AVX2
377 #if defined _MSC_VER && (defined _M_IX86 || defined _M_X64)
378 #define OPENCV_HAVE_X86_CPUID_EX 1
379 __cpuidex(cpuid_data_ex, 7, 0);
380 #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__)
381 #define OPENCV_HAVE_X86_CPUID_EX 1
388 :[eax]"=a"(cpuid_data_ex[0]),[ebx]"=b"(cpuid_data_ex[1]),[ecx]"=c"(cpuid_data_ex[2]),[edx]"=d"(cpuid_data_ex[3])
401 : "=r"(cpuid_data_ex[1]), "=c"(cpuid_data_ex[2])
408 #ifdef OPENCV_HAVE_X86_CPUID_EX
409 have[CV_CPU_AVX2] = (cpuid_data_ex[1] & (1<<5)) != 0;
411 have[CV_CPU_AVX_512F] = (cpuid_data_ex[1] & (1<<16)) != 0;
412 have[CV_CPU_AVX_512DQ] = (cpuid_data_ex[1] & (1<<17)) != 0;
413 have[CV_CPU_AVX_512IFMA512] = (cpuid_data_ex[1] & (1<<21)) != 0;
414 have[CV_CPU_AVX_512PF] = (cpuid_data_ex[1] & (1<<26)) != 0;
415 have[CV_CPU_AVX_512ER] = (cpuid_data_ex[1] & (1<<27)) != 0;
416 have[CV_CPU_AVX_512CD] = (cpuid_data_ex[1] & (1<<28)) != 0;
417 have[CV_CPU_AVX_512BW] = (cpuid_data_ex[1] & (1<<30)) != 0;
418 have[CV_CPU_AVX_512VL] = (cpuid_data_ex[1] & (1<<31)) != 0;
419 have[CV_CPU_AVX_512VBMI] = (cpuid_data_ex[2] & (1<<1)) != 0;
421 CV_UNUSED(cpuid_data_ex);
424 bool have_AVX_OS_support = true;
425 bool have_AVX512_OS_support = true;
426 if (!(cpuid_data[2] & (1<<27)))
427 have_AVX_OS_support = false; // OS uses XSAVE_XRSTORE and CPU support AVX
431 #ifdef _XCR_XFEATURE_ENABLED_MASK // requires immintrin.h
432 xcr0 = (int)_xgetbv(_XCR_XFEATURE_ENABLED_MASK);
433 #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__)
434 __asm__ ("xgetbv" : "=a" (xcr0) : "c" (0) : "%edx" );
436 if ((xcr0 & 0x6) != 0x6)
437 have_AVX_OS_support = false; // YMM registers
438 if ((xcr0 & 0xe6) != 0xe6)
439 have_AVX512_OS_support = false; // ZMM registers
442 if (!have_AVX_OS_support)
444 have[CV_CPU_AVX] = false;
445 have[CV_CPU_FP16] = false;
446 have[CV_CPU_AVX2] = false;
447 have[CV_CPU_FMA3] = false;
449 if (!have_AVX_OS_support || !have_AVX512_OS_support)
451 have[CV_CPU_AVX_512F] = false;
452 have[CV_CPU_AVX_512BW] = false;
453 have[CV_CPU_AVX_512CD] = false;
454 have[CV_CPU_AVX_512DQ] = false;
455 have[CV_CPU_AVX_512ER] = false;
456 have[CV_CPU_AVX_512IFMA512] = false;
457 have[CV_CPU_AVX_512PF] = false;
458 have[CV_CPU_AVX_512VBMI] = false;
459 have[CV_CPU_AVX_512VL] = false;
462 if (have[CV_CPU_AVX_512F])
464 have[CV_CPU_AVX512_SKX] = have[CV_CPU_AVX_512F] & have[CV_CPU_AVX_512CD] & have[CV_CPU_AVX_512BW] & have[CV_CPU_AVX_512DQ] & have[CV_CPU_AVX_512VL];
468 CV_UNUSED(cpuid_data);
469 CV_UNUSED(cpuid_data_ex);
470 #endif // OPENCV_HAVE_X86_CPUID
472 #if defined __ANDROID__ || defined __linux__
474 have[CV_CPU_NEON] = true;
475 have[CV_CPU_FP16] = true;
476 #elif defined __arm__ && defined __ANDROID__
477 #if defined HAVE_CPUFEATURES
478 __android_log_print(ANDROID_LOG_INFO, "OpenCV", "calling android_getCpuFeatures() ...");
479 uint64_t features = android_getCpuFeatures();
480 __android_log_print(ANDROID_LOG_INFO, "OpenCV", "calling android_getCpuFeatures() ... Done (%llx)", features);
481 have[CV_CPU_NEON] = (features & ANDROID_CPU_ARM_FEATURE_NEON) != 0;
482 have[CV_CPU_FP16] = (features & ANDROID_CPU_ARM_FEATURE_VFP_FP16) != 0;
484 __android_log_print(ANDROID_LOG_INFO, "OpenCV", "cpufeatures library is not avaialble for CPU detection");
486 __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- NEON instructions is enabled via build flags");
487 have[CV_CPU_NEON] = true;
489 __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- NEON instructions is NOT enabled via build flags");
492 __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- FP16 instructions is enabled via build flags");
493 have[CV_CPU_FP16] = true;
495 __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- FP16 instructions is NOT enabled via build flags");
498 #elif defined __arm__
499 int cpufile = open("/proc/self/auxv", O_RDONLY);
504 const size_t size_auxv_t = sizeof(auxv);
506 while ((size_t)read(cpufile, &auxv, size_auxv_t) == size_auxv_t)
508 if (auxv.a_type == AT_HWCAP)
510 have[CV_CPU_NEON] = (auxv.a_un.a_val & 4096) != 0;
511 have[CV_CPU_FP16] = (auxv.a_un.a_val & 2) != 0;
519 #elif (defined __clang__ || defined __APPLE__)
520 #if (defined __ARM_NEON__ || (defined __ARM_NEON && defined __aarch64__))
521 have[CV_CPU_NEON] = true;
523 #if (defined __ARM_FP && (((__ARM_FP & 0x2) != 0) && defined __ARM_NEON__))
524 have[CV_CPU_FP16] = true;
529 have[CV_CPU_VSX] = true;
530 #elif (defined __PPC64__ && defined __linux__)
531 uint64 hwcaps = getauxval(AT_HWCAP);
532 uint64 hwcap2 = getauxval(AT_HWCAP2);
533 have[CV_CPU_VSX] = (hwcaps & PPC_FEATURE_PPC_LE && hwcaps & PPC_FEATURE_HAS_VSX && hwcap2 & PPC_FEATURE2_ARCH_2_07);
535 have[CV_CPU_VSX] = false;
538 int baseline_features[] = { CV_CPU_BASELINE_FEATURES };
539 if (!checkFeatures(baseline_features, sizeof(baseline_features) / sizeof(baseline_features[0])))
542 "******************************************************************\n"
544 "* This OpenCV build doesn't support current CPU/HW configuration *\n"
546 "* Use OPENCV_DUMP_CONFIG=1 environment variable for details *\n"
547 "******************************************************************\n");
548 fprintf(stderr, "\nRequired baseline features:\n");
549 checkFeatures(baseline_features, sizeof(baseline_features) / sizeof(baseline_features[0]), true);
550 CV_ErrorNoReturn(cv::Error::StsAssert, "Missing support for required CPU baseline features. Check OpenCV build configuration and required CPU/HW setup.");
553 readSettings(baseline_features, sizeof(baseline_features) / sizeof(baseline_features[0]));
556 bool checkFeatures(const int* features, int count, bool dump = false)
559 for (int i = 0; i < count; i++)
561 int feature = features[i];
566 if (dump) fprintf(stderr, "%s - OK\n", getHWFeatureNameSafe(feature));
571 if (dump) fprintf(stderr, "%s - NOT AVAILABLE\n", getHWFeatureNameSafe(feature));
578 static inline bool isSymbolSeparator(char c)
580 return c == ',' || c == ';' || c == '-';
583 void readSettings(const int* baseline_features, int baseline_count)
586 const char* disabled_features =
588 getenv("OPENCV_CPU_DISABLE");
592 if (disabled_features && disabled_features[0] != 0)
594 const char* start = disabled_features;
597 while (start[0] != 0 && isSymbolSeparator(start[0]))
603 const char* end = start;
604 while (end[0] != 0 && !isSymbolSeparator(end[0]))
610 cv::String feature(start, end);
613 CV_Assert(feature.size() > 0);
616 for (int i = 0; i < CV_HARDWARE_MAX_FEATURE; i++)
618 if (!g_hwFeatureNames[i]) continue;
619 size_t len = strlen(g_hwFeatureNames[i]);
620 if (len != feature.size()) continue;
621 if (feature.compare(g_hwFeatureNames[i]) == 0)
623 bool isBaseline = false;
624 for (int k = 0; k < baseline_count; k++)
626 if (baseline_features[k] == i)
634 if (dump) fprintf(stderr, "OPENCV: Trying to disable baseline CPU feature: '%s'. This has very limited effect, because code optimizations for this feature are executed unconditionally in the most cases.\n", getHWFeatureNameSafe(i));
638 if (dump) fprintf(stderr, "OPENCV: Trying to disable unavailable CPU feature on the current platform: '%s'.\n", getHWFeatureNameSafe(i));
648 if (dump) fprintf(stderr, "OPENCV: Trying to disable unknown CPU feature: '%s'.\n", feature.c_str());
654 bool have[MAX_FEATURE+1];
657 static HWFeatures featuresEnabled(true), featuresDisabled = HWFeatures(false);
658 static HWFeatures* currentFeatures = &featuresEnabled;
660 bool checkHardwareSupport(int feature)
662 CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
663 return currentFeatures->have[feature];
667 volatile bool useOptimizedFlag = true;
669 void setUseOptimized( bool flag )
671 useOptimizedFlag = flag;
672 currentFeatures = flag ? &featuresEnabled : &featuresDisabled;
674 ipp::setUseIPP(flag);
676 ocl::setUseOpenCL(flag);
678 #ifdef HAVE_TEGRA_OPTIMIZATION
679 ::tegra::setUseTegra(flag);
683 bool useOptimized(void)
685 return useOptimizedFlag;
688 int64 getTickCount(void)
690 #if defined _WIN32 || defined WINCE
691 LARGE_INTEGER counter;
692 QueryPerformanceCounter( &counter );
693 return (int64)counter.QuadPart;
694 #elif defined __linux || defined __linux__
696 clock_gettime(CLOCK_MONOTONIC, &tp);
697 return (int64)tp.tv_sec*1000000000 + tp.tv_nsec;
698 #elif defined __MACH__ && defined __APPLE__
699 return (int64)mach_absolute_time();
703 gettimeofday( &tv, &tz );
704 return (int64)tv.tv_sec*1000000 + tv.tv_usec;
708 double getTickFrequency(void)
710 #if defined _WIN32 || defined WINCE
712 QueryPerformanceFrequency(&freq);
713 return (double)freq.QuadPart;
714 #elif defined __linux || defined __linux__
716 #elif defined __MACH__ && defined __APPLE__
717 static double freq = 0;
720 mach_timebase_info_data_t sTimebaseInfo;
721 mach_timebase_info(&sTimebaseInfo);
722 freq = sTimebaseInfo.denom*1e9/sTimebaseInfo.numer;
730 #if defined __GNUC__ && (defined __i386__ || defined __x86_64__ || defined __ppc__)
731 #if defined(__i386__)
733 int64 getCPUTickCount(void)
736 __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
739 #elif defined(__x86_64__)
741 int64 getCPUTickCount(void)
744 __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
745 return (int64)lo | ((int64)hi << 32);
748 #elif defined(__ppc__)
750 int64 getCPUTickCount(void)
753 unsigned upper, lower, tmp;
761 : "=r"(upper),"=r"(lower),"=r"(tmp)
763 return lower | ((int64)upper << 32);
768 #error "RDTSC not defined"
772 #elif defined _MSC_VER && defined _WIN32 && defined _M_IX86
774 int64 getCPUTickCount(void)
783 //int64 getCPUTickCount(void)
785 // return ippGetCpuClocks();
788 int64 getCPUTickCount(void)
790 return getTickCount();
796 const String& getBuildInformation()
798 static String build_info =
799 #include "version_string.inc"
804 String format( const char* fmt, ... )
806 AutoBuffer<char, 1024> buf;
812 int bsize = static_cast<int>(buf.size());
813 int len = cv_vsnprintf((char *)buf, bsize, fmt, va);
816 CV_Assert(len >= 0 && "Check format string for errors");
823 return String((char *)buf, len);
827 String tempfile( const char* suffix )
831 const char *temp_dir = getenv("OPENCV_TEMP_PATH");
836 RoInitialize(RO_INIT_MULTITHREADED);
837 std::wstring temp_dir = GetTempPathWinRT();
839 std::wstring temp_file = GetTempFileNameWinRT(L"ocv");
840 if (temp_file.empty())
843 temp_file = temp_dir.append(std::wstring(L"\\")).append(temp_file);
844 DeleteFileW(temp_file.c_str());
846 char aname[MAX_PATH];
847 size_t copied = wcstombs(aname, temp_file.c_str(), MAX_PATH);
848 CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
849 fname = String(aname);
852 char temp_dir2[MAX_PATH] = { 0 };
853 char temp_file[MAX_PATH] = { 0 };
855 if (temp_dir == 0 || temp_dir[0] == 0)
857 ::GetTempPathA(sizeof(temp_dir2), temp_dir2);
858 temp_dir = temp_dir2;
860 if(0 == ::GetTempFileNameA(temp_dir, "ocv", 0, temp_file))
863 DeleteFileA(temp_file);
869 //char defaultTemplate[] = "/mnt/sdcard/__opencv_temp.XXXXXX";
870 char defaultTemplate[] = "/data/local/tmp/__opencv_temp.XXXXXX";
872 char defaultTemplate[] = "/tmp/__opencv_temp.XXXXXX";
875 if (temp_dir == 0 || temp_dir[0] == 0)
876 fname = defaultTemplate;
880 char ech = fname[fname.size() - 1];
881 if(ech != '/' && ech != '\\')
883 fname = fname + "__opencv_temp.XXXXXX";
886 const int fd = mkstemp((char*)fname.c_str());
887 if (fd == -1) return String();
890 remove(fname.c_str());
895 if (suffix[0] != '.')
896 return fname + "." + suffix;
898 return fname + suffix;
903 static ErrorCallback customErrorCallback = 0;
904 static void* customErrorCallbackData = 0;
905 static bool breakOnError = false;
907 bool setBreakOnError(bool value)
909 bool prevVal = breakOnError;
910 breakOnError = value;
914 int cv_snprintf(char* buf, int len, const char* fmt, ...)
918 int res = cv_vsnprintf(buf, len, fmt, va);
923 int cv_vsnprintf(char* buf, int len, const char* fmt, va_list args)
926 if (len <= 0) return len == 0 ? 1024 : -1;
927 int res = _vsnprintf_s(buf, len, _TRUNCATE, fmt, args);
928 // ensure null terminating on VS
929 if (res >= 0 && res < len)
936 buf[len - 1] = 0; // truncate happened
937 return res >= len ? res : (len * 2);
940 return vsnprintf(buf, len, fmt, args);
944 void error( const Exception& exc )
946 if (customErrorCallback != 0)
947 customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(),
948 exc.file.c_str(), exc.line, customErrorCallbackData);
951 const char* errorStr = cvErrorStr(exc.code);
954 cv_snprintf(buf, sizeof(buf),
955 "OpenCV Error: %s (%s) in %s, file %s, line %d",
956 errorStr, exc.err.c_str(), exc.func.size() > 0 ?
957 exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line);
958 fprintf( stderr, "%s\n", buf );
961 __android_log_print(ANDROID_LOG_ERROR, "cv::error()", "%s", buf);
967 static volatile int* p = 0;
974 void error(int _code, const String& _err, const char* _func, const char* _file, int _line)
976 error(cv::Exception(_code, _err, _func, _file, _line));
981 redirectError( ErrorCallback errCallback, void* userdata, void** prevUserdata)
984 *prevUserdata = customErrorCallbackData;
986 ErrorCallback prevCallback = customErrorCallback;
988 customErrorCallback = errCallback;
989 customErrorCallbackData = userdata;
996 CV_IMPL int cvCheckHardwareSupport(int feature)
998 CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
999 return cv::currentFeatures->have[feature];
1002 CV_IMPL int cvUseOptimized( int flag )
1004 int prevMode = cv::useOptimizedFlag;
1005 cv::setUseOptimized( flag != 0 );
1009 CV_IMPL int64 cvGetTickCount(void)
1011 return cv::getTickCount();
1014 CV_IMPL double cvGetTickFrequency(void)
1016 return cv::getTickFrequency()*1e-6;
1019 CV_IMPL CvErrorCallback
1020 cvRedirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata)
1022 return cv::redirectError(errCallback, userdata, prevUserdata);
1025 CV_IMPL int cvNulDevReport( int, const char*, const char*,
1026 const char*, int, void* )
1031 CV_IMPL int cvStdErrReport( int, const char*, const char*,
1032 const char*, int, void* )
1037 CV_IMPL int cvGuiBoxReport( int, const char*, const char*,
1038 const char*, int, void* )
1043 CV_IMPL int cvGetErrInfo( const char**, const char**, const char**, int* )
1049 CV_IMPL const char* cvErrorStr( int status )
1051 static char buf[256];
1055 case CV_StsOk : return "No Error";
1056 case CV_StsBackTrace : return "Backtrace";
1057 case CV_StsError : return "Unspecified error";
1058 case CV_StsInternal : return "Internal error";
1059 case CV_StsNoMem : return "Insufficient memory";
1060 case CV_StsBadArg : return "Bad argument";
1061 case CV_StsNoConv : return "Iterations do not converge";
1062 case CV_StsAutoTrace : return "Autotrace call";
1063 case CV_StsBadSize : return "Incorrect size of input array";
1064 case CV_StsNullPtr : return "Null pointer";
1065 case CV_StsDivByZero : return "Division by zero occurred";
1066 case CV_BadStep : return "Image step is wrong";
1067 case CV_StsInplaceNotSupported : return "Inplace operation is not supported";
1068 case CV_StsObjectNotFound : return "Requested object was not found";
1069 case CV_BadDepth : return "Input image depth is not supported by function";
1070 case CV_StsUnmatchedFormats : return "Formats of input arguments do not match";
1071 case CV_StsUnmatchedSizes : return "Sizes of input arguments do not match";
1072 case CV_StsOutOfRange : return "One of arguments\' values is out of range";
1073 case CV_StsUnsupportedFormat : return "Unsupported format or combination of formats";
1074 case CV_BadCOI : return "Input COI is not supported";
1075 case CV_BadNumChannels : return "Bad number of channels";
1076 case CV_StsBadFlag : return "Bad flag (parameter or structure field)";
1077 case CV_StsBadPoint : return "Bad parameter of type CvPoint";
1078 case CV_StsBadMask : return "Bad type of mask argument";
1079 case CV_StsParseError : return "Parsing error";
1080 case CV_StsNotImplemented : return "The function/feature is not implemented";
1081 case CV_StsBadMemBlock : return "Memory block has been corrupted";
1082 case CV_StsAssert : return "Assertion failed";
1083 case CV_GpuNotSupported : return "No CUDA support";
1084 case CV_GpuApiCallError : return "Gpu API call";
1085 case CV_OpenGlNotSupported : return "No OpenGL support";
1086 case CV_OpenGlApiCallError : return "OpenGL API call";
1089 sprintf(buf, "Unknown %s code %d", status >= 0 ? "status":"error", status);
1093 CV_IMPL int cvGetErrMode(void)
1098 CV_IMPL int cvSetErrMode(int)
1103 CV_IMPL int cvGetErrStatus(void)
1108 CV_IMPL void cvSetErrStatus(int)
1113 CV_IMPL void cvError( int code, const char* func_name,
1114 const char* err_msg,
1115 const char* file_name, int line )
1117 cv::error(cv::Exception(code, err_msg, func_name, file_name, line));
1120 /* function, which converts int to int */
1122 cvErrorFromIppStatus( int status )
1126 case CV_BADSIZE_ERR: return CV_StsBadSize;
1127 case CV_BADMEMBLOCK_ERR: return CV_StsBadMemBlock;
1128 case CV_NULLPTR_ERR: return CV_StsNullPtr;
1129 case CV_DIV_BY_ZERO_ERR: return CV_StsDivByZero;
1130 case CV_BADSTEP_ERR: return CV_BadStep;
1131 case CV_OUTOFMEM_ERR: return CV_StsNoMem;
1132 case CV_BADARG_ERR: return CV_StsBadArg;
1133 case CV_NOTDEFINED_ERR: return CV_StsError;
1134 case CV_INPLACE_NOT_SUPPORTED_ERR: return CV_StsInplaceNotSupported;
1135 case CV_NOTFOUND_ERR: return CV_StsObjectNotFound;
1136 case CV_BADCONVERGENCE_ERR: return CV_StsNoConv;
1137 case CV_BADDEPTH_ERR: return CV_BadDepth;
1138 case CV_UNMATCHED_FORMATS_ERR: return CV_StsUnmatchedFormats;
1139 case CV_UNSUPPORTED_COI_ERR: return CV_BadCOI;
1140 case CV_UNSUPPORTED_CHANNELS_ERR: return CV_BadNumChannels;
1141 case CV_BADFLAG_ERR: return CV_StsBadFlag;
1142 case CV_BADRANGE_ERR: return CV_StsBadArg;
1143 case CV_BADCOEF_ERR: return CV_StsBadArg;
1144 case CV_BADFACTOR_ERR: return CV_StsBadArg;
1145 case CV_BADPOINT_ERR: return CV_StsBadPoint;
1153 bool __termination = false;
1159 #if defined _WIN32 || defined WINCE
1165 #if (_WIN32_WINNT >= 0x0600)
1166 ::InitializeCriticalSectionEx(&cs, 1000, 0);
1168 ::InitializeCriticalSection(&cs);
1172 ~Impl() { DeleteCriticalSection(&cs); }
1174 void lock() { EnterCriticalSection(&cs); }
1175 bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
1176 void unlock() { LeaveCriticalSection(&cs); }
1178 CRITICAL_SECTION cs;
1188 pthread_mutexattr_t attr;
1189 pthread_mutexattr_init(&attr);
1190 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1191 pthread_mutex_init(&mt, &attr);
1192 pthread_mutexattr_destroy(&attr);
1196 ~Impl() { pthread_mutex_destroy(&mt); }
1198 void lock() { pthread_mutex_lock(&mt); }
1199 bool trylock() { return pthread_mutex_trylock(&mt) == 0; }
1200 void unlock() { pthread_mutex_unlock(&mt); }
1210 impl = new Mutex::Impl;
1215 if( CV_XADD(&impl->refcount, -1) == 1 )
1220 Mutex::Mutex(const Mutex& m)
1223 CV_XADD(&impl->refcount, 1);
1226 Mutex& Mutex::operator = (const Mutex& m)
1230 CV_XADD(&m.impl->refcount, 1);
1231 if( CV_XADD(&impl->refcount, -1) == 1 )
1238 void Mutex::lock() { impl->lock(); }
1239 void Mutex::unlock() { impl->unlock(); }
1240 bool Mutex::trylock() { return impl->trylock(); }
1243 //////////////////////////////// thread-local storage ////////////////////////////////
1247 #pragma warning(disable:4505) // unreferenced local function has been removed
1249 #ifndef TLS_OUT_OF_INDEXES
1250 #define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF)
1254 // TLS platform abstraction layer
1255 class TlsAbstraction
1260 void* GetData() const;
1261 void SetData(void *pData);
1269 pthread_key_t tlsKey;
1275 static __declspec( thread ) void* tlsData = NULL; // using C++11 thread attribute for local thread data
1276 TlsAbstraction::TlsAbstraction() {}
1277 TlsAbstraction::~TlsAbstraction() {}
1278 void* TlsAbstraction::GetData() const
1282 void TlsAbstraction::SetData(void *pData)
1287 TlsAbstraction::TlsAbstraction()
1289 tlsKey = TlsAlloc();
1290 CV_Assert(tlsKey != TLS_OUT_OF_INDEXES);
1292 TlsAbstraction::~TlsAbstraction()
1296 void* TlsAbstraction::GetData() const
1298 return TlsGetValue(tlsKey);
1300 void TlsAbstraction::SetData(void *pData)
1302 CV_Assert(TlsSetValue(tlsKey, pData) == TRUE);
1306 TlsAbstraction::TlsAbstraction()
1308 CV_Assert(pthread_key_create(&tlsKey, NULL) == 0);
1310 TlsAbstraction::~TlsAbstraction()
1312 CV_Assert(pthread_key_delete(tlsKey) == 0);
1314 void* TlsAbstraction::GetData() const
1316 return pthread_getspecific(tlsKey);
1318 void TlsAbstraction::SetData(void *pData)
1320 CV_Assert(pthread_setspecific(tlsKey, pData) == 0);
1324 // Per-thread data structure
1333 std::vector<void*> slots; // Data array for a thread
1334 size_t idx; // Thread index in TLS storage. This is not OS thread ID!
1337 // Main TLS storage class
1344 tlsSlots.reserve(32);
1345 threads.reserve(32);
1349 for(size_t i = 0; i < threads.size(); i++)
1353 /* Current architecture doesn't allow proper global objects release, so this check can cause crashes
1355 // Check if all slots were properly cleared
1356 for(size_t j = 0; j < threads[i]->slots.size(); j++)
1358 CV_Assert(threads[i]->slots[j] == 0);
1367 void releaseThread()
1369 AutoLock guard(mtxGlobalAccess);
1370 ThreadData *pTD = (ThreadData*)tls.GetData();
1371 for(size_t i = 0; i < threads.size(); i++)
1373 if(pTD == threads[i])
1383 // Reserve TLS storage index
1384 size_t reserveSlot()
1386 AutoLock guard(mtxGlobalAccess);
1387 CV_Assert(tlsSlotsSize == tlsSlots.size());
1389 // Find unused slots
1390 for(size_t slot = 0; slot < tlsSlotsSize; slot++)
1400 tlsSlots.push_back(1); tlsSlotsSize++;
1401 return tlsSlotsSize - 1;
1404 // Release TLS storage index and pass associated data to caller
1405 void releaseSlot(size_t slotIdx, std::vector<void*> &dataVec, bool keepSlot = false)
1407 AutoLock guard(mtxGlobalAccess);
1408 CV_Assert(tlsSlotsSize == tlsSlots.size());
1409 CV_Assert(tlsSlotsSize > slotIdx);
1411 for(size_t i = 0; i < threads.size(); i++)
1415 std::vector<void*>& thread_slots = threads[i]->slots;
1416 if (thread_slots.size() > slotIdx && thread_slots[slotIdx])
1418 dataVec.push_back(thread_slots[slotIdx]);
1419 thread_slots[slotIdx] = NULL;
1425 tlsSlots[slotIdx] = 0;
1428 // Get data by TLS storage index
1429 void* getData(size_t slotIdx) const
1431 #ifndef CV_THREAD_SANITIZER
1432 CV_Assert(tlsSlotsSize > slotIdx);
1435 ThreadData* threadData = (ThreadData*)tls.GetData();
1436 if(threadData && threadData->slots.size() > slotIdx)
1437 return threadData->slots[slotIdx];
1442 // Gather data from threads by TLS storage index
1443 void gather(size_t slotIdx, std::vector<void*> &dataVec)
1445 AutoLock guard(mtxGlobalAccess);
1446 CV_Assert(tlsSlotsSize == tlsSlots.size());
1447 CV_Assert(tlsSlotsSize > slotIdx);
1449 for(size_t i = 0; i < threads.size(); i++)
1453 std::vector<void*>& thread_slots = threads[i]->slots;
1454 if (thread_slots.size() > slotIdx && thread_slots[slotIdx])
1455 dataVec.push_back(thread_slots[slotIdx]);
1460 // Set data to storage index
1461 void setData(size_t slotIdx, void* pData)
1463 #ifndef CV_THREAD_SANITIZER
1464 CV_Assert(tlsSlotsSize > slotIdx);
1467 ThreadData* threadData = (ThreadData*)tls.GetData();
1470 threadData = new ThreadData;
1471 tls.SetData((void*)threadData);
1473 AutoLock guard(mtxGlobalAccess);
1474 threadData->idx = threads.size();
1475 threads.push_back(threadData);
1479 if(slotIdx >= threadData->slots.size())
1481 AutoLock guard(mtxGlobalAccess); // keep synchronization with gather() calls
1482 threadData->slots.resize(slotIdx + 1, NULL);
1484 threadData->slots[slotIdx] = pData;
1488 TlsAbstraction tls; // TLS abstraction layer instance
1490 Mutex mtxGlobalAccess; // Shared objects operation guard
1491 size_t tlsSlotsSize; // equal to tlsSlots.size() in synchronized sections
1492 // without synchronization this counter doesn't desrease - it is used for slotIdx sanity checks
1493 std::vector<int> tlsSlots; // TLS keys state
1494 std::vector<ThreadData*> threads; // Array for all allocated data. Thread data pointers are placed here to allow data cleanup
1497 // Create global TLS storage object
1498 static TlsStorage &getTlsStorage()
1500 CV_SINGLETON_LAZY_INIT_REF(TlsStorage, new TlsStorage())
1503 TLSDataContainer::TLSDataContainer()
1505 key_ = (int)getTlsStorage().reserveSlot(); // Reserve key from TLS storage
1508 TLSDataContainer::~TLSDataContainer()
1510 CV_Assert(key_ == -1); // Key must be released in child object
1513 void TLSDataContainer::gatherData(std::vector<void*> &data) const
1515 getTlsStorage().gather(key_, data);
1518 void TLSDataContainer::release()
1520 std::vector<void*> data;
1522 getTlsStorage().releaseSlot(key_, data); // Release key and get stored data for proper destruction
1524 for(size_t i = 0; i < data.size(); i++) // Delete all associated data
1525 deleteDataInstance(data[i]);
1528 void TLSDataContainer::cleanup()
1530 std::vector<void*> data;
1532 getTlsStorage().releaseSlot(key_, data, true); // Extract stored data with removal from TLS tables
1533 for(size_t i = 0; i < data.size(); i++) // Delete all associated data
1534 deleteDataInstance(data[i]);
1537 void* TLSDataContainer::getData() const
1539 CV_Assert(key_ != -1 && "Can't fetch data from terminated TLS container.");
1540 void* pData = getTlsStorage().getData(key_); // Check if data was already allocated
1543 // Create new data instance and save it to TLS storage
1544 pData = createDataInstance();
1545 getTlsStorage().setData(key_, pData);
1550 TLSData<CoreTLSData>& getCoreTlsData()
1552 CV_SINGLETON_LAZY_INIT_REF(TLSData<CoreTLSData>, new TLSData<CoreTLSData>())
1555 #if defined CVAPI_EXPORTS && defined _WIN32 && !defined WINCE
1557 #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
1561 BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved);
1564 BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved)
1566 if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
1568 if (lpReserved != NULL) // called after ExitProcess() call
1570 cv::__termination = true;
1574 // Not allowed to free resources if lpReserved is non-null
1575 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583.aspx
1576 cv::getTlsStorage().releaseThread();
1585 static int g_threadNum = 0;
1590 id(CV_XADD(&g_threadNum, 1))
1592 #ifdef OPENCV_WITH_ITT
1593 __itt_thread_set_name(cv::format("OpenCVThread-%03d", id).c_str());
1598 static TLSData<ThreadID>& getThreadIDTLS()
1600 CV_SINGLETON_LAZY_INIT_REF(TLSData<ThreadID>, new TLSData<ThreadID>());
1604 int utils::getThreadID() { return getThreadIDTLS().get()->id; }
1606 bool utils::getConfigurationParameterBool(const char* name, bool defaultValue)
1609 const char* envValue = NULL;
1611 const char* envValue = getenv(name);
1613 if (envValue == NULL)
1615 return defaultValue;
1617 cv::String value = envValue;
1618 if (value == "1" || value == "True" || value == "true" || value == "TRUE")
1622 if (value == "0" || value == "False" || value == "false" || value == "FALSE")
1626 CV_ErrorNoReturn(cv::Error::StsBadArg, cv::format("Invalid value for %s parameter: %s", name, value.c_str()));
1630 size_t utils::getConfigurationParameterSizeT(const char* name, size_t defaultValue)
1633 const char* envValue = NULL;
1635 const char* envValue = getenv(name);
1637 if (envValue == NULL)
1639 return defaultValue;
1641 cv::String value = envValue;
1643 for (; pos < value.size(); pos++)
1645 if (!isdigit(value[pos]))
1648 cv::String valueStr = value.substr(0, pos);
1649 cv::String suffixStr = value.substr(pos, value.length() - pos);
1650 int v = atoi(valueStr.c_str());
1651 if (suffixStr.length() == 0)
1653 else if (suffixStr == "MB" || suffixStr == "Mb" || suffixStr == "mb")
1654 return v * 1024 * 1024;
1655 else if (suffixStr == "KB" || suffixStr == "Kb" || suffixStr == "kb")
1657 CV_ErrorNoReturn(cv::Error::StsBadArg, cv::format("Invalid value for %s parameter: %s", name, value.c_str()));
1660 cv::String utils::getConfigurationParameterString(const char* name, const char* defaultValue)
1663 const char* envValue = NULL;
1665 const char* envValue = getenv(name);
1667 if (envValue == NULL)
1669 return defaultValue;
1671 cv::String value = envValue;
1676 #ifdef CV_COLLECT_IMPL_DATA
1677 ImplCollector& getImplData()
1679 CV_SINGLETON_LAZY_INIT_REF(ImplCollector, new ImplCollector())
1682 void setImpl(int flags)
1684 cv::AutoLock lock(getImplData().mutex);
1686 getImplData().implFlags = flags;
1687 getImplData().implCode.clear();
1688 getImplData().implFun.clear();
1691 void addImpl(int flag, const char* func)
1693 cv::AutoLock lock(getImplData().mutex);
1695 getImplData().implFlags |= flag;
1696 if(func) // use lazy collection if name was not specified
1698 size_t index = getImplData().implCode.size();
1699 if(!index || (getImplData().implCode[index-1] != flag || getImplData().implFun[index-1].compare(func))) // avoid duplicates
1701 getImplData().implCode.push_back(flag);
1702 getImplData().implFun.push_back(func);
1707 int getImpl(std::vector<int> &impl, std::vector<String> &funName)
1709 cv::AutoLock lock(getImplData().mutex);
1711 impl = getImplData().implCode;
1712 funName = getImplData().implFun;
1713 return getImplData().implFlags; // return actual flags for lazy collection
1716 bool useCollection()
1718 return getImplData().useCollection;
1721 void setUseCollection(bool flag)
1723 cv::AutoLock lock(getImplData().mutex);
1725 getImplData().useCollection = flag;
1731 bool useInstrumentation()
1733 #ifdef ENABLE_INSTRUMENTATION
1734 return getInstrumentStruct().useInstr;
1740 void setUseInstrumentation(bool flag)
1742 #ifdef ENABLE_INSTRUMENTATION
1743 getInstrumentStruct().useInstr = flag;
1749 InstrNode* getTrace()
1751 #ifdef ENABLE_INSTRUMENTATION
1752 return &getInstrumentStruct().rootNode;
1760 #ifdef ENABLE_INSTRUMENTATION
1761 getInstrumentStruct().rootNode.removeChilds();
1762 getInstrumentTLSStruct().pCurrentNode = &getInstrumentStruct().rootNode;
1766 void setFlags(FLAGS modeFlags)
1768 #ifdef ENABLE_INSTRUMENTATION
1769 getInstrumentStruct().flags = modeFlags;
1771 CV_UNUSED(modeFlags);
1776 #ifdef ENABLE_INSTRUMENTATION
1777 return (FLAGS)getInstrumentStruct().flags;
1783 NodeData::NodeData(const char* funName, const char* fileName, int lineNum, void* retAddress, bool alwaysExpand, cv::instr::TYPE instrType, cv::instr::IMPL implType)
1785 m_funName = funName;
1786 m_instrType = instrType;
1787 m_implType = implType;
1788 m_fileName = fileName;
1789 m_lineNum = lineNum;
1790 m_retAddress = retAddress;
1791 m_alwaysExpand = alwaysExpand;
1799 NodeData::NodeData(NodeData &ref)
1803 NodeData& NodeData::operator=(const NodeData &right)
1805 this->m_funName = right.m_funName;
1806 this->m_instrType = right.m_instrType;
1807 this->m_implType = right.m_implType;
1808 this->m_fileName = right.m_fileName;
1809 this->m_lineNum = right.m_lineNum;
1810 this->m_retAddress = right.m_retAddress;
1811 this->m_alwaysExpand = right.m_alwaysExpand;
1813 this->m_threads = right.m_threads;
1814 this->m_counter = right.m_counter;
1815 this->m_ticksTotal = right.m_ticksTotal;
1817 this->m_funError = right.m_funError;
1821 NodeData::~NodeData()
1824 bool operator==(const NodeData& left, const NodeData& right)
1826 if(left.m_lineNum == right.m_lineNum && left.m_funName == right.m_funName && left.m_fileName == right.m_fileName)
1828 if(left.m_retAddress == right.m_retAddress || !(cv::instr::getFlags()&cv::instr::FLAGS_EXPAND_SAME_NAMES || left.m_alwaysExpand))
1834 #ifdef ENABLE_INSTRUMENTATION
1835 InstrStruct& getInstrumentStruct()
1837 static InstrStruct instr;
1841 InstrTLSStruct& getInstrumentTLSStruct()
1843 return *getInstrumentStruct().tlsStruct.get();
1846 InstrNode* getCurrentNode()
1848 return getInstrumentTLSStruct().pCurrentNode;
1851 IntrumentationRegion::IntrumentationRegion(const char* funName, const char* fileName, int lineNum, void *retAddress, bool alwaysExpand, TYPE instrType, IMPL implType)
1856 InstrStruct *pStruct = &getInstrumentStruct();
1857 if(pStruct->useInstr)
1859 InstrTLSStruct *pTLS = &getInstrumentTLSStruct();
1861 // Disable in case of failure
1862 if(!pTLS->pCurrentNode)
1868 int depth = pTLS->pCurrentNode->getDepth();
1869 if(pStruct->maxDepth && pStruct->maxDepth <= depth)
1875 NodeData payload(funName, fileName, lineNum, retAddress, alwaysExpand, instrType, implType);
1876 Node<NodeData>* pChild = NULL;
1878 if(pStruct->flags&FLAGS_MAPPING)
1881 cv::AutoLock guard(pStruct->mutexCreate); // Guard from concurrent child creation
1882 pChild = pTLS->pCurrentNode->findChild(payload);
1885 pChild = new Node<NodeData>(payload);
1886 pTLS->pCurrentNode->addChild(pChild);
1891 pChild = pTLS->pCurrentNode->findChild(payload);
1898 pTLS->pCurrentNode = pChild;
1900 m_regionTicks = getTickCount();
1904 IntrumentationRegion::~IntrumentationRegion()
1906 InstrStruct *pStruct = &getInstrumentStruct();
1907 if(pStruct->useInstr)
1911 InstrTLSStruct *pTLS = &getInstrumentTLSStruct();
1913 if (pTLS->pCurrentNode->m_payload.m_implType == cv::instr::IMPL_OPENCL &&
1914 (pTLS->pCurrentNode->m_payload.m_instrType == cv::instr::TYPE_FUN ||
1915 pTLS->pCurrentNode->m_payload.m_instrType == cv::instr::TYPE_WRAPPER))
1917 cv::ocl::finish(); // TODO Support "async" OpenCL instrumentation
1920 uint64 ticks = (getTickCount() - m_regionTicks);
1922 cv::AutoLock guard(pStruct->mutexCount); // Concurrent ticks accumulation
1923 pTLS->pCurrentNode->m_payload.m_counter++;
1924 pTLS->pCurrentNode->m_payload.m_ticksTotal += ticks;
1925 pTLS->pCurrentNode->m_payload.m_tls.get()->m_ticksTotal += ticks;
1928 pTLS->pCurrentNode = pTLS->pCurrentNode->m_pParent;
1939 struct IPPInitSingleton
1955 ippStatus = ippGetCpuFeatures(&cpuFeatures, NULL);
1958 std::cerr << "ERROR: IPP cannot detect CPU features, IPP was disabled " << std::endl;
1962 ippFeatures = cpuFeatures;
1964 const char* pIppEnv = getenv("OPENCV_IPP");
1965 cv::String env = pIppEnv;
1968 #if IPP_VERSION_X100 >= 201703
1969 const Ipp64u minorFeatures = ippCPUID_MOVBE|ippCPUID_AES|ippCPUID_CLMUL|ippCPUID_ABR|ippCPUID_RDRAND|ippCPUID_F16C|
1970 ippCPUID_ADCOX|ippCPUID_RDSEED|ippCPUID_PREFETCHW|ippCPUID_SHA|ippCPUID_MPX|ippCPUID_AVX512CD|ippCPUID_AVX512ER|
1971 ippCPUID_AVX512PF|ippCPUID_AVX512BW|ippCPUID_AVX512DQ|ippCPUID_AVX512VL|ippCPUID_AVX512VBMI;
1972 #elif IPP_VERSION_X100 >= 201700
1973 const Ipp64u minorFeatures = ippCPUID_MOVBE|ippCPUID_AES|ippCPUID_CLMUL|ippCPUID_ABR|ippCPUID_RDRAND|ippCPUID_F16C|
1974 ippCPUID_ADCOX|ippCPUID_RDSEED|ippCPUID_PREFETCHW|ippCPUID_SHA|ippCPUID_AVX512CD|ippCPUID_AVX512ER|
1975 ippCPUID_AVX512PF|ippCPUID_AVX512BW|ippCPUID_AVX512DQ|ippCPUID_AVX512VL|ippCPUID_AVX512VBMI;
1977 const Ipp64u minorFeatures = 0;
1980 env = env.toLowerCase();
1981 if(env.substr(0, 2) == "ne")
1984 env = env.substr(3, env.size());
1987 if(env == "disabled")
1989 std::cerr << "WARNING: IPP was disabled by OPENCV_IPP environment variable" << std::endl;
1992 else if(env == "sse42")
1993 ippFeatures = minorFeatures|ippCPUID_SSE2|ippCPUID_SSE3|ippCPUID_SSSE3|ippCPUID_SSE41|ippCPUID_SSE42;
1994 else if(env == "avx2")
1995 ippFeatures = minorFeatures|ippCPUID_SSE2|ippCPUID_SSE3|ippCPUID_SSSE3|ippCPUID_SSE41|ippCPUID_SSE42|ippCPUID_AVX|ippCPUID_AVX2;
1996 #if IPP_VERSION_X100 >= 201700
1997 #if defined (_M_AMD64) || defined (__x86_64__)
1998 else if(env == "avx512")
1999 ippFeatures = minorFeatures|ippCPUID_SSE2|ippCPUID_SSE3|ippCPUID_SSSE3|ippCPUID_SSE41|ippCPUID_SSE42|ippCPUID_AVX|ippCPUID_AVX2|ippCPUID_AVX512F;
2003 std::cerr << "ERROR: Improper value of OPENCV_IPP: " << env.c_str() << ". Correct values are: disabled, sse42, avx2, avx512 (Intel64 only)" << std::endl;
2005 // Trim unsupported features
2006 ippFeatures &= cpuFeatures;
2009 // Disable AVX1 since we don't track regressions for it. SSE42 will be used instead
2010 if(cpuFeatures&ippCPUID_AVX && !(cpuFeatures&ippCPUID_AVX2))
2011 ippFeatures &= ~((Ipp64u)ippCPUID_AVX);
2013 // IPP integrations in OpenCV support only SSE4.2, AVX2 and AVX-512 optimizations.
2015 #if IPP_VERSION_X100 >= 201700
2016 cpuFeatures&ippCPUID_AVX512F ||
2018 cpuFeatures&ippCPUID_AVX2 ||
2019 cpuFeatures&ippCPUID_SSE42
2026 if(ippFeatures == cpuFeatures)
2029 IPP_INITIALIZER(ippFeatures)
2030 ippFeatures = ippGetEnabledCpuFeatures();
2032 // Detect top level optimizations to make comparison easier for optimizations dependent conditions
2033 #if IPP_VERSION_X100 >= 201700
2034 if(ippFeatures&ippCPUID_AVX512F)
2036 if((ippFeatures&ippCPUID_AVX512_SKX) == ippCPUID_AVX512_SKX)
2037 ippTopFeatures = ippCPUID_AVX512_SKX;
2038 else if((ippFeatures&ippCPUID_AVX512_KNL) == ippCPUID_AVX512_KNL)
2039 ippTopFeatures = ippCPUID_AVX512_KNL;
2041 ippTopFeatures = ippCPUID_AVX512F; // Unknown AVX512 configuration
2045 if(ippFeatures&ippCPUID_AVX2)
2046 ippTopFeatures = ippCPUID_AVX2;
2047 else if(ippFeatures&ippCPUID_SSE42)
2048 ippTopFeatures = ippCPUID_SSE42;
2050 pIppLibInfo = ippiGetLibVersion();
2057 int ippStatus; // 0 - all is ok, -1 - IPP functions failed
2058 const char *funcname;
2059 const char *filename;
2063 Ipp64u ippTopFeatures;
2064 const IppLibraryVersion *pIppLibInfo;
2067 static IPPInitSingleton& getIPPSingleton()
2069 CV_SINGLETON_LAZY_INIT_REF(IPPInitSingleton, new IPPInitSingleton())
2073 #if OPENCV_ABI_COMPATIBILITY > 300
2074 unsigned long long getIppFeatures()
2076 int getIppFeatures()
2080 #if OPENCV_ABI_COMPATIBILITY > 300
2081 return getIPPSingleton().ippFeatures;
2083 return (int)getIPPSingleton().ippFeatures;
2090 unsigned long long getIppTopFeatures();
2092 unsigned long long getIppTopFeatures()
2095 return getIPPSingleton().ippTopFeatures;
2101 void setIppStatus(int status, const char * const _funcname, const char * const _filename, int _line)
2104 getIPPSingleton().ippStatus = status;
2105 getIPPSingleton().funcname = _funcname;
2106 getIPPSingleton().filename = _filename;
2107 getIPPSingleton().linen = _line;
2109 CV_UNUSED(status); CV_UNUSED(_funcname); CV_UNUSED(_filename); CV_UNUSED(_line);
2116 return getIPPSingleton().ippStatus;
2122 String getIppErrorLocation()
2125 return format("%s:%d %s", getIPPSingleton().filename ? getIPPSingleton().filename : "", getIPPSingleton().linen, getIPPSingleton().funcname ? getIPPSingleton().funcname : "");
2131 String getIppVersion()
2134 const IppLibraryVersion *pInfo = getIPPSingleton().pIppLibInfo;
2136 return format("%s %s %s", pInfo->Name, pInfo->Version, pInfo->BuildDate);
2138 return String("error");
2140 return String("disabled");
2147 CoreTLSData* data = getCoreTlsData().get();
2148 if(data->useIPP < 0)
2150 data->useIPP = getIPPSingleton().useIPP;
2152 return (data->useIPP > 0);
2158 void setUseIPP(bool flag)
2160 CoreTLSData* data = getCoreTlsData().get();
2162 data->useIPP = (getIPPSingleton().useIPP)?flag:false;
2165 data->useIPP = false;
2172 CoreTLSData* data = getCoreTlsData().get();
2173 if(data->useIPP_NE < 0)
2175 data->useIPP_NE = getIPPSingleton().useIPP_NE;
2177 return (data->useIPP_NE > 0);
2183 void setUseIPP_NE(bool flag)
2185 CoreTLSData* data = getCoreTlsData().get();
2187 data->useIPP_NE = (getIPPSingleton().useIPP_NE)?flag:false;
2190 data->useIPP_NE = false;
2198 #ifdef HAVE_TEGRA_OPTIMIZATION
2204 cv::CoreTLSData* data = cv::getCoreTlsData().get();
2206 if (data->useTegra < 0)
2208 const char* pTegraEnv = getenv("OPENCV_TEGRA");
2209 if (pTegraEnv && (cv::String(pTegraEnv) == "disabled"))
2210 data->useTegra = false;
2212 data->useTegra = true;
2215 return (data->useTegra > 0);
2218 void setUseTegra(bool flag)
2220 cv::CoreTLSData* data = cv::getCoreTlsData().get();
2221 data->useTegra = flag;
2224 } // namespace tegra