opencv_version: dump detected HW features
[platform/upstream/opencv.git] / modules / core / src / system.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
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.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
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.
17 //
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
20 //
21 //   * Redistribution's of source code must retain the above copyright notice,
22 //     this list of conditions and the following disclaimer.
23 //
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.
27 //
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.
30 //
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.
41 //
42 //M*/
43
44 #include "precomp.hpp"
45 #include <iostream>
46
47 #include <opencv2/core/utils/configuration.private.hpp>
48 #include <opencv2/core/utils/trace.private.hpp>
49
50 namespace cv {
51
52 static Mutex* __initialization_mutex = NULL;
53 Mutex& getInitializationMutex()
54 {
55     if (__initialization_mutex == NULL)
56         __initialization_mutex = new Mutex();
57     return *__initialization_mutex;
58 }
59 // force initialization (single-threaded environment)
60 Mutex* __initialization_mutex_initializer = &getInitializationMutex();
61
62 } // namespace cv
63
64 #ifdef _MSC_VER
65 # if _MSC_VER >= 1700
66 #  pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
67 # endif
68 #endif
69
70 #if defined __ANDROID__ || defined __linux__ || defined __FreeBSD__ || defined __HAIKU__
71 #  include <unistd.h>
72 #  include <fcntl.h>
73 #  include <elf.h>
74 #if defined __ANDROID__ || defined __linux__
75 #  include <linux/auxvec.h>
76 #endif
77 #endif
78
79 #if defined __ANDROID__ && defined HAVE_CPUFEATURES
80 #  include <cpu-features.h>
81 #endif
82
83 #ifndef __VSX__
84 # if defined __PPC64__ && defined __linux__
85 #   include "sys/auxv.h"
86 #   ifndef AT_HWCAP2
87 #     define AT_HWCAP2 26
88 #   endif
89 #   ifndef PPC_FEATURE2_ARCH_2_07
90 #     define PPC_FEATURE2_ARCH_2_07 0x80000000
91 #   endif
92 # endif
93 #endif
94
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
98 #endif
99 #include <windows.h>
100 #if (_WIN32_WINNT >= 0x0602)
101   #include <synchapi.h>
102 #endif
103 #undef small
104 #undef min
105 #undef max
106 #undef abs
107 #include <tchar.h>
108 #if defined _MSC_VER
109   #if _MSC_VER >= 1400
110     #include <intrin.h>
111   #elif defined _M_IX86
112     static void __cpuid(int* cpuid_data, int)
113     {
114         __asm
115         {
116             push ebx
117             push edi
118             mov edi, cpuid_data
119             mov eax, 1
120             cpuid
121             mov [edi], eax
122             mov [edi + 4], ebx
123             mov [edi + 8], ecx
124             mov [edi + 12], edx
125             pop edi
126             pop ebx
127         }
128     }
129     static void __cpuidex(int* cpuid_data, int, int)
130     {
131         __asm
132         {
133             push edi
134             mov edi, cpuid_data
135             mov eax, 7
136             mov ecx, 0
137             cpuid
138             mov [edi], eax
139             mov [edi + 4], ebx
140             mov [edi + 8], ecx
141             mov [edi + 12], edx
142             pop edi
143         }
144     }
145   #endif
146 #endif
147
148 #ifdef WINRT
149 #include <wrl/client.h>
150 #ifndef __cplusplus_winrt
151 #include <windows.storage.h>
152 #pragma comment(lib, "runtimeobject.lib")
153 #endif
154
155 std::wstring GetTempPathWinRT()
156 {
157 #ifdef __cplusplus_winrt
158     return std::wstring(Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data());
159 #else
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;
164     HSTRING str;
165     HSTRING_HEADER hstrHead;
166     std::wstring wstr;
167     if (FAILED(WindowsCreateStringReference(RuntimeClass_Windows_Storage_ApplicationData,
168                                             (UINT32)wcslen(RuntimeClass_Windows_Storage_ApplicationData), &hstrHead, &str)))
169         return wstr;
170     if (FAILED(RoGetActivationFactory(str, IID_PPV_ARGS(appdataFactory.ReleaseAndGetAddressOf()))))
171         return wstr;
172     if (FAILED(appdataFactory->get_Current(appdataRef.ReleaseAndGetAddressOf())))
173         return wstr;
174     if (FAILED(appdataRef->get_TemporaryFolder(storagefolderRef.ReleaseAndGetAddressOf())))
175         return wstr;
176     if (FAILED(storagefolderRef.As(&storageitemRef)))
177         return wstr;
178     str = NULL;
179     if (FAILED(storageitemRef->get_Path(&str)))
180         return wstr;
181     wstr = WindowsGetStringRawBuffer(str, NULL);
182     WindowsDeleteString(str);
183     return wstr;
184 #endif
185 }
186
187 std::wstring GetTempFileNameWinRT(std::wstring prefix)
188 {
189     wchar_t guidStr[40];
190     GUID g;
191     CoCreateGuid(&g);
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]));
197
198     return prefix.append(std::wstring(guidStr));
199 }
200
201 #endif
202 #else
203 #include <pthread.h>
204 #include <sys/time.h>
205 #include <time.h>
206
207 #if defined __MACH__ && defined __APPLE__
208 #include <mach/mach.h>
209 #include <mach/mach_time.h>
210 #endif
211
212 #endif
213
214 #ifdef _OPENMP
215 #include "omp.h"
216 #endif
217
218 #if defined __linux__ || defined __APPLE__ || defined __EMSCRIPTEN__ || defined __FreeBSD__ || defined __GLIBC__ || defined __HAIKU__
219 #include <unistd.h>
220 #include <stdio.h>
221 #include <sys/types.h>
222 #if defined __ANDROID__
223 #include <sys/sysconf.h>
224 #endif
225 #endif
226
227 #ifdef __ANDROID__
228 # include <android/log.h>
229 #endif
230
231 namespace cv
232 {
233
234 Exception::Exception() { code = 0; line = 0; }
235
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)
238 {
239     formatMessage();
240 }
241
242 Exception::~Exception() throw() {}
243
244 /*!
245  \return the error description and the context as a text string.
246  */
247 const char* Exception::what() const throw() { return msg.c_str(); }
248
249 void Exception::formatMessage()
250 {
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());
253     else
254         msg = format("%s:%d: error: (%d) %s\n", file.c_str(), line, code, err.c_str());
255 }
256
257 static const char* g_hwFeatureNames[CV_HARDWARE_MAX_FEATURE] = { NULL };
258
259 static const char* getHWFeatureName(int id)
260 {
261     return (id < CV_HARDWARE_MAX_FEATURE) ? g_hwFeatureNames[id] : NULL;
262 }
263 static const char* getHWFeatureNameSafe(int id)
264 {
265     const char* name = getHWFeatureName(id);
266     return name ? name : "Unknown feature";
267 }
268
269 struct HWFeatures
270 {
271     enum { MAX_FEATURE = CV_HARDWARE_MAX_FEATURE };
272
273     HWFeatures(bool run_initialize = false)
274     {
275         memset( have, 0, sizeof(have[0]) * MAX_FEATURE );
276         if (run_initialize)
277             initialize();
278     }
279
280     static void initializeNames()
281     {
282         for (int i = 0; i < CV_HARDWARE_MAX_FEATURE; i++)
283         {
284             g_hwFeatureNames[i] = 0;
285         }
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";
298
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";
308
309         g_hwFeatureNames[CPU_NEON] = "NEON";
310
311         g_hwFeatureNames[CPU_VSX] = "VSX";
312
313         g_hwFeatureNames[CPU_AVX512_SKX] = "AVX512-SKX";
314     }
315
316     void initialize(void)
317     {
318 #ifndef WINRT
319         if (getenv("OPENCV_DUMP_CONFIG"))
320         {
321             fprintf(stderr, "\nOpenCV build configuration is:\n%s\n",
322                 cv::getBuildInformation().c_str());
323         }
324 #endif
325
326         initializeNames();
327
328         int cpuid_data[4] = { 0, 0, 0, 0 };
329         int cpuid_data_ex[4] = { 0, 0, 0, 0 };
330
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
336         #ifdef __x86_64__
337         asm __volatile__
338         (
339          "movl $1, %%eax\n\t"
340          "cpuid\n\t"
341          :[eax]"=a"(cpuid_data[0]),[ebx]"=b"(cpuid_data[1]),[ecx]"=c"(cpuid_data[2]),[edx]"=d"(cpuid_data[3])
342          :
343          : "cc"
344         );
345         #else
346         asm volatile
347         (
348          "pushl %%ebx\n\t"
349          "movl $1,%%eax\n\t"
350          "cpuid\n\t"
351          "popl %%ebx\n\t"
352          : "=a"(cpuid_data[0]), "=c"(cpuid_data[2]), "=d"(cpuid_data[3])
353          :
354          : "cc"
355         );
356         #endif
357     #endif
358
359     #ifdef OPENCV_HAVE_X86_CPUID
360         int x86_family = (cpuid_data[0] >> 8) & 15;
361         if( x86_family >= 6 )
362         {
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;
374
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
382             #ifdef __x86_64__
383             asm __volatile__
384             (
385              "movl $7, %%eax\n\t"
386              "movl $0, %%ecx\n\t"
387              "cpuid\n\t"
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])
389              :
390              : "cc"
391             );
392             #else
393             asm volatile
394             (
395              "pushl %%ebx\n\t"
396              "movl $7,%%eax\n\t"
397              "movl $0,%%ecx\n\t"
398              "cpuid\n\t"
399              "movl %%ebx, %0\n\t"
400              "popl %%ebx\n\t"
401              : "=r"(cpuid_data_ex[1]), "=c"(cpuid_data_ex[2])
402              :
403              : "cc"
404             );
405             #endif
406         #endif
407
408         #ifdef OPENCV_HAVE_X86_CPUID_EX
409             have[CV_CPU_AVX2]   = (cpuid_data_ex[1] & (1<<5)) != 0;
410
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;
420         #else
421             CV_UNUSED(cpuid_data_ex);
422         #endif
423
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
428             else
429             {
430                 int xcr0 = 0;
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" );
435             #endif
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
440             }
441
442             if (!have_AVX_OS_support)
443             {
444                 have[CV_CPU_AVX] = false;
445                 have[CV_CPU_FP16] = false;
446                 have[CV_CPU_AVX2] = false;
447                 have[CV_CPU_FMA3] = false;
448             }
449             if (!have_AVX_OS_support || !have_AVX512_OS_support)
450             {
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;
460             }
461
462             if (have[CV_CPU_AVX_512F])
463             {
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];
465             }
466         }
467     #else
468         CV_UNUSED(cpuid_data);
469         CV_UNUSED(cpuid_data_ex);
470     #endif // OPENCV_HAVE_X86_CPUID
471
472     #if defined __ANDROID__ || defined __linux__
473     #ifdef __aarch64__
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;
483       #else
484         __android_log_print(ANDROID_LOG_INFO, "OpenCV", "cpufeatures library is not avaialble for CPU detection");
485         #if CV_NEON
486         __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- NEON instructions is enabled via build flags");
487         have[CV_CPU_NEON] = true;
488         #else
489         __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- NEON instructions is NOT enabled via build flags");
490         #endif
491         #if CV_FP16
492         __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- FP16 instructions is enabled via build flags");
493         have[CV_CPU_FP16] = true;
494         #else
495         __android_log_print(ANDROID_LOG_INFO, "OpenCV", "- FP16 instructions is NOT enabled via build flags");
496         #endif
497       #endif
498     #elif defined __arm__
499         int cpufile = open("/proc/self/auxv", O_RDONLY);
500
501         if (cpufile >= 0)
502         {
503             Elf32_auxv_t auxv;
504             const size_t size_auxv_t = sizeof(auxv);
505
506             while ((size_t)read(cpufile, &auxv, size_auxv_t) == size_auxv_t)
507             {
508                 if (auxv.a_type == AT_HWCAP)
509                 {
510                     have[CV_CPU_NEON] = (auxv.a_un.a_val & 4096) != 0;
511                     have[CV_CPU_FP16] = (auxv.a_un.a_val & 2) != 0;
512                     break;
513                 }
514             }
515
516             close(cpufile);
517         }
518     #endif
519     #elif (defined __clang__ || defined __APPLE__)
520     #if (defined __ARM_NEON__ || (defined __ARM_NEON && defined __aarch64__))
521         have[CV_CPU_NEON] = true;
522     #endif
523     #if (defined __ARM_FP  && (((__ARM_FP & 0x2) != 0) && defined __ARM_NEON__))
524         have[CV_CPU_FP16] = true;
525     #endif
526     #endif
527
528     #ifdef __VSX__
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);
534     #else
535         have[CV_CPU_VSX] = false;
536     #endif
537
538         int baseline_features[] = { CV_CPU_BASELINE_FEATURES };
539         if (!checkFeatures(baseline_features, sizeof(baseline_features) / sizeof(baseline_features[0])))
540         {
541             fprintf(stderr, "\n"
542                     "******************************************************************\n"
543                     "* FATAL ERROR:                                                   *\n"
544                     "* This OpenCV build doesn't support current CPU/HW configuration *\n"
545                     "*                                                                *\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.");
551         }
552
553         readSettings(baseline_features, sizeof(baseline_features) / sizeof(baseline_features[0]));
554     }
555
556     bool checkFeatures(const int* features, int count, bool dump = false)
557     {
558         bool result = true;
559         for (int i = 0; i < count; i++)
560         {
561             int feature = features[i];
562             if (feature)
563             {
564                 if (have[feature])
565                 {
566                     if (dump) fprintf(stderr, "%s - OK\n", getHWFeatureNameSafe(feature));
567                 }
568                 else
569                 {
570                     result = false;
571                     if (dump) fprintf(stderr, "%s - NOT AVAILABLE\n", getHWFeatureNameSafe(feature));
572                 }
573             }
574         }
575         return result;
576     }
577
578     static inline bool isSymbolSeparator(char c)
579     {
580         return c == ',' || c == ';' || c == '-';
581     }
582
583     void readSettings(const int* baseline_features, int baseline_count)
584     {
585         bool dump = true;
586         const char* disabled_features =
587 #ifndef WINRT
588                 getenv("OPENCV_CPU_DISABLE");
589 #else
590                 NULL;
591 #endif
592         if (disabled_features && disabled_features[0] != 0)
593         {
594             const char* start = disabled_features;
595             for (;;)
596             {
597                 while (start[0] != 0 && isSymbolSeparator(start[0]))
598                 {
599                     start++;
600                 }
601                 if (start[0] == 0)
602                     break;
603                 const char* end = start;
604                 while (end[0] != 0 && !isSymbolSeparator(end[0]))
605                 {
606                     end++;
607                 }
608                 if (end == start)
609                     continue;
610                 cv::String feature(start, end);
611                 start = end;
612
613                 CV_Assert(feature.size() > 0);
614
615                 bool found = false;
616                 for (int i = 0; i < CV_HARDWARE_MAX_FEATURE; i++)
617                 {
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)
622                     {
623                         bool isBaseline = false;
624                         for (int k = 0; k < baseline_count; k++)
625                         {
626                             if (baseline_features[k] == i)
627                             {
628                                 isBaseline = true;
629                                 break;
630                             }
631                         }
632                         if (isBaseline)
633                         {
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));
635                         }
636                         if (!have[i])
637                         {
638                             if (dump) fprintf(stderr, "OPENCV: Trying to disable unavailable CPU feature on the current platform: '%s'.\n", getHWFeatureNameSafe(i));
639                         }
640                         have[i] = false;
641
642                         found = true;
643                         break;
644                     }
645                 }
646                 if (!found)
647                 {
648                     if (dump) fprintf(stderr, "OPENCV: Trying to disable unknown CPU feature: '%s'.\n", feature.c_str());
649                 }
650             }
651         }
652     }
653
654     bool have[MAX_FEATURE+1];
655 };
656
657 static HWFeatures  featuresEnabled(true), featuresDisabled = HWFeatures(false);
658 static HWFeatures* currentFeatures = &featuresEnabled;
659
660 bool checkHardwareSupport(int feature)
661 {
662     CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
663     return currentFeatures->have[feature];
664 }
665
666 String getHardwareFeatureName(int feature)
667 {
668     const char* name = getHWFeatureName(feature);
669     return name ? String(name) : String();
670 }
671
672 volatile bool useOptimizedFlag = true;
673
674 void setUseOptimized( bool flag )
675 {
676     useOptimizedFlag = flag;
677     currentFeatures = flag ? &featuresEnabled : &featuresDisabled;
678
679     ipp::setUseIPP(flag);
680 #ifdef HAVE_OPENCL
681     ocl::setUseOpenCL(flag);
682 #endif
683 #ifdef HAVE_TEGRA_OPTIMIZATION
684     ::tegra::setUseTegra(flag);
685 #endif
686 }
687
688 bool useOptimized(void)
689 {
690     return useOptimizedFlag;
691 }
692
693 int64 getTickCount(void)
694 {
695 #if defined _WIN32 || defined WINCE
696     LARGE_INTEGER counter;
697     QueryPerformanceCounter( &counter );
698     return (int64)counter.QuadPart;
699 #elif defined __linux || defined __linux__
700     struct timespec tp;
701     clock_gettime(CLOCK_MONOTONIC, &tp);
702     return (int64)tp.tv_sec*1000000000 + tp.tv_nsec;
703 #elif defined __MACH__ && defined __APPLE__
704     return (int64)mach_absolute_time();
705 #else
706     struct timeval tv;
707     struct timezone tz;
708     gettimeofday( &tv, &tz );
709     return (int64)tv.tv_sec*1000000 + tv.tv_usec;
710 #endif
711 }
712
713 double getTickFrequency(void)
714 {
715 #if defined _WIN32 || defined WINCE
716     LARGE_INTEGER freq;
717     QueryPerformanceFrequency(&freq);
718     return (double)freq.QuadPart;
719 #elif defined __linux || defined __linux__
720     return 1e9;
721 #elif defined __MACH__ && defined __APPLE__
722     static double freq = 0;
723     if( freq == 0 )
724     {
725         mach_timebase_info_data_t sTimebaseInfo;
726         mach_timebase_info(&sTimebaseInfo);
727         freq = sTimebaseInfo.denom*1e9/sTimebaseInfo.numer;
728     }
729     return freq;
730 #else
731     return 1e6;
732 #endif
733 }
734
735 #if defined __GNUC__ && (defined __i386__ || defined __x86_64__ || defined __ppc__)
736 #if defined(__i386__)
737
738 int64 getCPUTickCount(void)
739 {
740     int64 x;
741     __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
742     return x;
743 }
744 #elif defined(__x86_64__)
745
746 int64 getCPUTickCount(void)
747 {
748     unsigned hi, lo;
749     __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
750     return (int64)lo | ((int64)hi << 32);
751 }
752
753 #elif defined(__ppc__)
754
755 int64 getCPUTickCount(void)
756 {
757     int64 result = 0;
758     unsigned upper, lower, tmp;
759     __asm__ volatile(
760                      "0:                  \n"
761                      "\tmftbu   %0           \n"
762                      "\tmftb    %1           \n"
763                      "\tmftbu   %2           \n"
764                      "\tcmpw    %2,%0        \n"
765                      "\tbne     0b         \n"
766                      : "=r"(upper),"=r"(lower),"=r"(tmp)
767                      );
768     return lower | ((int64)upper << 32);
769 }
770
771 #else
772
773 #error "RDTSC not defined"
774
775 #endif
776
777 #elif defined _MSC_VER && defined _WIN32 && defined _M_IX86
778
779 int64 getCPUTickCount(void)
780 {
781     __asm _emit 0x0f;
782     __asm _emit 0x31;
783 }
784
785 #else
786
787 //#ifdef HAVE_IPP
788 //int64 getCPUTickCount(void)
789 //{
790 //    return ippGetCpuClocks();
791 //}
792 //#else
793 int64 getCPUTickCount(void)
794 {
795     return getTickCount();
796 }
797 //#endif
798
799 #endif
800
801 const String& getBuildInformation()
802 {
803     static String build_info =
804 #include "version_string.inc"
805     ;
806     return build_info;
807 }
808
809 String format( const char* fmt, ... )
810 {
811     AutoBuffer<char, 1024> buf;
812
813     for ( ; ; )
814     {
815         va_list va;
816         va_start(va, fmt);
817         int bsize = static_cast<int>(buf.size());
818         int len = cv_vsnprintf((char *)buf, bsize, fmt, va);
819         va_end(va);
820
821         CV_Assert(len >= 0 && "Check format string for errors");
822         if (len >= bsize)
823         {
824             buf.resize(len + 1);
825             continue;
826         }
827         buf[bsize - 1] = 0;
828         return String((char *)buf, len);
829     }
830 }
831
832 String tempfile( const char* suffix )
833 {
834     String fname;
835 #ifndef WINRT
836     const char *temp_dir = getenv("OPENCV_TEMP_PATH");
837 #endif
838
839 #if defined _WIN32
840 #ifdef WINRT
841     RoInitialize(RO_INIT_MULTITHREADED);
842     std::wstring temp_dir = GetTempPathWinRT();
843
844     std::wstring temp_file = GetTempFileNameWinRT(L"ocv");
845     if (temp_file.empty())
846         return String();
847
848     temp_file = temp_dir.append(std::wstring(L"\\")).append(temp_file);
849     DeleteFileW(temp_file.c_str());
850
851     char aname[MAX_PATH];
852     size_t copied = wcstombs(aname, temp_file.c_str(), MAX_PATH);
853     CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
854     fname = String(aname);
855     RoUninitialize();
856 #else
857     char temp_dir2[MAX_PATH] = { 0 };
858     char temp_file[MAX_PATH] = { 0 };
859
860     if (temp_dir == 0 || temp_dir[0] == 0)
861     {
862         ::GetTempPathA(sizeof(temp_dir2), temp_dir2);
863         temp_dir = temp_dir2;
864     }
865     if(0 == ::GetTempFileNameA(temp_dir, "ocv", 0, temp_file))
866         return String();
867
868     DeleteFileA(temp_file);
869
870     fname = temp_file;
871 #endif
872 # else
873 #  ifdef __ANDROID__
874     //char defaultTemplate[] = "/mnt/sdcard/__opencv_temp.XXXXXX";
875     char defaultTemplate[] = "/data/local/tmp/__opencv_temp.XXXXXX";
876 #  else
877     char defaultTemplate[] = "/tmp/__opencv_temp.XXXXXX";
878 #  endif
879
880     if (temp_dir == 0 || temp_dir[0] == 0)
881         fname = defaultTemplate;
882     else
883     {
884         fname = temp_dir;
885         char ech = fname[fname.size() - 1];
886         if(ech != '/' && ech != '\\')
887             fname = fname + "/";
888         fname = fname + "__opencv_temp.XXXXXX";
889     }
890
891     const int fd = mkstemp((char*)fname.c_str());
892     if (fd == -1) return String();
893
894     close(fd);
895     remove(fname.c_str());
896 # endif
897
898     if (suffix)
899     {
900         if (suffix[0] != '.')
901             return fname + "." + suffix;
902         else
903             return fname + suffix;
904     }
905     return fname;
906 }
907
908 static ErrorCallback customErrorCallback = 0;
909 static void* customErrorCallbackData = 0;
910 static bool breakOnError = false;
911
912 bool setBreakOnError(bool value)
913 {
914     bool prevVal = breakOnError;
915     breakOnError = value;
916     return prevVal;
917 }
918
919 int cv_snprintf(char* buf, int len, const char* fmt, ...)
920 {
921     va_list va;
922     va_start(va, fmt);
923     int res = cv_vsnprintf(buf, len, fmt, va);
924     va_end(va);
925     return res;
926 }
927
928 int cv_vsnprintf(char* buf, int len, const char* fmt, va_list args)
929 {
930 #if defined _MSC_VER
931     if (len <= 0) return len == 0 ? 1024 : -1;
932     int res = _vsnprintf_s(buf, len, _TRUNCATE, fmt, args);
933     // ensure null terminating on VS
934     if (res >= 0 && res < len)
935     {
936         buf[res] = 0;
937         return res;
938     }
939     else
940     {
941         buf[len - 1] = 0; // truncate happened
942         return res >= len ? res : (len * 2);
943     }
944 #else
945     return vsnprintf(buf, len, fmt, args);
946 #endif
947 }
948
949 void error( const Exception& exc )
950 {
951     if (customErrorCallback != 0)
952         customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(),
953                             exc.file.c_str(), exc.line, customErrorCallbackData);
954     else
955     {
956         const char* errorStr = cvErrorStr(exc.code);
957         char buf[1 << 12];
958
959         cv_snprintf(buf, sizeof(buf),
960             "OpenCV Error: %s (%s) in %s, file %s, line %d",
961             errorStr, exc.err.c_str(), exc.func.size() > 0 ?
962             exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line);
963         fprintf( stderr, "%s\n", buf );
964         fflush( stderr );
965 #  ifdef __ANDROID__
966         __android_log_print(ANDROID_LOG_ERROR, "cv::error()", "%s", buf);
967 #  endif
968     }
969
970     if(breakOnError)
971     {
972         static volatile int* p = 0;
973         *p = 0;
974     }
975
976     CV_THROW(exc);
977 }
978
979 void error(int _code, const String& _err, const char* _func, const char* _file, int _line)
980 {
981     error(cv::Exception(_code, _err, _func, _file, _line));
982 }
983
984
985 ErrorCallback
986 redirectError( ErrorCallback errCallback, void* userdata, void** prevUserdata)
987 {
988     if( prevUserdata )
989         *prevUserdata = customErrorCallbackData;
990
991     ErrorCallback prevCallback = customErrorCallback;
992
993     customErrorCallback     = errCallback;
994     customErrorCallbackData = userdata;
995
996     return prevCallback;
997 }
998
999 }
1000
1001 CV_IMPL int cvCheckHardwareSupport(int feature)
1002 {
1003     CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
1004     return cv::currentFeatures->have[feature];
1005 }
1006
1007 CV_IMPL int cvUseOptimized( int flag )
1008 {
1009     int prevMode = cv::useOptimizedFlag;
1010     cv::setUseOptimized( flag != 0 );
1011     return prevMode;
1012 }
1013
1014 CV_IMPL int64  cvGetTickCount(void)
1015 {
1016     return cv::getTickCount();
1017 }
1018
1019 CV_IMPL double cvGetTickFrequency(void)
1020 {
1021     return cv::getTickFrequency()*1e-6;
1022 }
1023
1024 CV_IMPL CvErrorCallback
1025 cvRedirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata)
1026 {
1027     return cv::redirectError(errCallback, userdata, prevUserdata);
1028 }
1029
1030 CV_IMPL int cvNulDevReport( int, const char*, const char*,
1031                             const char*, int, void* )
1032 {
1033     return 0;
1034 }
1035
1036 CV_IMPL int cvStdErrReport( int, const char*, const char*,
1037                             const char*, int, void* )
1038 {
1039     return 0;
1040 }
1041
1042 CV_IMPL int cvGuiBoxReport( int, const char*, const char*,
1043                             const char*, int, void* )
1044 {
1045     return 0;
1046 }
1047
1048 CV_IMPL int cvGetErrInfo( const char**, const char**, const char**, int* )
1049 {
1050     return 0;
1051 }
1052
1053
1054 CV_IMPL const char* cvErrorStr( int status )
1055 {
1056     static char buf[256];
1057
1058     switch (status)
1059     {
1060     case CV_StsOk :                  return "No Error";
1061     case CV_StsBackTrace :           return "Backtrace";
1062     case CV_StsError :               return "Unspecified error";
1063     case CV_StsInternal :            return "Internal error";
1064     case CV_StsNoMem :               return "Insufficient memory";
1065     case CV_StsBadArg :              return "Bad argument";
1066     case CV_StsNoConv :              return "Iterations do not converge";
1067     case CV_StsAutoTrace :           return "Autotrace call";
1068     case CV_StsBadSize :             return "Incorrect size of input array";
1069     case CV_StsNullPtr :             return "Null pointer";
1070     case CV_StsDivByZero :           return "Division by zero occurred";
1071     case CV_BadStep :                return "Image step is wrong";
1072     case CV_StsInplaceNotSupported : return "Inplace operation is not supported";
1073     case CV_StsObjectNotFound :      return "Requested object was not found";
1074     case CV_BadDepth :               return "Input image depth is not supported by function";
1075     case CV_StsUnmatchedFormats :    return "Formats of input arguments do not match";
1076     case CV_StsUnmatchedSizes :      return "Sizes of input arguments do not match";
1077     case CV_StsOutOfRange :          return "One of arguments\' values is out of range";
1078     case CV_StsUnsupportedFormat :   return "Unsupported format or combination of formats";
1079     case CV_BadCOI :                 return "Input COI is not supported";
1080     case CV_BadNumChannels :         return "Bad number of channels";
1081     case CV_StsBadFlag :             return "Bad flag (parameter or structure field)";
1082     case CV_StsBadPoint :            return "Bad parameter of type CvPoint";
1083     case CV_StsBadMask :             return "Bad type of mask argument";
1084     case CV_StsParseError :          return "Parsing error";
1085     case CV_StsNotImplemented :      return "The function/feature is not implemented";
1086     case CV_StsBadMemBlock :         return "Memory block has been corrupted";
1087     case CV_StsAssert :              return "Assertion failed";
1088     case CV_GpuNotSupported :        return "No CUDA support";
1089     case CV_GpuApiCallError :        return "Gpu API call";
1090     case CV_OpenGlNotSupported :     return "No OpenGL support";
1091     case CV_OpenGlApiCallError :     return "OpenGL API call";
1092     };
1093
1094     sprintf(buf, "Unknown %s code %d", status >= 0 ? "status":"error", status);
1095     return buf;
1096 }
1097
1098 CV_IMPL int cvGetErrMode(void)
1099 {
1100     return 0;
1101 }
1102
1103 CV_IMPL int cvSetErrMode(int)
1104 {
1105     return 0;
1106 }
1107
1108 CV_IMPL int cvGetErrStatus(void)
1109 {
1110     return 0;
1111 }
1112
1113 CV_IMPL void cvSetErrStatus(int)
1114 {
1115 }
1116
1117
1118 CV_IMPL void cvError( int code, const char* func_name,
1119                       const char* err_msg,
1120                       const char* file_name, int line )
1121 {
1122     cv::error(cv::Exception(code, err_msg, func_name, file_name, line));
1123 }
1124
1125 /* function, which converts int to int */
1126 CV_IMPL int
1127 cvErrorFromIppStatus( int status )
1128 {
1129     switch (status)
1130     {
1131     case CV_BADSIZE_ERR:               return CV_StsBadSize;
1132     case CV_BADMEMBLOCK_ERR:           return CV_StsBadMemBlock;
1133     case CV_NULLPTR_ERR:               return CV_StsNullPtr;
1134     case CV_DIV_BY_ZERO_ERR:           return CV_StsDivByZero;
1135     case CV_BADSTEP_ERR:               return CV_BadStep;
1136     case CV_OUTOFMEM_ERR:              return CV_StsNoMem;
1137     case CV_BADARG_ERR:                return CV_StsBadArg;
1138     case CV_NOTDEFINED_ERR:            return CV_StsError;
1139     case CV_INPLACE_NOT_SUPPORTED_ERR: return CV_StsInplaceNotSupported;
1140     case CV_NOTFOUND_ERR:              return CV_StsObjectNotFound;
1141     case CV_BADCONVERGENCE_ERR:        return CV_StsNoConv;
1142     case CV_BADDEPTH_ERR:              return CV_BadDepth;
1143     case CV_UNMATCHED_FORMATS_ERR:     return CV_StsUnmatchedFormats;
1144     case CV_UNSUPPORTED_COI_ERR:       return CV_BadCOI;
1145     case CV_UNSUPPORTED_CHANNELS_ERR:  return CV_BadNumChannels;
1146     case CV_BADFLAG_ERR:               return CV_StsBadFlag;
1147     case CV_BADRANGE_ERR:              return CV_StsBadArg;
1148     case CV_BADCOEF_ERR:               return CV_StsBadArg;
1149     case CV_BADFACTOR_ERR:             return CV_StsBadArg;
1150     case CV_BADPOINT_ERR:              return CV_StsBadPoint;
1151
1152     default:
1153       return CV_StsError;
1154     }
1155 }
1156
1157 namespace cv {
1158 bool __termination = false;
1159 }
1160
1161 namespace cv
1162 {
1163
1164 #if defined _WIN32 || defined WINCE
1165
1166 struct Mutex::Impl
1167 {
1168     Impl()
1169     {
1170 #if (_WIN32_WINNT >= 0x0600)
1171         ::InitializeCriticalSectionEx(&cs, 1000, 0);
1172 #else
1173         ::InitializeCriticalSection(&cs);
1174 #endif
1175         refcount = 1;
1176     }
1177     ~Impl() { DeleteCriticalSection(&cs); }
1178
1179     void lock() { EnterCriticalSection(&cs); }
1180     bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
1181     void unlock() { LeaveCriticalSection(&cs); }
1182
1183     CRITICAL_SECTION cs;
1184     int refcount;
1185 };
1186
1187 #else
1188
1189 struct Mutex::Impl
1190 {
1191     Impl()
1192     {
1193         pthread_mutexattr_t attr;
1194         pthread_mutexattr_init(&attr);
1195         pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
1196         pthread_mutex_init(&mt, &attr);
1197         pthread_mutexattr_destroy(&attr);
1198
1199         refcount = 1;
1200     }
1201     ~Impl() { pthread_mutex_destroy(&mt); }
1202
1203     void lock() { pthread_mutex_lock(&mt); }
1204     bool trylock() { return pthread_mutex_trylock(&mt) == 0; }
1205     void unlock() { pthread_mutex_unlock(&mt); }
1206
1207     pthread_mutex_t mt;
1208     int refcount;
1209 };
1210
1211 #endif
1212
1213 Mutex::Mutex()
1214 {
1215     impl = new Mutex::Impl;
1216 }
1217
1218 Mutex::~Mutex()
1219 {
1220     if( CV_XADD(&impl->refcount, -1) == 1 )
1221         delete impl;
1222     impl = 0;
1223 }
1224
1225 Mutex::Mutex(const Mutex& m)
1226 {
1227     impl = m.impl;
1228     CV_XADD(&impl->refcount, 1);
1229 }
1230
1231 Mutex& Mutex::operator = (const Mutex& m)
1232 {
1233     if (this != &m)
1234     {
1235         CV_XADD(&m.impl->refcount, 1);
1236         if( CV_XADD(&impl->refcount, -1) == 1 )
1237             delete impl;
1238         impl = m.impl;
1239     }
1240     return *this;
1241 }
1242
1243 void Mutex::lock() { impl->lock(); }
1244 void Mutex::unlock() { impl->unlock(); }
1245 bool Mutex::trylock() { return impl->trylock(); }
1246
1247
1248 //////////////////////////////// thread-local storage ////////////////////////////////
1249
1250 #ifdef _WIN32
1251 #ifdef _MSC_VER
1252 #pragma warning(disable:4505) // unreferenced local function has been removed
1253 #endif
1254 #ifndef TLS_OUT_OF_INDEXES
1255 #define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF)
1256 #endif
1257 #endif
1258
1259 // TLS platform abstraction layer
1260 class TlsAbstraction
1261 {
1262 public:
1263     TlsAbstraction();
1264     ~TlsAbstraction();
1265     void* GetData() const;
1266     void  SetData(void *pData);
1267
1268 private:
1269 #ifdef _WIN32
1270 #ifndef WINRT
1271     DWORD tlsKey;
1272 #endif
1273 #else // _WIN32
1274     pthread_key_t  tlsKey;
1275 #endif
1276 };
1277
1278 #ifdef _WIN32
1279 #ifdef WINRT
1280 static __declspec( thread ) void* tlsData = NULL; // using C++11 thread attribute for local thread data
1281 TlsAbstraction::TlsAbstraction() {}
1282 TlsAbstraction::~TlsAbstraction() {}
1283 void* TlsAbstraction::GetData() const
1284 {
1285     return tlsData;
1286 }
1287 void  TlsAbstraction::SetData(void *pData)
1288 {
1289     tlsData = pData;
1290 }
1291 #else //WINRT
1292 TlsAbstraction::TlsAbstraction()
1293 {
1294     tlsKey = TlsAlloc();
1295     CV_Assert(tlsKey != TLS_OUT_OF_INDEXES);
1296 }
1297 TlsAbstraction::~TlsAbstraction()
1298 {
1299     TlsFree(tlsKey);
1300 }
1301 void* TlsAbstraction::GetData() const
1302 {
1303     return TlsGetValue(tlsKey);
1304 }
1305 void  TlsAbstraction::SetData(void *pData)
1306 {
1307     CV_Assert(TlsSetValue(tlsKey, pData) == TRUE);
1308 }
1309 #endif
1310 #else // _WIN32
1311 TlsAbstraction::TlsAbstraction()
1312 {
1313     CV_Assert(pthread_key_create(&tlsKey, NULL) == 0);
1314 }
1315 TlsAbstraction::~TlsAbstraction()
1316 {
1317     CV_Assert(pthread_key_delete(tlsKey) == 0);
1318 }
1319 void* TlsAbstraction::GetData() const
1320 {
1321     return pthread_getspecific(tlsKey);
1322 }
1323 void  TlsAbstraction::SetData(void *pData)
1324 {
1325     CV_Assert(pthread_setspecific(tlsKey, pData) == 0);
1326 }
1327 #endif
1328
1329 // Per-thread data structure
1330 struct ThreadData
1331 {
1332     ThreadData()
1333     {
1334         idx = 0;
1335         slots.reserve(32);
1336     }
1337
1338     std::vector<void*> slots; // Data array for a thread
1339     size_t idx;               // Thread index in TLS storage. This is not OS thread ID!
1340 };
1341
1342 // Main TLS storage class
1343 class TlsStorage
1344 {
1345 public:
1346     TlsStorage() :
1347         tlsSlotsSize(0)
1348     {
1349         tlsSlots.reserve(32);
1350         threads.reserve(32);
1351     }
1352     ~TlsStorage()
1353     {
1354         for(size_t i = 0; i < threads.size(); i++)
1355         {
1356             if(threads[i])
1357             {
1358                 /* Current architecture doesn't allow proper global objects release, so this check can cause crashes
1359
1360                 // Check if all slots were properly cleared
1361                 for(size_t j = 0; j < threads[i]->slots.size(); j++)
1362                 {
1363                     CV_Assert(threads[i]->slots[j] == 0);
1364                 }
1365                 */
1366                 delete threads[i];
1367             }
1368         }
1369         threads.clear();
1370     }
1371
1372     void releaseThread()
1373     {
1374         AutoLock guard(mtxGlobalAccess);
1375         ThreadData *pTD = (ThreadData*)tls.GetData();
1376         for(size_t i = 0; i < threads.size(); i++)
1377         {
1378             if(pTD == threads[i])
1379             {
1380                 threads[i] = 0;
1381                 break;
1382             }
1383         }
1384         tls.SetData(0);
1385         delete pTD;
1386     }
1387
1388     // Reserve TLS storage index
1389     size_t reserveSlot()
1390     {
1391         AutoLock guard(mtxGlobalAccess);
1392         CV_Assert(tlsSlotsSize == tlsSlots.size());
1393
1394         // Find unused slots
1395         for(size_t slot = 0; slot < tlsSlotsSize; slot++)
1396         {
1397             if(!tlsSlots[slot])
1398             {
1399                 tlsSlots[slot] = 1;
1400                 return slot;
1401             }
1402         }
1403
1404         // Create new slot
1405         tlsSlots.push_back(1); tlsSlotsSize++;
1406         return tlsSlotsSize - 1;
1407     }
1408
1409     // Release TLS storage index and pass associated data to caller
1410     void releaseSlot(size_t slotIdx, std::vector<void*> &dataVec, bool keepSlot = false)
1411     {
1412         AutoLock guard(mtxGlobalAccess);
1413         CV_Assert(tlsSlotsSize == tlsSlots.size());
1414         CV_Assert(tlsSlotsSize > slotIdx);
1415
1416         for(size_t i = 0; i < threads.size(); i++)
1417         {
1418             if(threads[i])
1419             {
1420                 std::vector<void*>& thread_slots = threads[i]->slots;
1421                 if (thread_slots.size() > slotIdx && thread_slots[slotIdx])
1422                 {
1423                     dataVec.push_back(thread_slots[slotIdx]);
1424                     thread_slots[slotIdx] = NULL;
1425                 }
1426             }
1427         }
1428
1429         if (!keepSlot)
1430             tlsSlots[slotIdx] = 0;
1431     }
1432
1433     // Get data by TLS storage index
1434     void* getData(size_t slotIdx) const
1435     {
1436 #ifndef CV_THREAD_SANITIZER
1437         CV_Assert(tlsSlotsSize > slotIdx);
1438 #endif
1439
1440         ThreadData* threadData = (ThreadData*)tls.GetData();
1441         if(threadData && threadData->slots.size() > slotIdx)
1442             return threadData->slots[slotIdx];
1443
1444         return NULL;
1445     }
1446
1447     // Gather data from threads by TLS storage index
1448     void gather(size_t slotIdx, std::vector<void*> &dataVec)
1449     {
1450         AutoLock guard(mtxGlobalAccess);
1451         CV_Assert(tlsSlotsSize == tlsSlots.size());
1452         CV_Assert(tlsSlotsSize > slotIdx);
1453
1454         for(size_t i = 0; i < threads.size(); i++)
1455         {
1456             if(threads[i])
1457             {
1458                 std::vector<void*>& thread_slots = threads[i]->slots;
1459                 if (thread_slots.size() > slotIdx && thread_slots[slotIdx])
1460                     dataVec.push_back(thread_slots[slotIdx]);
1461             }
1462         }
1463     }
1464
1465     // Set data to storage index
1466     void setData(size_t slotIdx, void* pData)
1467     {
1468 #ifndef CV_THREAD_SANITIZER
1469         CV_Assert(tlsSlotsSize > slotIdx);
1470 #endif
1471
1472         ThreadData* threadData = (ThreadData*)tls.GetData();
1473         if(!threadData)
1474         {
1475             threadData = new ThreadData;
1476             tls.SetData((void*)threadData);
1477             {
1478                 AutoLock guard(mtxGlobalAccess);
1479                 threadData->idx = threads.size();
1480                 threads.push_back(threadData);
1481             }
1482         }
1483
1484         if(slotIdx >= threadData->slots.size())
1485         {
1486             AutoLock guard(mtxGlobalAccess); // keep synchronization with gather() calls
1487             threadData->slots.resize(slotIdx + 1, NULL);
1488         }
1489         threadData->slots[slotIdx] = pData;
1490     }
1491
1492 private:
1493     TlsAbstraction tls; // TLS abstraction layer instance
1494
1495     Mutex  mtxGlobalAccess;           // Shared objects operation guard
1496     size_t tlsSlotsSize;              // equal to tlsSlots.size() in synchronized sections
1497                                       // without synchronization this counter doesn't desrease - it is used for slotIdx sanity checks
1498     std::vector<int> tlsSlots;        // TLS keys state
1499     std::vector<ThreadData*> threads; // Array for all allocated data. Thread data pointers are placed here to allow data cleanup
1500 };
1501
1502 // Create global TLS storage object
1503 static TlsStorage &getTlsStorage()
1504 {
1505     CV_SINGLETON_LAZY_INIT_REF(TlsStorage, new TlsStorage())
1506 }
1507
1508 TLSDataContainer::TLSDataContainer()
1509 {
1510     key_ = (int)getTlsStorage().reserveSlot(); // Reserve key from TLS storage
1511 }
1512
1513 TLSDataContainer::~TLSDataContainer()
1514 {
1515     CV_Assert(key_ == -1); // Key must be released in child object
1516 }
1517
1518 void TLSDataContainer::gatherData(std::vector<void*> &data) const
1519 {
1520     getTlsStorage().gather(key_, data);
1521 }
1522
1523 void TLSDataContainer::release()
1524 {
1525     std::vector<void*> data;
1526     data.reserve(32);
1527     getTlsStorage().releaseSlot(key_, data); // Release key and get stored data for proper destruction
1528     key_ = -1;
1529     for(size_t i = 0; i < data.size(); i++)  // Delete all associated data
1530         deleteDataInstance(data[i]);
1531 }
1532
1533 void TLSDataContainer::cleanup()
1534 {
1535     std::vector<void*> data;
1536     data.reserve(32);
1537     getTlsStorage().releaseSlot(key_, data, true); // Extract stored data with removal from TLS tables
1538     for(size_t i = 0; i < data.size(); i++)  // Delete all associated data
1539         deleteDataInstance(data[i]);
1540 }
1541
1542 void* TLSDataContainer::getData() const
1543 {
1544     CV_Assert(key_ != -1 && "Can't fetch data from terminated TLS container.");
1545     void* pData = getTlsStorage().getData(key_); // Check if data was already allocated
1546     if(!pData)
1547     {
1548         // Create new data instance and save it to TLS storage
1549         pData = createDataInstance();
1550         getTlsStorage().setData(key_, pData);
1551     }
1552     return pData;
1553 }
1554
1555 TLSData<CoreTLSData>& getCoreTlsData()
1556 {
1557     CV_SINGLETON_LAZY_INIT_REF(TLSData<CoreTLSData>, new TLSData<CoreTLSData>())
1558 }
1559
1560 #if defined CVAPI_EXPORTS && defined _WIN32 && !defined WINCE
1561 #ifdef WINRT
1562     #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
1563 #endif
1564
1565 extern "C"
1566 BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved);
1567
1568 extern "C"
1569 BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved)
1570 {
1571     if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
1572     {
1573         if (lpReserved != NULL) // called after ExitProcess() call
1574         {
1575             cv::__termination = true;
1576         }
1577         else
1578         {
1579             // Not allowed to free resources if lpReserved is non-null
1580             // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583.aspx
1581             cv::getTlsStorage().releaseThread();
1582         }
1583     }
1584     return TRUE;
1585 }
1586 #endif
1587
1588
1589 namespace {
1590 static int g_threadNum = 0;
1591 class ThreadID {
1592 public:
1593     const int id;
1594     ThreadID() :
1595         id(CV_XADD(&g_threadNum, 1))
1596     {
1597 #ifdef OPENCV_WITH_ITT
1598         __itt_thread_set_name(cv::format("OpenCVThread-%03d", id).c_str());
1599 #endif
1600     }
1601 };
1602
1603 static TLSData<ThreadID>& getThreadIDTLS()
1604 {
1605     CV_SINGLETON_LAZY_INIT_REF(TLSData<ThreadID>, new TLSData<ThreadID>());
1606 }
1607
1608 } // namespace
1609 int utils::getThreadID() { return getThreadIDTLS().get()->id; }
1610
1611 bool utils::getConfigurationParameterBool(const char* name, bool defaultValue)
1612 {
1613 #ifdef NO_GETENV
1614     const char* envValue = NULL;
1615 #else
1616     const char* envValue = getenv(name);
1617 #endif
1618     if (envValue == NULL)
1619     {
1620         return defaultValue;
1621     }
1622     cv::String value = envValue;
1623     if (value == "1" || value == "True" || value == "true" || value == "TRUE")
1624     {
1625         return true;
1626     }
1627     if (value == "0" || value == "False" || value == "false" || value == "FALSE")
1628     {
1629         return false;
1630     }
1631     CV_ErrorNoReturn(cv::Error::StsBadArg, cv::format("Invalid value for %s parameter: %s", name, value.c_str()));
1632 }
1633
1634
1635 size_t utils::getConfigurationParameterSizeT(const char* name, size_t defaultValue)
1636 {
1637 #ifdef NO_GETENV
1638     const char* envValue = NULL;
1639 #else
1640     const char* envValue = getenv(name);
1641 #endif
1642     if (envValue == NULL)
1643     {
1644         return defaultValue;
1645     }
1646     cv::String value = envValue;
1647     size_t pos = 0;
1648     for (; pos < value.size(); pos++)
1649     {
1650         if (!isdigit(value[pos]))
1651             break;
1652     }
1653     cv::String valueStr = value.substr(0, pos);
1654     cv::String suffixStr = value.substr(pos, value.length() - pos);
1655     int v = atoi(valueStr.c_str());
1656     if (suffixStr.length() == 0)
1657         return v;
1658     else if (suffixStr == "MB" || suffixStr == "Mb" || suffixStr == "mb")
1659         return v * 1024 * 1024;
1660     else if (suffixStr == "KB" || suffixStr == "Kb" || suffixStr == "kb")
1661         return v * 1024;
1662     CV_ErrorNoReturn(cv::Error::StsBadArg, cv::format("Invalid value for %s parameter: %s", name, value.c_str()));
1663 }
1664
1665 cv::String utils::getConfigurationParameterString(const char* name, const char* defaultValue)
1666 {
1667 #ifdef NO_GETENV
1668     const char* envValue = NULL;
1669 #else
1670     const char* envValue = getenv(name);
1671 #endif
1672     if (envValue == NULL)
1673     {
1674         return defaultValue;
1675     }
1676     cv::String value = envValue;
1677     return value;
1678 }
1679
1680
1681 #ifdef CV_COLLECT_IMPL_DATA
1682 ImplCollector& getImplData()
1683 {
1684     CV_SINGLETON_LAZY_INIT_REF(ImplCollector, new ImplCollector())
1685 }
1686
1687 void setImpl(int flags)
1688 {
1689     cv::AutoLock lock(getImplData().mutex);
1690
1691     getImplData().implFlags = flags;
1692     getImplData().implCode.clear();
1693     getImplData().implFun.clear();
1694 }
1695
1696 void addImpl(int flag, const char* func)
1697 {
1698     cv::AutoLock lock(getImplData().mutex);
1699
1700     getImplData().implFlags |= flag;
1701     if(func) // use lazy collection if name was not specified
1702     {
1703         size_t index = getImplData().implCode.size();
1704         if(!index || (getImplData().implCode[index-1] != flag || getImplData().implFun[index-1].compare(func))) // avoid duplicates
1705         {
1706             getImplData().implCode.push_back(flag);
1707             getImplData().implFun.push_back(func);
1708         }
1709     }
1710 }
1711
1712 int getImpl(std::vector<int> &impl, std::vector<String> &funName)
1713 {
1714     cv::AutoLock lock(getImplData().mutex);
1715
1716     impl    = getImplData().implCode;
1717     funName = getImplData().implFun;
1718     return getImplData().implFlags; // return actual flags for lazy collection
1719 }
1720
1721 bool useCollection()
1722 {
1723     return getImplData().useCollection;
1724 }
1725
1726 void setUseCollection(bool flag)
1727 {
1728     cv::AutoLock lock(getImplData().mutex);
1729
1730     getImplData().useCollection = flag;
1731 }
1732 #endif
1733
1734 namespace instr
1735 {
1736 bool useInstrumentation()
1737 {
1738 #ifdef ENABLE_INSTRUMENTATION
1739     return getInstrumentStruct().useInstr;
1740 #else
1741     return false;
1742 #endif
1743 }
1744
1745 void setUseInstrumentation(bool flag)
1746 {
1747 #ifdef ENABLE_INSTRUMENTATION
1748     getInstrumentStruct().useInstr = flag;
1749 #else
1750     CV_UNUSED(flag);
1751 #endif
1752 }
1753
1754 InstrNode* getTrace()
1755 {
1756 #ifdef ENABLE_INSTRUMENTATION
1757     return &getInstrumentStruct().rootNode;
1758 #else
1759     return NULL;
1760 #endif
1761 }
1762
1763 void resetTrace()
1764 {
1765 #ifdef ENABLE_INSTRUMENTATION
1766     getInstrumentStruct().rootNode.removeChilds();
1767     getInstrumentTLSStruct().pCurrentNode = &getInstrumentStruct().rootNode;
1768 #endif
1769 }
1770
1771 void setFlags(FLAGS modeFlags)
1772 {
1773 #ifdef ENABLE_INSTRUMENTATION
1774     getInstrumentStruct().flags = modeFlags;
1775 #else
1776     CV_UNUSED(modeFlags);
1777 #endif
1778 }
1779 FLAGS getFlags()
1780 {
1781 #ifdef ENABLE_INSTRUMENTATION
1782     return (FLAGS)getInstrumentStruct().flags;
1783 #else
1784     return (FLAGS)0;
1785 #endif
1786 }
1787
1788 NodeData::NodeData(const char* funName, const char* fileName, int lineNum, void* retAddress, bool alwaysExpand, cv::instr::TYPE instrType, cv::instr::IMPL implType)
1789 {
1790     m_funName       = funName;
1791     m_instrType     = instrType;
1792     m_implType      = implType;
1793     m_fileName      = fileName;
1794     m_lineNum       = lineNum;
1795     m_retAddress    = retAddress;
1796     m_alwaysExpand  = alwaysExpand;
1797
1798     m_threads    = 1;
1799     m_counter    = 0;
1800     m_ticksTotal = 0;
1801
1802     m_funError  = false;
1803 }
1804 NodeData::NodeData(NodeData &ref)
1805 {
1806     *this = ref;
1807 }
1808 NodeData& NodeData::operator=(const NodeData &right)
1809 {
1810     this->m_funName      = right.m_funName;
1811     this->m_instrType    = right.m_instrType;
1812     this->m_implType     = right.m_implType;
1813     this->m_fileName     = right.m_fileName;
1814     this->m_lineNum      = right.m_lineNum;
1815     this->m_retAddress   = right.m_retAddress;
1816     this->m_alwaysExpand = right.m_alwaysExpand;
1817
1818     this->m_threads     = right.m_threads;
1819     this->m_counter     = right.m_counter;
1820     this->m_ticksTotal  = right.m_ticksTotal;
1821
1822     this->m_funError    = right.m_funError;
1823
1824     return *this;
1825 }
1826 NodeData::~NodeData()
1827 {
1828 }
1829 bool operator==(const NodeData& left, const NodeData& right)
1830 {
1831     if(left.m_lineNum == right.m_lineNum && left.m_funName == right.m_funName && left.m_fileName == right.m_fileName)
1832     {
1833         if(left.m_retAddress == right.m_retAddress || !(cv::instr::getFlags()&cv::instr::FLAGS_EXPAND_SAME_NAMES || left.m_alwaysExpand))
1834             return true;
1835     }
1836     return false;
1837 }
1838
1839 #ifdef ENABLE_INSTRUMENTATION
1840 InstrStruct& getInstrumentStruct()
1841 {
1842     static InstrStruct instr;
1843     return instr;
1844 }
1845
1846 InstrTLSStruct& getInstrumentTLSStruct()
1847 {
1848     return *getInstrumentStruct().tlsStruct.get();
1849 }
1850
1851 InstrNode* getCurrentNode()
1852 {
1853     return getInstrumentTLSStruct().pCurrentNode;
1854 }
1855
1856 IntrumentationRegion::IntrumentationRegion(const char* funName, const char* fileName, int lineNum, void *retAddress, bool alwaysExpand, TYPE instrType, IMPL implType)
1857 {
1858     m_disabled    = false;
1859     m_regionTicks = 0;
1860
1861     InstrStruct *pStruct = &getInstrumentStruct();
1862     if(pStruct->useInstr)
1863     {
1864         InstrTLSStruct *pTLS = &getInstrumentTLSStruct();
1865
1866         // Disable in case of failure
1867         if(!pTLS->pCurrentNode)
1868         {
1869             m_disabled = true;
1870             return;
1871         }
1872
1873         int depth = pTLS->pCurrentNode->getDepth();
1874         if(pStruct->maxDepth && pStruct->maxDepth <= depth)
1875         {
1876             m_disabled = true;
1877             return;
1878         }
1879
1880         NodeData payload(funName, fileName, lineNum, retAddress, alwaysExpand, instrType, implType);
1881         Node<NodeData>* pChild = NULL;
1882
1883         if(pStruct->flags&FLAGS_MAPPING)
1884         {
1885             // Critical section
1886             cv::AutoLock guard(pStruct->mutexCreate); // Guard from concurrent child creation
1887             pChild = pTLS->pCurrentNode->findChild(payload);
1888             if(!pChild)
1889             {
1890                 pChild = new Node<NodeData>(payload);
1891                 pTLS->pCurrentNode->addChild(pChild);
1892             }
1893         }
1894         else
1895         {
1896             pChild = pTLS->pCurrentNode->findChild(payload);
1897             if(!pChild)
1898             {
1899                 m_disabled = true;
1900                 return;
1901             }
1902         }
1903         pTLS->pCurrentNode = pChild;
1904
1905         m_regionTicks = getTickCount();
1906     }
1907 }
1908
1909 IntrumentationRegion::~IntrumentationRegion()
1910 {
1911     InstrStruct *pStruct = &getInstrumentStruct();
1912     if(pStruct->useInstr)
1913     {
1914         if(!m_disabled)
1915         {
1916             InstrTLSStruct *pTLS = &getInstrumentTLSStruct();
1917
1918             if (pTLS->pCurrentNode->m_payload.m_implType == cv::instr::IMPL_OPENCL &&
1919                 (pTLS->pCurrentNode->m_payload.m_instrType == cv::instr::TYPE_FUN ||
1920                     pTLS->pCurrentNode->m_payload.m_instrType == cv::instr::TYPE_WRAPPER))
1921             {
1922                 cv::ocl::finish(); // TODO Support "async" OpenCL instrumentation
1923             }
1924
1925             uint64 ticks = (getTickCount() - m_regionTicks);
1926             {
1927                 cv::AutoLock guard(pStruct->mutexCount); // Concurrent ticks accumulation
1928                 pTLS->pCurrentNode->m_payload.m_counter++;
1929                 pTLS->pCurrentNode->m_payload.m_ticksTotal += ticks;
1930                 pTLS->pCurrentNode->m_payload.m_tls.get()->m_ticksTotal += ticks;
1931             }
1932
1933             pTLS->pCurrentNode = pTLS->pCurrentNode->m_pParent;
1934         }
1935     }
1936 }
1937 #endif
1938 }
1939
1940 namespace ipp
1941 {
1942
1943 #ifdef HAVE_IPP
1944 struct IPPInitSingleton
1945 {
1946 public:
1947     IPPInitSingleton()
1948     {
1949         useIPP         = true;
1950         useIPP_NE      = false;
1951         ippStatus      = 0;
1952         funcname       = NULL;
1953         filename       = NULL;
1954         linen          = 0;
1955         cpuFeatures    = 0;
1956         ippFeatures    = 0;
1957         ippTopFeatures = 0;
1958         pIppLibInfo    = NULL;
1959
1960         ippStatus = ippGetCpuFeatures(&cpuFeatures, NULL);
1961         if(ippStatus < 0)
1962         {
1963             std::cerr << "ERROR: IPP cannot detect CPU features, IPP was disabled " << std::endl;
1964             useIPP = false;
1965             return;
1966         }
1967         ippFeatures = cpuFeatures;
1968
1969         const char* pIppEnv = getenv("OPENCV_IPP");
1970         cv::String env = pIppEnv;
1971         if(env.size())
1972         {
1973 #if IPP_VERSION_X100 >= 201703
1974             const Ipp64u minorFeatures = ippCPUID_MOVBE|ippCPUID_AES|ippCPUID_CLMUL|ippCPUID_ABR|ippCPUID_RDRAND|ippCPUID_F16C|
1975                 ippCPUID_ADCOX|ippCPUID_RDSEED|ippCPUID_PREFETCHW|ippCPUID_SHA|ippCPUID_MPX|ippCPUID_AVX512CD|ippCPUID_AVX512ER|
1976                 ippCPUID_AVX512PF|ippCPUID_AVX512BW|ippCPUID_AVX512DQ|ippCPUID_AVX512VL|ippCPUID_AVX512VBMI;
1977 #elif IPP_VERSION_X100 >= 201700
1978             const Ipp64u minorFeatures = ippCPUID_MOVBE|ippCPUID_AES|ippCPUID_CLMUL|ippCPUID_ABR|ippCPUID_RDRAND|ippCPUID_F16C|
1979                 ippCPUID_ADCOX|ippCPUID_RDSEED|ippCPUID_PREFETCHW|ippCPUID_SHA|ippCPUID_AVX512CD|ippCPUID_AVX512ER|
1980                 ippCPUID_AVX512PF|ippCPUID_AVX512BW|ippCPUID_AVX512DQ|ippCPUID_AVX512VL|ippCPUID_AVX512VBMI;
1981 #else
1982             const Ipp64u minorFeatures = 0;
1983 #endif
1984
1985             env = env.toLowerCase();
1986             if(env.substr(0, 2) == "ne")
1987             {
1988                 useIPP_NE = true;
1989                 env = env.substr(3, env.size());
1990             }
1991
1992             if(env == "disabled")
1993             {
1994                 std::cerr << "WARNING: IPP was disabled by OPENCV_IPP environment variable" << std::endl;
1995                 useIPP = false;
1996             }
1997             else if(env == "sse42")
1998                 ippFeatures = minorFeatures|ippCPUID_SSE2|ippCPUID_SSE3|ippCPUID_SSSE3|ippCPUID_SSE41|ippCPUID_SSE42;
1999             else if(env == "avx2")
2000                 ippFeatures = minorFeatures|ippCPUID_SSE2|ippCPUID_SSE3|ippCPUID_SSSE3|ippCPUID_SSE41|ippCPUID_SSE42|ippCPUID_AVX|ippCPUID_AVX2;
2001 #if IPP_VERSION_X100 >= 201700
2002 #if defined (_M_AMD64) || defined (__x86_64__)
2003             else if(env == "avx512")
2004                 ippFeatures = minorFeatures|ippCPUID_SSE2|ippCPUID_SSE3|ippCPUID_SSSE3|ippCPUID_SSE41|ippCPUID_SSE42|ippCPUID_AVX|ippCPUID_AVX2|ippCPUID_AVX512F;
2005 #endif
2006 #endif
2007             else
2008                 std::cerr << "ERROR: Improper value of OPENCV_IPP: " << env.c_str() << ". Correct values are: disabled, sse42, avx2, avx512 (Intel64 only)" << std::endl;
2009
2010             // Trim unsupported features
2011             ippFeatures &= cpuFeatures;
2012         }
2013
2014         // Disable AVX1 since we don't track regressions for it. SSE42 will be used instead
2015         if(cpuFeatures&ippCPUID_AVX && !(cpuFeatures&ippCPUID_AVX2))
2016             ippFeatures &= ~((Ipp64u)ippCPUID_AVX);
2017
2018         // IPP integrations in OpenCV support only SSE4.2, AVX2 and AVX-512 optimizations.
2019         if(!(
2020 #if IPP_VERSION_X100 >= 201700
2021             cpuFeatures&ippCPUID_AVX512F ||
2022 #endif
2023             cpuFeatures&ippCPUID_AVX2 ||
2024             cpuFeatures&ippCPUID_SSE42
2025             ))
2026         {
2027             useIPP = false;
2028             return;
2029         }
2030
2031         if(ippFeatures == cpuFeatures)
2032             IPP_INITIALIZER(0)
2033         else
2034             IPP_INITIALIZER(ippFeatures)
2035         ippFeatures = ippGetEnabledCpuFeatures();
2036
2037         // Detect top level optimizations to make comparison easier for optimizations dependent conditions
2038 #if IPP_VERSION_X100 >= 201700
2039         if(ippFeatures&ippCPUID_AVX512F)
2040         {
2041             if((ippFeatures&ippCPUID_AVX512_SKX) == ippCPUID_AVX512_SKX)
2042                 ippTopFeatures = ippCPUID_AVX512_SKX;
2043             else if((ippFeatures&ippCPUID_AVX512_KNL) == ippCPUID_AVX512_KNL)
2044                 ippTopFeatures = ippCPUID_AVX512_KNL;
2045             else
2046                 ippTopFeatures = ippCPUID_AVX512F; // Unknown AVX512 configuration
2047         }
2048         else
2049 #endif
2050         if(ippFeatures&ippCPUID_AVX2)
2051             ippTopFeatures = ippCPUID_AVX2;
2052         else if(ippFeatures&ippCPUID_SSE42)
2053             ippTopFeatures = ippCPUID_SSE42;
2054
2055         pIppLibInfo = ippiGetLibVersion();
2056     }
2057
2058 public:
2059     bool        useIPP;
2060     bool        useIPP_NE;
2061
2062     int         ippStatus;  // 0 - all is ok, -1 - IPP functions failed
2063     const char *funcname;
2064     const char *filename;
2065     int         linen;
2066     Ipp64u      ippFeatures;
2067     Ipp64u      cpuFeatures;
2068     Ipp64u      ippTopFeatures;
2069     const IppLibraryVersion *pIppLibInfo;
2070 };
2071
2072 static IPPInitSingleton& getIPPSingleton()
2073 {
2074     CV_SINGLETON_LAZY_INIT_REF(IPPInitSingleton, new IPPInitSingleton())
2075 }
2076 #endif
2077
2078 #if OPENCV_ABI_COMPATIBILITY > 300
2079 unsigned long long getIppFeatures()
2080 #else
2081 int getIppFeatures()
2082 #endif
2083 {
2084 #ifdef HAVE_IPP
2085 #if OPENCV_ABI_COMPATIBILITY > 300
2086     return getIPPSingleton().ippFeatures;
2087 #else
2088     return (int)getIPPSingleton().ippFeatures;
2089 #endif
2090 #else
2091     return 0;
2092 #endif
2093 }
2094
2095 unsigned long long getIppTopFeatures();
2096
2097 unsigned long long getIppTopFeatures()
2098 {
2099 #ifdef HAVE_IPP
2100     return getIPPSingleton().ippTopFeatures;
2101 #else
2102     return 0;
2103 #endif
2104 }
2105
2106 void setIppStatus(int status, const char * const _funcname, const char * const _filename, int _line)
2107 {
2108 #ifdef HAVE_IPP
2109     getIPPSingleton().ippStatus = status;
2110     getIPPSingleton().funcname = _funcname;
2111     getIPPSingleton().filename = _filename;
2112     getIPPSingleton().linen = _line;
2113 #else
2114     CV_UNUSED(status); CV_UNUSED(_funcname); CV_UNUSED(_filename); CV_UNUSED(_line);
2115 #endif
2116 }
2117
2118 int getIppStatus()
2119 {
2120 #ifdef HAVE_IPP
2121     return getIPPSingleton().ippStatus;
2122 #else
2123     return 0;
2124 #endif
2125 }
2126
2127 String getIppErrorLocation()
2128 {
2129 #ifdef HAVE_IPP
2130     return format("%s:%d %s", getIPPSingleton().filename ? getIPPSingleton().filename : "", getIPPSingleton().linen, getIPPSingleton().funcname ? getIPPSingleton().funcname : "");
2131 #else
2132     return String();
2133 #endif
2134 }
2135
2136 String getIppVersion()
2137 {
2138 #ifdef HAVE_IPP
2139     const IppLibraryVersion *pInfo = getIPPSingleton().pIppLibInfo;
2140     if(pInfo)
2141         return format("%s %s %s", pInfo->Name, pInfo->Version, pInfo->BuildDate);
2142     else
2143         return String("error");
2144 #else
2145     return String("disabled");
2146 #endif
2147 }
2148
2149 bool useIPP()
2150 {
2151 #ifdef HAVE_IPP
2152     CoreTLSData* data = getCoreTlsData().get();
2153     if(data->useIPP < 0)
2154     {
2155         data->useIPP = getIPPSingleton().useIPP;
2156     }
2157     return (data->useIPP > 0);
2158 #else
2159     return false;
2160 #endif
2161 }
2162
2163 void setUseIPP(bool flag)
2164 {
2165     CoreTLSData* data = getCoreTlsData().get();
2166 #ifdef HAVE_IPP
2167     data->useIPP = (getIPPSingleton().useIPP)?flag:false;
2168 #else
2169     (void)flag;
2170     data->useIPP = false;
2171 #endif
2172 }
2173
2174 bool useIPP_NE()
2175 {
2176 #ifdef HAVE_IPP
2177     CoreTLSData* data = getCoreTlsData().get();
2178     if(data->useIPP_NE < 0)
2179     {
2180         data->useIPP_NE = getIPPSingleton().useIPP_NE;
2181     }
2182     return (data->useIPP_NE > 0);
2183 #else
2184     return false;
2185 #endif
2186 }
2187
2188 void setUseIPP_NE(bool flag)
2189 {
2190     CoreTLSData* data = getCoreTlsData().get();
2191 #ifdef HAVE_IPP
2192     data->useIPP_NE = (getIPPSingleton().useIPP_NE)?flag:false;
2193 #else
2194     (void)flag;
2195     data->useIPP_NE = false;
2196 #endif
2197 }
2198
2199 } // namespace ipp
2200
2201 } // namespace cv
2202
2203 #ifdef HAVE_TEGRA_OPTIMIZATION
2204
2205 namespace tegra {
2206
2207 bool useTegra()
2208 {
2209     cv::CoreTLSData* data = cv::getCoreTlsData().get();
2210
2211     if (data->useTegra < 0)
2212     {
2213         const char* pTegraEnv = getenv("OPENCV_TEGRA");
2214         if (pTegraEnv && (cv::String(pTegraEnv) == "disabled"))
2215             data->useTegra = false;
2216         else
2217             data->useTegra = true;
2218     }
2219
2220     return (data->useTegra > 0);
2221 }
2222
2223 void setUseTegra(bool flag)
2224 {
2225     cv::CoreTLSData* data = cv::getCoreTlsData().get();
2226     data->useTegra = flag;
2227 }
2228
2229 } // namespace tegra
2230
2231 #endif
2232
2233 /* End of file. */