/
ocl.cpp
6761 lines (5971 loc) · 220 KB
/
ocl.cpp
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
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
241
242
243
244
245
246
247
248
249
250
251
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
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
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
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
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
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
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*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) 2013, OpenCV Foundation, 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 OpenCV Foundation 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"
#include <list>
#include <map>
#include <deque>
#include <set>
#include <string>
#include <sstream>
#include <iostream> // std::cerr
#include <fstream>
#if !(defined _MSC_VER) || (defined _MSC_VER && _MSC_VER > 1700)
#include <inttypes.h>
#endif
#include <opencv2/core/utils/configuration.private.hpp>
#include <opencv2/core/utils/logger.defines.hpp>
#undef CV_LOG_STRIP_LEVEL
#define CV_LOG_STRIP_LEVEL CV_LOG_LEVEL_DEBUG + 1
#include <opencv2/core/utils/logger.hpp>
#include "opencv2/core/ocl_genbase.hpp"
#include "opencl_kernels_core.hpp"
#include "opencv2/core/utils/lock.private.hpp"
#include "opencv2/core/utils/filesystem.hpp"
#include "opencv2/core/utils/filesystem.private.hpp"
#define CV__ALLOCATOR_STATS_LOG(...) CV_LOG_VERBOSE(NULL, 0, "OpenCL allocator: " << __VA_ARGS__)
#include "opencv2/core/utils/allocator_stats.impl.hpp"
#undef CV__ALLOCATOR_STATS_LOG
#define CV_OPENCL_ALWAYS_SHOW_BUILD_LOG 0
#define CV_OPENCL_SHOW_RUN_KERNELS 0
#define CV_OPENCL_TRACE_CHECK 0
#define CV_OPENCL_VALIDATE_BINARY_PROGRAMS 1
#define CV_OPENCL_SHOW_SVM_ERROR_LOG 1
#define CV_OPENCL_SHOW_SVM_LOG 0
#include "opencv2/core/bufferpool.hpp"
#ifndef LOG_BUFFER_POOL
# if 0
# define LOG_BUFFER_POOL printf
# else
# define LOG_BUFFER_POOL(...)
# endif
#endif
#if CV_OPENCL_SHOW_SVM_LOG
// TODO add timestamp logging
#define CV_OPENCL_SVM_TRACE_P printf("line %d (ocl.cpp): ", __LINE__); printf
#else
#define CV_OPENCL_SVM_TRACE_P(...)
#endif
#if CV_OPENCL_SHOW_SVM_ERROR_LOG
// TODO add timestamp logging
#define CV_OPENCL_SVM_TRACE_ERROR_P printf("Error on line %d (ocl.cpp): ", __LINE__); printf
#else
#define CV_OPENCL_SVM_TRACE_ERROR_P(...)
#endif
#include "opencv2/core/opencl/runtime/opencl_clamdblas.hpp"
#include "opencv2/core/opencl/runtime/opencl_clamdfft.hpp"
#ifdef HAVE_OPENCL
#include "opencv2/core/opencl/runtime/opencl_core.hpp"
#else
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4100)
#pragma warning(disable : 4702)
#elif defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-parameter"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
// TODO FIXIT: This file can't be build without OPENCL
#include "ocl_deprecated.hpp"
#endif // HAVE_OPENCL
#ifdef HAVE_OPENCL_SVM
#include "opencv2/core/opencl/runtime/opencl_svm_20.hpp"
#include "opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp"
#include "opencv2/core/opencl/opencl_svm.hpp"
#endif
#include "umatrix.hpp"
namespace cv { namespace ocl {
#define IMPLEMENT_REFCOUNTABLE() \
void addref() { CV_XADD(&refcount, 1); } \
void release() { if( CV_XADD(&refcount, -1) == 1 && !cv::__termination) delete this; } \
int refcount
static cv::utils::AllocatorStatistics opencl_allocator_stats;
CV_EXPORTS cv::utils::AllocatorStatisticsInterface& getOpenCLAllocatorStatistics();
cv::utils::AllocatorStatisticsInterface& getOpenCLAllocatorStatistics()
{
return opencl_allocator_stats;
}
#ifndef HAVE_OPENCL
#define CV_OPENCL_NO_SUPPORT() CV_Error(cv::Error::OpenCLApiCallError, "OpenCV build without OpenCL support")
namespace {
struct DummyImpl
{
DummyImpl() { CV_OPENCL_NO_SUPPORT(); }
~DummyImpl() { /* do not throw in desctructors */ }
IMPLEMENT_REFCOUNTABLE();
};
} // namespace
// TODO Replace to empty body (without HAVE_OPENCL)
#define CV_OCL_TRACE_CHECK_RESULT(status, message) /* nothing */
#define CV_OCL_API_ERROR_MSG(check_result, msg) cv::String()
#define CV_OCL_CHECK_RESULT(check_result, msg) (void)check_result
#define CV_OCL_CHECK_(expr, check_result) expr; (void)check_result
#define CV_OCL_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_CHECK_RESULT(__cl_result, #expr); } while (0)
#define CV_OCL_DBG_CHECK_RESULT(check_result, msg) (void)check_result
#define CV_OCL_DBG_CHECK_(expr, check_result) expr; (void)check_result
#define CV_OCL_DBG_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_CHECK_RESULT(__cl_result, #expr); } while (0)
static const bool CV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS = false;
#else // HAVE_OPENCL
#ifndef _DEBUG
static bool isRaiseError()
{
static bool initialized = false;
static bool value = false;
if (!initialized)
{
value = cv::utils::getConfigurationParameterBool("OPENCV_OPENCL_RAISE_ERROR", false);
initialized = true;
}
return value;
}
#endif
#if CV_OPENCL_TRACE_CHECK
static inline
void traceOpenCLCheck(cl_int status, const char* message)
{
std::cout << "OpenCV(OpenCL:" << status << "): " << message << std::endl << std::flush;
}
#define CV_OCL_TRACE_CHECK_RESULT(status, message) traceOpenCLCheck(status, message)
#else
#define CV_OCL_TRACE_CHECK_RESULT(status, message) /* nothing */
#endif
#define CV_OCL_API_ERROR_MSG(check_result, msg) \
cv::format("OpenCL error %s (%d) during call: %s", getOpenCLErrorString(check_result), check_result, msg)
#define CV_OCL_CHECK_RESULT(check_result, msg) \
do { \
CV_OCL_TRACE_CHECK_RESULT(check_result, msg); \
if (check_result != CL_SUCCESS) \
{ \
static_assert(std::is_convertible<decltype(msg), const char*>::value, "msg of CV_OCL_CHECK_RESULT must be const char*"); \
cv::String error_msg = CV_OCL_API_ERROR_MSG(check_result, msg); \
CV_Error(Error::OpenCLApiCallError, error_msg); \
} \
} while (0)
#define CV_OCL_CHECK_(expr, check_result) do { expr; CV_OCL_CHECK_RESULT(check_result, #expr); } while (0)
#define CV_OCL_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_CHECK_RESULT(__cl_result, #expr); } while (0)
#ifdef _DEBUG
#define CV_OCL_DBG_CHECK_RESULT(check_result, msg) CV_OCL_CHECK_RESULT(check_result, msg)
#define CV_OCL_DBG_CHECK(expr) CV_OCL_CHECK(expr)
#define CV_OCL_DBG_CHECK_(expr, check_result) CV_OCL_CHECK_(expr, check_result)
#else
#define CV_OCL_DBG_CHECK_RESULT(check_result, msg) \
do { \
CV_OCL_TRACE_CHECK_RESULT(check_result, msg); \
if (check_result != CL_SUCCESS && isRaiseError()) \
{ \
static_assert(std::is_convertible<decltype(msg), const char*>::value, "msg of CV_OCL_DBG_CHECK_RESULT must be const char*"); \
cv::String error_msg = CV_OCL_API_ERROR_MSG(check_result, msg); \
CV_Error(Error::OpenCLApiCallError, error_msg); \
} \
} while (0)
#define CV_OCL_DBG_CHECK_(expr, check_result) do { expr; CV_OCL_DBG_CHECK_RESULT(check_result, #expr); } while (0)
#define CV_OCL_DBG_CHECK(expr) do { cl_int __cl_result = (expr); CV_OCL_DBG_CHECK_RESULT(__cl_result, #expr); } while (0)
#endif
static const bool CV_OPENCL_CACHE_ENABLE = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_ENABLE", true);
static const bool CV_OPENCL_CACHE_WRITE = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_WRITE", true);
static const bool CV_OPENCL_CACHE_LOCK_ENABLE = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_LOCK_ENABLE", true);
static const bool CV_OPENCL_CACHE_CLEANUP = utils::getConfigurationParameterBool("OPENCV_OPENCL_CACHE_CLEANUP", true);
#if CV_OPENCL_VALIDATE_BINARY_PROGRAMS
static const bool CV_OPENCL_VALIDATE_BINARY_PROGRAMS_VALUE = utils::getConfigurationParameterBool("OPENCV_OPENCL_VALIDATE_BINARY_PROGRAMS", false);
#endif
// Option to disable calls clEnqueueReadBufferRect / clEnqueueWriteBufferRect / clEnqueueCopyBufferRect
static const bool CV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS = utils::getConfigurationParameterBool("OPENCV_OPENCL_DISABLE_BUFFER_RECT_OPERATIONS",
#ifdef __APPLE__
true
#else
false
#endif
);
static const String getBuildExtraOptions()
{
static String param_buildExtraOptions;
static bool initialized = false;
if (!initialized)
{
param_buildExtraOptions = utils::getConfigurationParameterString("OPENCV_OPENCL_BUILD_EXTRA_OPTIONS", "");
initialized = true;
if (!param_buildExtraOptions.empty())
CV_LOG_WARNING(NULL, "OpenCL: using extra build options: '" << param_buildExtraOptions << "'");
}
return param_buildExtraOptions;
}
static const bool CV_OPENCL_ENABLE_MEM_USE_HOST_PTR = utils::getConfigurationParameterBool("OPENCV_OPENCL_ENABLE_MEM_USE_HOST_PTR", true);
static const size_t CV_OPENCL_ALIGNMENT_MEM_USE_HOST_PTR = utils::getConfigurationParameterSizeT("OPENCV_OPENCL_ALIGNMENT_MEM_USE_HOST_PTR", 4);
#endif // HAVE_OPENCL
struct UMat2D
{
UMat2D(const UMat& m)
{
offset = (int)m.offset;
step = (int)m.step;
rows = m.rows;
cols = m.cols;
}
int offset;
int step;
int rows;
int cols;
};
struct UMat3D
{
UMat3D(const UMat& m)
{
offset = (int)m.offset;
step = (int)m.step.p[1];
slicestep = (int)m.step.p[0];
slices = (int)m.size.p[0];
rows = m.size.p[1];
cols = m.size.p[2];
}
int offset;
int slicestep;
int step;
int slices;
int rows;
int cols;
};
// Computes 64-bit "cyclic redundancy check" sum, as specified in ECMA-182
static uint64 crc64( const uchar* data, size_t size, uint64 crc0=0 )
{
static uint64 table[256];
static bool initialized = false;
if( !initialized )
{
for( int i = 0; i < 256; i++ )
{
uint64 c = i;
for( int j = 0; j < 8; j++ )
c = ((c & 1) ? CV_BIG_UINT(0xc96c5795d7870f42) : 0) ^ (c >> 1);
table[i] = c;
}
initialized = true;
}
uint64 crc = ~crc0;
for( size_t idx = 0; idx < size; idx++ )
crc = table[(uchar)crc ^ data[idx]] ^ (crc >> 8);
return ~crc;
}
#if defined HAVE_OPENCL && OPENCV_HAVE_FILESYSTEM_SUPPORT
struct OpenCLBinaryCacheConfigurator
{
cv::String cache_path_;
cv::String cache_lock_filename_;
cv::Ptr<utils::fs::FileLock> cache_lock_;
typedef std::map<std::string, std::string> ContextCacheType;
ContextCacheType prepared_contexts_;
Mutex mutex_prepared_contexts_;
OpenCLBinaryCacheConfigurator()
{
CV_LOG_DEBUG(NULL, "Initializing OpenCL cache configuration...");
if (!CV_OPENCL_CACHE_ENABLE)
{
CV_LOG_INFO(NULL, "OpenCL cache is disabled");
return;
}
cache_path_ = utils::fs::getCacheDirectory("opencl_cache", "OPENCV_OPENCL_CACHE_DIR");
if (cache_path_.empty())
{
CV_LOG_INFO(NULL, "Specify OPENCV_OPENCL_CACHE_DIR configuration parameter to enable OpenCL cache");
}
do
{
try
{
if (cache_path_.empty())
break;
if (cache_path_ == "disabled")
break;
if (!utils::fs::createDirectories(cache_path_))
{
CV_LOG_DEBUG(NULL, "Can't use OpenCL cache directory: " << cache_path_);
clear();
break;
}
if (CV_OPENCL_CACHE_LOCK_ENABLE)
{
cache_lock_filename_ = cache_path_ + ".lock";
if (!utils::fs::exists(cache_lock_filename_))
{
CV_LOG_DEBUG(NULL, "Creating lock file... (" << cache_lock_filename_ << ")");
std::ofstream lock_filename(cache_lock_filename_.c_str(), std::ios::out);
if (!lock_filename.is_open())
{
CV_LOG_WARNING(NULL, "Can't create lock file for OpenCL program cache: " << cache_lock_filename_);
break;
}
}
try
{
cache_lock_ = makePtr<utils::fs::FileLock>(cache_lock_filename_.c_str());
CV_LOG_VERBOSE(NULL, 0, "Checking cache lock... (" << cache_lock_filename_ << ")");
{
utils::shared_lock_guard<utils::fs::FileLock> lock(*cache_lock_);
}
CV_LOG_VERBOSE(NULL, 0, "Checking cache lock... Done!");
}
catch (const cv::Exception& e)
{
CV_LOG_WARNING(NULL, "Can't create OpenCL program cache lock: " << cache_lock_filename_ << std::endl << e.what());
}
catch (...)
{
CV_LOG_WARNING(NULL, "Can't create OpenCL program cache lock: " << cache_lock_filename_);
}
}
else
{
if (CV_OPENCL_CACHE_WRITE)
{
CV_LOG_WARNING(NULL, "OpenCL cache lock is disabled while cache write is allowed "
"(not safe for multiprocess environment)");
}
else
{
CV_LOG_INFO(NULL, "OpenCL cache lock is disabled");
}
}
}
catch (const cv::Exception& e)
{
CV_LOG_WARNING(NULL, "Can't prepare OpenCL program cache: " << cache_path_ << std::endl << e.what());
clear();
}
} while (0);
if (!cache_path_.empty())
{
if (cache_lock_.empty() && CV_OPENCL_CACHE_LOCK_ENABLE)
{
CV_LOG_WARNING(NULL, "Initialized OpenCL cache directory, but interprocess synchronization lock is not available. "
"Consider to disable OpenCL cache: OPENCV_OPENCL_CACHE_DIR=disabled");
}
else
{
CV_LOG_INFO(NULL, "Successfully initialized OpenCL cache directory: " << cache_path_);
}
}
}
void clear()
{
cache_path_.clear();
cache_lock_filename_.clear();
cache_lock_.release();
}
std::string prepareCacheDirectoryForContext(const std::string& ctx_prefix,
const std::string& cleanup_prefix)
{
if (cache_path_.empty())
return std::string();
AutoLock lock(mutex_prepared_contexts_);
ContextCacheType::iterator found_it = prepared_contexts_.find(ctx_prefix);
if (found_it != prepared_contexts_.end())
return found_it->second;
CV_LOG_INFO(NULL, "Preparing OpenCL cache configuration for context: " << ctx_prefix);
std::string target_directory = cache_path_ + ctx_prefix + "/";
bool result = utils::fs::isDirectory(target_directory);
if (!result)
{
try
{
CV_LOG_VERBOSE(NULL, 0, "Creating directory: " << target_directory);
if (utils::fs::createDirectories(target_directory))
{
result = true;
}
else
{
CV_LOG_WARNING(NULL, "Can't create directory: " << target_directory);
}
}
catch (const cv::Exception& e)
{
CV_LOG_ERROR(NULL, "Can't create OpenCL program cache directory for context: " << target_directory << std::endl << e.what());
}
}
target_directory = result ? target_directory : std::string();
prepared_contexts_.insert(std::pair<std::string, std::string>(ctx_prefix, target_directory));
if (result && CV_OPENCL_CACHE_CLEANUP && CV_OPENCL_CACHE_WRITE && !cleanup_prefix.empty())
{
try
{
std::vector<String> entries;
utils::fs::glob_relative(cache_path_, cleanup_prefix + "*", entries, false, true);
std::vector<String> remove_entries;
for (size_t i = 0; i < entries.size(); i++)
{
const String& name = entries[i];
if (0 == name.find(cleanup_prefix))
{
if (0 == name.find(ctx_prefix))
continue; // skip current
remove_entries.push_back(name);
}
}
if (!remove_entries.empty())
{
CV_LOG_WARNING(NULL, (remove_entries.size() == 1
? "Detected OpenCL cache directory for other version of OpenCL device."
: "Detected OpenCL cache directories for other versions of OpenCL device.")
<< " We assume that these directories are obsolete after OpenCL runtime/drivers upgrade.");
CV_LOG_WARNING(NULL, "Trying to remove these directories...");
for (size_t i = 0; i < remove_entries.size(); i++)
{
CV_LOG_WARNING(NULL, "- " << remove_entries[i]);
}
CV_LOG_WARNING(NULL, "Note: You can disable this behavior via this option: OPENCV_OPENCL_CACHE_CLEANUP=0");
for (size_t i = 0; i < remove_entries.size(); i++)
{
const String& name = remove_entries[i];
cv::String path = utils::fs::join(cache_path_, name);
try
{
utils::fs::remove_all(path);
CV_LOG_WARNING(NULL, "Removed: " << path);
}
catch (const cv::Exception& e)
{
CV_LOG_ERROR(NULL, "Exception during removal of obsolete OpenCL cache directory: " << path << std::endl << e.what());
}
}
}
}
catch (...)
{
CV_LOG_WARNING(NULL, "Can't check for obsolete OpenCL cache directories");
}
}
CV_LOG_VERBOSE(NULL, 1, " Result: " << (target_directory.empty() ? std::string("Failed") : target_directory));
return target_directory;
}
static OpenCLBinaryCacheConfigurator& getSingletonInstance()
{
CV_SINGLETON_LAZY_INIT_REF(OpenCLBinaryCacheConfigurator, new OpenCLBinaryCacheConfigurator());
}
};
class BinaryProgramFile
{
enum { MAX_ENTRIES = 64 };
typedef unsigned int uint32_t;
struct CV_DECL_ALIGNED(4) FileHeader
{
uint32_t sourceSignatureSize;
//char sourceSignature[];
};
struct CV_DECL_ALIGNED(4) FileTable
{
uint32_t numberOfEntries;
//uint32_t firstEntryOffset[];
};
struct CV_DECL_ALIGNED(4) FileEntry
{
uint32_t nextEntryFileOffset; // 0 for the last entry in chain
uint32_t keySize;
uint32_t dataSize;
//char key[];
//char data[];
};
const std::string fileName_;
const char* const sourceSignature_;
const size_t sourceSignatureSize_;
std::fstream f;
uint32_t entryOffsets[MAX_ENTRIES];
uint32_t getHash(const std::string& options)
{
uint64 hash = crc64((const uchar*)options.c_str(), options.size(), 0);
return hash & (MAX_ENTRIES - 1);
}
inline size_t getFileSize()
{
size_t pos = (size_t)f.tellg();
f.seekg(0, std::fstream::end);
size_t fileSize = (size_t)f.tellg();
f.seekg(pos, std::fstream::beg);
return fileSize;
}
inline uint32_t readUInt32()
{
uint32_t res = 0;
f.read((char*)&res, sizeof(uint32_t));
CV_Assert(!f.fail());
return res;
}
inline void writeUInt32(const uint32_t value)
{
uint32_t v = value;
f.write((char*)&v, sizeof(uint32_t));
CV_Assert(!f.fail());
}
inline void seekReadAbsolute(size_t pos)
{
f.seekg(pos, std::fstream::beg);
CV_Assert(!f.fail());
}
inline void seekReadRelative(size_t pos)
{
f.seekg(pos, std::fstream::cur);
CV_Assert(!f.fail());
}
inline void seekWriteAbsolute(size_t pos)
{
f.seekp(pos, std::fstream::beg);
CV_Assert(!f.fail());
}
void clearFile()
{
f.close();
if (0 != remove(fileName_.c_str()))
CV_LOG_ERROR(NULL, "Can't remove: " << fileName_);
return;
}
public:
BinaryProgramFile(const std::string& fileName, const char* sourceSignature)
: fileName_(fileName), sourceSignature_(sourceSignature), sourceSignatureSize_(sourceSignature_ ? strlen(sourceSignature_) : 0)
{
CV_StaticAssert(sizeof(uint32_t) == 4, "");
CV_Assert(sourceSignature_ != NULL);
CV_Assert(sourceSignatureSize_ > 0);
memset(entryOffsets, 0, sizeof(entryOffsets));
f.rdbuf()->pubsetbuf(0, 0); // disable buffering
f.open(fileName_.c_str(), std::ios::in|std::ios::out|std::ios::binary);
if(f.is_open() && getFileSize() > 0)
{
bool isValid = false;
try
{
uint32_t fileSourceSignatureSize = readUInt32();
if (fileSourceSignatureSize == sourceSignatureSize_)
{
cv::AutoBuffer<char> fileSourceSignature(fileSourceSignatureSize + 1);
f.read(fileSourceSignature.data(), fileSourceSignatureSize);
if (f.eof())
{
CV_LOG_ERROR(NULL, "Unexpected EOF");
}
else if (memcmp(sourceSignature, fileSourceSignature.data(), fileSourceSignatureSize) == 0)
{
isValid = true;
}
}
if (!isValid)
{
CV_LOG_ERROR(NULL, "Source code signature/hash mismatch (program source code has been changed/updated)");
}
}
catch (const cv::Exception& e)
{
CV_LOG_ERROR(NULL, "Can't open binary program file: " << fileName << " : " << e.what());
}
catch (...)
{
CV_LOG_ERROR(NULL, "Can't open binary program file: " << fileName << " : Unknown error");
}
if (!isValid)
{
clearFile();
}
else
{
seekReadAbsolute(0);
}
}
}
bool read(const std::string& key, std::vector<char>& buf)
{
if (!f.is_open())
return false;
size_t fileSize = getFileSize();
if (fileSize == 0)
{
CV_LOG_ERROR(NULL, "Invalid file (empty): " << fileName_);
clearFile();
return false;
}
seekReadAbsolute(0);
// bypass FileHeader
uint32_t fileSourceSignatureSize = readUInt32();
CV_Assert(fileSourceSignatureSize > 0);
seekReadRelative(fileSourceSignatureSize);
uint32_t numberOfEntries = readUInt32();
CV_Assert(numberOfEntries > 0);
if (numberOfEntries != MAX_ENTRIES)
{
CV_LOG_ERROR(NULL, "Invalid file: " << fileName_);
clearFile();
return false;
}
f.read((char*)&entryOffsets[0], sizeof(entryOffsets));
CV_Assert(!f.fail());
uint32_t entryNum = getHash(key);
uint32_t entryOffset = entryOffsets[entryNum];
FileEntry entry;
while (entryOffset > 0)
{
seekReadAbsolute(entryOffset);
//CV_StaticAssert(sizeof(entry) == sizeof(uint32_t) * 3, "");
f.read((char*)&entry, sizeof(entry));
CV_Assert(!f.fail());
cv::AutoBuffer<char> fileKey(entry.keySize + 1);
if (key.size() == entry.keySize)
{
if (entry.keySize > 0)
{
f.read(fileKey.data(), entry.keySize);
CV_Assert(!f.fail());
}
if (memcmp(fileKey.data(), key.c_str(), entry.keySize) == 0)
{
buf.resize(entry.dataSize);
f.read(&buf[0], entry.dataSize);
CV_Assert(!f.fail());
seekReadAbsolute(0);
CV_LOG_VERBOSE(NULL, 0, "Read...");
return true;
}
}
if (entry.nextEntryFileOffset == 0)
break;
entryOffset = entry.nextEntryFileOffset;
}
return false;
}
bool write(const std::string& key, std::vector<char>& buf)
{
if (!f.is_open())
{
f.open(fileName_.c_str(), std::ios::in|std::ios::out|std::ios::binary);
if (!f.is_open())
{
f.open(fileName_.c_str(), std::ios::out|std::ios::binary);
if (!f.is_open())
{
CV_LOG_ERROR(NULL, "Can't create file: " << fileName_);
return false;
}
}
}
size_t fileSize = getFileSize();
if (fileSize == 0)
{
// Write header
seekWriteAbsolute(0);
writeUInt32((uint32_t)sourceSignatureSize_);
f.write(sourceSignature_, sourceSignatureSize_);
CV_Assert(!f.fail());
writeUInt32(MAX_ENTRIES);
memset(entryOffsets, 0, sizeof(entryOffsets));
f.write((char*)entryOffsets, sizeof(entryOffsets));
CV_Assert(!f.fail());
f.flush();
CV_Assert(!f.fail());
f.close();
f.open(fileName_.c_str(), std::ios::in|std::ios::out|std::ios::binary);
CV_Assert(f.is_open());
fileSize = getFileSize();
}
seekReadAbsolute(0);
// bypass FileHeader
uint32_t fileSourceSignatureSize = readUInt32();
CV_Assert(fileSourceSignatureSize == sourceSignatureSize_);
seekReadRelative(fileSourceSignatureSize);
uint32_t numberOfEntries = readUInt32();
CV_Assert(numberOfEntries > 0);
if (numberOfEntries != MAX_ENTRIES)
{
CV_LOG_ERROR(NULL, "Invalid file: " << fileName_);
clearFile();
return false;
}
size_t tableEntriesOffset = (size_t)f.tellg();
f.read((char*)&entryOffsets[0], sizeof(entryOffsets));
CV_Assert(!f.fail());
uint32_t entryNum = getHash(key);
uint32_t entryOffset = entryOffsets[entryNum];
FileEntry entry;
while (entryOffset > 0)
{
seekReadAbsolute(entryOffset);
//CV_StaticAssert(sizeof(entry) == sizeof(uint32_t) * 3, "");
f.read((char*)&entry, sizeof(entry));
CV_Assert(!f.fail());
cv::AutoBuffer<char> fileKey(entry.keySize + 1);
if (key.size() == entry.keySize)
{
if (entry.keySize > 0)
{
f.read(fileKey.data(), entry.keySize);
CV_Assert(!f.fail());
}
if (0 == memcmp(fileKey.data(), key.c_str(), entry.keySize))
{
// duplicate
CV_LOG_VERBOSE(NULL, 0, "Duplicate key ignored: " << fileName_);
return false;
}
}
if (entry.nextEntryFileOffset == 0)
break;
entryOffset = entry.nextEntryFileOffset;
}
seekReadAbsolute(0);
if (entryOffset > 0)
{
seekWriteAbsolute(entryOffset);
entry.nextEntryFileOffset = (uint32_t)fileSize;
f.write((char*)&entry, sizeof(entry));
CV_Assert(!f.fail());
}
else
{
entryOffsets[entryNum] = (uint32_t)fileSize;
seekWriteAbsolute(tableEntriesOffset);
f.write((char*)entryOffsets, sizeof(entryOffsets));
CV_Assert(!f.fail());
}
seekWriteAbsolute(fileSize);
entry.nextEntryFileOffset = 0;
entry.dataSize = (uint32_t)buf.size();
entry.keySize = (uint32_t)key.size();
f.write((char*)&entry, sizeof(entry));
CV_Assert(!f.fail());
f.write(key.c_str(), entry.keySize);
CV_Assert(!f.fail());
f.write(&buf[0], entry.dataSize);
CV_Assert(!f.fail());
f.flush();
CV_Assert(!f.fail());
CV_LOG_VERBOSE(NULL, 0, "Write... (" << buf.size() << " bytes)");
return true;
}
};
#endif // OPENCV_HAVE_FILESYSTEM_SUPPORT
// true if we have initialized OpenCL subsystem with available platforms
static bool g_isOpenCVActivated = false;
bool haveOpenCL()
{
CV_TRACE_FUNCTION();
#ifdef HAVE_OPENCL
static bool g_isOpenCLInitialized = false;
static bool g_isOpenCLAvailable = false;
if (!g_isOpenCLInitialized)
{
CV_TRACE_REGION("Init_OpenCL_Runtime");
const char* envPath = getenv("OPENCV_OPENCL_RUNTIME");
if (envPath)
{
if (cv::String(envPath) == "disabled")
{
g_isOpenCLAvailable = false;
g_isOpenCLInitialized = true;
}
}
CV_LOG_INFO(NULL, "Initialize OpenCL runtime...");
try
{
cl_uint n = 0;
g_isOpenCLAvailable = ::clGetPlatformIDs(0, NULL, &n) == CL_SUCCESS;
g_isOpenCVActivated = n > 0;
}
catch (...)
{
g_isOpenCLAvailable = false;
}
g_isOpenCLInitialized = true;
}
return g_isOpenCLAvailable;
#else
return false;
#endif
}
bool useOpenCL()
{
CoreTLSData& data = getCoreTlsData();
if (data.useOpenCL < 0)
{
try
{
data.useOpenCL = (int)(haveOpenCL() && Device::getDefault().ptr() && Device::getDefault().available()) ? 1 : 0;
}
catch (...)
{
data.useOpenCL = 0;
}
}
return data.useOpenCL > 0;
}
#ifdef HAVE_OPENCL
bool isOpenCLActivated()
{
if (!g_isOpenCVActivated)
return false; // prevent unnecessary OpenCL activation via useOpenCL()->haveOpenCL() calls
return useOpenCL();
}
#endif
void setUseOpenCL(bool flag)
{
CV_TRACE_FUNCTION();
CoreTLSData& data = getCoreTlsData();
if (!flag)
{
data.useOpenCL = 0;
}
else if( haveOpenCL() )
{
data.useOpenCL = (Device::getDefault().ptr() != NULL) ? 1 : 0;
}
}
#ifdef HAVE_CLAMDBLAS
class AmdBlasHelper
{
public:
static AmdBlasHelper & getInstance()
{
CV_SINGLETON_LAZY_INIT_REF(AmdBlasHelper, new AmdBlasHelper())
}
bool isAvailable() const
{
return g_isAmdBlasAvailable;
}
~AmdBlasHelper()
{
try
{
clAmdBlasTeardown();
}
catch (...) { }
}
protected:
AmdBlasHelper()
{
if (!g_isAmdBlasInitialized)
{
AutoLock lock(getInitializationMutex());
if (!g_isAmdBlasInitialized)
{
if (haveOpenCL())
{
try
{
g_isAmdBlasAvailable = clAmdBlasSetup() == clAmdBlasSuccess;
}
catch (...)
{
g_isAmdBlasAvailable = false;
}
}
else
g_isAmdBlasAvailable = false;
g_isAmdBlasInitialized = true;
}
}