gapi_async_test.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  1. // This file is part of OpenCV project.
  2. // It is subject to the license terms in the LICENSE file found in the top-level directory
  3. // of this distribution and at http://opencv.org/license.html.
  4. //
  5. // Copyright (C) 2019 Intel Corporation
  6. #include "test_precomp.hpp"
  7. #include <opencv2/gapi/gcomputation_async.hpp>
  8. #include <opencv2/gapi/gcompiled_async.hpp>
  9. #include <opencv2/gapi/gasync_context.hpp>
  10. #include <condition_variable>
  11. #include <stdexcept>
  12. namespace opencv_test
  13. {
  14. //Main idea behind these tests is to have the same test script that is parameterized in order to test all setups (GCompiled vs apply, callback vs future).
  15. //So these differences are factored into devoted helper classes (mixins) which are then used by the common test script by help of CRTP.
  16. //Actual GAPI Computation with parameters to run on is mixed into test via CRTP as well.
  17. struct SumOfSum2x2 {
  18. cv::GComputation sum_of_sum;
  19. SumOfSum2x2() : sum_of_sum([]{
  20. cv::GMat in;
  21. cv::GScalar out = cv::gapi::sum(in + in);
  22. return GComputation{in, out};
  23. })
  24. {}
  25. const cv::Size sz{2, 2};
  26. cv::Mat in_mat{sz, CV_8U, cv::Scalar(1)};
  27. cv::Scalar out_sc;
  28. cv::GCompiled compile(){
  29. return sum_of_sum.compile(descr_of(in_mat));
  30. }
  31. cv::GComputation& computation(){
  32. return sum_of_sum;
  33. }
  34. cv::GCompileArgs compile_args(){
  35. return {};
  36. }
  37. cv::GRunArgs in_args(){
  38. return cv::gin(in_mat);
  39. }
  40. cv::GRunArgsP out_args(){
  41. return cv::gout(out_sc);
  42. }
  43. void verify(){
  44. EXPECT_EQ(8, out_sc[0]);
  45. }
  46. };
  47. namespace {
  48. G_TYPED_KERNEL(GThrow, <GMat(GMat)>, "org.opencv.test.throw")
  49. {
  50. static GMatDesc outMeta(GMatDesc in) { return in; }
  51. };
  52. struct gthrow_exception : std::runtime_error {
  53. using std::runtime_error::runtime_error;
  54. };
  55. GAPI_OCV_KERNEL(GThrowImpl, GThrow)
  56. {
  57. static void run(const cv::Mat& in, cv::Mat&)
  58. {
  59. //this condition is needed to avoid "Unreachable code" warning on windows inside OCVCallHelper
  60. if (!in.empty())
  61. {
  62. throw gthrow_exception{"test"};
  63. }
  64. }
  65. };
  66. //TODO: unify with callback helper code
  67. struct cancel_struct {
  68. std::atomic<int> num_tasks_to_spawn;
  69. cv::gapi::wip::GAsyncContext ctx;
  70. cancel_struct(int tasks_to_spawn) : num_tasks_to_spawn(tasks_to_spawn) {}
  71. };
  72. G_TYPED_KERNEL(GCancelationAdHoc, <GMat(GMat, cancel_struct*)>, "org.opencv.test.cancel_ad_hoc")
  73. {
  74. static GMatDesc outMeta(GMatDesc in, cancel_struct* ) { return in; }
  75. };
  76. GAPI_OCV_KERNEL(GCancelationAdHocImpl, GCancelationAdHoc)
  77. {
  78. static void run(const cv::Mat& , cancel_struct* cancel_struct_p, cv::Mat&) {
  79. auto& cancel_struct_ = * cancel_struct_p;
  80. auto num_tasks_to_spawn = -- cancel_struct_.num_tasks_to_spawn;
  81. cancel_struct_.ctx.cancel();
  82. EXPECT_GT(num_tasks_to_spawn, 0)<<"Incorrect Test setup - to small number of tasks to feed the queue \n";
  83. }
  84. };
  85. }
  86. struct ExceptionOnExecution {
  87. cv::GComputation throwing_gcomp;
  88. ExceptionOnExecution() : throwing_gcomp([]{
  89. cv::GMat in;
  90. auto gout = GThrow::on(in);
  91. return GComputation{in, gout};
  92. })
  93. {}
  94. const cv::Size sz{2, 2};
  95. cv::Mat in_mat{sz, CV_8U, cv::Scalar(1)};
  96. cv::Mat out;
  97. cv::GCompiled compile(){
  98. return throwing_gcomp.compile(descr_of(in_mat), compile_args());
  99. }
  100. cv::GComputation& computation(){
  101. return throwing_gcomp;
  102. }
  103. cv::GRunArgs in_args(){
  104. return cv::gin(in_mat);
  105. }
  106. cv::GRunArgsP out_args(){
  107. return cv::gout(out);
  108. }
  109. cv::GCompileArgs compile_args(){
  110. auto pkg = cv::gapi::kernels<GThrowImpl>();
  111. return cv::compile_args(pkg);
  112. }
  113. };
  114. struct SelfCanceling {
  115. cv::GComputation self_cancel;
  116. SelfCanceling(cancel_struct* cancel_struct_p) : self_cancel([cancel_struct_p]{
  117. cv::GMat in;
  118. cv::GMat out = GCancelationAdHoc::on(in, cancel_struct_p);
  119. return GComputation{in, out};
  120. })
  121. {}
  122. const cv::Size sz{2, 2};
  123. cv::Mat in_mat{sz, CV_8U, cv::Scalar(1)};
  124. cv::Mat out_mat;
  125. cv::GCompiled compile(){
  126. return self_cancel.compile(descr_of(in_mat), compile_args());
  127. }
  128. cv::GComputation& computation(){
  129. return self_cancel;
  130. }
  131. cv::GRunArgs in_args(){
  132. return cv::gin(in_mat);
  133. }
  134. cv::GRunArgsP out_args(){
  135. return cv::gout(out_mat);
  136. }
  137. cv::GCompileArgs compile_args(){
  138. auto pkg = cv::gapi::kernels<GCancelationAdHocImpl>();
  139. return cv::compile_args(pkg);
  140. }
  141. };
  142. template<typename crtp_final_t>
  143. struct crtp_cast {
  144. template<typename crtp_base_t>
  145. static crtp_final_t* crtp_cast_(crtp_base_t* this_)
  146. {
  147. return static_cast<crtp_final_t*>(this_);
  148. }
  149. };
  150. //Test Mixin, hiding details of callback based notification
  151. template<typename crtp_final_t>
  152. struct CallBack: crtp_cast<crtp_final_t> {
  153. std::atomic<bool> callback_called = {false};
  154. std::mutex mtx;
  155. std::exception_ptr ep;
  156. std::condition_variable cv;
  157. std::function<void(std::exception_ptr)> callback(){
  158. return [&](std::exception_ptr ep_){
  159. ep = ep_;
  160. callback_called = true;
  161. mtx.lock();
  162. mtx.unlock();
  163. cv.notify_one();
  164. };
  165. };
  166. template<typename... Args >
  167. void start_async(Args&&... args){
  168. this->crtp_cast_(this)->async(callback(), std::forward<Args>(args)...);
  169. }
  170. template<typename... Args >
  171. void start_async(cv::gapi::wip::GAsyncContext& ctx, Args&&... args){
  172. this->crtp_cast_(this)->async(ctx, callback(), std::forward<Args>(args)...);
  173. }
  174. void wait_for_result()
  175. {
  176. std::unique_lock<std::mutex> lck{mtx};
  177. cv.wait(lck,[&]{return callback_called == true;});
  178. if (ep)
  179. {
  180. std::rethrow_exception(ep);
  181. }
  182. }
  183. };
  184. //Test Mixin, hiding details of future based notification
  185. template<typename crtp_final_t>
  186. struct Future: crtp_cast<crtp_final_t> {
  187. std::future<void> f;
  188. template<typename... Args >
  189. void start_async(Args&&... args){
  190. f = this->crtp_cast_(this)->async(std::forward<Args>(args)...);
  191. }
  192. void wait_for_result()
  193. {
  194. f.get();
  195. }
  196. };
  197. //Test Mixin, hiding details of using compiled GAPI object
  198. template<typename crtp_final_t>
  199. struct AsyncCompiled : crtp_cast<crtp_final_t>{
  200. template<typename... Args>
  201. auto async(Args&&... args) -> decltype(cv::gapi::wip::async(std::declval<cv::GCompiled&>(), std::forward<Args>(args)...)){
  202. auto gcmpld = this->crtp_cast_(this)->compile();
  203. return cv::gapi::wip::async(gcmpld, std::forward<Args>(args)...);
  204. }
  205. template<typename... Args>
  206. auto async(cv::gapi::wip::GAsyncContext& ctx, Args&&... args) ->
  207. decltype(cv::gapi::wip::async(std::declval<cv::GCompiled&>(), std::forward<Args>(args)..., std::declval<cv::gapi::wip::GAsyncContext&>()))
  208. {
  209. auto gcmpld = this->crtp_cast_(this)->compile();
  210. return cv::gapi::wip::async(gcmpld, std::forward<Args>(args)..., ctx);
  211. }
  212. };
  213. //Test Mixin, hiding details of calling apply (async_apply) on GAPI Computation object
  214. template<typename crtp_final_t>
  215. struct AsyncApply : crtp_cast<crtp_final_t> {
  216. template<typename... Args>
  217. auto async(Args&&... args) ->
  218. decltype(cv::gapi::wip::async_apply(std::declval<cv::GComputation&>(), std::forward<Args>(args)..., std::declval<cv::GCompileArgs>()))
  219. {
  220. return cv::gapi::wip::async_apply(
  221. this->crtp_cast_(this)->computation(), std::forward<Args>(args)..., this->crtp_cast_(this)->compile_args()
  222. );
  223. }
  224. template<typename... Args>
  225. auto async(cv::gapi::wip::GAsyncContext& ctx, Args&&... args) ->
  226. decltype(cv::gapi::wip::async_apply(std::declval<cv::GComputation&>(), std::forward<Args>(args)... , std::declval<cv::GCompileArgs>(), std::declval<cv::gapi::wip::GAsyncContext&>()))
  227. {
  228. return cv::gapi::wip::async_apply(
  229. this->crtp_cast_(this)->computation(), std::forward<Args>(args)..., this->crtp_cast_(this)->compile_args(), ctx
  230. );
  231. }
  232. };
  233. template<typename case_t>
  234. struct normal: ::testing::Test, case_t{};
  235. TYPED_TEST_CASE_P(normal);
  236. TYPED_TEST_P(normal, basic){
  237. //Normal scenario: start function asynchronously and wait for the result, and verify it
  238. this->start_async(this->in_args(), this->out_args());
  239. this->wait_for_result();
  240. this->verify();
  241. }
  242. REGISTER_TYPED_TEST_CASE_P(normal,
  243. basic
  244. );
  245. template<typename case_t>
  246. struct exception: ::testing::Test, case_t{};
  247. TYPED_TEST_CASE_P(exception);
  248. TYPED_TEST_P(exception, basic){
  249. //Exceptional scenario: start function asynchronously and make sure exception is passed to the user
  250. this->start_async(this->in_args(), this->out_args());
  251. EXPECT_THROW(this->wait_for_result(), gthrow_exception);
  252. }
  253. REGISTER_TYPED_TEST_CASE_P(exception,
  254. basic
  255. );
  256. template<typename case_t>
  257. struct stress : ::testing::Test{};
  258. TYPED_TEST_CASE_P(stress);
  259. TYPED_TEST_P(stress, test){
  260. //Some stress testing: use a number of threads to start a bunch of async requests
  261. const std::size_t request_per_thread = 10;
  262. const std::size_t number_of_threads = 4;
  263. auto thread_body = [&](){
  264. std::vector<TypeParam> requests(request_per_thread);
  265. for (auto&& r : requests){
  266. r.start_async(r.in_args(), r.out_args());
  267. }
  268. for (auto&& r : requests){
  269. r.wait_for_result();
  270. r.verify();
  271. }
  272. };
  273. std::vector<std::thread> pool {number_of_threads};
  274. for (auto&& t : pool){
  275. t = std::thread{thread_body};
  276. }
  277. for (auto&& t : pool){
  278. t.join();
  279. }
  280. }
  281. REGISTER_TYPED_TEST_CASE_P(stress, test);
  282. template<typename case_t>
  283. struct cancel : ::testing::Test{};
  284. TYPED_TEST_CASE_P(cancel);
  285. TYPED_TEST_P(cancel, basic)
  286. {
  287. #if defined(__GNUC__) && __GNUC__ >= 11
  288. // std::vector<TypeParam> requests can't handle type with ctor parameter (SelfCanceling)
  289. FAIL() << "Test code is not available due to compilation error with GCC 11";
  290. #else
  291. constexpr int num_tasks = 100;
  292. cancel_struct cancel_struct_ {num_tasks};
  293. std::vector<TypeParam> requests; requests.reserve(num_tasks);
  294. for (auto i = num_tasks; i>0; i--){
  295. requests.emplace_back(&cancel_struct_);
  296. }
  297. for (auto&& r : requests){
  298. //first request will cancel other on it's execution
  299. r.start_async(cancel_struct_.ctx, r.in_args(), r.out_args());
  300. }
  301. unsigned int canceled = 0 ;
  302. for (auto&& r : requests){
  303. try {
  304. r.wait_for_result();
  305. }catch (cv::gapi::wip::GAsyncCanceled&){
  306. ++canceled;
  307. }
  308. }
  309. ASSERT_GT(canceled, 0u);
  310. #endif
  311. }
  312. namespace {
  313. GRunArgs deep_copy_out_args(const GRunArgsP& args ){
  314. GRunArgs result; result.reserve(args.size());
  315. for (auto&& arg : args){
  316. //FIXME: replace this switch with use of visit() on variant, when it will be available
  317. switch (arg.index()){
  318. case GRunArgP::index_of<cv::UMat*>() : result.emplace_back(*util::get<cv::UMat*>(arg)); break;
  319. case GRunArgP::index_of<cv::Mat*>() : result.emplace_back(*util::get<cv::Mat*>(arg)); break;
  320. case GRunArgP::index_of<cv::Scalar*>() : result.emplace_back(*util::get<cv::Scalar*> (arg)); break;
  321. case GRunArgP::index_of<cv::detail::VectorRef>() : result.emplace_back(util::get<cv::detail::VectorRef> (arg)); break;
  322. default : ;
  323. }
  324. }
  325. return result;
  326. }
  327. GRunArgsP args_p_from_args(GRunArgs& args){
  328. GRunArgsP result; result.reserve(args.size());
  329. for (auto&& arg : args){
  330. switch (arg.index()){
  331. case GRunArg::index_of<cv::Mat>() : result.emplace_back(&util::get<cv::Mat>(arg)); break;
  332. case GRunArg::index_of<cv::UMat>() : result.emplace_back(&util::get<cv::UMat>(arg)); break;
  333. case GRunArg::index_of<cv::Scalar>() : result.emplace_back(&util::get<cv::Scalar> (arg)); break;
  334. case GRunArg::index_of<cv::detail::VectorRef>() : result.emplace_back(util::get<cv::detail::VectorRef> (arg)); break;
  335. default : ;
  336. }
  337. }
  338. return result;
  339. }
  340. }
  341. REGISTER_TYPED_TEST_CASE_P(cancel, basic);
  342. template<typename case_t>
  343. struct output_args_lifetime : ::testing::Test{
  344. static constexpr const int num_of_requests = 20;
  345. };
  346. TYPED_TEST_CASE_P(output_args_lifetime);
  347. //There are intentionally no actual checks (asserts and verify) in output_args_lifetime tests.
  348. //They are more of example use-cases than real tests. (ASAN/valgrind can still catch issues here)
  349. TYPED_TEST_P(output_args_lifetime, callback){
  350. std::atomic<int> active_requests = {0};
  351. for (int i=0; i<this->num_of_requests; i++)
  352. {
  353. TypeParam r;
  354. //As output arguments are __captured by reference__ calling code
  355. //__must__ ensure they live long enough to complete asynchronous activity.
  356. //(i.e. live at least until callback is called)
  357. auto out_args_ptr = std::make_shared<cv::GRunArgs>(deep_copy_out_args(r.out_args()));
  358. //Extend lifetime of out_args_ptr content by capturing it into a callback
  359. auto cb = [&active_requests, out_args_ptr](std::exception_ptr ){
  360. --active_requests;
  361. };
  362. ++active_requests;
  363. r.async(cb, r.in_args(), args_p_from_args(*out_args_ptr));
  364. }
  365. while(active_requests){
  366. std::this_thread::sleep_for(std::chrono::milliseconds{2});
  367. }
  368. }
  369. TYPED_TEST_P(output_args_lifetime, future){
  370. std::vector<std::future<void>> fs(this->num_of_requests);
  371. std::vector<std::shared_ptr<cv::GRunArgs>> out_ptrs(this->num_of_requests);
  372. for (int i=0; i<this->num_of_requests; i++)
  373. {
  374. TypeParam r;
  375. //As output arguments are __captured by reference__ calling code
  376. //__must__ ensure they live long enough to complete asynchronous activity.
  377. //(i.e. live at least until future.get()/wait() is returned)
  378. auto out_args_ptr = std::make_shared<cv::GRunArgs>(deep_copy_out_args(r.out_args()));
  379. //Extend lifetime of out_args_ptr content
  380. out_ptrs[i] = out_args_ptr;
  381. fs[i] = r.async(r.in_args(), args_p_from_args(*out_args_ptr));
  382. }
  383. for (auto const& ftr : fs ){
  384. ftr.wait();
  385. }
  386. }
  387. REGISTER_TYPED_TEST_CASE_P(output_args_lifetime, callback, future);
  388. //little helpers to match up all combinations of setups
  389. template<typename compute_fixture_t, template<typename> class... args_t>
  390. struct Case
  391. : compute_fixture_t,
  392. args_t<Case<compute_fixture_t, args_t...>> ...
  393. {
  394. template<typename... Args>
  395. Case(Args&&... args) : compute_fixture_t(std::forward<Args>(args)...) { }
  396. Case(Case const & ) = default;
  397. Case(Case && ) = default;
  398. Case() = default;
  399. };
  400. template<typename computation_t>
  401. using cases = ::testing::Types<
  402. Case<computation_t, CallBack, AsyncCompiled>,
  403. Case<computation_t, CallBack, AsyncApply>,
  404. Case<computation_t, Future, AsyncCompiled>,
  405. Case<computation_t, Future, AsyncApply>
  406. >;
  407. INSTANTIATE_TYPED_TEST_CASE_P(AsyncAPINormalFlow_, normal, cases<SumOfSum2x2>);
  408. INSTANTIATE_TYPED_TEST_CASE_P(AsyncAPIExceptionHandling_, exception, cases<ExceptionOnExecution>);
  409. INSTANTIATE_TYPED_TEST_CASE_P(AsyncAPIStress, stress, cases<SumOfSum2x2>);
  410. INSTANTIATE_TYPED_TEST_CASE_P(AsyncAPICancelation, cancel, cases<SelfCanceling>);
  411. template<typename computation_t>
  412. using explicit_wait_cases = ::testing::Types<
  413. Case<computation_t, AsyncCompiled>,
  414. Case<computation_t, AsyncApply>,
  415. Case<computation_t, AsyncCompiled>,
  416. Case<computation_t, AsyncApply>
  417. >;
  418. INSTANTIATE_TYPED_TEST_CASE_P(AsyncAPIOutArgsLifetTime, output_args_lifetime, explicit_wait_cases<SumOfSum2x2>);
  419. } // namespace opencv_test