system.cpp 36.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                           License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
I
Ilya Lavrenov 已提交
15
// Copyright (C) 2015, Itseez Inc., all rights reserved.
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//
//   * The name of the copyright holders may not be used to endorse or promote products
//     derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/

#include "precomp.hpp"

46 47 48 49 50 51 52 53 54 55 56 57 58 59
namespace cv {

static Mutex* __initialization_mutex = NULL;
Mutex& getInitializationMutex()
{
    if (__initialization_mutex == NULL)
        __initialization_mutex = new Mutex();
    return *__initialization_mutex;
}
// force initialization (single-threaded environment)
Mutex* __initialization_mutex_initializer = &getInitializationMutex();

} // namespace cv

60 61 62 63 64 65
#ifdef _MSC_VER
# if _MSC_VER >= 1700
#  pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
# endif
#endif

I
Ilya Lavrenov 已提交
66 67 68 69 70 71 72
#if defined ANDROID || defined __linux__
#  include <unistd.h>
#  include <fcntl.h>
#  include <elf.h>
#  include <linux/auxvec.h>
#endif

73
#if defined WIN32 || defined _WIN32 || defined WINCE
74 75 76 77
#ifndef _WIN32_WINNT           // This is needed for the declaration of TryEnterCriticalSection in winbase.h with Visual Studio 2005 (and older?)
  #define _WIN32_WINNT 0x0400  // http://msdn.microsoft.com/en-us/library/ms686857(VS.85).aspx
#endif
#include <windows.h>
78
#if (_WIN32_WINNT >= 0x0602)
79
  #include <synchapi.h>
80
#endif
81 82 83 84
#undef small
#undef min
#undef max
#undef abs
85 86 87 88
#include <tchar.h>
#if defined _MSC_VER
  #if _MSC_VER >= 1400
    #include <intrin.h>
89
  #elif defined _M_IX86
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    static void __cpuid(int* cpuid_data, int)
    {
        __asm
        {
            push ebx
            push edi
            mov edi, cpuid_data
            mov eax, 1
            cpuid
            mov [edi], eax
            mov [edi + 4], ebx
            mov [edi + 8], ecx
            mov [edi + 12], edx
            pop edi
            pop ebx
        }
    }
I
avx2  
Ilya Lavrenov 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    static void __cpuidex(int* cpuid_data, int, int)
    {
        __asm
        {
            push edi
            mov edi, cpuid_data
            mov eax, 7
            mov ecx, 0
            cpuid
            mov [edi], eax
            mov [edi + 4], ebx
            mov [edi + 8], ecx
            mov [edi + 12], edx
            pop edi
        }
    }
123 124
  #endif
#endif
125

126
#ifdef WINRT
127
#include <wrl/client.h>
G
GregoryMorse 已提交
128 129 130 131
#ifndef __cplusplus_winrt
#include <windows.storage.h>
#pragma comment(lib, "runtimeobject.lib")
#endif
132 133 134

std::wstring GetTempPathWinRT()
{
G
GregoryMorse 已提交
135
#ifdef __cplusplus_winrt
136
    return std::wstring(Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data());
G
GregoryMorse 已提交
137 138 139 140 141 142 143 144 145 146 147
#else
    Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> appdataFactory;
    Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> appdataRef;
    Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> storagefolderRef;
    Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageItem> storageitemRef;
    HSTRING str;
    HSTRING_HEADER hstrHead;
    std::wstring wstr;
    if (FAILED(WindowsCreateStringReference(RuntimeClass_Windows_Storage_ApplicationData,
                                            (UINT32)wcslen(RuntimeClass_Windows_Storage_ApplicationData), &hstrHead, &str)))
        return wstr;
G
GregoryMorse 已提交
148
    if (FAILED(RoGetActivationFactory(str, IID_PPV_ARGS(appdataFactory.ReleaseAndGetAddressOf()))))
G
GregoryMorse 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162
        return wstr;
    if (FAILED(appdataFactory->get_Current(appdataRef.ReleaseAndGetAddressOf())))
        return wstr;
    if (FAILED(appdataRef->get_TemporaryFolder(storagefolderRef.ReleaseAndGetAddressOf())))
        return wstr;
    if (FAILED(storagefolderRef.As(&storageitemRef)))
        return wstr;
    str = NULL;
    if (FAILED(storageitemRef->get_Path(&str)))
        return wstr;
    wstr = WindowsGetStringRawBuffer(str, NULL);
    WindowsDeleteString(str);
    return wstr;
#endif
163 164 165 166
}

std::wstring GetTempFileNameWinRT(std::wstring prefix)
{
167 168 169
    wchar_t guidStr[40];
    GUID g;
    CoCreateGuid(&g);
170
    wchar_t* mask = L"%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x";
171 172 173 174
    swprintf(&guidStr[0], sizeof(guidStr)/sizeof(wchar_t), mask,
             g.Data1, g.Data2, g.Data3, UINT(g.Data4[0]), UINT(g.Data4[1]),
             UINT(g.Data4[2]), UINT(g.Data4[3]), UINT(g.Data4[4]),
             UINT(g.Data4[5]), UINT(g.Data4[6]), UINT(g.Data4[7]));
175

176
    return prefix.append(std::wstring(guidStr));
177 178 179
}

#endif
180 181 182 183 184
#else
#include <pthread.h>
#include <sys/time.h>
#include <time.h>

185
#if defined __MACH__ && defined __APPLE__
186 187 188 189 190 191 192 193 194 195 196 197
#include <mach/mach.h>
#include <mach/mach_time.h>
#endif

#endif

#ifdef _OPENMP
#include "omp.h"
#endif

#include <stdarg.h>

198
#if defined __linux__ || defined __APPLE__ || defined __EMSCRIPTEN__
199 200
#include <unistd.h>
#include <stdio.h>
201
#include <sys/types.h>
A
Andrey Kamaev 已提交
202 203
#if defined ANDROID
#include <sys/sysconf.h>
204
#endif
A
Andrey Kamaev 已提交
205
#endif
206

207 208 209 210
#ifdef ANDROID
# include <android/log.h>
#endif

211 212 213
namespace cv
{

214 215
Exception::Exception() { code = 0; line = 0; }

216
Exception::Exception(int _code, const String& _err, const String& _func, const String& _file, int _line)
217 218 219 220 221 222 223 224 225
: code(_code), err(_err), func(_func), file(_file), line(_line)
{
    formatMessage();
}

Exception::~Exception() throw() {}

/*!
 \return the error description and the context as a text string.
226
 */
227 228 229 230 231 232 233 234 235
const char* Exception::what() const throw() { return msg.c_str(); }

void Exception::formatMessage()
{
    if( func.size() > 0 )
        msg = format("%s:%d: error: (%d) %s in function %s\n", file.c_str(), line, code, err.c_str(), func.c_str());
    else
        msg = format("%s:%d: error: (%d) %s\n", file.c_str(), line, code, err.c_str());
}
236

237 238 239
struct HWFeatures
{
    enum { MAX_FEATURE = CV_HARDWARE_MAX_FEATURE };
240 241

    HWFeatures(void)
I
avx2  
Ilya Lavrenov 已提交
242
    {
243 244 245
        memset( have, 0, sizeof(have) );
        x86_family = 0;
    }
246 247

    static HWFeatures initialize(void)
248 249
    {
        HWFeatures f;
250 251
        int cpuid_data[4] = { 0, 0, 0, 0 };

252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
    #if defined _MSC_VER && (defined _M_IX86 || defined _M_X64)
        __cpuid(cpuid_data, 1);
    #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__)
        #ifdef __x86_64__
        asm __volatile__
        (
         "movl $1, %%eax\n\t"
         "cpuid\n\t"
         :[eax]"=a"(cpuid_data[0]),[ebx]"=b"(cpuid_data[1]),[ecx]"=c"(cpuid_data[2]),[edx]"=d"(cpuid_data[3])
         :
         : "cc"
        );
        #else
        asm volatile
        (
         "pushl %%ebx\n\t"
         "movl $1,%%eax\n\t"
         "cpuid\n\t"
         "popl %%ebx\n\t"
         : "=a"(cpuid_data[0]), "=c"(cpuid_data[2]), "=d"(cpuid_data[3])
         :
         : "cc"
        );
        #endif
    #endif
277

278 279 280
        f.x86_family = (cpuid_data[0] >> 8) & 15;
        if( f.x86_family >= 6 )
        {
281 282 283 284 285
            f.have[CV_CPU_MMX]    = (cpuid_data[3] & (1 << 23)) != 0;
            f.have[CV_CPU_SSE]    = (cpuid_data[3] & (1<<25)) != 0;
            f.have[CV_CPU_SSE2]   = (cpuid_data[3] & (1<<26)) != 0;
            f.have[CV_CPU_SSE3]   = (cpuid_data[2] & (1<<0)) != 0;
            f.have[CV_CPU_SSSE3]  = (cpuid_data[2] & (1<<9)) != 0;
I
Ilya Lavrenov 已提交
286
            f.have[CV_CPU_FMA3]  = (cpuid_data[2] & (1<<12)) != 0;
287 288
            f.have[CV_CPU_SSE4_1] = (cpuid_data[2] & (1<<19)) != 0;
            f.have[CV_CPU_SSE4_2] = (cpuid_data[2] & (1<<20)) != 0;
289
            f.have[CV_CPU_POPCNT] = (cpuid_data[2] & (1<<23)) != 0;
290
            f.have[CV_CPU_AVX]    = (((cpuid_data[2] & (1<<28)) != 0)&&((cpuid_data[2] & (1<<27)) != 0));//OS uses XSAVE_XRSTORE and CPU support AVX
I
avx2  
Ilya Lavrenov 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

            // make the second call to the cpuid command in order to get
            // information about extended features like AVX2
        #if defined _MSC_VER && (defined _M_IX86 || defined _M_X64)
            __cpuidex(cpuid_data, 7, 0);
        #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__)
            #ifdef __x86_64__
            asm __volatile__
            (
             "movl $7, %%eax\n\t"
             "movl $0, %%ecx\n\t"
             "cpuid\n\t"
             :[eax]"=a"(cpuid_data[0]),[ebx]"=b"(cpuid_data[1]),[ecx]"=c"(cpuid_data[2]),[edx]"=d"(cpuid_data[3])
             :
             : "cc"
            );
            #else
            asm volatile
            (
I
Ilya Lavrenov 已提交
310
             "pushl %%ebx\n\t"
I
avx2  
Ilya Lavrenov 已提交
311 312 313
             "movl $7,%%eax\n\t"
             "movl $0,%%ecx\n\t"
             "cpuid\n\t"
I
Ilya Lavrenov 已提交
314 315 316
             "movl %%ebx, %0\n\t"
             "popl %%ebx\n\t"
             : "=r"(cpuid_data[1]), "=c"(cpuid_data[2])
I
avx2  
Ilya Lavrenov 已提交
317 318 319 320 321 322 323
             :
             : "cc"
            );
            #endif
        #endif
            f.have[CV_CPU_AVX2]   = (cpuid_data[1] & (1<<5)) != 0;

I
Ilya Lavrenov 已提交
324 325 326 327 328 329 330 331 332
            f.have[CV_CPU_AVX_512F]       = (cpuid_data[1] & (1<<16)) != 0;
            f.have[CV_CPU_AVX_512DQ]      = (cpuid_data[1] & (1<<17)) != 0;
            f.have[CV_CPU_AVX_512IFMA512] = (cpuid_data[1] & (1<<21)) != 0;
            f.have[CV_CPU_AVX_512PF]      = (cpuid_data[1] & (1<<26)) != 0;
            f.have[CV_CPU_AVX_512ER]      = (cpuid_data[1] & (1<<27)) != 0;
            f.have[CV_CPU_AVX_512CD]      = (cpuid_data[1] & (1<<28)) != 0;
            f.have[CV_CPU_AVX_512BW]      = (cpuid_data[1] & (1<<30)) != 0;
            f.have[CV_CPU_AVX_512VL]      = (cpuid_data[1] & (1<<31)) != 0;
            f.have[CV_CPU_AVX_512VBMI]    = (cpuid_data[2] &  (1<<1)) != 0;
333
        }
334

I
Ilya Lavrenov 已提交
335
    #if defined ANDROID || defined __linux__
I
Ilya Lavrenov 已提交
336 337 338
    #ifdef __aarch64__
        f.have[CV_CPU_NEON] = true;
    #else
I
Ilya Lavrenov 已提交
339 340 341 342 343
        int cpufile = open("/proc/self/auxv", O_RDONLY);

        if (cpufile >= 0)
        {
            Elf32_auxv_t auxv;
D
Dmitry-Me 已提交
344
            const size_t size_auxv_t = sizeof(auxv);
I
Ilya Lavrenov 已提交
345

D
Dmitry-Me 已提交
346
            while ((size_t)read(cpufile, &auxv, size_auxv_t) == size_auxv_t)
I
Ilya Lavrenov 已提交
347 348 349 350 351 352 353 354 355 356
            {
                if (auxv.a_type == AT_HWCAP)
                {
                    f.have[CV_CPU_NEON] = (auxv.a_un.a_val & 4096) != 0;
                    break;
                }
            }

            close(cpufile);
        }
I
Ilya Lavrenov 已提交
357 358
    #endif
    #elif (defined __clang__ || defined __APPLE__) && (defined __ARM_NEON__ || (defined __ARM_NEON && defined __aarch64__))
I
Ilya Lavrenov 已提交
359 360 361
        f.have[CV_CPU_NEON] = true;
    #endif

362 363
        return f;
    }
364

365 366 367
    int x86_family;
    bool have[MAX_FEATURE+1];
};
368 369

static HWFeatures  featuresEnabled = HWFeatures::initialize(), featuresDisabled = HWFeatures();
370 371 372 373 374 375 376 377 378
static HWFeatures* currentFeatures = &featuresEnabled;

bool checkHardwareSupport(int feature)
{
    CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
    return currentFeatures->have[feature];
}


379 380
volatile bool useOptimizedFlag = true;
#ifdef HAVE_IPP
381 382
struct IPPInitializer
{
A
Alexander Alekhin 已提交
383 384 385 386 387 388 389 390
    IPPInitializer(void)
    {
#if IPP_VERSION_MAJOR >= 8
        ippInit();
#else
        ippStaticInit();
#endif
    }
391 392 393 394 395
};

IPPInitializer ippInitializer;
#endif

396
volatile bool USE_SSE2 = featuresEnabled.have[CV_CPU_SSE2];
397 398
volatile bool USE_SSE4_2 = featuresEnabled.have[CV_CPU_SSE4_2];
volatile bool USE_AVX = featuresEnabled.have[CV_CPU_AVX];
I
avx2  
Ilya Lavrenov 已提交
399
volatile bool USE_AVX2 = featuresEnabled.have[CV_CPU_AVX2];
400

401 402 403 404
void setUseOptimized( bool flag )
{
    useOptimizedFlag = flag;
    currentFeatures = flag ? &featuresEnabled : &featuresDisabled;
405
    USE_SSE2 = currentFeatures->have[CV_CPU_SSE2];
406 407 408 409 410 411

    ipp::setUseIPP(flag);
    ocl::setUseOpenCL(flag);
#ifdef HAVE_TEGRA_OPTIMIZATION
    ::tegra::setUseTegra(flag);
#endif
412 413
}

414
bool useOptimized(void)
415 416 417
{
    return useOptimizedFlag;
}
418 419

int64 getTickCount(void)
420
{
421
#if defined WIN32 || defined _WIN32 || defined WINCE
422 423 424 425 426 427 428
    LARGE_INTEGER counter;
    QueryPerformanceCounter( &counter );
    return (int64)counter.QuadPart;
#elif defined __linux || defined __linux__
    struct timespec tp;
    clock_gettime(CLOCK_MONOTONIC, &tp);
    return (int64)tp.tv_sec*1000000000 + tp.tv_nsec;
429
#elif defined __MACH__ && defined __APPLE__
430
    return (int64)mach_absolute_time();
431
#else
432 433 434 435 436 437 438
    struct timeval tv;
    struct timezone tz;
    gettimeofday( &tv, &tz );
    return (int64)tv.tv_sec*1000000 + tv.tv_usec;
#endif
}

439
double getTickFrequency(void)
440
{
441
#if defined WIN32 || defined _WIN32 || defined WINCE
442 443 444 445 446
    LARGE_INTEGER freq;
    QueryPerformanceFrequency(&freq);
    return (double)freq.QuadPart;
#elif defined __linux || defined __linux__
    return 1e9;
447
#elif defined __MACH__ && defined __APPLE__
448 449 450 451 452 453 454
    static double freq = 0;
    if( freq == 0 )
    {
        mach_timebase_info_data_t sTimebaseInfo;
        mach_timebase_info(&sTimebaseInfo);
        freq = sTimebaseInfo.denom*1e9/sTimebaseInfo.numer;
    }
455
    return freq;
456 457 458 459 460
#else
    return 1e6;
#endif
}

461
#if defined __GNUC__ && (defined __i386__ || defined __x86_64__ || defined __ppc__)
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
#if defined(__i386__)

int64 getCPUTickCount(void)
{
    int64 x;
    __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
    return x;
}
#elif defined(__x86_64__)

int64 getCPUTickCount(void)
{
    unsigned hi, lo;
    __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
    return (int64)lo | ((int64)hi << 32);
}

#elif defined(__ppc__)

int64 getCPUTickCount(void)
{
483
    int64 result = 0;
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    unsigned upper, lower, tmp;
    __asm__ volatile(
                     "0:                  \n"
                     "\tmftbu   %0           \n"
                     "\tmftb    %1           \n"
                     "\tmftbu   %2           \n"
                     "\tcmpw    %2,%0        \n"
                     "\tbne     0b         \n"
                     : "=r"(upper),"=r"(lower),"=r"(tmp)
                     );
    return lower | ((int64)upper << 32);
}

#else

#error "RDTSC not defined"

#endif

503
#elif defined _MSC_VER && defined WIN32 && defined _M_IX86
504 505 506 507 508 509 510 511 512

int64 getCPUTickCount(void)
{
    __asm _emit 0x0f;
    __asm _emit 0x31;
}

#else

V
vbystricky 已提交
513 514 515 516 517 518
//#ifdef HAVE_IPP
//int64 getCPUTickCount(void)
//{
//    return ippGetCpuClocks();
//}
//#else
519
int64 getCPUTickCount(void)
520 521 522
{
    return getTickCount();
}
V
vbystricky 已提交
523
//#endif
524 525 526

#endif

527
const String& getBuildInformation()
528
{
529
    static String build_info =
530 531 532 533 534
#include "version_string.inc"
    ;
    return build_info;
}

535
String format( const char* fmt, ... )
536
{
I
Ilya Lavrenov 已提交
537
    AutoBuffer<char, 1024> buf;
538

I
Ilya Lavrenov 已提交
539
    for ( ; ; )
540
    {
I
Ilya Lavrenov 已提交
541
        va_list va;
542
        va_start(va, fmt);
I
Ilya Lavrenov 已提交
543 544
        int bsize = static_cast<int>(buf.size()),
                len = vsnprintf((char *)buf, bsize, fmt, va);
545 546
        va_end(va);

I
Ilya Lavrenov 已提交
547 548 549 550 551 552 553
        if (len < 0 || len >= bsize)
        {
            buf.resize(std::max(bsize << 1, len + 1));
            continue;
        }
        return String((char *)buf, len);
    }
554 555
}

556
String tempfile( const char* suffix )
557
{
558
    String fname;
559
#ifndef WINRT
G
GregoryMorse 已提交
560
    const char *temp_dir = getenv("OPENCV_TEMP_PATH");
561
#endif
562

563
#if defined WIN32 || defined _WIN32
564
#ifdef WINRT
565
    RoInitialize(RO_INIT_MULTITHREADED);
566
    std::wstring temp_dir = GetTempPathWinRT();
567

568
    std::wstring temp_file = GetTempFileNameWinRT(L"ocv");
569
    if (temp_file.empty())
G
GregoryMorse 已提交
570
        return String();
571

572
    temp_file = temp_dir.append(std::wstring(L"\\")).append(temp_file);
573 574
    DeleteFileW(temp_file.c_str());

575 576 577
    char aname[MAX_PATH];
    size_t copied = wcstombs(aname, temp_file.c_str(), MAX_PATH);
    CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
G
GregoryMorse 已提交
578
    fname = String(aname);
579 580
    RoUninitialize();
#else
581 582
    char temp_dir2[MAX_PATH] = { 0 };
    char temp_file[MAX_PATH] = { 0 };
583

584 585 586 587 588
    if (temp_dir == 0 || temp_dir[0] == 0)
    {
        ::GetTempPathA(sizeof(temp_dir2), temp_dir2);
        temp_dir = temp_dir2;
    }
589
    if(0 == ::GetTempFileNameA(temp_dir, "ocv", 0, temp_file))
590
        return String();
591

R
Roy Reapor 已提交
592 593
    DeleteFileA(temp_file);

594
    fname = temp_file;
595
#endif
596 597 598 599 600 601 602 603
# else
#  ifdef ANDROID
    //char defaultTemplate[] = "/mnt/sdcard/__opencv_temp.XXXXXX";
    char defaultTemplate[] = "/data/local/tmp/__opencv_temp.XXXXXX";
#  else
    char defaultTemplate[] = "/tmp/__opencv_temp.XXXXXX";
#  endif

604
    if (temp_dir == 0 || temp_dir[0] == 0)
605 606 607 608 609 610
        fname = defaultTemplate;
    else
    {
        fname = temp_dir;
        char ech = fname[fname.size() - 1];
        if(ech != '/' && ech != '\\')
611 612
            fname = fname + "/";
        fname = fname + "__opencv_temp.XXXXXX";
613 614 615
    }

    const int fd = mkstemp((char*)fname.c_str());
616
    if (fd == -1) return String();
617

618 619
    close(fd);
    remove(fname.c_str());
620
# endif
621

622
    if (suffix)
623 624
    {
        if (suffix[0] != '.')
625
            return fname + "." + suffix;
626
        else
627
            return fname + suffix;
628 629
    }
    return fname;
630 631
}

632 633 634 635 636 637 638 639 640
static CvErrorCallback customErrorCallback = 0;
static void* customErrorCallbackData = 0;
static bool breakOnError = false;

bool setBreakOnError(bool value)
{
    bool prevVal = breakOnError;
    breakOnError = value;
    return prevVal;
641
}
642 643 644

void error( const Exception& exc )
{
645
    if (customErrorCallback != 0)
646 647 648 649 650 651 652 653 654 655 656 657
        customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(),
                            exc.file.c_str(), exc.line, customErrorCallbackData);
    else
    {
        const char* errorStr = cvErrorStr(exc.code);
        char buf[1 << 16];

        sprintf( buf, "OpenCV Error: %s (%s) in %s, file %s, line %d",
            errorStr, exc.err.c_str(), exc.func.size() > 0 ?
            exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
        fprintf( stderr, "%s\n", buf );
        fflush( stderr );
658
#  ifdef __ANDROID__
659 660
        __android_log_print(ANDROID_LOG_ERROR, "cv::error()", "%s", buf);
#  endif
661
    }
662

663 664 665 666 667
    if(breakOnError)
    {
        static volatile int* p = 0;
        *p = 0;
    }
668

669 670
    throw exc;
}
671

672 673 674 675 676
void error(int _code, const String& _err, const char* _func, const char* _file, int _line)
{
    error(cv::Exception(_code, _err, _func, _file, _line));
}

677 678 679 680 681
CvErrorCallback
redirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata)
{
    if( prevUserdata )
        *prevUserdata = customErrorCallbackData;
682

683
    CvErrorCallback prevCallback = customErrorCallback;
684 685

    customErrorCallback     = errCallback;
686
    customErrorCallbackData = userdata;
687

688 689
    return prevCallback;
}
690

691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
}

CV_IMPL int cvCheckHardwareSupport(int feature)
{
    CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
    return cv::currentFeatures->have[feature];
}

CV_IMPL int cvUseOptimized( int flag )
{
    int prevMode = cv::useOptimizedFlag;
    cv::setUseOptimized( flag != 0 );
    return prevMode;
}

CV_IMPL int64  cvGetTickCount(void)
{
    return cv::getTickCount();
}

CV_IMPL double cvGetTickFrequency(void)
{
    return cv::getTickFrequency()*1e-6;
}

CV_IMPL CvErrorCallback
cvRedirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata)
{
    return cv::redirectError(errCallback, userdata, prevUserdata);
}

CV_IMPL int cvNulDevReport( int, const char*, const char*,
                            const char*, int, void* )
{
    return 0;
}

CV_IMPL int cvStdErrReport( int, const char*, const char*,
                            const char*, int, void* )
{
    return 0;
}

CV_IMPL int cvGuiBoxReport( int, const char*, const char*,
                            const char*, int, void* )
{
    return 0;
}

CV_IMPL int cvGetErrInfo( const char**, const char**, const char**, int* )
{
    return 0;
}


CV_IMPL const char* cvErrorStr( int status )
{
    static char buf[256];

    switch (status)
    {
752 753 754 755 756 757 758 759 760 761 762 763
    case CV_StsOk :                  return "No Error";
    case CV_StsBackTrace :           return "Backtrace";
    case CV_StsError :               return "Unspecified error";
    case CV_StsInternal :            return "Internal error";
    case CV_StsNoMem :               return "Insufficient memory";
    case CV_StsBadArg :              return "Bad argument";
    case CV_StsNoConv :              return "Iterations do not converge";
    case CV_StsAutoTrace :           return "Autotrace call";
    case CV_StsBadSize :             return "Incorrect size of input array";
    case CV_StsNullPtr :             return "Null pointer";
    case CV_StsDivByZero :           return "Division by zero occured";
    case CV_BadStep :                return "Image step is wrong";
764 765
    case CV_StsInplaceNotSupported : return "Inplace operation is not supported";
    case CV_StsObjectNotFound :      return "Requested object was not found";
766 767 768 769 770 771 772 773 774 775 776 777 778 779
    case CV_BadDepth :               return "Input image depth is not supported by function";
    case CV_StsUnmatchedFormats :    return "Formats of input arguments do not match";
    case CV_StsUnmatchedSizes :      return "Sizes of input arguments do not match";
    case CV_StsOutOfRange :          return "One of arguments\' values is out of range";
    case CV_StsUnsupportedFormat :   return "Unsupported format or combination of formats";
    case CV_BadCOI :                 return "Input COI is not supported";
    case CV_BadNumChannels :         return "Bad number of channels";
    case CV_StsBadFlag :             return "Bad flag (parameter or structure field)";
    case CV_StsBadPoint :            return "Bad parameter of type CvPoint";
    case CV_StsBadMask :             return "Bad type of mask argument";
    case CV_StsParseError :          return "Parsing error";
    case CV_StsNotImplemented :      return "The function/feature is not implemented";
    case CV_StsBadMemBlock :         return "Memory block has been corrupted";
    case CV_StsAssert :              return "Assertion failed";
V
Vladislav Vinogradov 已提交
780
    case CV_GpuNotSupported :        return "No CUDA support";
781 782 783
    case CV_GpuApiCallError :        return "Gpu API call";
    case CV_OpenGlNotSupported :     return "No OpenGL support";
    case CV_OpenGlApiCallError :     return "OpenGL API call";
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
    };

    sprintf(buf, "Unknown %s code %d", status >= 0 ? "status":"error", status);
    return buf;
}

CV_IMPL int cvGetErrMode(void)
{
    return 0;
}

CV_IMPL int cvSetErrMode(int)
{
    return 0;
}

800
CV_IMPL int cvGetErrStatus(void)
801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
{
    return 0;
}

CV_IMPL void cvSetErrStatus(int)
{
}


CV_IMPL void cvError( int code, const char* func_name,
                      const char* err_msg,
                      const char* file_name, int line )
{
    cv::error(cv::Exception(code, err_msg, func_name, file_name, line));
}

/* function, which converts int to int */
CV_IMPL int
cvErrorFromIppStatus( int status )
{
    switch (status)
    {
823 824 825 826 827 828 829 830
    case CV_BADSIZE_ERR:               return CV_StsBadSize;
    case CV_BADMEMBLOCK_ERR:           return CV_StsBadMemBlock;
    case CV_NULLPTR_ERR:               return CV_StsNullPtr;
    case CV_DIV_BY_ZERO_ERR:           return CV_StsDivByZero;
    case CV_BADSTEP_ERR:               return CV_BadStep;
    case CV_OUTOFMEM_ERR:              return CV_StsNoMem;
    case CV_BADARG_ERR:                return CV_StsBadArg;
    case CV_NOTDEFINED_ERR:            return CV_StsError;
831
    case CV_INPLACE_NOT_SUPPORTED_ERR: return CV_StsInplaceNotSupported;
832 833 834 835 836 837 838 839 840 841 842 843 844 845
    case CV_NOTFOUND_ERR:              return CV_StsObjectNotFound;
    case CV_BADCONVERGENCE_ERR:        return CV_StsNoConv;
    case CV_BADDEPTH_ERR:              return CV_BadDepth;
    case CV_UNMATCHED_FORMATS_ERR:     return CV_StsUnmatchedFormats;
    case CV_UNSUPPORTED_COI_ERR:       return CV_BadCOI;
    case CV_UNSUPPORTED_CHANNELS_ERR:  return CV_BadNumChannels;
    case CV_BADFLAG_ERR:               return CV_StsBadFlag;
    case CV_BADRANGE_ERR:              return CV_StsBadArg;
    case CV_BADCOEF_ERR:               return CV_StsBadArg;
    case CV_BADFACTOR_ERR:             return CV_StsBadArg;
    case CV_BADPOINT_ERR:              return CV_StsBadPoint;

    default:
      return CV_StsError;
846 847 848
    }
}

849 850 851
namespace cv {
bool __termination = false;
}
852

853 854 855 856 857 858 859
namespace cv
{

#if defined WIN32 || defined _WIN32 || defined WINCE

struct Mutex::Impl
{
860 861 862 863 864 865 866 867 868
    Impl()
    {
#if (_WIN32_WINNT >= 0x0600)
        ::InitializeCriticalSectionEx(&cs, 1000, 0);
#else
        ::InitializeCriticalSection(&cs);
#endif
        refcount = 1;
    }
869
    ~Impl() { DeleteCriticalSection(&cs); }
870

871 872 873
    void lock() { EnterCriticalSection(&cs); }
    bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
    void unlock() { LeaveCriticalSection(&cs); }
874

875 876 877
    CRITICAL_SECTION cs;
    int refcount;
};
878

879 880 881 882
#else

struct Mutex::Impl
{
I
Ilya Lavrenov 已提交
883 884 885 886 887 888 889 890 891 892 893
    Impl()
    {
        pthread_mutexattr_t attr;
        pthread_mutexattr_init(&attr);
        pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
        pthread_mutex_init(&mt, &attr);
        pthread_mutexattr_destroy(&attr);

        refcount = 1;
    }
    ~Impl() { pthread_mutex_destroy(&mt); }
894

I
Ilya Lavrenov 已提交
895 896 897
    void lock() { pthread_mutex_lock(&mt); }
    bool trylock() { return pthread_mutex_trylock(&mt) == 0; }
    void unlock() { pthread_mutex_unlock(&mt); }
898

I
Ilya Lavrenov 已提交
899
    pthread_mutex_t mt;
900 901 902 903 904 905 906 907 908
    int refcount;
};

#endif

Mutex::Mutex()
{
    impl = new Mutex::Impl;
}
909

910 911 912 913 914 915
Mutex::~Mutex()
{
    if( CV_XADD(&impl->refcount, -1) == 1 )
        delete impl;
    impl = 0;
}
916

917 918 919 920 921 922 923 924 925 926 927 928 929 930
Mutex::Mutex(const Mutex& m)
{
    impl = m.impl;
    CV_XADD(&impl->refcount, 1);
}

Mutex& Mutex::operator = (const Mutex& m)
{
    CV_XADD(&m.impl->refcount, 1);
    if( CV_XADD(&impl->refcount, -1) == 1 )
        delete impl;
    impl = m.impl;
    return *this;
}
931

932 933
void Mutex::lock() { impl->lock(); }
void Mutex::unlock() { impl->unlock(); }
934
bool Mutex::trylock() { return impl->trylock(); }
935

A
Alexander Alekhin 已提交
936 937 938

//////////////////////////////// thread-local storage ////////////////////////////////

P
Pavel Vlasov 已提交
939 940 941 942 943 944 945 946 947 948 949
#ifdef WIN32
#ifdef _MSC_VER
#pragma warning(disable:4505) // unreferenced local function has been removed
#endif
#ifndef TLS_OUT_OF_INDEXES
#define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF)
#endif
#endif

// TLS platform abstraction layer
class TlsAbstraction
A
Alexander Alekhin 已提交
950 951
{
public:
P
Pavel Vlasov 已提交
952 953 954 955
    TlsAbstraction();
    ~TlsAbstraction();
    void* GetData() const;
    void  SetData(void *pData);
A
Alexander Alekhin 已提交
956

P
Pavel Vlasov 已提交
957
private:
A
Alexander Alekhin 已提交
958
#ifdef WIN32
P
Pavel Vlasov 已提交
959 960
#ifndef WINRT
    DWORD tlsKey;
A
Alexander Alekhin 已提交
961
#endif
P
Pavel Vlasov 已提交
962 963 964 965
#else // WIN32
    pthread_key_t  tlsKey;
#endif
};
A
Alexander Alekhin 已提交
966

P
Pavel Vlasov 已提交
967
#ifdef WIN32
968
#ifdef WINRT
P
Pavel Vlasov 已提交
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
static __declspec( thread ) void* tlsData = NULL; // using C++11 thread attribute for local thread data
TlsAbstraction::TlsAbstraction() {}
TlsAbstraction::~TlsAbstraction() {}
void* TlsAbstraction::GetData() const
{
    return tlsData;
}
void  TlsAbstraction::SetData(void *pData)
{
    tlsData = pData;
}
#else //WINRT
TlsAbstraction::TlsAbstraction()
{
    tlsKey = TlsAlloc();
    CV_Assert(tlsKey != TLS_OUT_OF_INDEXES);
}
TlsAbstraction::~TlsAbstraction()
{
    TlsFree(tlsKey);
}
void* TlsAbstraction::GetData() const
{
    return TlsGetValue(tlsKey);
}
void  TlsAbstraction::SetData(void *pData)
{
    CV_Assert(TlsSetValue(tlsKey, pData) == TRUE);
}
#endif
#else // WIN32
TlsAbstraction::TlsAbstraction()
{
    CV_Assert(pthread_key_create(&tlsKey, NULL) == 0);
}
TlsAbstraction::~TlsAbstraction()
{
    CV_Assert(pthread_key_delete(tlsKey) == 0);
}
void* TlsAbstraction::GetData() const
{
    return pthread_getspecific(tlsKey);
}
void  TlsAbstraction::SetData(void *pData)
{
    CV_Assert(pthread_setspecific(tlsKey, pData) == 0);
}
#endif
A
Alexander Alekhin 已提交
1017

P
Pavel Vlasov 已提交
1018 1019 1020 1021
// Per-thread data structure
struct ThreadData
{
    ThreadData()
A
Alexander Alekhin 已提交
1022
    {
P
Pavel Vlasov 已提交
1023 1024
        idx = 0;
        slots.reserve(32);
A
Alexander Alekhin 已提交
1025 1026
    }

P
Pavel Vlasov 已提交
1027 1028 1029
    std::vector<void*> slots; // Data array for a thread
    size_t idx;               // Thread index in TLS storage. This is not OS thread ID!
};
A
Alexander Alekhin 已提交
1030

P
Pavel Vlasov 已提交
1031 1032 1033 1034 1035
// Main TLS storage class
class TlsStorage
{
public:
    TlsStorage()
A
Alexander Alekhin 已提交
1036
    {
P
Pavel Vlasov 已提交
1037 1038
        tlsSlots = 0;
        threads.reserve(32);
A
Alexander Alekhin 已提交
1039
    }
P
Pavel Vlasov 已提交
1040
    ~TlsStorage()
A
Alexander Alekhin 已提交
1041
    {
P
Pavel Vlasov 已提交
1042
        for(size_t i = 0; i < threads.size(); i++)
A
Alexander Alekhin 已提交
1043
        {
P
Pavel Vlasov 已提交
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
            if(threads[i])
            {
                /* Current architecture doesn't allow proper global objects relase, so this check can cause crashes

                // Check if all slots were properly cleared
                for(size_t j = 0; j < threads[i]->slots.size(); j++)
                {
                    CV_Assert(threads[i]->slots[j] == 0);
                }
                */
                delete threads[i];
            }
A
Alexander Alekhin 已提交
1056
        }
P
Pavel Vlasov 已提交
1057
        threads.clear();
A
Alexander Alekhin 已提交
1058 1059
    }

P
Pavel Vlasov 已提交
1060
    void releaseThread()
A
Alexander Alekhin 已提交
1061
    {
P
Pavel Vlasov 已提交
1062 1063 1064
        AutoLock guard(mtxGlobalAccess);
        ThreadData *pTD = (ThreadData*)tls.GetData();
        for(size_t i = 0; i < threads.size(); i++)
1065
        {
P
Pavel Vlasov 已提交
1066 1067 1068 1069 1070
            if(pTD == threads[i])
            {
                threads[i] = 0;
                break;
            }
1071
        }
P
Pavel Vlasov 已提交
1072 1073
        tls.SetData(0);
        delete pTD;
A
Alexander Alekhin 已提交
1074 1075
    }

P
Pavel Vlasov 已提交
1076 1077
    // Reserve TLS storage index
    size_t reserveSlot()
A
Alexander Alekhin 已提交
1078
    {
P
Pavel Vlasov 已提交
1079 1080 1081
        AutoLock guard(mtxGlobalAccess);
        tlsSlots++;
        return (tlsSlots-1);
A
Alexander Alekhin 已提交
1082 1083
    }

P
Pavel Vlasov 已提交
1084 1085
    // Release TLS storage index and pass assosiated data to caller
    void releaseSlot(size_t slotIdx, std::vector<void*> &dataVec)
A
Alexander Alekhin 已提交
1086
    {
P
Pavel Vlasov 已提交
1087 1088
        AutoLock guard(mtxGlobalAccess);
        CV_Assert(tlsSlots > slotIdx);
A
Alexander Alekhin 已提交
1089

P
Pavel Vlasov 已提交
1090
        for(size_t i = 0; i < threads.size(); i++)
A
Alexander Alekhin 已提交
1091
        {
1092 1093
            std::vector<void*>& thread_slots = threads[i]->slots;
            if (thread_slots.size() > slotIdx && thread_slots[slotIdx])
P
Pavel Vlasov 已提交
1094
            {
1095
                dataVec.push_back(thread_slots[slotIdx]);
P
Pavel Vlasov 已提交
1096 1097
                threads[i]->slots[slotIdx] = 0;
            }
A
Alexander Alekhin 已提交
1098
        }
P
Pavel Vlasov 已提交
1099 1100 1101
        // If we removing last element, decriment slots size to save space
        if(tlsSlots-1 == slotIdx)
            tlsSlots--;
A
Alexander Alekhin 已提交
1102 1103
    }

P
Pavel Vlasov 已提交
1104 1105
    // Get data by TLS storage index
    void* getData(size_t slotIdx) const
A
Alexander Alekhin 已提交
1106
    {
P
Pavel Vlasov 已提交
1107
        CV_Assert(tlsSlots > slotIdx);
A
Alexander Alekhin 已提交
1108

P
Pavel Vlasov 已提交
1109 1110 1111 1112 1113
        ThreadData* threadData = (ThreadData*)tls.GetData();
        if(threadData && threadData->slots.size() > slotIdx)
            return threadData->slots[slotIdx];

        return NULL;
A
Alexander Alekhin 已提交
1114 1115
    }

P
Pavel Vlasov 已提交
1116 1117
    // Set data to storage index
    void setData(size_t slotIdx, void* pData)
A
Alexander Alekhin 已提交
1118
    {
P
Pavel Vlasov 已提交
1119 1120 1121 1122
        CV_Assert(pData != NULL);

        ThreadData* threadData = (ThreadData*)tls.GetData();
        if(!threadData)
A
Alexander Alekhin 已提交
1123
        {
P
Pavel Vlasov 已提交
1124 1125 1126 1127 1128 1129 1130
            threadData = new ThreadData;
            tls.SetData((void*)threadData);
            {
                AutoLock guard(mtxGlobalAccess);
                threadData->idx = threads.size();
                threads.push_back(threadData);
            }
A
Alexander Alekhin 已提交
1131
        }
P
Pavel Vlasov 已提交
1132 1133 1134 1135

        if(slotIdx >= threadData->slots.size())
            threadData->slots.resize(slotIdx+1);
        threadData->slots[slotIdx] = pData;
A
Alexander Alekhin 已提交
1136
    }
P
Pavel Vlasov 已提交
1137 1138 1139 1140 1141 1142 1143

private:
    TlsAbstraction tls; // TLS abstraction layer instance

    Mutex  mtxGlobalAccess;           // Shared objects operation guard
    size_t tlsSlots;                  // TLS storage counter
    std::vector<ThreadData*> threads; // Array for all allocated data. Thread data pointers are placed here to allow data cleanup
A
Alexander Alekhin 已提交
1144
};
1145

P
Pavel Vlasov 已提交
1146 1147
// Create global TLS storage object
static TlsStorage &getTlsStorage()
1148
{
P
Pavel Vlasov 已提交
1149
    CV_SINGLETON_LAZY_INIT_REF(TlsStorage, new TlsStorage())
1150
}
A
Alexander Alekhin 已提交
1151 1152 1153

TLSDataContainer::TLSDataContainer()
{
P
Pavel Vlasov 已提交
1154
    key_ = (int)getTlsStorage().reserveSlot(); // Reserve key from TLS storage
1155 1156
}

A
Alexander Alekhin 已提交
1157 1158
TLSDataContainer::~TLSDataContainer()
{
P
Pavel Vlasov 已提交
1159
    CV_Assert(key_ == -1); // Key must be released in child object
A
Alexander Alekhin 已提交
1160 1161
}

P
Pavel Vlasov 已提交
1162
void TLSDataContainer::release()
A
Alexander Alekhin 已提交
1163
{
P
Pavel Vlasov 已提交
1164 1165 1166 1167 1168 1169
    std::vector<void*> data;
    data.reserve(32);
    getTlsStorage().releaseSlot(key_, data); // Release key and get stored data for proper destruction
    for(size_t i = 0; i < data.size(); i++)  // Delete all assosiated data
        deleteDataInstance(data[i]);
    key_ = -1;
A
Alexander Alekhin 已提交
1170 1171
}

P
Pavel Vlasov 已提交
1172
void* TLSDataContainer::getData() const
A
Alexander Alekhin 已提交
1173
{
P
Pavel Vlasov 已提交
1174 1175
    void* pData = getTlsStorage().getData(key_); // Check if data was already allocated
    if(!pData)
A
Alexander Alekhin 已提交
1176
    {
P
Pavel Vlasov 已提交
1177 1178 1179
        // Create new data instance and save it to TLS storage
        pData = createDataInstance();
        getTlsStorage().setData(key_, pData);
A
Alexander Alekhin 已提交
1180
    }
P
Pavel Vlasov 已提交
1181
    return pData;
A
Alexander Alekhin 已提交
1182 1183
}

1184 1185
TLSData<CoreTLSData>& getCoreTlsData()
{
1186
    CV_SINGLETON_LAZY_INIT_REF(TLSData<CoreTLSData>, new TLSData<CoreTLSData>())
1187 1188
}

P
Pavel Vlasov 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
#if defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE
#ifdef WINRT
    #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
#endif

extern "C"
BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved)
{
    if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
    {
        if (lpReserved != NULL) // called after ExitProcess() call
        {
            cv::__termination = true;
        }
        else
        {
            // Not allowed to free resources if lpReserved is non-null
            // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583.aspx
            cv::deleteThreadAllocData();
            cv::getTlsStorage().releaseThread();
        }
    }
    return TRUE;
}
#endif
1214

1215
#ifdef CV_COLLECT_IMPL_DATA
P
Pavel Vlasov 已提交
1216 1217
ImplCollector& getImplData()
{
1218
    CV_SINGLETON_LAZY_INIT_REF(ImplCollector, new ImplCollector())
P
Pavel Vlasov 已提交
1219 1220
}

1221 1222
void setImpl(int flags)
{
P
Pavel Vlasov 已提交
1223 1224 1225 1226 1227
    cv::AutoLock lock(getImplData().mutex);

    getImplData().implFlags = flags;
    getImplData().implCode.clear();
    getImplData().implFun.clear();
1228 1229 1230 1231
}

void addImpl(int flag, const char* func)
{
P
Pavel Vlasov 已提交
1232 1233 1234
    cv::AutoLock lock(getImplData().mutex);

    getImplData().implFlags |= flag;
1235 1236
    if(func) // use lazy collection if name was not specified
    {
P
Pavel Vlasov 已提交
1237 1238
        size_t index = getImplData().implCode.size();
        if(!index || (getImplData().implCode[index-1] != flag || getImplData().implFun[index-1].compare(func))) // avoid duplicates
1239
        {
P
Pavel Vlasov 已提交
1240 1241
            getImplData().implCode.push_back(flag);
            getImplData().implFun.push_back(func);
1242 1243 1244 1245 1246 1247
        }
    }
}

int getImpl(std::vector<int> &impl, std::vector<String> &funName)
{
P
Pavel Vlasov 已提交
1248 1249 1250 1251 1252
    cv::AutoLock lock(getImplData().mutex);

    impl    = getImplData().implCode;
    funName = getImplData().implFun;
    return getImplData().implFlags; // return actual flags for lazy collection
1253 1254 1255 1256
}

bool useCollection()
{
P
Pavel Vlasov 已提交
1257
    return getImplData().useCollection;
1258 1259 1260 1261
}

void setUseCollection(bool flag)
{
P
Pavel Vlasov 已提交
1262 1263 1264
    cv::AutoLock lock(getImplData().mutex);

    getImplData().useCollection = flag;
1265 1266 1267
}
#endif

I
Ilya Lavrenov 已提交
1268 1269 1270
namespace ipp
{

I
Ilya Lavrenov 已提交
1271
static int ippStatus = 0; // 0 - all is ok, -1 - IPP functions failed
I
Ilya Lavrenov 已提交
1272 1273
static const char * funcname = NULL, * filename = NULL;
static int linen = 0;
I
Ilya Lavrenov 已提交
1274 1275

void setIppStatus(int status, const char * const _funcname, const char * const _filename, int _line)
I
Ilya Lavrenov 已提交
1276
{
I
Ilya Lavrenov 已提交
1277 1278 1279 1280
    ippStatus = status;
    funcname = _funcname;
    filename = _filename;
    linen = _line;
I
Ilya Lavrenov 已提交
1281 1282 1283 1284
}

int getIppStatus()
{
I
Ilya Lavrenov 已提交
1285 1286 1287 1288 1289 1290
    return ippStatus;
}

String getIppErrorLocation()
{
    return format("%s:%d %s", filename ? filename : "", linen, funcname ? funcname : "");
I
Ilya Lavrenov 已提交
1291 1292
}

1293 1294 1295
bool useIPP()
{
#ifdef HAVE_IPP
1296
    CoreTLSData* data = getCoreTlsData().get();
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
    if(data->useIPP < 0)
    {
        const char* pIppEnv = getenv("OPENCV_IPP");
        if(pIppEnv && (cv::String(pIppEnv) == "disabled"))
            data->useIPP = false;
        else
            data->useIPP = true;
    }
    return (data->useIPP > 0);
#else
    return false;
#endif
}

void setUseIPP(bool flag)
{
1313
    CoreTLSData* data = getCoreTlsData().get();
1314 1315 1316 1317 1318 1319 1320 1321
#ifdef HAVE_IPP
    data->useIPP = flag;
#else
    (void)flag;
    data->useIPP = false;
#endif
}

I
Ilya Lavrenov 已提交
1322 1323
} // namespace ipp

1324 1325
} // namespace cv

1326 1327 1328 1329 1330 1331
#ifdef HAVE_TEGRA_OPTIMIZATION

namespace tegra {

bool useTegra()
{
1332
    cv::CoreTLSData* data = cv::getCoreTlsData().get();
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

    if (data->useTegra < 0)
    {
        const char* pTegraEnv = getenv("OPENCV_TEGRA");
        if (pTegraEnv && (cv::String(pTegraEnv) == "disabled"))
            data->useTegra = false;
        else
            data->useTegra = true;
    }

    return (data->useTegra > 0);
}

void setUseTegra(bool flag)
{
1348
    cv::CoreTLSData* data = cv::getCoreTlsData().get();
1349 1350 1351 1352 1353 1354 1355
    data->useTegra = flag;
}

} // namespace tegra

#endif

1356
/* End of file. */