cnstream_frame_va.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*************************************************************************
  2. * Copyright (C) [2019] by Cambricon, Inc. All rights reserved
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * The above copyright notice and this permission notice shall be included in
  11. * all copies or substantial portions of the Software.
  12. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13. * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  15. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. * THE SOFTWARE.
  19. *************************************************************************/
  20. #ifndef CNSTREAM_FRAME_VA_HPP_
  21. #define CNSTREAM_FRAME_VA_HPP_
  22. /**
  23. * @file cnstream_frame_va.hpp
  24. *
  25. * This file contains a declaration of the CNFrameData & CNInferObject struct and its substructure.
  26. */
  27. #include <opencv2/highgui/highgui.hpp>
  28. #include <opencv2/imgproc/imgproc.hpp>
  29. #if (CV_MAJOR_VERSION >= 3)
  30. #include <opencv2/imgcodecs/imgcodecs.hpp>
  31. #endif
  32. #include <memory>
  33. #include <mutex>
  34. #include <string>
  35. #include <unordered_map>
  36. #include <utility>
  37. #include <vector>
  38. #include "cnstream_common.hpp"
  39. #include "cnstream_frame.hpp"
  40. #include "cnstream_syncmem.hpp"
  41. #include "private/cnstream_allocator.hpp"
  42. #include "util/cnstream_any.hpp"
  43. constexpr int CN_MAX_PLANES = 6;
  44. namespace cnstream {
  45. /**
  46. * @enum CNDataFormat
  47. *
  48. * @brief Enumeration variables describling the pixel format of the data in CNDataFrame.
  49. */
  50. enum class CNDataFormat {
  51. CN_INVALID = -1, /*!< This frame is invalid. */
  52. CN_PIXEL_FORMAT_YUV420_NV21 = 0, /*!< This frame is in the YUV420SP(NV21) format. */
  53. CN_PIXEL_FORMAT_YUV420_NV12, /*!< This frame is in the YUV420sp(NV12) format. */
  54. CN_PIXEL_FORMAT_BGR24, /*!< This frame is in the BGR24 format. */
  55. CN_PIXEL_FORMAT_RGB24, /*!< This frame is in the RGB24 format. */
  56. CN_PIXEL_FORMAT_ARGB32, /*!< This frame is in the ARGB32 format. */
  57. CN_PIXEL_FORMAT_ABGR32, /*!< This frame is in the ABGR32 format. */
  58. CN_PIXEL_FORMAT_RGBA32, /*!< This frame is in the RGBA32 format. */
  59. CN_PIXEL_FORMAT_BGRA32 /*!< This frame is in the BGRA32 format. */
  60. };
  61. /**
  62. * @struct DevContext
  63. *
  64. * @brief DevContext is a structure holding the information that CNDataFrame data is allocated by CPU or MLU.
  65. */
  66. struct DevContext {
  67. enum class DevType {
  68. INVALID = -1, /*!< Invalid device type. */
  69. CPU = 0, /*!< The data is allocated by CPU. */
  70. MLU = 1, /*!< The data is allocated by MLU. */
  71. } dev_type = DevType::INVALID; /*!< Device type. The default value is ``INVALID``.*/
  72. int dev_id = 0; /*!< Ordinal device ID. */
  73. int ddr_channel = 0; /*!< Ordinal channel ID for MLU. The value should be in the range [0, 4). */
  74. };
  75. // Group:Video Analysis Function
  76. /**
  77. * @brief Gets image plane number by a specified image format.
  78. *
  79. * @param[in] fmt The format of the image.
  80. *
  81. * @retval 0: Unsupported image format.
  82. * @retval >0: Image plane number.
  83. */
  84. inline int CNGetPlanes(CNDataFormat fmt) {
  85. switch (fmt) {
  86. case CNDataFormat::CN_PIXEL_FORMAT_BGR24:
  87. case CNDataFormat::CN_PIXEL_FORMAT_RGB24:
  88. return 1;
  89. case CNDataFormat::CN_PIXEL_FORMAT_YUV420_NV12:
  90. case CNDataFormat::CN_PIXEL_FORMAT_YUV420_NV21:
  91. return 2;
  92. default:
  93. return 0;
  94. }
  95. return 0;
  96. }
  97. /**
  98. * @class CNDataFrame
  99. *
  100. * @brief CNDataFrame is a class holding a data frame and the frame description.
  101. */
  102. class CNDataFrame : public NonCopyable {
  103. public:
  104. /**
  105. * @brief Constructs an object.
  106. *
  107. * @return No return value.
  108. */
  109. CNDataFrame() = default;
  110. /**
  111. * @brief Destructs an object.
  112. *
  113. * @return No return value.
  114. */
  115. ~CNDataFrame() = default;
  116. /**
  117. * @brief Gets plane count for a specified frame.
  118. *
  119. *
  120. * @return Returns the plane count of this frame.
  121. */
  122. int GetPlanes() const { return CNGetPlanes(fmt); }
  123. /**
  124. * @brief Gets the number of bytes in a specified plane.
  125. *
  126. * @param[in] plane_idx The index of the plane. The index increments from 0.
  127. *
  128. * @return Returns the number of bytes in the plane.
  129. */
  130. size_t GetPlaneBytes(int plane_idx) const;
  131. /**
  132. * @brief Gets the number of bytes in a frame.
  133. *
  134. * @return Returns the number of bytes in a frame.
  135. */
  136. size_t GetBytes() const;
  137. public:
  138. /*!
  139. * @brief Synchronizes the source data into ::CNSyncedMemory.
  140. *
  141. * @param[in] ptr_src The source data's address. This API internally judges the address is MLU memory or not.
  142. * @param[in] dst_mlu The flag shows whether synchronizes the data to MLU memory.
  143. *
  144. * @note Sets the ``width``,``height``,``fmt``,``ctx``,``stride``,``dst_device_id``,``deAllocator_`` before calling
  145. * this function.
  146. * There are 5 situations:
  147. * 1. Reuse codec's buffer and do not copy anything. Just assign the ptr_src to CNSyncedMemory mlu_ptr_.
  148. * 2. This API allocates MLU buffer, and copy the source MLU data to the allocated buffer as the MLU destination.
  149. * 3. This API allocates MLU buffer, and copy the source CPU data to the allocated buffer as the MLU destination.
  150. * 4. This API allocates CPU buffer, and copy the source MLU data to the allocated buffer as the CPU destination.
  151. * 5. This API allocates CPU buffer, and copy the source CPU data to the allocated buffer as the CPU destination.
  152. * Whatever which situation happens, ::CNSyncedMemory doesn't own the buffer and it isn't responsible for releasing
  153. * the data.
  154. */
  155. void CopyToSyncMem(void** ptr_src, bool dst_mlu);
  156. /**
  157. * @brief Converts data to the BGR format.
  158. *
  159. * @return Returns data with OpenCV mat type.
  160. *
  161. * @note This function is called after CNDataFrame::CopyToSyncMem() is invoked.
  162. */
  163. cv::Mat ImageBGR();
  164. /**
  165. * @brief Converts data to the BGR format.
  166. *
  167. * @return Returns data with OpenCV mat type.
  168. *
  169. * @note This function is called after CNDataFrame::CopyToSyncMem() is invoked.
  170. */
  171. cv::Mat ImageBGR_NO_OSD();
  172. /**
  173. * @brief Checks whether there is BGR image stored.
  174. *
  175. * @return Returns true if has BGR image, otherwise returns false.
  176. */
  177. bool HasBGRImage() {
  178. std::lock_guard<std::mutex> lk(mtx);
  179. if (bgr_mat.empty()) return false;
  180. return true;
  181. }
  182. /**
  183. * @brief Synchronizes source data to specific device, and resets ctx.dev_id to device_id when synced, for
  184. * multi-device case.
  185. * @param[in] device_id The device id.
  186. * @return No return value.
  187. */
  188. void CopyToSyncMemOnDevice(int device_id);
  189. std::shared_ptr<void> cpu_data = nullptr; /*!< A shared pointer to the CPU data. */
  190. std::shared_ptr<void> mlu_data = nullptr; /*!< A shared pointer to the MLU data. */
  191. std::unique_ptr<CNSyncedMemory> data[CN_MAX_PLANES]; /*!< Synchronizes data helper. */
  192. uint64_t frame_id = -1; /*!< The frame index that incremented from 0. */
  193. CNDataFormat fmt; /*!< The format of the frame. */
  194. int width; /*!< The width of the frame. */
  195. int height; /*!< The height of the frame. */
  196. int stride[CN_MAX_PLANES]; /*!< The strides of the frame. */
  197. DevContext ctx; /*!< The device context of SOURCE data (ptr_mlu/ptr_cpu). */
  198. std::unique_ptr<IDataDeallocator> deAllocator_ = nullptr; /*!< The dedicated deallocator for CNDecoder buffer. */
  199. std::atomic<int> dst_device_id{-1}; /*!< The device context of SyncedMemory. */
  200. private:
  201. std::mutex mtx;
  202. cv::Mat bgr_mat; /*!< A Mat stores BGR image. */
  203. cv::Mat bgr_mat_ON;
  204. }; // class CNDataFrame
  205. /**
  206. * @struct CNInferBoundingBox
  207. *
  208. * @brief CNInferBoundingBox is a structure holding the bounding box information of a detected object in normalized
  209. * coordinates.
  210. */
  211. struct CNInferBoundingBox {
  212. float x; ///< The x-axis coordinate in the upper left corner of the bounding box.
  213. float y; ///< The y-axis coordinate in the upper left corner of the bounding box.
  214. float w; ///< The width of the bounding box.
  215. float h; ///< The height of the bounding box.
  216. };
  217. /**
  218. * @struct CNInferAttr
  219. *
  220. * @brief CNInferAttr is a structure holding the classification properties of an object.
  221. */
  222. typedef struct {
  223. int id = -1; ///< The unique ID of the classification. The value -1 means invalid.
  224. int value = -1; ///< The label value of the classification.
  225. float score = 0; ///< The label score of the classification.
  226. } CNInferAttr;
  227. /**
  228. * Defines an alias for std::vector<float>. CNInferFeature contains one kind of inference feature.
  229. */
  230. using CNInferFeature = std::vector<float>;
  231. /**
  232. * Defines an alias for std::vector<std::pair<std::string, std::vector<float>>>. CNInferFeatures contains all kinds of
  233. * features for one object.
  234. */
  235. using CNInferFeatures = std::vector<std::pair<std::string, CNInferFeature>>;
  236. /**
  237. * Defines an alias for std::vector<std::pair<std::string, std::string>>.
  238. */
  239. using StringPairs = std::vector<std::pair<std::string, std::string>>;
  240. /**
  241. * @class CNInferObject
  242. *
  243. * @brief CNInferObject is a class holding the information of an object.
  244. */
  245. class CNInferObject {
  246. public:
  247. CNS_IGNORE_DEPRECATED_PUSH
  248. /**
  249. * @brief Constructs an instance storing inference results.
  250. *
  251. * @return No return value.
  252. */
  253. CNInferObject() = default;
  254. /**
  255. * @brief Constructs an instance.
  256. *
  257. * @return No return value.
  258. */
  259. ~CNInferObject() = default;
  260. CNS_IGNORE_DEPRECATED_POP
  261. std::string id; ///< The ID of the classification (label value).
  262. std::string track_id; ///< The tracking result.
  263. float score; ///< The label score.
  264. CNInferBoundingBox bbox; ///< The object normalized coordinates.
  265. CNS_DEPRECATED std::unordered_map<int, any> datas; ///< (Deprecated) User-defined structured information.
  266. Collection collection; ///< User-defined structured information.
  267. /**
  268. * @brief Adds the key of an attribute to a specified object.
  269. *
  270. * @param[in] key The Key of the attribute you want to add to. See GetAttribute().
  271. * @param[in] value The value of the attribute.
  272. *
  273. * @return Returns true if the attribute has been added successfully. Returns false if the attribute
  274. * already existed.
  275. *
  276. * @note This is a thread-safe function.
  277. */
  278. bool AddAttribute(const std::string& key, const CNInferAttr& value);
  279. /**
  280. * @brief Adds the key pairs of an attribute to a specified object.
  281. *
  282. * @param[in] attribute The attribute pair (key, value) to be added.
  283. *
  284. * @return Returns true if the attribute has been added successfully. Returns false if the attribute
  285. * has already existed.
  286. *
  287. * @note This is a thread-safe function.
  288. */
  289. bool AddAttribute(const std::pair<std::string, CNInferAttr>& attribute);
  290. /**
  291. * @brief Gets an attribute by key.
  292. *
  293. * @param[in] key The key of an attribute you want to query. See AddAttribute().
  294. *
  295. * @return Returns the attribute key. If the attribute
  296. * does not exist, CNInferAttr::id will be set to -1.
  297. *
  298. * @note This is a thread-safe function.
  299. */
  300. CNInferAttr GetAttribute(const std::string& key);
  301. /**
  302. * @brief Adds the key of the extended attribute to a specified object.
  303. *
  304. * @param[in] key The key of an attribute. You can get this attribute by key. See GetExtraAttribute().
  305. * @param[in] value The value of the attribute.
  306. *
  307. * @return Returns true if the attribute has been added successfully. Returns false if the attribute
  308. * has already existed in the object.
  309. *
  310. * @note This is a thread-safe function.
  311. */
  312. bool AddExtraAttribute(const std::string& key, const std::string& value);
  313. /**
  314. * @brief Adds the key pairs of the extended attributes to a specified object.
  315. *
  316. * @param[in] attributes Attributes to be added.
  317. *
  318. * @return Returns true if the attribute has been added successfully. Returns false if the attribute
  319. * has already existed.
  320. * @note This is a thread-safe function.
  321. */
  322. bool AddExtraAttributes(const std::vector<std::pair<std::string, std::string>>& attributes);
  323. /**
  324. * @brief Gets an extended attribute by key.
  325. *
  326. * @param[in] key The key of an identified attribute. See AddExtraAttribute().
  327. *
  328. * @return Returns the attribute that is identified by the key. If the attribute
  329. * does not exist, returns NULL.
  330. *
  331. * @note This is a thread-safe function.
  332. */
  333. std::string GetExtraAttribute(const std::string& key);
  334. /**
  335. * @brief Removes an attribute by key.
  336. *
  337. * @param[in] key The key of an attribute you want to remove. See AddAttribute.
  338. *
  339. * @return Return true.
  340. *
  341. * @note This is a thread-safe function.
  342. */
  343. bool RemoveExtraAttribute(const std::string& key);
  344. /**
  345. * @brief Gets all extended attributes of an object.
  346. *
  347. * @return Returns all extended attributes.
  348. *
  349. * @note This is a thread-safe function.
  350. */
  351. StringPairs GetExtraAttributes();
  352. /**
  353. * @brief Adds the key of feature to a specified object.
  354. *
  355. * @param[in] key The Key of feature you want to add the feature to. See GetFeature.
  356. * @param[in] value The value of the feature.
  357. *
  358. * @return Returns true if the feature is added successfully. Returns false if the feature
  359. * identified by the key already exists.
  360. *
  361. * @note This is a thread-safe function.
  362. */
  363. bool AddFeature(const std::string &key, const CNInferFeature &feature);
  364. /**
  365. * @brief Gets an feature by key.
  366. *
  367. * @param[in] key The key of an feature you want to query. See AddFeature.
  368. *
  369. * @return Return the feature of the key. If the feature identified by the key
  370. * is not exists, CNInferFeature will be empty.
  371. *
  372. * @note This is a thread-safe function.
  373. */
  374. CNInferFeature GetFeature(const std::string &key);
  375. /**
  376. * @brief Gets the features of an object.
  377. *
  378. * @return Returns the features of an object.
  379. *
  380. * @note This is a thread-safe function.
  381. */
  382. CNInferFeatures GetFeatures();
  383. private:
  384. std::unordered_map<std::string, CNInferAttr> attributes_;
  385. std::unordered_map<std::string, std::string> extra_attributes_;
  386. std::unordered_map<std::string, CNInferFeature> features_;
  387. std::mutex attribute_mutex_;
  388. std::mutex feature_mutex_;
  389. };
  390. /*!
  391. * Defines an alias for the std::shared_ptr<CNInferObject>. CNInferObjectPtr now denotes a shared pointer of inference
  392. * objects.
  393. */
  394. using CNInferObjectPtr = std::shared_ptr<CNInferObject>;
  395. /**
  396. * @struct CNInferObjs
  397. *
  398. * @brief CNInferObjs is a structure holding inference results.
  399. */
  400. struct CNInferObjs : public NonCopyable {
  401. std::vector<std::shared_ptr<CNInferObject>> objs_; /// The objects storing inference results.
  402. std::mutex mutex_; /// mutex of CNInferObjs
  403. };
  404. /**
  405. * @struct InferData
  406. *
  407. * @brief InferData is a structure holding the information of raw inference input & outputs.
  408. */
  409. struct InferData {
  410. // infer input
  411. CNDataFormat input_fmt_; /*!< The input image's pixel format.*/
  412. int input_width_; /*!< The input image's width.*/
  413. int input_height_; /*!< The input image's height. */
  414. std::shared_ptr<void> input_cpu_addr_; /*!< The input data's CPU address.*/
  415. size_t input_size_; /*!< The input data's size. */
  416. // infer output
  417. std::vector<std::shared_ptr<void>> output_cpu_addr_; /*!< The corresponding inference outputs to the input data. */
  418. std::vector<size_t> output_sizes_; /*!< The inference outputs' sizes.*/
  419. size_t output_num_; /*!< The inference output count.*/
  420. };
  421. /**
  422. * @struct CNInferData
  423. *
  424. * @brief CNInferData is a structure holding a map between module name and InferData.
  425. */
  426. struct CNInferData : public NonCopyable {
  427. std::unordered_map<std::string, std::vector<std::shared_ptr<InferData>>> datas_map_;
  428. /*!< The map between module name and InferData.*/
  429. std::mutex mutex_; /*!< Inference data mutex.*/
  430. };
  431. /*!
  432. * Defines an alias for the std::shared_ptr<CNDataFrame>.
  433. */
  434. using CNDataFramePtr = std::shared_ptr<CNDataFrame>;
  435. /*!
  436. * Defines an alias for the std::shared_ptr<CNInferObjs>.
  437. */
  438. using CNInferObjsPtr = std::shared_ptr<CNInferObjs>;
  439. /*!
  440. * Defines an alias for the std::vector<std::shared_ptr<CNInferObject>>.
  441. */
  442. using CNObjsVec = std::vector<std::shared_ptr<CNInferObject>>;
  443. /*!
  444. * Defines an alias for the std::shared_ptr<CNInferData>.
  445. */
  446. using CNInferDataPtr = std::shared_ptr<CNInferData>;
  447. /*
  448. * @deprecated
  449. * user-defined data structure: Key-value
  450. * key type-- int
  451. * value type -- cnstream::any, since we store it in an map, std::share_ptr<T> should be used
  452. */
  453. CNS_DEPRECATED static constexpr int CNDataFramePtrKey = 0;
  454. CNS_DEPRECATED static constexpr int CNInferObjsPtrKey = 1;
  455. CNS_DEPRECATED static constexpr int CNInferDataPtrKey = 2;
  456. CNS_IGNORE_DEPRECATED_PUSH
  457. // Group:Video Analysis Function
  458. /**
  459. * @brief This helper will be deprecated in the future versions. Uses ``Collection::Get<CNDataFramePtr>(kCNDataFrameTag)`` instead.
  460. */
  461. CNS_DEPRECATED static inline
  462. CNDataFramePtr GetCNDataFramePtr(std::shared_ptr<CNFrameInfo> frameInfo) {
  463. std::lock_guard<std::mutex> guard(frameInfo->datas_lock_);
  464. return cnstream::any_cast<CNDataFramePtr>(frameInfo->datas[CNDataFramePtrKey]);
  465. }
  466. // Group:Video Analysis Function
  467. /**
  468. * @brief This helper will be deprecated in the future versions. Uses ``Collection::Get<CNInferObjsPtr>(kCNInferObjsTag)`` instead.
  469. */
  470. CNS_DEPRECATED static inline
  471. CNInferObjsPtr GetCNInferObjsPtr(std::shared_ptr<CNFrameInfo> frameInfo) {
  472. std::lock_guard<std::mutex> guard(frameInfo->datas_lock_);
  473. return cnstream::any_cast<CNInferObjsPtr>(frameInfo->datas[CNInferObjsPtrKey]);
  474. }
  475. // Group:Video Analysis Function
  476. /**
  477. * @brief This helper will be deprecated in the future versions. Uses ``Collection::Get<CNInferDataPtr>(kCNInferDataTag)`` instead.
  478. */
  479. CNS_DEPRECATED static inline
  480. CNInferDataPtr GetCNInferDataPtr(std::shared_ptr<CNFrameInfo> frameInfo) {
  481. std::lock_guard<std::mutex> guard(frameInfo->datas_lock_);
  482. return cnstream::any_cast<CNInferDataPtr>(frameInfo->datas[CNInferDataPtrKey]);
  483. }
  484. CNS_IGNORE_DEPRECATED_POP
  485. // Used by CNFrameInfo::Collection, the tags of data used by modules
  486. static constexpr char kCNDataFrameTag[] = "CNDataFrame"; /*!< value type in CNFrameInfo::Collection : CNDataFramePtr. */
  487. static constexpr char kCNInferObjsTag[] = "CNInferObjs"; /*!< value type in CNFrameInfo::Collection : CNInferObjsPtr. */
  488. static constexpr char kCNInferDataTag[] = "CNInferData"; /*!< value type in CNFrameInfo::Collection : CNInferDataPtr. */
  489. } // namespace cnstream
  490. #endif // CNSTREAM_FRAME_VA_HPP_