|
|
NVIDIA DeepStream SDK API Reference
|
9.1 Release
|
Go to the documentation of this file.
25 #ifndef __NVDSINFER_SERVER_INFER_UTILS_H__
26 #define __NVDSINFER_SERVER_INFER_UTILS_H__
30 #include <infer_datatypes.h>
69 inline const char*
safeStr(
const char* str) {
70 return !str ?
"" : str;
73 inline const char*
safeStr(
const std::string& str) {
83 return !str || strlen(str) == 0;
93 return (access(path, F_OK) != -1);
104 template <
typename T>
116 std::string
dims2Str(
const InferDims& d);
130 bool fEqual(
float a,
float b);
142 DlLibHandle(
const std::string& path,
int mode = RTLD_LAZY);
157 const std::string&
getPath()
const {
return m_LibPath; }
164 template <
typename FuncPtr>
170 return (FuncPtr)dlsym(m_LibHandle, func);
173 template <
typename FuncPtr>
174 FuncPtr
symbol(
const std::string& func) {
175 return symbol<FuncPtr>(func.c_str());
183 void* m_LibHandle{
nullptr};
187 const std::string m_LibPath;
198 const char*
what() const noexcept
override {
return m_Msg.c_str(); }
207 template <
typename Container>
210 typedef typename Container::value_type
T;
215 std::unique_lock<std::mutex> lock(m_Mutex);
216 m_Queue.emplace_back(std::move(data));
226 std::unique_lock<std::mutex> lock(m_Mutex);
228 lock, [
this]() {
return m_WakeupOnce || !m_Queue.empty(); });
230 m_WakeupOnce =
false;
231 InferDebug(
"GuardQueue pop end on wakeup signal");
234 assert(!m_Queue.empty());
235 T ret = std::move(*m_Queue.begin());
236 m_Queue.erase(m_Queue.begin());
244 std::unique_lock<std::mutex> lock(m_Mutex);
253 std::unique_lock<std::mutex> lock(m_Mutex);
255 m_WakeupOnce =
false;
261 std::unique_lock<std::mutex> lock(m_Mutex);
262 return m_Queue.size();
273 std::condition_variable m_Cond;
281 bool m_WakeupOnce =
false;
291 template <
typename Container>
294 using Item =
typename Container::value_type;
305 std::promise<void> p;
306 std::future<void> f = p.get_future();
307 InferDebug(
"QueueThread starting new thread");
308 m_Thread = std::thread([&p,
this]() {
320 assert(!name.empty());
322 if (m_Thread.joinable()) {
323 const int kMakLen = 16;
325 strncpy(cName, name.c_str(), kMakLen);
326 cName[kMakLen - 1] = 0;
327 if (pthread_setname_np(m_Thread.native_handle(), cName) != 0) {
331 InferDebug(
"QueueThread set new thread name:%s", cName);
341 if (m_Thread.joinable()) {
342 m_Queue.wakeupOnce();
351 m_Queue.push(std::move(item));
366 Item item = m_Queue.pop();
367 if (!m_Run(std::move(item))) {
372 catch (
const WakeupException& e) {
378 "QueueThread:%s internal unexpected error, may cause stop",
390 std::thread m_Thread;
402 GuardQueue<Container> m_Queue;
409 template <
class UniPtr>
410 class BufferPool :
public std::enable_shared_from_this<BufferPool<UniPtr> > {
425 "BufferPool: %s deleted with free buffer size:%d",
safeStr(m_Name),
426 m_FreeBuffers.size());
436 m_FreeBuffers.push(std::move(buf));
437 InferDebug(
"BufferPool: %s set buf to free, available size:%d",
438 safeStr(m_Name), m_FreeBuffers.size());
444 int size() {
return m_FreeBuffers.size(); }
457 UniPtr p = m_FreeBuffers.pop();
458 auto deleter = p.get_deleter();
459 std::weak_ptr<BufferPool<UniPtr>> poolPtr =
460 this->shared_from_this();
462 p.release(), [poolPtr, d = deleter](
ItemType* buf) {
465 auto pool = poolPtr.lock();
467 InferDebug(
"BufferPool: %s release a buffer", safeStr(pool->m_Name));
468 pool->setBuffer(std::move(data));
470 InferError(
"BufferPool is deleted, check internal error.");
474 InferDebug(
"BufferPool: %s acquired buffer, available free buffer left:%d",
475 safeStr(m_Name), m_FreeBuffers.size());
479 "BufferPool: %s acquired buffer failed, queue maybe waked up.",
490 GuardQueue<std::deque<UniPtr>> m_FreeBuffers;
494 const std::string m_Name;
497 template <
class UniPtr>
505 template<
typename Key,
typename UniqBuffer>
521 "MapBufferPool: %s deleted with buffer pool size:%d",
522 safeStr(m_Name), (
int)m_MapPool.size());
542 std::unique_lock<std::shared_timed_mutex> uniqLock(m_MapPoolMutex);
546 uint32_t
id = m_MapPool.size() - 1;
547 std::string poolName = m_Name + std::to_string(
id);
548 pool = std::make_shared<BufferPool<UniqBuffer>>(poolName);
550 InferDebug(
"MapBufferPool: %s create new pool id:%d",
556 return pool->setBuffer(std::move(buf));
581 "MapBufferPool: %s acquire buffer failed, no key found",
586 return pool->acquireBuffer();
593 std::unique_lock<std::shared_timed_mutex> uniqLock(m_MapPoolMutex);
601 SharedPool findPool(
const Key& key) {
602 std::shared_lock<std::shared_timed_mutex> sharedLock(m_MapPoolMutex);
603 auto iter = m_MapPool.find(key);
604 if (iter != m_MapPool.end()) {
605 assert(iter->second);
615 std::map<Key, SharedPool> m_MapPool;
619 std::shared_timed_mutex m_MapPoolMutex;
623 const std::string m_Name;
631 case InferDataType::kInt32:
632 case InferDataType::kUint32:
633 case InferDataType::kFp32:
635 case InferDataType::kFp16:
636 case InferDataType::kInt16:
637 case InferDataType::kUint16:
639 case InferDataType::kInt8:
640 case InferDataType::kUint8:
641 case InferDataType::kBool:
643 case InferDataType::kString:
645 case InferDataType::kFp64:
646 case InferDataType::kInt64:
647 case InferDataType::kUint64:
650 InferError(
"Failed to get element size on Unknown datatype:%d",
651 static_cast<int>(t));
664 dims.d, dims.d + dims.numDims,
665 [](
int d) { return d <= INFER_WILDCARD_DIM_VALUE; });
680 return std::accumulate(
681 dims.d, dims.d + dims.numDims, 1,
682 [](
int s,
int i) { return s * i; });
700 bool operator<=(
const InferDims& a,
const InferDims& b);
701 bool operator>(
const InferDims& a,
const InferDims& b);
702 bool operator==(
const InferDims& a,
const InferDims& b);
703 bool operator!=(
const InferDims& a,
const InferDims& b);
706 struct LayerDescription;
725 const InferBufferDescription& desc,
void* buf =
nullptr);
748 const InferDims& a,
const InferDims& b, InferDims& c);
761 std::string
joinPath(
const std::string& a,
const std::string& b);
762 std::string
dirName(
const std::string& path);
764 bool realPath(
const std::string &inPath, std::string &absPath);
783 InferDims
fullDims(
int batchSize,
const InferDims& in);
794 const InferDims& full, InferDims& debatched, uint32_t& batch);
804 bool squeezeMatch(
const InferDims& a,
const InferDims& b);
820 bool reCalcBytes =
false);
832 bool reCalcBytes =
false);
875 const std::string& configStr,
const std::string& path, std::string& updated);
This is a header file for pre-processing cuda kernels with normalization and mean subtraction require...
InferDataType
Datatype of the tensor buffer.
bool isNonBatch(T b)
Checks if the input batch size is zero.
T pop()
Pop an item from the queue.
bool intersectDims(const InferDims &a, const InferDims &b, InferDims &c)
Get the intersection of the two input dimensions.
bool operator<=(const InferDims &a, const InferDims &b)
Comparison operators for the InferDims type.
InferDataType grpcStr2DataType(const std::string &type)
bool debatchFullDims(const InferDims &full, InferDims &debatched, uint32_t &batch)
Separates batch size from given dimensions.
bool operator>(const InferDims &a, const InferDims &b)
Template class for creating a thread safe queue for the given container class.
std::string dims2Str(const InferDims &d)
Helper functions to convert the various data types to string values for debug, log information.
bool realPath(const std::string &inPath, std::string &absPath)
NvDsInferNetworkInfo dims2ImageInfo(const InferDims &d, InferTensorOrder order)
MapBufferPool(const std::string &name)
Construct the buffer pool map with a name.
NvDsInferDims toCapi(const InferDims &dims)
Convert the InferDims to NvDsInferDims of the library interface.
#define InferDebug(fmt,...)
typename Container::value_type Item
uint32_t getElementSize(InferDataType t)
Get the size of the element from the data type.
std::shared_ptr< BaseBatchBuffer > SharedBatchBuf
Common buffer interfaces (internal).
std::string dataType2GrpcStr(const InferDataType type)
InferTensorOrder
The type of tensor order.
bool setBuffer(UniPtr buf)
Add a buffer to the pool.
Holds the dimensions of a layer.
std::string joinPath(const std::string &a, const std::string &b)
Helper functions for parsing the configuration file.
NvDsInferLayerInfo toCapiLayerInfo(const InferBufferDescription &desc, void *buf=nullptr)
Generate NvDsInferLayerInfo of the interface from the buffer description and buffer pointer.
FuncPtr symbol(const char *func)
const char * what() const noexcept override
virtual ~BufferPool()
Destructor.
std::string dirName(const std::string &path)
Helper class for dynamic loading of custom library.
std::shared_ptr< BufferPool< UniPtr > > SharedBufPool
void wakeupOnce()
Send the wakeup trigger to the queue thread.
size_t dimsSize(const InferDims &dims)
Calculate the total number of elements for the given dimensions.
#define InferError(fmt,...)
Template class for a map of buffer pools.
std::unique_ptr< ItemType, std::function< void(ItemType *)> > RecylePtr
void push(T data)
Push an item to the queue.
FuncPtr symbol(const std::string &func)
NvDsInferLogLevel
Enum for the log levels of NvDsInferContext.
bool squeezeMatch(const InferDims &a, const InferDims &b)
Check that the two dimensions are equal ignoring single element values.
void dsInferLogPrint__(NvDsInferLogLevel level, const char *fmt,...)
Print the nvinferserver log messages as per the configured log level.
NvDsInferDataType
Specifies the data type of a layer.
void dsInferLogVPrint__(NvDsInferLogLevel level, const char *fmt, va_list args)
Helper function to print the nvinferserver logs.
void clear()
Remove all pools from the map.
uint32_t getPoolSize(const Key &key)
Get the size of a pool from the map.
Template class for buffer pool of the specified buffer type.
QueueThread(RunFunc runFunc, const std::string &name)
Create a new thread that runs the specified function over the queued items in a loop.
Header file of the common declarations for the nvinferserver library.
std::string batchDims2Str(const InferBatchDims &d)
bool queueItem(Item item)
Add an item to the queue for processing.
Template class for running the specified function on the queue items in a separate thread.
Header file of batch buffer related class declarations.
std::shared_ptr< CudaStream > SharedCuStream
Cuda based pointers.
INFER_EXPORT_API bool validateInferConfigStr(const std::string &configStr, const std::string &path, std::string &updated)
Validates the provided nvinferserver configuration string.
Holds information about the model network.
bool file_accessible(const std::string &path)
Holds information about one layer in the model.
int size()
Current size of the queue.
std::string memType2Str(InferMemType type)
Returns a string object corresponding to the InferMemType name.
~QueueThread()
Destructor.
NvDsInferDataType toCapiDataType(InferDataType dt)
Convert the InferDataType to NvDsInferDataType of the library interface.
BufferPool(const std::string &name)
Constructor.
bool isAbsolutePath(const std::string &path)
Wrapper class for handling exception.
typename BufferPool< UniqBuffer >::RecylePtr RecylePtr
bool isPrivateTensor(const std::string &tensorName)
Check if the given tensor is marked as private (contains INFER_SERVER_PRIVATE_BUF in the name).
std::string dataType2Str(const InferDataType type)
std::string tensorOrder2Str(InferTensorOrder order)
const std::string & getPath() const
std::function< bool(Item)> RunFunc
void normalizeDims(InferDims &dims)
Recalculates the total number of elements for the dimensions.
RecylePtr acquireBuffer(const Key &key)
Acquire a buffer from the selected pool.
bool isCpuMem(InferMemType type)
Check if the memory type uses CPU memory (kCpu or kCpuCuda).
virtual ~MapBufferPool()
Destructor.
bool setBuffer(const Key &key, UniqBuffer buf)
Add a buffer to the pool map.
SharedBufPool< UniqBuffer > SharedPool
InferMemType
The memory types of inference buffers.
bool hasWildcard(const InferDims &dims)
Check if any of the InferDims dimensions are of dynamic size (-1 or negative values).
const char * safeStr(const std::string &str)
const INFER_EXPORT_API char * NvDsInferStatus2Str(NvDsInferStatus status)
Returns the NvDsInferStatus enum name as a string.
bool operator==(const InferDims &a, const InferDims &b)
int size()
Get the number of free buffers.
RecylePtr acquireBuffer()
Acquire a buffer from the pool.
bool fEqual(float a, float b)
Check if the two floating point values are equal, the difference is less than or equal to the epsilon...
WakeupException(const std::string &s)
void setThreadName(const std::string &name)
Set the internal (m_Name) name of the thread and system name using pthread_setname_np().
bool operator!=(const InferDims &a, const InferDims &b)
#define InferWarning(fmt,...)
SharedBatchBuf reshapeToFullDimsBuf(const SharedBatchBuf &buf, bool reCalcBytes=false)
Reshape the buffer dimensions with batch size added as new dimension.
void clear()
Clear the queue.
SharedBatchBuf ReshapeBuf(const SharedBatchBuf &in, uint32_t batch, const InferDims &dims, bool reCalcBytes=false)
Update the buffer dimensions as per provided new dimensions.
bool string_empty(const char *str)
Helper function, returns true if the input C string is empty or null.
InferDims fullDims(int batchSize, const InferDims &in)
Extend the dimensions to include batch size.
NvDsInferStatus tensorBufferCopy(const SharedBatchBuf &in, const SharedBatchBuf &out, const SharedCuStream &stream)
Copy one tensor buffer to another.
typename UniPtr::element_type ItemType
NvDsInferStatus
Enum for the status codes returned by NvDsInferContext.