1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
14 // Copyright (C) 2009, Willow Garage Inc., all rights reserved.
15 // Copyright (C) 2015, Itseez Inc., all rights reserved.
16 // Third party copyrights are property of their respective owners.
18 // Redistribution and use in source and binary forms, with or without modification,
19 // are permitted provided that the following conditions are met:
21 // * Redistribution's of source code must retain the above copyright notice,
22 // this list of conditions and the following disclaimer.
24 // * Redistribution's in binary form must reproduce the above copyright notice,
25 // this list of conditions and the following disclaimer in the documentation
26 // and/or other materials provided with the distribution.
28 // * The name of the copyright holders may not be used to endorse or promote products
29 // derived from this software without specific prior written permission.
31 // This software is provided by the copyright holders and contributors "as is" and
32 // any express or implied warranties, including, but not limited to, the implied
33 // warranties of merchantability and fitness for a particular purpose are disclaimed.
34 // In no event shall the Intel Corporation or contributors be liable for any direct,
35 // indirect, incidental, special, exemplary, or consequential damages
36 // (including, but not limited to, procurement of substitute goods or services;
37 // loss of use, data, or profits; or business interruption) however caused
38 // and on any theory of liability, whether in contract, strict liability,
39 // or tort (including negligence or otherwise) arising in any way out of
40 // the use of this software, even if advised of the possibility of such damage.
44 #include "precomp.hpp"
49 static Mutex* __initialization_mutex = NULL;
50 Mutex& getInitializationMutex()
52 if (__initialization_mutex == NULL)
53 __initialization_mutex = new Mutex();
54 return *__initialization_mutex;
56 // force initialization (single-threaded environment)
57 Mutex* __initialization_mutex_initializer = &getInitializationMutex();
63 # pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
67 #if defined ANDROID || defined __linux__ || defined __FreeBSD__
71 #if defined ANDROID || defined __linux__
72 # include <linux/auxvec.h>
76 #if defined WIN32 || defined _WIN32 || defined WINCE
77 #ifndef _WIN32_WINNT // This is needed for the declaration of TryEnterCriticalSection in winbase.h with Visual Studio 2005 (and older?)
78 #define _WIN32_WINNT 0x0400 // http://msdn.microsoft.com/en-us/library/ms686857(VS.85).aspx
81 #if (_WIN32_WINNT >= 0x0602)
91 #include <wrl/client.h>
92 #ifndef __cplusplus_winrt
93 #include <windows.storage.h>
94 #pragma comment(lib, "runtimeobject.lib")
97 std::wstring GetTempPathWinRT()
99 #ifdef __cplusplus_winrt
100 return std::wstring(Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data());
102 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> appdataFactory;
103 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> appdataRef;
104 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> storagefolderRef;
105 Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageItem> storageitemRef;
107 HSTRING_HEADER hstrHead;
109 if (FAILED(WindowsCreateStringReference(RuntimeClass_Windows_Storage_ApplicationData,
110 (UINT32)wcslen(RuntimeClass_Windows_Storage_ApplicationData), &hstrHead, &str)))
112 if (FAILED(RoGetActivationFactory(str, IID_PPV_ARGS(appdataFactory.ReleaseAndGetAddressOf()))))
114 if (FAILED(appdataFactory->get_Current(appdataRef.ReleaseAndGetAddressOf())))
116 if (FAILED(appdataRef->get_TemporaryFolder(storagefolderRef.ReleaseAndGetAddressOf())))
118 if (FAILED(storagefolderRef.As(&storageitemRef)))
121 if (FAILED(storageitemRef->get_Path(&str)))
123 wstr = WindowsGetStringRawBuffer(str, NULL);
124 WindowsDeleteString(str);
129 std::wstring GetTempFileNameWinRT(std::wstring prefix)
134 wchar_t* mask = L"%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x";
135 swprintf(&guidStr[0], sizeof(guidStr)/sizeof(wchar_t), mask,
136 g.Data1, g.Data2, g.Data3, UINT(g.Data4[0]), UINT(g.Data4[1]),
137 UINT(g.Data4[2]), UINT(g.Data4[3]), UINT(g.Data4[4]),
138 UINT(g.Data4[5]), UINT(g.Data4[6]), UINT(g.Data4[7]));
140 return prefix.append(std::wstring(guidStr));
146 #include <sys/time.h>
149 #if defined __MACH__ && defined __APPLE__
150 #include <mach/mach.h>
151 #include <mach/mach_time.h>
162 #if defined __linux__ || defined __APPLE__ || defined __EMSCRIPTEN__
165 #include <sys/types.h>
167 #include <sys/sysconf.h>
172 # include <android/log.h>
178 Exception::Exception() { code = 0; line = 0; }
180 Exception::Exception(int _code, const String& _err, const String& _func, const String& _file, int _line)
181 : code(_code), err(_err), func(_func), file(_file), line(_line)
186 Exception::~Exception() throw() {}
189 \return the error description and the context as a text string.
191 const char* Exception::what() const throw() { return msg.c_str(); }
193 void Exception::formatMessage()
195 if( func.size() > 0 )
196 msg = format("%s:%d: error: (%d) %s in function %s\n", file.c_str(), line, code, err.c_str(), func.c_str());
198 msg = format("%s:%d: error: (%d) %s\n", file.c_str(), line, code, err.c_str());
201 bool checkHardwareSupport(int feature)
203 CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
204 return cv::hal::checkHardwareSupport(feature);
207 void setUseOptimized( bool flag )
209 cv::hal::setUseOptimized(flag);
211 ipp::setUseIPP(flag);
213 ocl::setUseOpenCL(flag);
215 #ifdef HAVE_TEGRA_OPTIMIZATION
216 ::tegra::setUseTegra(flag);
220 bool useOptimized(void)
222 return cv::hal::useOptimized();
225 int64 getTickCount(void)
227 #if defined WIN32 || defined _WIN32 || defined WINCE
228 LARGE_INTEGER counter;
229 QueryPerformanceCounter( &counter );
230 return (int64)counter.QuadPart;
231 #elif defined __linux || defined __linux__
233 clock_gettime(CLOCK_MONOTONIC, &tp);
234 return (int64)tp.tv_sec*1000000000 + tp.tv_nsec;
235 #elif defined __MACH__ && defined __APPLE__
236 return (int64)mach_absolute_time();
240 gettimeofday( &tv, &tz );
241 return (int64)tv.tv_sec*1000000 + tv.tv_usec;
245 double getTickFrequency(void)
247 #if defined WIN32 || defined _WIN32 || defined WINCE
249 QueryPerformanceFrequency(&freq);
250 return (double)freq.QuadPart;
251 #elif defined __linux || defined __linux__
253 #elif defined __MACH__ && defined __APPLE__
254 static double freq = 0;
257 mach_timebase_info_data_t sTimebaseInfo;
258 mach_timebase_info(&sTimebaseInfo);
259 freq = sTimebaseInfo.denom*1e9/sTimebaseInfo.numer;
267 #if defined __GNUC__ && (defined __i386__ || defined __x86_64__ || defined __ppc__)
268 #if defined(__i386__)
270 int64 getCPUTickCount(void)
273 __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x));
276 #elif defined(__x86_64__)
278 int64 getCPUTickCount(void)
281 __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
282 return (int64)lo | ((int64)hi << 32);
285 #elif defined(__ppc__)
287 int64 getCPUTickCount(void)
290 unsigned upper, lower, tmp;
298 : "=r"(upper),"=r"(lower),"=r"(tmp)
300 return lower | ((int64)upper << 32);
305 #error "RDTSC not defined"
309 #elif defined _MSC_VER && defined WIN32 && defined _M_IX86
311 int64 getCPUTickCount(void)
320 //int64 getCPUTickCount(void)
322 // return ippGetCpuClocks();
325 int64 getCPUTickCount(void)
327 return getTickCount();
333 const String& getBuildInformation()
335 static String build_info =
336 #include "version_string.inc"
341 String format( const char* fmt, ... )
343 AutoBuffer<char, 1024> buf;
349 int bsize = static_cast<int>(buf.size()),
350 len = vsnprintf((char *)buf, bsize, fmt, va);
353 if (len < 0 || len >= bsize)
355 buf.resize(std::max(bsize << 1, len + 1));
358 return String((char *)buf, len);
362 String tempfile( const char* suffix )
366 const char *temp_dir = getenv("OPENCV_TEMP_PATH");
369 #if defined WIN32 || defined _WIN32
371 RoInitialize(RO_INIT_MULTITHREADED);
372 std::wstring temp_dir = GetTempPathWinRT();
374 std::wstring temp_file = GetTempFileNameWinRT(L"ocv");
375 if (temp_file.empty())
378 temp_file = temp_dir.append(std::wstring(L"\\")).append(temp_file);
379 DeleteFileW(temp_file.c_str());
381 char aname[MAX_PATH];
382 size_t copied = wcstombs(aname, temp_file.c_str(), MAX_PATH);
383 CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
384 fname = String(aname);
387 char temp_dir2[MAX_PATH] = { 0 };
388 char temp_file[MAX_PATH] = { 0 };
390 if (temp_dir == 0 || temp_dir[0] == 0)
392 ::GetTempPathA(sizeof(temp_dir2), temp_dir2);
393 temp_dir = temp_dir2;
395 if(0 == ::GetTempFileNameA(temp_dir, "ocv", 0, temp_file))
398 DeleteFileA(temp_file);
404 //char defaultTemplate[] = "/mnt/sdcard/__opencv_temp.XXXXXX";
405 char defaultTemplate[] = "/data/local/tmp/__opencv_temp.XXXXXX";
407 char defaultTemplate[] = "/tmp/__opencv_temp.XXXXXX";
410 if (temp_dir == 0 || temp_dir[0] == 0)
411 fname = defaultTemplate;
415 char ech = fname[fname.size() - 1];
416 if(ech != '/' && ech != '\\')
418 fname = fname + "__opencv_temp.XXXXXX";
421 const int fd = mkstemp((char*)fname.c_str());
422 if (fd == -1) return String();
425 remove(fname.c_str());
430 if (suffix[0] != '.')
431 return fname + "." + suffix;
433 return fname + suffix;
438 static CvErrorCallback customErrorCallback = 0;
439 static void* customErrorCallbackData = 0;
440 static bool breakOnError = false;
442 bool setBreakOnError(bool value)
444 bool prevVal = breakOnError;
445 breakOnError = value;
449 void error( const Exception& exc )
451 if (customErrorCallback != 0)
452 customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(),
453 exc.file.c_str(), exc.line, customErrorCallbackData);
456 const char* errorStr = cvErrorStr(exc.code);
459 sprintf( buf, "OpenCV Error: %s (%s) in %s, file %s, line %d",
460 errorStr, exc.err.c_str(), exc.func.size() > 0 ?
461 exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line );
462 fprintf( stderr, "%s\n", buf );
465 __android_log_print(ANDROID_LOG_ERROR, "cv::error()", "%s", buf);
471 static volatile int* p = 0;
478 void error(int _code, const String& _err, const char* _func, const char* _file, int _line)
480 error(cv::Exception(_code, _err, _func, _file, _line));
484 redirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata)
487 *prevUserdata = customErrorCallbackData;
489 CvErrorCallback prevCallback = customErrorCallback;
491 customErrorCallback = errCallback;
492 customErrorCallbackData = userdata;
499 CV_IMPL int cvCheckHardwareSupport(int feature)
501 CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE );
502 return cv::hal::checkHardwareSupport(feature);
505 CV_IMPL int cvUseOptimized( int flag )
507 int prevMode = cv::useOptimized();
508 cv::setUseOptimized( flag != 0 );
512 CV_IMPL int64 cvGetTickCount(void)
514 return cv::getTickCount();
517 CV_IMPL double cvGetTickFrequency(void)
519 return cv::getTickFrequency()*1e-6;
522 CV_IMPL CvErrorCallback
523 cvRedirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata)
525 return cv::redirectError(errCallback, userdata, prevUserdata);
528 CV_IMPL int cvNulDevReport( int, const char*, const char*,
529 const char*, int, void* )
534 CV_IMPL int cvStdErrReport( int, const char*, const char*,
535 const char*, int, void* )
540 CV_IMPL int cvGuiBoxReport( int, const char*, const char*,
541 const char*, int, void* )
546 CV_IMPL int cvGetErrInfo( const char**, const char**, const char**, int* )
552 CV_IMPL const char* cvErrorStr( int status )
554 static char buf[256];
558 case CV_StsOk : return "No Error";
559 case CV_StsBackTrace : return "Backtrace";
560 case CV_StsError : return "Unspecified error";
561 case CV_StsInternal : return "Internal error";
562 case CV_StsNoMem : return "Insufficient memory";
563 case CV_StsBadArg : return "Bad argument";
564 case CV_StsNoConv : return "Iterations do not converge";
565 case CV_StsAutoTrace : return "Autotrace call";
566 case CV_StsBadSize : return "Incorrect size of input array";
567 case CV_StsNullPtr : return "Null pointer";
568 case CV_StsDivByZero : return "Division by zero occured";
569 case CV_BadStep : return "Image step is wrong";
570 case CV_StsInplaceNotSupported : return "Inplace operation is not supported";
571 case CV_StsObjectNotFound : return "Requested object was not found";
572 case CV_BadDepth : return "Input image depth is not supported by function";
573 case CV_StsUnmatchedFormats : return "Formats of input arguments do not match";
574 case CV_StsUnmatchedSizes : return "Sizes of input arguments do not match";
575 case CV_StsOutOfRange : return "One of arguments\' values is out of range";
576 case CV_StsUnsupportedFormat : return "Unsupported format or combination of formats";
577 case CV_BadCOI : return "Input COI is not supported";
578 case CV_BadNumChannels : return "Bad number of channels";
579 case CV_StsBadFlag : return "Bad flag (parameter or structure field)";
580 case CV_StsBadPoint : return "Bad parameter of type CvPoint";
581 case CV_StsBadMask : return "Bad type of mask argument";
582 case CV_StsParseError : return "Parsing error";
583 case CV_StsNotImplemented : return "The function/feature is not implemented";
584 case CV_StsBadMemBlock : return "Memory block has been corrupted";
585 case CV_StsAssert : return "Assertion failed";
586 case CV_GpuNotSupported : return "No CUDA support";
587 case CV_GpuApiCallError : return "Gpu API call";
588 case CV_OpenGlNotSupported : return "No OpenGL support";
589 case CV_OpenGlApiCallError : return "OpenGL API call";
592 sprintf(buf, "Unknown %s code %d", status >= 0 ? "status":"error", status);
596 CV_IMPL int cvGetErrMode(void)
601 CV_IMPL int cvSetErrMode(int)
606 CV_IMPL int cvGetErrStatus(void)
611 CV_IMPL void cvSetErrStatus(int)
616 CV_IMPL void cvError( int code, const char* func_name,
618 const char* file_name, int line )
620 cv::error(cv::Exception(code, err_msg, func_name, file_name, line));
623 /* function, which converts int to int */
625 cvErrorFromIppStatus( int status )
629 case CV_BADSIZE_ERR: return CV_StsBadSize;
630 case CV_BADMEMBLOCK_ERR: return CV_StsBadMemBlock;
631 case CV_NULLPTR_ERR: return CV_StsNullPtr;
632 case CV_DIV_BY_ZERO_ERR: return CV_StsDivByZero;
633 case CV_BADSTEP_ERR: return CV_BadStep;
634 case CV_OUTOFMEM_ERR: return CV_StsNoMem;
635 case CV_BADARG_ERR: return CV_StsBadArg;
636 case CV_NOTDEFINED_ERR: return CV_StsError;
637 case CV_INPLACE_NOT_SUPPORTED_ERR: return CV_StsInplaceNotSupported;
638 case CV_NOTFOUND_ERR: return CV_StsObjectNotFound;
639 case CV_BADCONVERGENCE_ERR: return CV_StsNoConv;
640 case CV_BADDEPTH_ERR: return CV_BadDepth;
641 case CV_UNMATCHED_FORMATS_ERR: return CV_StsUnmatchedFormats;
642 case CV_UNSUPPORTED_COI_ERR: return CV_BadCOI;
643 case CV_UNSUPPORTED_CHANNELS_ERR: return CV_BadNumChannels;
644 case CV_BADFLAG_ERR: return CV_StsBadFlag;
645 case CV_BADRANGE_ERR: return CV_StsBadArg;
646 case CV_BADCOEF_ERR: return CV_StsBadArg;
647 case CV_BADFACTOR_ERR: return CV_StsBadArg;
648 case CV_BADPOINT_ERR: return CV_StsBadPoint;
656 bool __termination = false;
662 #if defined WIN32 || defined _WIN32 || defined WINCE
668 #if (_WIN32_WINNT >= 0x0600)
669 ::InitializeCriticalSectionEx(&cs, 1000, 0);
671 ::InitializeCriticalSection(&cs);
675 ~Impl() { DeleteCriticalSection(&cs); }
677 void lock() { EnterCriticalSection(&cs); }
678 bool trylock() { return TryEnterCriticalSection(&cs) != 0; }
679 void unlock() { LeaveCriticalSection(&cs); }
691 pthread_mutexattr_t attr;
692 pthread_mutexattr_init(&attr);
693 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
694 pthread_mutex_init(&mt, &attr);
695 pthread_mutexattr_destroy(&attr);
699 ~Impl() { pthread_mutex_destroy(&mt); }
701 void lock() { pthread_mutex_lock(&mt); }
702 bool trylock() { return pthread_mutex_trylock(&mt) == 0; }
703 void unlock() { pthread_mutex_unlock(&mt); }
713 impl = new Mutex::Impl;
718 if( CV_XADD(&impl->refcount, -1) == 1 )
723 Mutex::Mutex(const Mutex& m)
726 CV_XADD(&impl->refcount, 1);
729 Mutex& Mutex::operator = (const Mutex& m)
731 CV_XADD(&m.impl->refcount, 1);
732 if( CV_XADD(&impl->refcount, -1) == 1 )
738 void Mutex::lock() { impl->lock(); }
739 void Mutex::unlock() { impl->unlock(); }
740 bool Mutex::trylock() { return impl->trylock(); }
743 //////////////////////////////// thread-local storage ////////////////////////////////
747 #pragma warning(disable:4505) // unreferenced local function has been removed
749 #ifndef TLS_OUT_OF_INDEXES
750 #define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF)
754 // TLS platform abstraction layer
760 void* GetData() const;
761 void SetData(void *pData);
769 pthread_key_t tlsKey;
775 static __declspec( thread ) void* tlsData = NULL; // using C++11 thread attribute for local thread data
776 TlsAbstraction::TlsAbstraction() {}
777 TlsAbstraction::~TlsAbstraction() {}
778 void* TlsAbstraction::GetData() const
782 void TlsAbstraction::SetData(void *pData)
787 TlsAbstraction::TlsAbstraction()
790 CV_Assert(tlsKey != TLS_OUT_OF_INDEXES);
792 TlsAbstraction::~TlsAbstraction()
796 void* TlsAbstraction::GetData() const
798 return TlsGetValue(tlsKey);
800 void TlsAbstraction::SetData(void *pData)
802 CV_Assert(TlsSetValue(tlsKey, pData) == TRUE);
806 TlsAbstraction::TlsAbstraction()
808 CV_Assert(pthread_key_create(&tlsKey, NULL) == 0);
810 TlsAbstraction::~TlsAbstraction()
812 CV_Assert(pthread_key_delete(tlsKey) == 0);
814 void* TlsAbstraction::GetData() const
816 return pthread_getspecific(tlsKey);
818 void TlsAbstraction::SetData(void *pData)
820 CV_Assert(pthread_setspecific(tlsKey, pData) == 0);
824 // Per-thread data structure
833 std::vector<void*> slots; // Data array for a thread
834 size_t idx; // Thread index in TLS storage. This is not OS thread ID!
837 // Main TLS storage class
843 tlsSlots.reserve(32);
848 for(size_t i = 0; i < threads.size(); i++)
852 /* Current architecture doesn't allow proper global objects relase, so this check can cause crashes
854 // Check if all slots were properly cleared
855 for(size_t j = 0; j < threads[i]->slots.size(); j++)
857 CV_Assert(threads[i]->slots[j] == 0);
868 AutoLock guard(mtxGlobalAccess);
869 ThreadData *pTD = (ThreadData*)tls.GetData();
870 for(size_t i = 0; i < threads.size(); i++)
872 if(pTD == threads[i])
882 // Reserve TLS storage index
885 AutoLock guard(mtxGlobalAccess);
888 for(size_t slot = 0; slot < tlsSlots.size(); slot++)
898 tlsSlots.push_back(1);
899 return (tlsSlots.size()-1);
902 // Release TLS storage index and pass assosiated data to caller
903 void releaseSlot(size_t slotIdx, std::vector<void*> &dataVec)
905 AutoLock guard(mtxGlobalAccess);
906 CV_Assert(tlsSlots.size() > slotIdx);
908 for(size_t i = 0; i < threads.size(); i++)
910 std::vector<void*>& thread_slots = threads[i]->slots;
911 if (thread_slots.size() > slotIdx && thread_slots[slotIdx])
913 dataVec.push_back(thread_slots[slotIdx]);
914 threads[i]->slots[slotIdx] = 0;
918 tlsSlots[slotIdx] = 0;
921 // Get data by TLS storage index
922 void* getData(size_t slotIdx) const
924 CV_Assert(tlsSlots.size() > slotIdx);
926 ThreadData* threadData = (ThreadData*)tls.GetData();
927 if(threadData && threadData->slots.size() > slotIdx)
928 return threadData->slots[slotIdx];
933 // Gather data from threads by TLS storage index
934 void gather(size_t slotIdx, std::vector<void*> &dataVec)
936 AutoLock guard(mtxGlobalAccess);
937 CV_Assert(tlsSlots.size() > slotIdx);
939 for(size_t i = 0; i < threads.size(); i++)
941 std::vector<void*>& thread_slots = threads[i]->slots;
942 if (thread_slots.size() > slotIdx && thread_slots[slotIdx])
943 dataVec.push_back(thread_slots[slotIdx]);
947 // Set data to storage index
948 void setData(size_t slotIdx, void* pData)
950 CV_Assert(tlsSlots.size() > slotIdx && pData != NULL);
952 ThreadData* threadData = (ThreadData*)tls.GetData();
955 threadData = new ThreadData;
956 tls.SetData((void*)threadData);
958 AutoLock guard(mtxGlobalAccess);
959 threadData->idx = threads.size();
960 threads.push_back(threadData);
964 if(slotIdx >= threadData->slots.size())
966 AutoLock guard(mtxGlobalAccess);
967 while(slotIdx >= threadData->slots.size())
968 threadData->slots.push_back(NULL);
970 threadData->slots[slotIdx] = pData;
974 TlsAbstraction tls; // TLS abstraction layer instance
976 Mutex mtxGlobalAccess; // Shared objects operation guard
977 std::vector<int> tlsSlots; // TLS keys state
978 std::vector<ThreadData*> threads; // Array for all allocated data. Thread data pointers are placed here to allow data cleanup
981 // Create global TLS storage object
982 static TlsStorage &getTlsStorage()
984 CV_SINGLETON_LAZY_INIT_REF(TlsStorage, new TlsStorage())
987 TLSDataContainer::TLSDataContainer()
989 key_ = (int)getTlsStorage().reserveSlot(); // Reserve key from TLS storage
992 TLSDataContainer::~TLSDataContainer()
994 CV_Assert(key_ == -1); // Key must be released in child object
997 void TLSDataContainer::gatherData(std::vector<void*> &data) const
999 getTlsStorage().gather(key_, data);
1002 void TLSDataContainer::release()
1004 std::vector<void*> data;
1006 getTlsStorage().releaseSlot(key_, data); // Release key and get stored data for proper destruction
1007 for(size_t i = 0; i < data.size(); i++) // Delete all assosiated data
1008 deleteDataInstance(data[i]);
1012 void* TLSDataContainer::getData() const
1014 void* pData = getTlsStorage().getData(key_); // Check if data was already allocated
1017 // Create new data instance and save it to TLS storage
1018 pData = createDataInstance();
1019 getTlsStorage().setData(key_, pData);
1024 TLSData<CoreTLSData>& getCoreTlsData()
1026 CV_SINGLETON_LAZY_INIT_REF(TLSData<CoreTLSData>, new TLSData<CoreTLSData>())
1029 #if defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE
1031 #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model
1035 BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved);
1038 BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved)
1040 if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
1042 if (lpReserved != NULL) // called after ExitProcess() call
1044 cv::__termination = true;
1048 // Not allowed to free resources if lpReserved is non-null
1049 // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583.aspx
1050 cv::deleteThreadAllocData();
1051 cv::getTlsStorage().releaseThread();
1058 #ifdef CV_COLLECT_IMPL_DATA
1059 ImplCollector& getImplData()
1061 CV_SINGLETON_LAZY_INIT_REF(ImplCollector, new ImplCollector())
1064 void setImpl(int flags)
1066 cv::AutoLock lock(getImplData().mutex);
1068 getImplData().implFlags = flags;
1069 getImplData().implCode.clear();
1070 getImplData().implFun.clear();
1073 void addImpl(int flag, const char* func)
1075 cv::AutoLock lock(getImplData().mutex);
1077 getImplData().implFlags |= flag;
1078 if(func) // use lazy collection if name was not specified
1080 size_t index = getImplData().implCode.size();
1081 if(!index || (getImplData().implCode[index-1] != flag || getImplData().implFun[index-1].compare(func))) // avoid duplicates
1083 getImplData().implCode.push_back(flag);
1084 getImplData().implFun.push_back(func);
1089 int getImpl(std::vector<int> &impl, std::vector<String> &funName)
1091 cv::AutoLock lock(getImplData().mutex);
1093 impl = getImplData().implCode;
1094 funName = getImplData().implFun;
1095 return getImplData().implFlags; // return actual flags for lazy collection
1098 bool useCollection()
1100 return getImplData().useCollection;
1103 void setUseCollection(bool flag)
1105 cv::AutoLock lock(getImplData().mutex);
1107 getImplData().useCollection = flag;
1114 struct IPPInitSingelton
1127 const char* pIppEnv = getenv("OPENCV_IPP");
1128 cv::String env = pIppEnv;
1131 if(env == "disabled")
1133 std::cerr << "WARNING: IPP was disabled by OPENCV_IPP environment variable" << std::endl;
1136 #if IPP_VERSION_X100 >= 900
1137 else if(env == "sse")
1138 ippFeatures = ippCPUID_SSE;
1139 else if(env == "sse2")
1140 ippFeatures = ippCPUID_SSE2;
1141 else if(env == "sse3")
1142 ippFeatures = ippCPUID_SSE3;
1143 else if(env == "ssse3")
1144 ippFeatures = ippCPUID_SSSE3;
1145 else if(env == "sse41")
1146 ippFeatures = ippCPUID_SSE41;
1147 else if(env == "sse42")
1148 ippFeatures = ippCPUID_SSE42;
1149 else if(env == "avx")
1150 ippFeatures = ippCPUID_AVX;
1151 else if(env == "avx2")
1152 ippFeatures = ippCPUID_AVX2;
1155 std::cerr << "ERROR: Improper value of OPENCV_IPP: " << env.c_str() << std::endl;
1158 IPP_INITIALIZER(ippFeatures)
1164 int ippStatus; // 0 - all is ok, -1 - IPP functions failed
1165 const char *funcname;
1166 const char *filename;
1171 static IPPInitSingelton& getIPPSingelton()
1173 CV_SINGLETON_LAZY_INIT_REF(IPPInitSingelton, new IPPInitSingelton())
1176 int getIppFeatures()
1179 return getIPPSingelton().ippFeatures;
1185 void setIppStatus(int status, const char * const _funcname, const char * const _filename, int _line)
1187 getIPPSingelton().ippStatus = status;
1188 getIPPSingelton().funcname = _funcname;
1189 getIPPSingelton().filename = _filename;
1190 getIPPSingelton().linen = _line;
1195 return getIPPSingelton().ippStatus;
1198 String getIppErrorLocation()
1200 return format("%s:%d %s", getIPPSingelton().filename ? getIPPSingelton().filename : "", getIPPSingelton().linen, getIPPSingelton().funcname ? getIPPSingelton().funcname : "");
1206 CoreTLSData* data = getCoreTlsData().get();
1207 if(data->useIPP < 0)
1209 data->useIPP = getIPPSingelton().useIPP;
1211 return (data->useIPP > 0);
1217 void setUseIPP(bool flag)
1219 CoreTLSData* data = getCoreTlsData().get();
1221 data->useIPP = flag;
1224 data->useIPP = false;
1232 #ifdef HAVE_TEGRA_OPTIMIZATION
1238 cv::CoreTLSData* data = cv::getCoreTlsData().get();
1240 if (data->useTegra < 0)
1242 const char* pTegraEnv = getenv("OPENCV_TEGRA");
1243 if (pTegraEnv && (cv::String(pTegraEnv) == "disabled"))
1244 data->useTegra = false;
1246 data->useTegra = true;
1249 return (data->useTegra > 0);
1252 void setUseTegra(bool flag)
1254 cv::CoreTLSData* data = cv::getCoreTlsData().get();
1255 data->useTegra = flag;
1258 } // namespace tegra