system.cpp 31.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
/*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.
// 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"

45 46 47 48 49 50
#ifdef _MSC_VER
# if _MSC_VER >= 1700
#  pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
# endif
#endif

51
#if defined WIN32 || defined _WIN32 || defined WINCE
52 53 54 55
#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>
56
#if (_WIN32_WINNT >= 0x0602)
57
  #include <synchapi.h>
58
#endif
59 60 61 62
#undef small
#undef min
#undef max
#undef abs
63 64 65 66
#include <tchar.h>
#if defined _MSC_VER
  #if _MSC_VER >= 1400
    #include <intrin.h>
67
  #elif defined _M_IX86
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    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
        }
    }
  #endif
#endif
87 88 89

#ifdef HAVE_WINRT
#include <wrl/client.h>
GregoryMorse's avatar
GregoryMorse committed
90 91 92 93
#ifndef __cplusplus_winrt
#include <windows.storage.h>
#pragma comment(lib, "runtimeobject.lib")
#endif
94 95 96

std::wstring GetTempPathWinRT()
{
GregoryMorse's avatar
GregoryMorse committed
97
#ifdef __cplusplus_winrt
98
    return std::wstring(Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data());
GregoryMorse's avatar
GregoryMorse committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
#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;
    if (FAILED(RoGetActivationFactory(str, IID_PPV_ARGS(appdataFactory.ReleaseAndGetAddressOf()))))
        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
125 126 127 128
}

std::wstring GetTempFileNameWinRT(std::wstring prefix)
{
129 130 131
    wchar_t guidStr[40];
    GUID g;
    CoCreateGuid(&g);
132
    wchar_t* mask = L"%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x";
133 134 135 136
    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]));
137 138 139 140 141

    return prefix + std::wstring(guidStr);
}

#endif
142 143 144 145 146
#else
#include <pthread.h>
#include <sys/time.h>
#include <time.h>

147
#if defined __MACH__ && defined __APPLE__
148 149 150 151 152 153 154 155 156 157 158 159
#include <mach/mach.h>
#include <mach/mach_time.h>
#endif

#endif

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

#include <stdarg.h>

160
#if defined __linux__ || defined __APPLE__ || defined __EMSCRIPTEN__
161 162
#include <unistd.h>
#include <stdio.h>
163
#include <sys/types.h>
Andrey Kamaev's avatar
Andrey Kamaev committed
164 165 166
#if defined ANDROID
#include <sys/sysconf.h>
#else
167 168
#include <sys/sysctl.h>
#endif
Andrey Kamaev's avatar
Andrey Kamaev committed
169
#endif
170

171 172 173 174
#ifdef ANDROID
# include <android/log.h>
#endif

175 176 177
namespace cv
{

178 179 180 181 182 183 184 185 186 187 188 189
Exception::Exception() { code = 0; line = 0; }

Exception::Exception(int _code, const string& _err, const string& _func, const string& _file, int _line)
: 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.
190
 */
191 192 193 194 195 196 197 198 199
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());
}
200

201 202 203
struct HWFeatures
{
    enum { MAX_FEATURE = CV_HARDWARE_MAX_FEATURE };
204 205 206

    HWFeatures(void)
     {
207 208 209
        memset( have, 0, sizeof(have) );
        x86_family = 0;
    }
210 211

    static HWFeatures initialize(void)
212 213
    {
        HWFeatures f;
214 215
        int cpuid_data[4] = { 0, 0, 0, 0 };

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
    #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
241

242 243 244
        f.x86_family = (cpuid_data[0] >> 8) & 15;
        if( f.x86_family >= 6 )
        {
245 246 247 248 249
            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;
250 251
            f.have[CV_CPU_SSE4_1] = (cpuid_data[2] & (1<<19)) != 0;
            f.have[CV_CPU_SSE4_2] = (cpuid_data[2] & (1<<20)) != 0;
252
            f.have[CV_CPU_POPCNT] = (cpuid_data[2] & (1<<23)) != 0;
253
            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
254
        }
255

256 257
        return f;
    }
258

259 260 261
    int x86_family;
    bool have[MAX_FEATURE+1];
};
262 263

static HWFeatures  featuresEnabled = HWFeatures::initialize(), featuresDisabled = HWFeatures();
264 265 266 267 268 269 270 271 272
static HWFeatures* currentFeatures = &featuresEnabled;

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


273 274
volatile bool useOptimizedFlag = true;
#ifdef HAVE_IPP
275 276
struct IPPInitializer
{
277
    IPPInitializer(void) { ippStaticInit(); }
278 279 280 281 282
};

IPPInitializer ippInitializer;
#endif

283
volatile bool USE_SSE2 = featuresEnabled.have[CV_CPU_SSE2];
284 285
volatile bool USE_SSE4_2 = featuresEnabled.have[CV_CPU_SSE4_2];
volatile bool USE_AVX = featuresEnabled.have[CV_CPU_AVX];
286

287 288 289 290
void setUseOptimized( bool flag )
{
    useOptimizedFlag = flag;
    currentFeatures = flag ? &featuresEnabled : &featuresDisabled;
291
    USE_SSE2 = currentFeatures->have[CV_CPU_SSE2];
292 293
}

294
bool useOptimized(void)
295 296 297
{
    return useOptimizedFlag;
}
298 299

int64 getTickCount(void)
300
{
301
#if defined WIN32 || defined _WIN32 || defined WINCE
302 303 304 305 306 307 308
    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;
309
#elif defined __MACH__ && defined __APPLE__
310
    return (int64)mach_absolute_time();
311
#else
312 313 314 315 316 317 318
    struct timeval tv;
    struct timezone tz;
    gettimeofday( &tv, &tz );
    return (int64)tv.tv_sec*1000000 + tv.tv_usec;
#endif
}

319
double getTickFrequency(void)
320
{
321
#if defined WIN32 || defined _WIN32 || defined WINCE
322 323 324 325 326
    LARGE_INTEGER freq;
    QueryPerformanceFrequency(&freq);
    return (double)freq.QuadPart;
#elif defined __linux || defined __linux__
    return 1e9;
327
#elif defined __MACH__ && defined __APPLE__
328 329 330 331 332 333 334
    static double freq = 0;
    if( freq == 0 )
    {
        mach_timebase_info_data_t sTimebaseInfo;
        mach_timebase_info(&sTimebaseInfo);
        freq = sTimebaseInfo.denom*1e9/sTimebaseInfo.numer;
    }
335
    return freq;
336 337 338 339 340
#else
    return 1e6;
#endif
}

341
#if defined __GNUC__ && (defined __i386__ || defined __x86_64__ || defined __ppc__)
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
#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)
{
363
    int64 result = 0;
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    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

383
#elif defined _MSC_VER && defined WIN32 && defined _M_IX86
384 385 386 387 388 389 390 391 392

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

#else

393 394 395 396 397 398 399
#ifdef HAVE_IPP
int64 getCPUTickCount(void)
{
    return ippGetCpuClocks();
}
#else
int64 getCPUTickCount(void)
400 401 402
{
    return getTickCount();
}
403
#endif
404 405 406

#endif

407 408 409 410 411 412 413 414
const std::string& getBuildInformation()
{
    static std::string build_info =
#include "version_string.inc"
    ;
    return build_info;
}

415 416 417 418 419 420 421 422 423
string format( const char* fmt, ... )
{
    char buf[1 << 16];
    va_list args;
    va_start( args, fmt );
    vsprintf( buf, fmt, args );
    return string(buf);
}

424 425
string tempfile( const char* suffix )
{
426 427
#ifdef HAVE_WINRT
    std::wstring temp_dir = L"";
428
    const wchar_t* opencv_temp_dir = _wgetenv(L"OPENCV_TEMP_PATH");
429 430 431
    if (opencv_temp_dir)
        temp_dir = std::wstring(opencv_temp_dir);
#else
432
    const char *temp_dir = getenv("OPENCV_TEMP_PATH");
433
#endif
434 435
    string fname;

436
#if defined WIN32 || defined _WIN32
437 438 439 440 441 442 443 444 445 446 447 448 449 450
#ifdef HAVE_WINRT
    RoInitialize(RO_INIT_MULTITHREADED);
    std::wstring temp_dir2;
    if (temp_dir.empty())
        temp_dir = GetTempPathWinRT();

    std::wstring temp_file;
    temp_file = GetTempFileNameWinRT(L"ocv");
    if (temp_file.empty())
        return std::string();

    temp_file = temp_dir + std::wstring(L"\\") + temp_file;
    DeleteFileW(temp_file.c_str());

451 452 453
    char aname[MAX_PATH];
    size_t copied = wcstombs(aname, temp_file.c_str(), MAX_PATH);
    CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
454 455 456
    fname = std::string(aname);
    RoUninitialize();
#else
457 458
    char temp_dir2[MAX_PATH] = { 0 };
    char temp_file[MAX_PATH] = { 0 };
459

460 461 462 463 464
    if (temp_dir == 0 || temp_dir[0] == 0)
    {
        ::GetTempPathA(sizeof(temp_dir2), temp_dir2);
        temp_dir = temp_dir2;
    }
465
    if(0 == ::GetTempFileNameA(temp_dir, "ocv", 0, temp_file))
466 467
        return string();

Roy Reapor's avatar
Roy Reapor committed
468 469
    DeleteFileA(temp_file);

470
    fname = temp_file;
471
#endif
472 473 474 475 476 477 478 479
# 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

480
    if (temp_dir == 0 || temp_dir[0] == 0)
481 482 483 484 485 486 487 488 489 490 491
        fname = defaultTemplate;
    else
    {
        fname = temp_dir;
        char ech = fname[fname.size() - 1];
        if(ech != '/' && ech != '\\')
            fname += "/";
        fname += "__opencv_temp.XXXXXX";
    }

    const int fd = mkstemp((char*)fname.c_str());
492 493
    if (fd == -1) return string();

494 495
    close(fd);
    remove(fname.c_str());
496
# endif
497

498
    if (suffix)
499 500
    {
        if (suffix[0] != '.')
501
            return fname + "." + suffix;
502
        else
503
            return fname + suffix;
504 505
    }
    return fname;
506 507
}

508 509 510 511 512 513 514 515 516
static CvErrorCallback customErrorCallback = 0;
static void* customErrorCallbackData = 0;
static bool breakOnError = false;

bool setBreakOnError(bool value)
{
    bool prevVal = breakOnError;
    breakOnError = value;
    return prevVal;
517
}
518 519 520

void error( const Exception& exc )
{
521
    if (customErrorCallback != 0)
522 523 524 525 526 527 528 529 530 531 532 533
        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 );
534
#  ifdef __ANDROID__
535 536
        __android_log_print(ANDROID_LOG_ERROR, "cv::error()", "%s", buf);
#  endif
537
    }
538

539 540 541 542 543
    if(breakOnError)
    {
        static volatile int* p = 0;
        *p = 0;
    }
544

545 546
    throw exc;
}
547

548 549 550 551 552
CvErrorCallback
redirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata)
{
    if( prevUserdata )
        *prevUserdata = customErrorCallbackData;
553

554
    CvErrorCallback prevCallback = customErrorCallback;
555 556

    customErrorCallback     = errCallback;
557
    customErrorCallbackData = userdata;
558

559 560
    return prevCallback;
}
561

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
}

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)
    {
623 624 625 626 627 628 629 630 631 632 633 634
    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";
635 636
    case CV_StsInplaceNotSupported : return "Inplace operation is not supported";
    case CV_StsObjectNotFound :      return "Requested object was not found";
637 638 639 640 641 642 643 644 645 646 647 648 649 650
    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";
651
    case CV_GpuNotSupported :        return "No GPU support";
652 653 654
    case CV_GpuApiCallError :        return "Gpu API call";
    case CV_OpenGlNotSupported :     return "No OpenGL support";
    case CV_OpenGlApiCallError :     return "OpenGL API call";
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670
    };

    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;
}

671
CV_IMPL int cvGetErrStatus(void)
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
{
    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)
    {
694 695 696 697 698 699 700 701
    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;
702
    case CV_INPLACE_NOT_SUPPORTED_ERR: return CV_StsInplaceNotSupported;
703 704 705 706 707 708 709 710 711 712 713 714 715 716
    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;
717 718 719 720 721
    }
}

static CvModuleInfo cxcore_info = { 0, "cxcore", CV_VERSION, 0 };

722
CvModuleInfo* CvModule::first = 0, *CvModule::last = 0;
723 724 725 726 727 728 729

CvModule::CvModule( CvModuleInfo* _info )
{
    cvRegisterModule( _info );
    info = last;
}

730
CvModule::~CvModule(void)
731 732 733 734 735 736
{
    if( info )
    {
        CvModuleInfo* p = first;
        for( ; p != 0 && p->next != info; p = p->next )
            ;
737

738 739
        if( p )
            p->next = info->next;
740

741 742
        if( first == info )
            first = info->next;
743

744 745
        if( last == info )
            last = p;
746

747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
        free( info );
        info = 0;
    }
}

CV_IMPL int
cvRegisterModule( const CvModuleInfo* module )
{
    CV_Assert( module != 0 && module->name != 0 && module->version != 0 );

    size_t name_len = strlen(module->name);
    size_t version_len = strlen(module->version);

    CvModuleInfo* module_copy = (CvModuleInfo*)malloc( sizeof(*module_copy) +
                                name_len + 1 + version_len + 1 );

    *module_copy = *module;
    module_copy->name = (char*)(module_copy + 1);
    module_copy->version = (char*)(module_copy + 1) + name_len + 1;

    memcpy( (void*)module_copy->name, module->name, name_len + 1 );
    memcpy( (void*)module_copy->version, module->version, version_len + 1 );
    module_copy->next = 0;

    if( CvModule::first == 0 )
        CvModule::first = module_copy;
    else
        CvModule::last->next = module_copy;
775

776
    CvModule::last = module_copy;
777

778 779 780 781 782 783 784 785
    return 0;
}

CvModule cxcore_module( &cxcore_info );

CV_IMPL void
cvGetModuleInfo( const char* name, const char **version, const char **plugin_list )
{
786
    static char joint_verinfo[1024]   = "";
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    static char plugin_list_buf[1024] = "";

    if( version )
        *version = 0;

    if( plugin_list )
        *plugin_list = 0;

    CvModuleInfo* module;

    if( version )
    {
        if( name )
        {
            size_t i, name_len = strlen(name);

            for( module = CvModule::first; module != 0; module = module->next )
            {
                if( strlen(module->name) == name_len )
                {
                    for( i = 0; i < name_len; i++ )
                    {
                        int c0 = toupper(module->name[i]), c1 = toupper(name[i]);
                        if( c0 != c1 )
                            break;
                    }
                    if( i == name_len )
                        break;
                }
            }
            if( !module )
                CV_Error( CV_StsObjectNotFound, "The module is not found" );

            *version = module->version;
        }
        else
        {
            char* ptr = joint_verinfo;

            for( module = CvModule::first; module != 0; module = module->next )
            {
                sprintf( ptr, "%s: %s%s", module->name, module->version, module->next ? ", " : "" );
                ptr += strlen(ptr);
            }

            *version = joint_verinfo;
        }
    }

    if( plugin_list )
        *plugin_list = plugin_list_buf;
}

840 841 842 843 844 845 846
namespace cv
{

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

struct Mutex::Impl
{
847 848 849 850 851 852 853 854 855
    Impl()
    {
#if (_WIN32_WINNT >= 0x0600)
        ::InitializeCriticalSectionEx(&cs, 1000, 0);
#else
        ::InitializeCriticalSection(&cs);
#endif
        refcount = 1;
    }
856
    ~Impl() { DeleteCriticalSection(&cs); }
857

858 859 860
    void lock() { EnterCriticalSection(&cs); }
    bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
    void unlock() { LeaveCriticalSection(&cs); }
861

862 863 864
    CRITICAL_SECTION cs;
    int refcount;
};
865

866
#ifndef __GNUC__
867 868 869 870 871 872 873 874
int _interlockedExchangeAdd(int* addr, int delta)
{
#if defined _MSC_VER && _MSC_VER >= 1500
    return (int)_InterlockedExchangeAdd((long volatile*)addr, delta);
#else
    return (int)InterlockedExchangeAdd((long volatile*)addr, delta);
#endif
}
875
#endif // __GNUC__
876 877 878 879 880 881 882 883 884

#elif defined __APPLE__

#include <libkern/OSAtomic.h>

struct Mutex::Impl
{
    Impl() { sl = OS_SPINLOCK_INIT; refcount = 1; }
    ~Impl() {}
885

886 887 888
    void lock() { OSSpinLockLock(&sl); }
    bool trylock() { return OSSpinLockTry(&sl); }
    void unlock() { OSSpinLockUnlock(&sl); }
889

890 891 892 893
    OSSpinLock sl;
    int refcount;
};

894
#elif defined __linux__ && !defined ANDROID
895 896 897 898 899

struct Mutex::Impl
{
    Impl() { pthread_spin_init(&sl, 0); refcount = 1; }
    ~Impl() { pthread_spin_destroy(&sl); }
900

901 902 903
    void lock() { pthread_spin_lock(&sl); }
    bool trylock() { return pthread_spin_trylock(&sl) == 0; }
    void unlock() { pthread_spin_unlock(&sl); }
904

905 906 907 908 909 910 911 912 913 914
    pthread_spinlock_t sl;
    int refcount;
};

#else

struct Mutex::Impl
{
    Impl() { pthread_mutex_init(&sl, 0); refcount = 1; }
    ~Impl() { pthread_mutex_destroy(&sl); }
915

916 917 918
    void lock() { pthread_mutex_lock(&sl); }
    bool trylock() { return pthread_mutex_trylock(&sl) == 0; }
    void unlock() { pthread_mutex_unlock(&sl); }
919

920 921 922 923 924 925 926 927 928 929
    pthread_mutex_t sl;
    int refcount;
};

#endif

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

931 932 933 934 935 936
Mutex::~Mutex()
{
    if( CV_XADD(&impl->refcount, -1) == 1 )
        delete impl;
    impl = 0;
}
937

938 939 940 941 942 943 944 945 946 947 948 949 950 951
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;
}
952

953 954
void Mutex::lock() { impl->lock(); }
void Mutex::unlock() { impl->unlock(); }
955
bool Mutex::trylock() { return impl->trylock(); }
956

957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984

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

class TLSStorage
{
    std::vector<void*> tlsData_;
public:
    TLSStorage() { tlsData_.reserve(16); }
    ~TLSStorage();
    inline void* getData(int key) const
    {
        CV_DbgAssert(key >= 0);
        return (key < (int)tlsData_.size()) ? tlsData_[key] : NULL;
    }
    inline void setData(int key, void* data)
    {
        CV_DbgAssert(key >= 0);
        if (key >= (int)tlsData_.size())
        {
            tlsData_.resize(key + 1, NULL);
        }
        tlsData_[key] = data;
    }

    inline static TLSStorage* get();
};

#ifdef WIN32
985
#ifdef _MSC_VER
986
#pragma warning(disable:4505) // unreferenced local function has been removed
987
#endif
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 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057

#ifdef HAVE_WINRT
    // using C++11 thread attribute for local thread data
    static __declspec( thread ) TLSStorage* g_tlsdata = NULL;

    static void deleteThreadData()
    {
        if (g_tlsdata)
        {
            delete g_tlsdata;
            g_tlsdata = NULL;
        }
    }

    inline TLSStorage* TLSStorage::get()
    {
        if (!g_tlsdata)
        {
            g_tlsdata = new TLSStorage;
        }
        return g_tlsdata;
    }
#else
#ifdef WINCE
#   define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF)
#endif
    static DWORD tlsKey = TLS_OUT_OF_INDEXES;

    static void deleteThreadData()
    {
        if(tlsKey != TLS_OUT_OF_INDEXES)
        {
            delete (TLSStorage*)TlsGetValue(tlsKey);
            TlsSetValue(tlsKey, NULL);
        }
    }

    inline TLSStorage* TLSStorage::get()
    {
        if (tlsKey == TLS_OUT_OF_INDEXES)
        {
            tlsKey = TlsAlloc();
            CV_Assert(tlsKey != TLS_OUT_OF_INDEXES);
        }
        TLSStorage* d = (TLSStorage*)TlsGetValue(tlsKey);
        if (!d)
        {
            d = new TLSStorage;
            TlsSetValue(tlsKey, d);
        }
        return d;
    }
#endif //HAVE_WINRT

#if defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE
#ifdef HAVE_WINRT
    #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
#endif

BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID);

BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID)
{
    if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
    {
        cv::deleteThreadAllocData();
        cv::deleteThreadRNGData();
        cv::deleteThreadData();
    }
    return TRUE;
1058
}
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
#endif

#else
    static pthread_key_t tlsKey = 0;
    static pthread_once_t tlsKeyOnce = PTHREAD_ONCE_INIT;

    static void deleteTLSStorage(void* data)
    {
        delete (TLSStorage*)data;
    }

    static void makeKey()
    {
        int errcode = pthread_key_create(&tlsKey, deleteTLSStorage);
        CV_Assert(errcode == 0);
    }

    inline TLSStorage* TLSStorage::get()
    {
        pthread_once(&tlsKeyOnce, makeKey);
        TLSStorage* d = (TLSStorage*)pthread_getspecific(tlsKey);
        if( !d )
        {
            d = new TLSStorage;
            pthread_setspecific(tlsKey, d);
        }
        return d;
    }
#endif

class TLSContainerStorage
{
    cv::Mutex mutex_;
    std::vector<TLSDataContainer*> tlsContainers_;
public:
    TLSContainerStorage() { }
    ~TLSContainerStorage()
    {
        for (size_t i = 0; i < tlsContainers_.size(); i++)
        {
            CV_DbgAssert(tlsContainers_[i] == NULL); // not all keys released
            tlsContainers_[i] = NULL;
        }
    }

    int allocateKey(TLSDataContainer* pContainer)
    {
        cv::AutoLock lock(mutex_);
        tlsContainers_.push_back(pContainer);
        return (int)tlsContainers_.size() - 1;
    }
    void releaseKey(int id, TLSDataContainer* pContainer)
    {
        cv::AutoLock lock(mutex_);
        CV_Assert(tlsContainers_[id] == pContainer);
        tlsContainers_[id] = NULL;
        // currently, we don't go into thread's TLSData and release data for this key
    }

    void destroyData(int key, void* data)
    {
        cv::AutoLock lock(mutex_);
        TLSDataContainer* k = tlsContainers_[key];
        if (!k)
            return;
        try
        {
            k->deleteDataInstance(data);
        }
        catch (...)
        {
            CV_DbgAssert(k == NULL); // Debug this!
        }
    }
};
1134 1135 1136 1137 1138 1139 1140 1141

// This is a wrapper function that will ensure 'tlsContainerStorage' is constructed on first use.
// For more information: http://www.parashift.com/c++-faq/static-init-order-on-first-use.html
static TLSContainerStorage& getTLSContainerStorage()
{
    static TLSContainerStorage *tlsContainerStorage = new TLSContainerStorage();
    return *tlsContainerStorage;
}
1142 1143 1144 1145

TLSDataContainer::TLSDataContainer()
    : key_(-1)
{
1146
    key_ = getTLSContainerStorage().allocateKey(this);
1147 1148 1149 1150
}

TLSDataContainer::~TLSDataContainer()
{
1151
    getTLSContainerStorage().releaseKey(key_, this);
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
    key_ = -1;
}

void* TLSDataContainer::getData() const
{
    CV_Assert(key_ >= 0);
    TLSStorage* tlsData = TLSStorage::get();
    void* data = tlsData->getData(key_);
    if (!data)
    {
        data = this->createDataInstance();
        CV_DbgAssert(data != NULL);
        tlsData->setData(key_, data);
    }
    return data;
}

TLSStorage::~TLSStorage()
{
    for (int i = 0; i < (int)tlsData_.size(); i++)
    {
        void*& data = tlsData_[i];
        if (data)
        {
1176
            getTLSContainerStorage().destroyData(i, data);
1177 1178 1179 1180 1181 1182 1183
            data = NULL;
        }
    }
    tlsData_.clear();
}

} // namespace cv
1184

1185
/* End of file. */