gkernel.hpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  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) 2018-2021 Intel Corporation
  6. #ifndef OPENCV_GAPI_GKERNEL_HPP
  7. #define OPENCV_GAPI_GKERNEL_HPP
  8. #include <functional>
  9. #include <iostream>
  10. #include <string> // string
  11. #include <type_traits> // false_type, true_type
  12. #include <unordered_map> // map (for GKernelPackage)
  13. #include <utility> // tuple
  14. #include <opencv2/gapi/gcommon.hpp> // CompileArgTag
  15. #include <opencv2/gapi/util/util.hpp> // Seq
  16. #include <opencv2/gapi/gcall.hpp>
  17. #include <opencv2/gapi/garg.hpp> // GArg
  18. #include <opencv2/gapi/gmetaarg.hpp> // GMetaArg
  19. #include <opencv2/gapi/gtype_traits.hpp> // GTypeTraits
  20. #include <opencv2/gapi/util/compiler_hints.hpp> //suppress_unused_warning
  21. #include <opencv2/gapi/gtransform.hpp>
  22. namespace cv {
  23. struct GTypeInfo
  24. {
  25. GShape shape;
  26. cv::detail::OpaqueKind kind;
  27. detail::HostCtor ctor;
  28. };
  29. using GShapes = std::vector<GShape>;
  30. using GKinds = std::vector<cv::detail::OpaqueKind>;
  31. using GCtors = std::vector<detail::HostCtor>;
  32. using GTypesInfo = std::vector<GTypeInfo>;
  33. // GKernel describes kernel API to the system
  34. // FIXME: add attributes of a kernel, (e.g. number and types
  35. // of inputs, etc)
  36. struct GAPI_EXPORTS GKernel
  37. {
  38. using M = std::function<GMetaArgs(const GMetaArgs &, const GArgs &)>;
  39. std::string name; // kernel ID, defined by its API (signature)
  40. std::string tag; // some (implementation-specific) tag
  41. M outMeta; // generic adaptor to API::outMeta(...)
  42. GShapes outShapes; // types (shapes) kernel's outputs
  43. GKinds inKinds; // kinds of kernel's inputs (fixme: below)
  44. GCtors outCtors; // captured constructors for template output types
  45. };
  46. // TODO: It's questionable if inKinds should really be here. Instead,
  47. // this information could come from meta.
  48. // GKernelImpl describes particular kernel implementation to the system
  49. struct GAPI_EXPORTS GKernelImpl
  50. {
  51. util::any opaque; // backend-specific opaque info
  52. GKernel::M outMeta; // for deserialized graphs, the outMeta is taken here
  53. };
  54. template<typename, typename> class GKernelTypeM;
  55. namespace detail
  56. {
  57. ////////////////////////////////////////////////////////////////////////////
  58. // yield() is used in graph construction time as a generic method to obtain
  59. // lazy "return value" of G-API operations
  60. //
  61. template<typename T> struct Yield;
  62. template<> struct Yield<cv::GMat>
  63. {
  64. static inline cv::GMat yield(cv::GCall &call, int i) { return call.yield(i); }
  65. };
  66. template<> struct Yield<cv::GMatP>
  67. {
  68. static inline cv::GMatP yield(cv::GCall &call, int i) { return call.yieldP(i); }
  69. };
  70. template<> struct Yield<cv::GScalar>
  71. {
  72. static inline cv::GScalar yield(cv::GCall &call, int i) { return call.yieldScalar(i); }
  73. };
  74. template<typename U> struct Yield<cv::GArray<U> >
  75. {
  76. static inline cv::GArray<U> yield(cv::GCall &call, int i) { return call.yieldArray<U>(i); }
  77. };
  78. template<typename U> struct Yield<cv::GOpaque<U> >
  79. {
  80. static inline cv::GOpaque<U> yield(cv::GCall &call, int i) { return call.yieldOpaque<U>(i); }
  81. };
  82. template<> struct Yield<GFrame>
  83. {
  84. static inline cv::GFrame yield(cv::GCall &call, int i) { return call.yieldFrame(i); }
  85. };
  86. ////////////////////////////////////////////////////////////////////////////
  87. // Helper classes which brings outputMeta() marshalling to kernel
  88. // implementations
  89. //
  90. // 1. MetaType establishes G#Type -> G#Meta mapping between G-API dynamic
  91. // types and its metadata descriptor types.
  92. // This mapping is used to transform types to call outMeta() callback.
  93. template<typename T> struct MetaType;
  94. template<> struct MetaType<cv::GMat> { using type = GMatDesc; };
  95. template<> struct MetaType<cv::GMatP> { using type = GMatDesc; };
  96. template<> struct MetaType<cv::GFrame> { using type = GFrameDesc; };
  97. template<> struct MetaType<cv::GScalar> { using type = GScalarDesc; };
  98. template<typename U> struct MetaType<cv::GArray<U> > { using type = GArrayDesc; };
  99. template<typename U> struct MetaType<cv::GOpaque<U> > { using type = GOpaqueDesc; };
  100. template<typename T> struct MetaType { using type = T; }; // opaque args passed as-is
  101. // FIXME: Move it to type traits?
  102. // 2. Hacky test based on MetaType to check if we operate on G-* type or not
  103. template<typename T> using is_nongapi_type = std::is_same<T, typename MetaType<T>::type>;
  104. // 3. Two ways to transform input arguments to its meta - for G-* and non-G* types:
  105. template<typename T>
  106. typename std::enable_if<!is_nongapi_type<T>::value, typename MetaType<T>::type>
  107. ::type get_in_meta(const GMetaArgs &in_meta, const GArgs &, int idx)
  108. {
  109. return util::get<typename MetaType<T>::type>(in_meta.at(idx));
  110. }
  111. template<typename T>
  112. typename std::enable_if<is_nongapi_type<T>::value, T>
  113. ::type get_in_meta(const GMetaArgs &, const GArgs &in_args, int idx)
  114. {
  115. return in_args.at(idx).template get<T>();
  116. }
  117. // 4. The MetaHelper itself: an entity which generates outMeta() call
  118. // based on kernel signature, with arguments properly substituted.
  119. // 4.1 - case for multiple return values
  120. // FIXME: probably can be simplified with std::apply or analogue.
  121. template<typename, typename, typename>
  122. struct MetaHelper;
  123. template<typename K, typename... Ins, typename... Outs>
  124. struct MetaHelper<K, std::tuple<Ins...>, std::tuple<Outs...> >
  125. {
  126. template<int... IIs, int... OIs>
  127. static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta,
  128. const GArgs &in_args,
  129. detail::Seq<IIs...>,
  130. detail::Seq<OIs...>)
  131. {
  132. // FIXME: decay?
  133. using R = std::tuple<typename MetaType<Outs>::type...>;
  134. const R r = K::outMeta( get_in_meta<Ins>(in_meta, in_args, IIs)... );
  135. return GMetaArgs{ GMetaArg(std::get<OIs>(r))... };
  136. }
  137. // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?)
  138. static GMetaArgs getOutMeta(const GMetaArgs &in_meta,
  139. const GArgs &in_args)
  140. {
  141. return getOutMeta_impl(in_meta,
  142. in_args,
  143. typename detail::MkSeq<sizeof...(Ins)>::type(),
  144. typename detail::MkSeq<sizeof...(Outs)>::type());
  145. }
  146. };
  147. // 4.1 - case for a single return value
  148. // FIXME: How to avoid duplication here?
  149. template<typename K, typename... Ins, typename Out>
  150. struct MetaHelper<K, std::tuple<Ins...>, Out >
  151. {
  152. template<int... IIs>
  153. static GMetaArgs getOutMeta_impl(const GMetaArgs &in_meta,
  154. const GArgs &in_args,
  155. detail::Seq<IIs...>)
  156. {
  157. // FIXME: decay?
  158. using R = typename MetaType<Out>::type;
  159. const R r = K::outMeta( get_in_meta<Ins>(in_meta, in_args, IIs)... );
  160. return GMetaArgs{ GMetaArg(r) };
  161. }
  162. // FIXME: help users identify how outMeta must look like (via default impl w/static_assert?)
  163. static GMetaArgs getOutMeta(const GMetaArgs &in_meta,
  164. const GArgs &in_args)
  165. {
  166. return getOutMeta_impl(in_meta,
  167. in_args,
  168. typename detail::MkSeq<sizeof...(Ins)>::type());
  169. }
  170. };
  171. ////////////////////////////////////////////////////////////////////////////
  172. // Helper class to introduce tags to calls. By default there's no tag
  173. struct NoTag {
  174. static constexpr const char *tag() { return ""; }
  175. };
  176. } // namespace detail
  177. // GKernelType and GKernelTypeM are base classes which implement typed ::on()
  178. // method based on kernel signature. GKernelTypeM stands for multiple-return-value kernels
  179. //
  180. // G_TYPED_KERNEL and G_TYPED_KERNEL_M macros inherit user classes from GKernelType and
  181. // GKernelTypeM respectively.
  182. template<typename K, typename... R, typename... Args>
  183. class GKernelTypeM<K, std::function<std::tuple<R...>(Args...)> >
  184. : public detail::MetaHelper<K, std::tuple<Args...>, std::tuple<R...>>
  185. , public detail::NoTag
  186. {
  187. template<int... IIs>
  188. static std::tuple<R...> yield(cv::GCall &call, detail::Seq<IIs...>)
  189. {
  190. return std::make_tuple(detail::Yield<R>::yield(call, IIs)...);
  191. }
  192. public:
  193. using InArgs = std::tuple<Args...>;
  194. using OutArgs = std::tuple<R...>;
  195. // TODO: Args&&... here?
  196. static std::tuple<R...> on(Args... args)
  197. {
  198. cv::GCall call(GKernel{ K::id()
  199. , K::tag()
  200. , &K::getOutMeta
  201. , {detail::GTypeTraits<R>::shape...}
  202. , {detail::GTypeTraits<Args>::op_kind...}
  203. , {detail::GObtainCtor<R>::get()...}});
  204. call.pass(args...); // TODO: std::forward() here?
  205. return yield(call, typename detail::MkSeq<sizeof...(R)>::type());
  206. }
  207. };
  208. template<typename, typename> class GKernelType;
  209. template<typename K, typename R, typename... Args>
  210. class GKernelType<K, std::function<R(Args...)> >
  211. : public detail::MetaHelper<K, std::tuple<Args...>, R>
  212. , public detail::NoTag
  213. {
  214. public:
  215. using InArgs = std::tuple<Args...>;
  216. using OutArgs = std::tuple<R>;
  217. static R on(Args... args)
  218. {
  219. cv::GCall call(GKernel{ K::id()
  220. , K::tag()
  221. , &K::getOutMeta
  222. , {detail::GTypeTraits<R>::shape}
  223. , {detail::GTypeTraits<Args>::op_kind...}
  224. , {detail::GObtainCtor<R>::get()}});
  225. call.pass(args...);
  226. return detail::Yield<R>::yield(call, 0);
  227. }
  228. };
  229. namespace detail {
  230. // This tiny class eliminates the semantic difference between
  231. // GKernelType and GKernelTypeM.
  232. template<typename, typename> class KernelTypeMedium;
  233. template<typename K, typename... R, typename... Args>
  234. class KernelTypeMedium<K, std::function<std::tuple<R...>(Args...)>> :
  235. public cv::GKernelTypeM<K, std::function<std::tuple<R...>(Args...)>> {};
  236. template<typename K, typename R, typename... Args>
  237. class KernelTypeMedium<K, std::function<R(Args...)>> :
  238. public cv::GKernelType<K, std::function<R(Args...)>> {};
  239. } // namespace detail
  240. } // namespace cv
  241. // FIXME: I don't know a better way so far. Feel free to suggest one
  242. // The problem is that every typed kernel should have ::id() but body
  243. // of the class is defined by user (with outMeta, other stuff)
  244. //! @cond IGNORED
  245. #define G_ID_HELPER_CLASS(Class) Class##IdHelper
  246. #define G_ID_HELPER_BODY(Class, Id) \
  247. struct G_ID_HELPER_CLASS(Class) \
  248. { \
  249. static constexpr const char * id() {return Id;} \
  250. }; \
  251. //! @endcond
  252. #define GET_G_TYPED_KERNEL(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, NAME, ...) NAME
  253. #define COMBINE_SIGNATURE(...) __VA_ARGS__
  254. // Ensure correct __VA_ARGS__ expansion on Windows
  255. #define __WRAP_VAARGS(x) x
  256. /**
  257. * Helper for G_TYPED_KERNEL declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api)
  258. * for more details.
  259. *
  260. * @param Class type name for this operation.
  261. * @param API an `std::function<>`-like signature for the operation;
  262. * return type is a single value or a tuple of multiple values.
  263. * @param Id string identifier for the operation. Must be unique.
  264. */
  265. #define G_TYPED_KERNEL_HELPER(Class, API, Id) \
  266. G_ID_HELPER_BODY(Class, Id) \
  267. struct Class final: public cv::detail::KernelTypeMedium<Class, std::function API >, \
  268. public G_ID_HELPER_CLASS(Class)
  269. // {body} is to be defined by user
  270. #define G_TYPED_KERNEL_HELPER_2(Class, _1, _2, Id) \
  271. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2), Id)
  272. #define G_TYPED_KERNEL_HELPER_3(Class, _1, _2, _3, Id) \
  273. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3), Id)
  274. #define G_TYPED_KERNEL_HELPER_4(Class, _1, _2, _3, _4, Id) \
  275. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4), Id)
  276. #define G_TYPED_KERNEL_HELPER_5(Class, _1, _2, _3, _4, _5, Id) \
  277. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5), Id)
  278. #define G_TYPED_KERNEL_HELPER_6(Class, _1, _2, _3, _4, _5, _6, Id) \
  279. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6), Id)
  280. #define G_TYPED_KERNEL_HELPER_7(Class, _1, _2, _3, _4, _5, _6, _7, Id) \
  281. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7), Id)
  282. #define G_TYPED_KERNEL_HELPER_8(Class, _1, _2, _3, _4, _5, _6, _7, _8, Id) \
  283. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8), Id)
  284. #define G_TYPED_KERNEL_HELPER_9(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, Id) \
  285. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9), Id)
  286. #define G_TYPED_KERNEL_HELPER_10(Class, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, Id) \
  287. G_TYPED_KERNEL_HELPER(Class, COMBINE_SIGNATURE(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10), Id)
  288. /**
  289. * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api)
  290. * for more details.
  291. *
  292. * @param Class type name for this operation.
  293. */
  294. #define G_TYPED_KERNEL(Class, ...) __WRAP_VAARGS(GET_G_TYPED_KERNEL(__VA_ARGS__, \
  295. G_TYPED_KERNEL_HELPER_10, \
  296. G_TYPED_KERNEL_HELPER_9, \
  297. G_TYPED_KERNEL_HELPER_8, \
  298. G_TYPED_KERNEL_HELPER_7, \
  299. G_TYPED_KERNEL_HELPER_6, \
  300. G_TYPED_KERNEL_HELPER_5, \
  301. G_TYPED_KERNEL_HELPER_4, \
  302. G_TYPED_KERNEL_HELPER_3, \
  303. G_TYPED_KERNEL_HELPER_2, \
  304. G_TYPED_KERNEL_HELPER)(Class, __VA_ARGS__)) \
  305. /**
  306. * Declares a new G-API Operation. See [Kernel API](@ref gapi_kernel_api) for more details.
  307. *
  308. * @deprecated This macro is deprecated in favor of `G_TYPED_KERNEL` that is used for declaring any
  309. * G-API Operation.
  310. *
  311. * @param Class type name for this operation.
  312. */
  313. #define G_TYPED_KERNEL_M G_TYPED_KERNEL
  314. #define G_API_OP G_TYPED_KERNEL
  315. #define G_API_OP_M G_API_OP
  316. namespace cv
  317. {
  318. namespace gapi
  319. {
  320. // Prework: model "Device" API before it gets to G-API headers.
  321. // FIXME: Don't mix with internal Backends class!
  322. /// @private
  323. class GAPI_EXPORTS GBackend
  324. {
  325. public:
  326. class Priv;
  327. // TODO: make it template (call `new` within??)
  328. GBackend();
  329. explicit GBackend(std::shared_ptr<Priv> &&p);
  330. Priv& priv();
  331. const Priv& priv() const;
  332. std::size_t hash() const;
  333. bool operator== (const GBackend &rhs) const;
  334. private:
  335. std::shared_ptr<Priv> m_priv;
  336. };
  337. inline bool operator != (const GBackend &lhs, const GBackend &rhs)
  338. {
  339. return !(lhs == rhs);
  340. }
  341. } // namespace gapi
  342. } // namespace cv
  343. namespace std
  344. {
  345. template<> struct hash<cv::gapi::GBackend>
  346. {
  347. std::size_t operator() (const cv::gapi::GBackend &b) const
  348. {
  349. return b.hash();
  350. }
  351. };
  352. } // namespace std
  353. namespace cv {
  354. class GAPI_EXPORTS_W_SIMPLE GKernelPackage;
  355. namespace gapi {
  356. GAPI_EXPORTS cv::GKernelPackage combine(const cv::GKernelPackage &lhs,
  357. const cv::GKernelPackage &rhs);
  358. /// @private
  359. class GFunctor
  360. {
  361. public:
  362. virtual cv::GKernelImpl impl() const = 0;
  363. virtual cv::gapi::GBackend backend() const = 0;
  364. const char* id() const { return m_id; }
  365. virtual ~GFunctor() = default;
  366. protected:
  367. GFunctor(const char* id) : m_id(id) { };
  368. private:
  369. const char* m_id;
  370. };
  371. } // namespace gapi
  372. /** \addtogroup gapi_compile_args
  373. * @{
  374. */
  375. // FIXME: Hide implementation
  376. /**
  377. * @brief A container class for heterogeneous kernel
  378. * implementation collections and graph transformations.
  379. *
  380. * GKernelPackage is a special container class which stores kernel
  381. * _implementations_ and graph _transformations_. Objects of this class
  382. * are created and passed to cv::GComputation::compile() to specify
  383. * which kernels to use and which transformations to apply in the
  384. * compiled graph. GKernelPackage may contain kernels of
  385. * different backends, e.g. be heterogeneous.
  386. *
  387. * The most easy way to create a kernel package is to use function
  388. * cv::gapi::kernels(). This template functions takes kernel
  389. * implementations in form of type list (variadic template) and
  390. * generates a kernel package atop of that.
  391. *
  392. * Kernel packages can be also generated programmatically, starting
  393. * with an empty package (created with the default constructor)
  394. * and then by populating it with kernels via call to
  395. * GKernelPackage::include(). Note this method is also a template
  396. * one since G-API kernel and transformation implementations are _types_,
  397. * not objects.
  398. *
  399. * Finally, two kernel packages can be combined into a new one
  400. * with function cv::gapi::combine().
  401. */
  402. class GAPI_EXPORTS_W_SIMPLE GKernelPackage
  403. {
  404. /// @private
  405. using M = std::unordered_map<std::string, std::pair<cv::gapi::GBackend, cv::GKernelImpl>>;
  406. /// @private
  407. M m_id_kernels;
  408. /// @private
  409. std::vector<GTransform> m_transformations;
  410. protected:
  411. /// @private
  412. // Remove ALL implementations of the given API (identified by ID)
  413. void removeAPI(const std::string &id);
  414. /// @private
  415. // Partial include() specialization for kernels
  416. template <typename KImpl>
  417. typename std::enable_if<(std::is_base_of<cv::detail::KernelTag, KImpl>::value), void>::type
  418. includeHelper()
  419. {
  420. auto backend = KImpl::backend();
  421. auto kernel_id = KImpl::API::id();
  422. auto kernel_impl = GKernelImpl{KImpl::kernel(), &KImpl::API::getOutMeta};
  423. removeAPI(kernel_id);
  424. m_id_kernels[kernel_id] = std::make_pair(backend, kernel_impl);
  425. }
  426. /// @private
  427. // Partial include() specialization for transformations
  428. template <typename TImpl>
  429. typename std::enable_if<(std::is_base_of<cv::detail::TransformTag, TImpl>::value), void>::type
  430. includeHelper()
  431. {
  432. m_transformations.emplace_back(TImpl::transformation());
  433. }
  434. public:
  435. void include(const cv::gapi::GFunctor& functor);
  436. /**
  437. * @brief Returns total number of kernels
  438. * in the package (across all backends included)
  439. *
  440. * @return a number of kernels in the package
  441. */
  442. std::size_t size() const;
  443. /**
  444. * @brief Returns vector of transformations included in the package
  445. *
  446. * @return vector of transformations included in the package
  447. */
  448. const std::vector<GTransform>& get_transformations() const;
  449. /**
  450. * @brief Returns vector of kernel ids included in the package
  451. *
  452. * @return vector of kernel ids included in the package
  453. */
  454. std::vector<std::string> get_kernel_ids() const;
  455. /**
  456. * @brief Test if a particular kernel _implementation_ KImpl is
  457. * included in this kernel package.
  458. *
  459. * @sa includesAPI()
  460. *
  461. * @note cannot be applied to transformations
  462. *
  463. * @return true if there is such kernel, false otherwise.
  464. */
  465. template<typename KImpl>
  466. bool includes() const
  467. {
  468. static_assert(std::is_base_of<cv::detail::KernelTag, KImpl>::value,
  469. "includes() can be applied to kernels only");
  470. auto kernel_it = m_id_kernels.find(KImpl::API::id());
  471. return kernel_it != m_id_kernels.end() &&
  472. kernel_it->second.first == KImpl::backend();
  473. }
  474. /**
  475. * @brief Remove all kernels associated with the given backend
  476. * from the package.
  477. *
  478. * Does nothing if there's no kernels of this backend in the package.
  479. *
  480. * @param backend backend which kernels to remove
  481. */
  482. void remove(const cv::gapi::GBackend& backend);
  483. /**
  484. * @brief Remove all kernels implementing the given API from
  485. * the package.
  486. *
  487. * Does nothing if there's no kernels implementing the given interface.
  488. */
  489. template<typename KAPI>
  490. void remove()
  491. {
  492. removeAPI(KAPI::id());
  493. }
  494. // FIXME: Rename to includes() and distinguish API/impl case by
  495. // statically?
  496. /**
  497. * Check if package contains ANY implementation of a kernel API
  498. * by API type.
  499. */
  500. template<typename KAPI>
  501. bool includesAPI() const
  502. {
  503. return includesAPI(KAPI::id());
  504. }
  505. /// @private
  506. bool includesAPI(const std::string &id) const;
  507. // FIXME: The below comment is wrong, and who needs this function?
  508. /**
  509. * @brief Find a kernel (by its API)
  510. *
  511. * Returns implementation corresponding id.
  512. * Throws if nothing found.
  513. *
  514. * @return Backend which hosts matching kernel implementation.
  515. *
  516. */
  517. template<typename KAPI>
  518. cv::gapi::GBackend lookup() const
  519. {
  520. return lookup(KAPI::id()).first;
  521. }
  522. /// @private
  523. std::pair<cv::gapi::GBackend, cv::GKernelImpl>
  524. lookup(const std::string &id) const;
  525. // FIXME: No overwrites allowed?
  526. /**
  527. * @brief Put a new kernel implementation or a new transformation
  528. * KImpl into the package.
  529. */
  530. template<typename KImpl>
  531. void include()
  532. {
  533. includeHelper<KImpl>();
  534. }
  535. /**
  536. * @brief Adds a new kernel based on it's backend and id into the kernel package
  537. *
  538. * @param backend backend associated with the kernel
  539. * @param kernel_id a name/id of the kernel
  540. */
  541. void include(const cv::gapi::GBackend& backend, const std::string& kernel_id);
  542. /**
  543. * @brief Lists all backends which are included into package
  544. *
  545. * @return vector of backends
  546. */
  547. std::vector<cv::gapi::GBackend> backends() const;
  548. // TODO: Doxygen bug -- it wants me to place this comment
  549. // here, not below.
  550. /**
  551. * @brief Create a new package based on `lhs` and `rhs`.
  552. *
  553. * @param lhs "Left-hand-side" package in the process
  554. * @param rhs "Right-hand-side" package in the process
  555. * @return a new kernel package.
  556. */
  557. friend GAPI_EXPORTS GKernelPackage cv::gapi::combine(const GKernelPackage &lhs,
  558. const GKernelPackage &rhs);
  559. };
  560. /** @} */
  561. namespace gapi {
  562. using GKernelPackage = cv::GKernelPackage; // Keep backward compatibility
  563. /** \addtogroup gapi_compile_args
  564. * @{
  565. */
  566. /**
  567. * @brief Create a kernel package object containing kernels
  568. * and transformations specified in variadic template argument.
  569. *
  570. * In G-API, kernel implementations and transformations are _types_.
  571. * Every backend has its own kernel API (like GAPI_OCV_KERNEL() and
  572. * GAPI_FLUID_KERNEL()) but all of that APIs define a new type for
  573. * each kernel implementation.
  574. *
  575. * Use this function to pass kernel implementations (defined in
  576. * either way) and transformations to the system. Example:
  577. *
  578. * @snippet samples/cpp/tutorial_code/gapi/doc_snippets/api_ref_snippets.cpp kernels_snippet
  579. *
  580. * Note that kernels() itself is a function returning object, not
  581. * a type, so having `()` at the end is important -- it must be a
  582. * function call.
  583. */
  584. template<typename... KK> GKernelPackage kernels()
  585. {
  586. // FIXME: currently there is no check that transformations' signatures are unique
  587. // and won't be any intersection in graph compilation stage
  588. static_assert(cv::detail::all_unique<typename KK::API...>::value, "Kernels API must be unique");
  589. GKernelPackage pkg;
  590. // For those who wonder - below is a trick to call a number of
  591. // methods based on parameter pack (zeroes just help hiding these
  592. // calls into a sequence which helps to expand this parameter pack).
  593. // Just note that `f(),a` always equals to `a` (with f() called!)
  594. // and parentheses are used to hide function call in the expanded sequence.
  595. // Leading 0 helps to handle case when KK is an empty list (kernels<>()).
  596. int unused[] = { 0, (pkg.include<KK>(), 0)... };
  597. cv::util::suppress_unused_warning(unused);
  598. return pkg;
  599. };
  600. template<typename... FF>
  601. GKernelPackage kernels(FF&... functors)
  602. {
  603. GKernelPackage pkg;
  604. int unused[] = { 0, (pkg.include(functors), 0)... };
  605. cv::util::suppress_unused_warning(unused);
  606. return pkg;
  607. };
  608. /** @} */
  609. /**
  610. * @brief Combines multiple G-API kernel packages into one
  611. *
  612. * @overload
  613. *
  614. * This function successively combines the passed kernel packages using a right fold.
  615. * Calling `combine(a, b, c)` is equal to `combine(a, combine(b, c))`.
  616. *
  617. * @return The resulting kernel package
  618. */
  619. template<typename... Ps>
  620. cv::GKernelPackage combine(const cv::GKernelPackage &a, const cv::GKernelPackage &b, Ps&&... rest)
  621. {
  622. return combine(a, combine(b, rest...));
  623. }
  624. /** \addtogroup gapi_compile_args
  625. * @{
  626. */
  627. /**
  628. * @brief cv::gapi::use_only() is a special combinator which hints G-API to use only
  629. * kernels specified in cv::GComputation::compile() (and not to extend kernels available by
  630. * default with that package).
  631. */
  632. struct GAPI_EXPORTS use_only
  633. {
  634. GKernelPackage pkg;
  635. };
  636. /** @} */
  637. } // namespace gapi
  638. namespace detail
  639. {
  640. template<> struct CompileArgTag<cv::GKernelPackage>
  641. {
  642. static const char* tag() { return "gapi.kernel_package"; }
  643. };
  644. template<> struct CompileArgTag<cv::gapi::use_only>
  645. {
  646. static const char* tag() { return "gapi.use_only"; }
  647. };
  648. } // namespace detail
  649. } // namespace cv
  650. #endif // OPENCV_GAPI_GKERNEL_HPP