diff --git a/src/left_over/MSRegionSurveilanceCpu.cpp b/src/left_over/MSRegionSurveilanceCpu.cpp index c92198d..a327f0e 100644 --- a/src/left_over/MSRegionSurveilanceCpu.cpp +++ b/src/left_over/MSRegionSurveilanceCpu.cpp @@ -1,5 +1,4 @@ #include "MSRegionSurveilanceCpu.h" -#include "head.h" #include #include #include diff --git a/src/left_over/MSRegionSurveilanceCpu.h b/src/left_over/MSRegionSurveilanceCpu.h index 3d45868..6d58397 100644 --- a/src/left_over/MSRegionSurveilanceCpu.h +++ b/src/left_over/MSRegionSurveilanceCpu.h @@ -2,7 +2,6 @@ #include "MSRegionSurveilance.h" #include "left_over_det.h" #include "RegionSurveillanceProcess.h" -#include "head.h" class IRegionSurveillanceCpu: public RegionSurveillanceProcess { public: IRegionSurveillanceCpu() diff --git a/src/left_over/RegionSurveillanceProcess.h b/src/left_over/RegionSurveillanceProcess.h index 5ec4fae..5d0b2d6 100644 --- a/src/left_over/RegionSurveillanceProcess.h +++ b/src/left_over/RegionSurveillanceProcess.h @@ -1,10 +1,24 @@ #pragma once -//#include "MSRegionSurveilance.h" #include "left_over_det.h" -//#include -#include "head.h" #include -//#include "MSRegionSurveilanceVpt.h" +#include "header.h" +#include "checkAuthor.h" +#define DEVICE_GPU 10 +typedef struct rs_params +{ + int mode; //运行模式(DEVICE_GPU / DEVICE_CPU) + int gpuid; //指定显卡id + //其余算法参数 如长短边等 + + sy_img image; + int channel_deal; + bool filt_flag; + int min_area; + int max_area; + + rs_params() :mode(DEVICE_GPU), gpuid(0), min_area(0), max_area(1000000) {}; +}rs_params; + class RegionSurveillanceProcess { public: @@ -37,8 +51,6 @@ public: virtual int rs_detect(const sy_img &img_data, region_info* region_infos, rs_result *result) = 0; //virtual int rs_get_arrowdir(const sy_point &p_roi0, const sy_point &p_roi1, const sy_point &dir) = 0; //void* handle; - int licence_status = -1; - int thrd_status = -1; double scale; //int long_side; //int short_side; @@ -48,6 +60,7 @@ public: bool init_flag = false; sy_rect rect[MAXVERTEXNUM]; //有效区域 unsigned char rect_num; //有效区域数量 + CheckAuthor * auth = nullptr; private: //int mode; //运行模式0 cpu //MS_RegionSurveillance MS1; diff --git a/src/left_over/auth/authorLog.h b/src/left_over/auth/authorLog.h new file mode 100644 index 0000000..5248c72 --- /dev/null +++ b/src/left_over/auth/authorLog.h @@ -0,0 +1,47 @@ +#pragma once +#include + +class AuthorLog +{ +public: + + static int FileSize(const char* fname) + { + struct stat statbuf; + if (stat(fname, &statbuf) == 0) + return statbuf.st_size; + return -1; + } + + static void Write(std::string log) { + try + { + std::string strfile = "./author.log"; + int ss = FileSize(strfile.c_str()); + if (ss > 1024 * 1024 * 10) + { + FILE* pf = fopen(strfile.c_str(), "wb"); + if (pf) + { + fclose(pf); + pf = nullptr; + } + } + std::ofstream ofs; + time_t t = time(0); + char tmp[64]; + strftime(tmp, sizeof(tmp), "[%Y-%m-%d %X]", localtime(&t)); + ofs.open(strfile.c_str(), std::ofstream::app); + + ofs << tmp << " - "; + ofs.write(log.c_str(), log.size()); + ofs << std::endl; + ofs.close(); + } + catch (...) + { + } + } +}; + + diff --git a/src/left_over/auth/checkAuthor.cpp b/src/left_over/auth/checkAuthor.cpp new file mode 100644 index 0000000..3d928a2 --- /dev/null +++ b/src/left_over/auth/checkAuthor.cpp @@ -0,0 +1,258 @@ +#include "checkAuthor.h" + +#include "httpSend.h" +#include "authorLog.h" + +CheckAuthor::CheckAuthor() +{ + m_nLog = 0; + m_nChannel = 0; //鎺堟潈閫氶亾 + m_strCode=""; //鎺堟潈鐮 + m_strId=""; //浜у搧搴忓垪鍙 + + m_nPort = 0; + m_strIp = ""; + + m_strHttpUrl = ""; + + m_lLastTime = 0; + m_lCheakTime = 1; //澶氬皯绉掓娴嬩竴娆 + + m_bFirst = true; + m_nStatus = 0; + m_lFailureTime = 0; + + //绉 + m_lFailureTotal = 1800; + + signal(SIGPIPE, SIG_IGN); +} + + +CheckAuthor::~CheckAuthor() +{ +} + +int CheckAuthor::Init(std::string strip, int port, + std::string code, std::string id, + int channel, int log) +{ + m_nLog = log; + m_strId = id; + m_strCode = code; + m_nChannel = channel; + + m_nPort = port; + m_strIp = strip; + + //http://192.168.10.4:8888/action/auth?authcode=f437a4fdc0674cc98356ccbf8d33db77&productid=2514B7CB4DDE47CCB592E573304C6B92&authchannel=1 + m_strHttpUrl = "http://" + m_strIp + ":" + std::to_string(m_nPort) + "/action/auth?authcode=" + m_strCode + "&productid=" + m_strId + "&authchannel=" + std::to_string(m_nChannel); + + start(); + + return 0; +} +int CheckAuthor::Uninit() +{ + stop(); + return 0; +} + +int CheckAuthor::run() +{ + while (!m_canExit) + { + long dtime = GetTickCount() / 1000; + + + int ntm = dtime - m_lLastTime; + if (ntm > m_lCheakTime) + { + if (m_lCheakTime < 20) + m_lCheakTime++; + + CHttpSend http; + int ret = http.Init(m_strHttpUrl, 1); + if (ret < 0) //杩炴帴鏈嶅姟澶辫触 + { + http.Uninit(); + + if (m_bFirst) + { + m_mtxStatus.lock(); + m_nStatus = 0; + m_mtxStatus.unlock(); + } + else + { + // + if (m_lFailureTime <= 0) + m_lFailureTime = dtime; + + if (dtime - m_lFailureTime > m_lFailureTotal) + { + m_mtxStatus.lock(); + m_nStatus = 0; + m_mtxStatus.unlock(); + } + } + if (m_bFirst) + m_bFirst = false; + continue; + } + + + std::string strJson = ""; + ret = http.SendHttpPost(strJson); + + if (m_bFirst && ret < 0) + { + m_mtxStatus.lock(); + m_nStatus = 0; + m_mtxStatus.unlock(); + } + + std::string strRes = ""; + if (ret >= 0) //璇峰埌搴旂瓟鍖 + { + strRes = http.GetJson(); + + _check_result_ sResult; + memset(&sResult, 0, sizeof(_check_result_)); + sprintf(sResult.sucess, "%s", "-1"); + + if(strRes.size() > 0) + ProJson(strRes, sResult); + + if (atoi(sResult.sucess) == 0) + { + m_mtxStatus.lock(); + m_nStatus = 1; + m_mtxStatus.unlock(); + + m_lFailureTime = 0; + } + else + { + if (m_bFirst) + { + m_mtxStatus.lock(); + m_nStatus = 0; + m_mtxStatus.unlock(); + } + else + { + if (m_lFailureTime <= 0) + m_lFailureTime = dtime; + + if (dtime - m_lFailureTime > m_lFailureTotal) + { + m_mtxStatus.lock(); + m_nStatus = 0; + m_mtxStatus.unlock(); + } + } + } + } + else + { + if (m_lFailureTime <= 0) + m_lFailureTime = dtime; + + if (dtime - m_lFailureTime > m_lFailureTotal) + { + m_mtxStatus.lock(); + m_nStatus = 0; + m_mtxStatus.unlock(); + } + } + + http.Uninit(); + m_lLastTime = dtime; + + if(m_bFirst) + m_bFirst = false; + } + + sleep(1); + + } + return 0; +} + +// 0-涓嶅彲鐢 1-鍙敤 +int CheckAuthor::GetAuthorStatus() +{ + if (m_bFirst) + { + while (m_bFirst) + { + //鍐呴儴杩樻病鏈夊噯澶囧ソ + sleep(1); + } + } + + int status = 0; + m_mtxStatus.lock(); + status = m_nStatus; + m_mtxStatus.unlock(); + + return status; +} + + +long CheckAuthor::GetTickCount() +{ + struct timeval tv; + gettimeofday(&tv, NULL); + return tv.tv_sec * 1000 + tv.tv_usec / 1000; //姣 +} + +int CheckAuthor::ProJson(std::string strJson, _check_result_& result) +{ + cJSON *pJsonRoot = cJSON_Parse(strJson.c_str()); + if (!pJsonRoot) + { + if (m_nLog == 1)AuthorLog::Write("json is error."); + + cJSON_Delete(pJsonRoot); + return 0; + } + + std::string strResult = ""; + std::string strSucess = ""; + std::string strAuthcount = ""; + + cJSON* pNode = cJSON_GetObjectItem(pJsonRoot, "result"); + if (pNode) + { + strResult = pNode->valuestring; + sprintf(result.result, "%s", strResult.c_str()); + std::string strInfo = "result: " + strResult; + if (m_nLog == 1)AuthorLog::Write(strInfo); + } + + pNode = cJSON_GetObjectItem(pJsonRoot, "sucess"); + if (pNode) + { + strSucess = pNode->valuestring; + sprintf(result.sucess, "%s", strSucess.c_str()); + + std::string strInfo = "sucess: " + strSucess; + if (m_nLog == 1)AuthorLog::Write(strInfo); + } + + pNode = cJSON_GetObjectItem(pJsonRoot, "authcount"); + if (pNode) + { + strAuthcount = pNode->valuestring; + sprintf(result.authcount, "%s", strAuthcount.c_str()); + + std::string strInfo = "authcount: " + strAuthcount; + + if (m_nLog == 1)AuthorLog::Write(strInfo); + } + cJSON_Delete(pJsonRoot); + + return 0; +} \ No newline at end of file diff --git a/src/left_over/auth/checkAuthor.h b/src/left_over/auth/checkAuthor.h new file mode 100644 index 0000000..64e7a2e --- /dev/null +++ b/src/left_over/auth/checkAuthor.h @@ -0,0 +1,59 @@ +#pragma once + +#include +#include "syInclude.h" + +struct _check_result_ +{ + char result[64]; + char authcount[64]; + char sucess[64]; +}; + + +class CheckAuthor : public comn::Thread +{ +public: + CheckAuthor(); + ~CheckAuthor(); + + int Init(std::string strip, int port, + std::string code, std::string id, + int channel, int log=0); + + int Uninit(); + + //0-涓嶅彲鐢 1-鍙敤 + int GetAuthorStatus(); + +private: + virtual int run(); + long GetTickCount(); + + int ProJson(std::string strJson, _check_result_& result); +private: + int m_nLog; + int m_nPort; + std::string m_strIp; + + int m_nChannel; //鎺堟潈閫氶亾 + std::string m_strCode; //鎺堟潈鐮 + std::string m_strId; //浜у搧搴忓垪鍙 + + std::string m_strHttpUrl; + + //-1: 鍐呴儴杩樻病鏈夊噯澶囧ソ锛岀瓑浼氶噸鏂拌幏鍙 0-涓嶅彲鐢 1-鍙敤 + int m_nStatus; + std::mutex m_mtxStatus; + + long m_lLastTime; //涓婃妫娴嬬殑鏃堕棿 (绉) + long m_lCheakTime;//澶氶暱鏃堕棿妫娴嬩竴娆(绉) + + long m_lFailureTime; //妫娴嬪け璐ョ殑鏃堕棿 + long m_lFailureTotal;//澶辫触瓒呮椂鏃堕棿 + + bool m_bFirst; + + +}; + diff --git a/src/left_over/auth/httpSend.cpp b/src/left_over/auth/httpSend.cpp new file mode 100644 index 0000000..a6b9325 --- /dev/null +++ b/src/left_over/auth/httpSend.cpp @@ -0,0 +1,243 @@ +#include "httpSend.h" +#include "syInclude.h" +#include "authorLog.h" + +CHttpSend::CHttpSend() +{ + m_nLog = 0; + m_sockfd = -1; + m_nThrdStart = 0; + m_nResStatus = 0; + pthread_mutex_init(&m_mutex, NULL); + + memset(m_buf, 0, sizeof(m_buf)); +} + +CHttpSend::~CHttpSend() +{ + pthread_mutex_destroy(&m_mutex); +} + + +int CHttpSend::Init(std::string& strUrl, int log) +{ + m_nLog = log; + if (AnalysisUrl(strUrl) < 0) + return -1; + + struct sockaddr_in address; + m_sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + address.sin_family = AF_INET; + address.sin_port = htons(m_nPort); //璁剧疆杩滅▼璁$畻鏈虹殑绔彛鍙 + address.sin_addr.s_addr = inet_addr(m_strIp.c_str()); + + if (-1 == connect(m_sockfd, (struct sockaddr *)&address, sizeof(address))) + { + if(m_nLog==1)AuthorLog::Write("connection error!"); + return -2; + } + + start(); + m_nThrdStart = 1; + + return 0; +} + +int CHttpSend::Uninit() +{ + if (m_sockfd != -1) + { + close(m_sockfd); + m_sockfd = -1; + } + + if (m_nThrdStart == 1) + { + stop(); + } + + return 0; +} + + +int CHttpSend::SendHttpPost( std::string& strJson) +{ + int s1 = strJson.size(); + int s2 = strJson.length(); + + //POST璇锋眰鏂瑰紡 + std::stringstream stream; + stream << "POST " << m_strTitle; + stream << " HTTP/1.0\r\n"; + stream << "Host: " << m_strIp << "\r\n"; + stream << "User-Agent: bj objecteye\r\n"; + stream << "Content-Type:application/json\r\n"; + stream << "Content-Length:" << strJson.length() << "\r\n"; + stream << "Connection:close\r\n\r\n"; + stream << strJson.c_str(); + + std::string strData = stream.str(); + + SetStatus(0); + int ret = SendData((char*)strData.c_str(), strData.length()); + if (ret < 0) + return -1; + + int rr = -1; + + int num = 0; + while (true) + { + if (num >= 4) + break; + + int ret = GetStatus(); + if (ret == 1) + { + rr = 0; + break; + } + num++; + sleep(1); + } + + if (num >= 4) + { + //鎺ユ敹搴旂瓟瓒呮椂 + if (m_nLog == 1)AuthorLog::Write("http: recv response timout."); + return -2; + } + + if (m_nLog == 1) + { + AuthorLog::Write("====== http: recv response ============"); + AuthorLog::Write(m_buf); + AuthorLog::Write("======================================="); + } + return rr; +} + + +int CHttpSend::run() +{ + while (!m_canExit) + { + int offset = 0; + int rc; + + rc = read(m_sockfd, m_buf + offset, 1024); + if (rc < 0) + break; + else if (rc == 0) + { + continue; + } + + offset += rc; + m_buf[offset] = 0; + + SetStatus(1); + break; + } + + return 0; +} + +std::string CHttpSend::GetResponse() +{ + return std::string(m_buf); +} + +std::string CHttpSend::GetJson() +{ + std::string strRes = GetResponse(); + + char* pTemp = m_buf; + char* p = strstr(pTemp, "\r\n\r\n"); + if (p && strlen(p) > 4) + { + p += 4; + return std::string(p); + } + return""; +} + + +int CHttpSend::AnalysisUrl(std::string& strUrl) +{ + m_strUrl = strUrl; + + std::string strTemp = strUrl; + + int pos = strTemp.find("http://"); + if (pos < 0) + return -1; + + strTemp = strTemp.substr(pos + strlen("http://")); + + pos = strTemp.find("/"); + if (pos < 0) + return -2; + + std::string strIpInfo = strTemp.substr(0, pos); + m_strTitle = strTemp.substr(pos); + + pos = strIpInfo.find(":"); + if (pos < 0) + { + m_nPort = 80; + m_strIp = strIpInfo; + } + else + { + m_strIp = strIpInfo.substr(0, pos); + strIpInfo = strIpInfo.substr(pos + 1); + + m_nPort = atoi(strIpInfo.c_str()); + + } + return 0; +} + +int CHttpSend::SendData(char* pbuf, int size) +{ + char* pTempBuf = pbuf; + int nTempSize = size; + + while (nTempSize > 0) + { + int ss = write(m_sockfd, pTempBuf, nTempSize); + if (ss < 0) + { + return -1; + } + else if (ss == 0) + { + usleep(1000); + continue; + } + nTempSize -= ss; + } + + return 0; +} + +int CHttpSend::SetStatus(int status) +{ + pthread_mutex_lock(&m_mutex); + m_nResStatus = status; + pthread_mutex_unlock(&m_mutex); + + return 0; +} + +int CHttpSend::GetStatus() +{ + int status = 0; + + pthread_mutex_lock(&m_mutex); + status = m_nResStatus; + pthread_mutex_unlock(&m_mutex); + + return status; +} \ No newline at end of file diff --git a/src/left_over/auth/httpSend.h b/src/left_over/auth/httpSend.h new file mode 100644 index 0000000..ac22d26 --- /dev/null +++ b/src/left_over/auth/httpSend.h @@ -0,0 +1,48 @@ +#pragma once +#include +#include "syThread.h" + +class CHttpSend : public comn::Thread +{ +public: + CHttpSend(); + ~CHttpSend(); + + int Init(std::string& strUrl, int log=0); + int Uninit(); + + int SendHttpPost(std::string& strJson); + std::string GetResponse(); + std::string GetJson(); + +private: + virtual int run(); + int AnalysisUrl(std::string& strUrl); + + int SendData(char* pbuf, int size); + int SetStatus(int status); + int GetStatus(); + + long GetTickCount(); +private: + int m_nPort; + std::string m_strUrl; + std::string m_strIp; + std::string m_strTitle; + + char m_buf[1024*2]; + + int m_sockfd; + + int m_nThrdStart; + + pthread_mutex_t m_mutex; + int m_nResStatus; + + int m_nLog; + + long m_lLastTime; //涓婃妫娴嬬殑鏃堕棿锛堢锛 + int m_lCheckTime; //澶氶暱鏃堕棿妫娴嬩竴娆★紙绉掞級 + +}; + diff --git a/src/left_over/auth/syInclude.h b/src/left_over/auth/syInclude.h new file mode 100644 index 0000000..d4246d8 --- /dev/null +++ b/src/left_over/auth/syInclude.h @@ -0,0 +1,44 @@ +#pragma once + +/* +sudo apt-get install libsqlite3-dev +sudo apt-get install libcurl4-openssl-dev + +*/ + +////////////////////////////////////////////////////////////////////////// +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + + +////////////////////////////////////////////////////////////////////////// +#include "syThread.h" +#include "sycJson.h" + diff --git a/src/left_over/auth/syThread.h b/src/left_over/auth/syThread.h new file mode 100644 index 0000000..0db3fc5 --- /dev/null +++ b/src/left_over/auth/syThread.h @@ -0,0 +1,348 @@ +/* + * TThread.h + * + * Created on: 2010-4-21 + * Author: + */ + +#ifndef TTHREAD_H_ +#define TTHREAD_H_ + +#ifdef WIN32 +#include +#include +#else // +#include +#include +#include +#include +#include +#include +#include +#include +#include +#endif //WIN32 +#include +//////////////////////////////////////////////////////////////////////////// + +namespace comn +{ + +#ifdef WIN32 + +class Thread +{ +public: + typedef HANDLE ThreadHandle; + typedef unsigned int ThreadID; + + Thread() + :m_stackSize(0),m_threadID(0),m_handle(0),m_canExit(false) + { + } + + explicit Thread(unsigned int stack_size) + :m_stackSize(stack_size),m_threadID(0),m_handle(0),m_canExit(false) + { + } + + virtual ~Thread() + { + assert(isRunning() == false); + } + + bool start() + { + m_canExit = false; + return createThread(); + } + + void stop() + { + tryStop(); + join(-1); + } + + void tryStop() + { + InterlockedExchange((LPLONG)&m_canExit, true); + doStop(); + } + + bool join(int millisecond = -1) + { + bool ok = true; + if (m_handle != 0) + { + DWORD dwMilliseconds = (millisecond >= 0) ? millisecond : INFINITE; + DWORD res = ::WaitForSingleObject(m_handle, dwMilliseconds); + ok = (WAIT_OBJECT_0 == res); + } + return ok; + } + + + ThreadHandle getHandle() const + { + return m_handle; + } + + ThreadID getThreadID() const + { + return m_threadID; + } + + bool isRunning() const + { + return (m_handle != 0); + } + + void setStackSize(unsigned int stack_size) + { + m_stackSize = stack_size; + } + +protected: + virtual int run() =0; + virtual bool startup() { return true; } + virtual void cleanup() {} + virtual void doStop() {} + + + unsigned int m_stackSize; + ThreadID m_threadID; + ThreadHandle m_handle; + bool m_canExit; + + + +private: + static unsigned __stdcall ThreadFunction(void* param) + { + int code = 0; + Thread* pThread = (Thread*)param; + if ( !pThread->m_canExit ) + { + if (pThread->startup()) + { + code = pThread->run(); + } + else + { + code = 1; + } + pThread->cleanup(); + } + ::CloseHandle(pThread->m_handle); + pThread->m_handle = 0; + pThread->m_threadID = 0; + _endthreadex(code); + return code; + } + + bool createThread() + { + unsigned int flag = 0; + void* param = (void*)this; + m_handle = (HANDLE)_beginthreadex(NULL, m_stackSize, ThreadFunction, + param, flag, &m_threadID); + return (m_handle != 0); + } + +}; + +#else //WIN32 + +class Thread +{ +public: + typedef pthread_t ThreadHandle; + typedef pthread_t ThreadID; + + Thread() + :m_stackSize(0),m_threadID(0),m_handle(-1),m_canExit(false) + { + } + + explicit Thread(unsigned int stack_size) + :m_stackSize(stack_size),m_threadID(0),m_handle(-1),m_canExit(false) + { + } + + virtual ~Thread() + { + assert(isRunning() == false); + } + + bool start() + { + m_canExit = false; + return createThread(); + } + + bool start(int num) + { + m_canExit = false; + return createThread(); + } + + void stop() + { + tryStop(); + join(-1); + } + + void tryStop() + { + m_canExit = true; + doStop(); + } + + bool join(int millisecond = -1) + { + bool ok = true; + if (m_handle != (pthread_t)-1) + { + if (millisecond <= 0) + { + ok = (0 == pthread_join(m_handle, NULL)); + m_handle = (pthread_t)-1; + } + else + { + struct timespec ts; + getTimeout( &ts, millisecond ); + ok = ( 0 == ::pthread_timedjoin_np(m_handle, NULL, &ts)); + } + } + + return ok; + } + + + ThreadHandle getHandle() const + { + return m_handle; + } + + ThreadID getThreadID() const + { + return m_threadID; + } + + bool isRunning() const + { + return (m_handle != (pthread_t)-1); + } + + void setStackSize(unsigned int stack_size) + { + m_stackSize = stack_size; + } + + int kill(int sig) + { + int ret = 0; + if (isRunning()) + { + ret = ::pthread_kill(m_handle, sig); + } + return ret; + } + +protected: + virtual int run() =0; + virtual bool startup() { return true; } + virtual bool startup(int num) { return true; } + virtual void cleanup() {} + virtual void doStop() {} + + + unsigned int m_stackSize; + ThreadID m_threadID; + ThreadHandle m_handle; + bool m_canExit; + + + +private: + static void* ThreadFunction(void* param) + { + int code = 0; + Thread* pThread = (Thread*)param; + pThread->m_threadID = syscall( SYS_gettid ); + if ( !pThread->m_canExit ) + { + if (pThread->startup()) + { + code = pThread->run(); + } + else + { + code = 1; + } + pThread->cleanup(); + } + // pThread->m_handle = (pthread_t)-1; + pThread->m_threadID = 0; + ::pthread_exit(&code); + return NULL; + } + + bool createThread() + { + pthread_attr_t attr; + ::pthread_attr_init( &attr ); + pthread_attr_t* pAttr = NULL; + if ( 0 != m_stackSize ) + { + ::pthread_attr_setstacksize( &attr, m_stackSize ); + pAttr = &attr; + } + int ret = ::pthread_create( &m_handle, pAttr, ThreadFunction, (void*)this ); + ::pthread_attr_destroy( &attr ); + return ( 0 == ret ); + } + + //绾跨▼缁戝畾CPU鐨勬牳 + bool createThread(int num) + { + pthread_attr_t attr; + ::pthread_attr_init(&attr); + pthread_attr_t* pAttr = NULL; + if (0 != m_stackSize) + { + ::pthread_attr_setstacksize(&attr, m_stackSize); + pAttr = &attr; + } + int ret = ::pthread_create(&m_handle, pAttr, ThreadFunction, (void*)this); + + cpu_set_t cpu_info; + CPU_ZERO(&cpu_info); + CPU_SET(num, &cpu_info); + if (0 != pthread_setaffinity_np(m_handle, sizeof(cpu_set_t), &cpu_info)) + { + printf("set affinity failed"); + } + + ::pthread_attr_destroy(&attr); + return (0 == ret); + } + + static void getTimeout(struct timespec *spec, int timer) + { + struct timeval current; + gettimeofday( ¤t, NULL ); + TIMEVAL_TO_TIMESPEC( ¤t, spec ); + spec->tv_sec = current.tv_sec + ((timer + current.tv_usec / 1000) / 1000); + spec->tv_nsec = ((current.tv_usec / 1000 + timer) % 1000) * 1000000; + } + +}; + +#endif //WIN32 + +} // end of namespace +//////////////////////////////////////////////////////////////////////////// + +#endif /* TTHREAD_H_ */ diff --git a/src/left_over/auth/sycJson.cpp b/src/left_over/auth/sycJson.cpp new file mode 100644 index 0000000..9c544da --- /dev/null +++ b/src/left_over/auth/sycJson.cpp @@ -0,0 +1,750 @@ +/* + Copyright (c) 2009 Dave Gamble + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +#include +#include +#include +#include +#include +#include +#include +#include "sycJson.h" + +static const char *ep; + +const char *cJSON_GetErrorPtr(void) {return ep;} + +static int cJSON_strcasecmp(const char *s1,const char *s2) +{ + if (!s1) return (s1==s2)?0:1;if (!s2) return 1; + for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; + return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); +} + +static void *(*cJSON_malloc)(size_t sz) = malloc; +static void (*cJSON_free)(void *ptr) = free; + +static char* cJSON_strdup(const char* str) +{ + size_t len; + char* copy; + + len = strlen(str) + 1; + if (!(copy = (char*)cJSON_malloc(len))) return 0; + memcpy(copy,str,len); + return copy; +} + +void cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (!hooks) { /* Reset hooks */ + cJSON_malloc = malloc; + cJSON_free = free; + return; + } + + cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; + cJSON_free = (hooks->free_fn)?hooks->free_fn:free; +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(void) +{ + cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); + if (node) memset(node,0,sizeof(cJSON)); + return node; +} + +/* Delete a cJSON structure. */ +void cJSON_Delete(cJSON *c) +{ + cJSON *next; + while (c) + { + next=c->next; + if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); + if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); + if (!(c->type&cJSON_StringIsConst) && c->string) cJSON_free(c->string); + cJSON_free(c); + c=next; + } +} + +/* Parse the input text to generate a number, and populate the result into item. */ +static const char *parse_number(cJSON *item,const char *num) +{ + double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; + + if (*num=='-') sign=-1,num++; /* Has sign? */ + if (*num=='0') num++; /* is zero */ + if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ + if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ + if (*num=='e' || *num=='E') /* Exponent? */ + { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ + while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ + } + + n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ + + item->valuedouble=n; + item->valueint=(int)n; + item->type=cJSON_Number; + return num; +} + +static int pow2gt (int x) { --x; x|=x>>1; x|=x>>2; x|=x>>4; x|=x>>8; x|=x>>16; return x+1; } + +typedef struct {char *buffer; int length; int offset; } printbuffer; + +static char* ensure(printbuffer *p,int needed) +{ + char *newbuffer;int newsize; + if (!p || !p->buffer) return 0; + needed+=p->offset; + if (needed<=p->length) return p->buffer+p->offset; + + newsize=pow2gt(needed); + newbuffer=(char*)cJSON_malloc(newsize); + if (!newbuffer) {cJSON_free(p->buffer);p->length=0,p->buffer=0;return 0;} + if (newbuffer) memcpy(newbuffer,p->buffer,p->length); + cJSON_free(p->buffer); + p->length=newsize; + p->buffer=newbuffer; + return newbuffer+p->offset; +} + +static int update(printbuffer *p) +{ + char *str; + if (!p || !p->buffer) return 0; + str=p->buffer+p->offset; + return p->offset+strlen(str); +} + +/* Render the number nicely from the given item into a string. */ +static char *print_number(cJSON *item,printbuffer *p) +{ + char *str=0; + double d=item->valuedouble; + if (d==0) + { + if (p) str=ensure(p,2); + else str=(char*)cJSON_malloc(2); /* special case for 0. */ + if (str) strcpy(str,"0"); + } + else if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) + { + if (p) str=ensure(p,21); + else str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ + if (str) sprintf(str,"%d",item->valueint); + } + else + { + if (p) str=ensure(p,64); + else str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ + if (str) + { + if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60)sprintf(str,"%.0f",d); + else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); + else sprintf(str,"%f",d); + } + } + return str; +} + +static unsigned parse_hex4(const char *str) +{ + unsigned h=0; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + return h; +} + +/* Parse the input text into an unescaped cstring, and populate item. */ +static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; +static const char *parse_string(cJSON *item,const char *str) +{ + const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; + if (*str!='\"') {ep=str;return 0;} /* not a string! */ + + while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ + + out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ + if (!out) return 0; + + ptr=str+1;ptr2=out; + while (*ptr!='\"' && *ptr) + { + if (*ptr!='\\') *ptr2++=*ptr++; + else + { + ptr++; + switch (*ptr) + { + case 'b': *ptr2++='\b'; break; + case 'f': *ptr2++='\f'; break; + case 'n': *ptr2++='\n'; break; + case 'r': *ptr2++='\r'; break; + case 't': *ptr2++='\t'; break; + case 'u': /* transcode utf16 to utf8. */ + uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ + + if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */ + + if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ + { + if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */ + uc2=parse_hex4(ptr+3);ptr+=6; + if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */ + uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); + } + + len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; + + switch (len) { + case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; + case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; + case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; + case 1: *--ptr2 =(uc | firstByteMark[len]); + } + ptr2+=len; + break; + default: *ptr2++=*ptr; break; + } + ptr++; + } + } + *ptr2=0; + if (*ptr=='\"') ptr++; + item->valuestring=out; + item->type=cJSON_String; + return ptr; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static char *print_string_ptr(const char *str,printbuffer *p) +{ + const char *ptr;char *ptr2,*out;int len=0,flag=0;unsigned char token; + + for (ptr=str;*ptr;ptr++) flag|=((*ptr>0 && *ptr<32)||(*ptr=='\"')||(*ptr=='\\'))?1:0; + if (!flag) + { + len=ptr-str; + if (p) out=ensure(p,len+3); + else out=(char*)cJSON_malloc(len+3); + if (!out) return 0; + ptr2=out;*ptr2++='\"'; + strcpy(ptr2,str); + ptr2[len]='\"'; + ptr2[len+1]=0; + return out; + } + + if (!str) + { + if (p) out=ensure(p,3); + else out=(char*)cJSON_malloc(3); + if (!out) return 0; + strcpy(out,"\"\""); + return out; + } + ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} + + if (p) out=ensure(p,len+3); + else out=(char*)cJSON_malloc(len+3); + if (!out) return 0; + + ptr2=out;ptr=str; + *ptr2++='\"'; + while (*ptr) + { + if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; + else + { + *ptr2++='\\'; + switch (token=*ptr++) + { + case '\\': *ptr2++='\\'; break; + case '\"': *ptr2++='\"'; break; + case '\b': *ptr2++='b'; break; + case '\f': *ptr2++='f'; break; + case '\n': *ptr2++='n'; break; + case '\r': *ptr2++='r'; break; + case '\t': *ptr2++='t'; break; + default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ + } + } + } + *ptr2++='\"';*ptr2++=0; + return out; +} +/* Invote print_string_ptr (which is useful) on an item. */ +static char *print_string(cJSON *item,printbuffer *p) {return print_string_ptr(item->valuestring,p);} + +/* Predeclare these prototypes. */ +static const char *parse_value(cJSON *item,const char *value); +static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p); +static const char *parse_array(cJSON *item,const char *value); +static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p); +static const char *parse_object(cJSON *item,const char *value); +static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p); + +/* Utility to jump whitespace and cr/lf */ +static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;} + +/* Parse an object - create a new root, and populate. */ +cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated) +{ + const char *end=0; + cJSON *c=cJSON_New_Item(); + ep=0; + if (!c) return 0; /* memory fail */ + + end=parse_value(c,skip(value)); + if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */ + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}} + if (return_parse_end) *return_parse_end=end; + return c; +} +/* Default options for cJSON_Parse */ +cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);} + +/* Render a cJSON item/entity/structure to text. */ +char *cJSON_Print(cJSON *item) {return print_value(item,0,1,0);} +char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0,0);} + +char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt) +{ + printbuffer p; + p.buffer=(char*)cJSON_malloc(prebuffer); + p.length=prebuffer; + p.offset=0; + return print_value(item,0,fmt,&p); + return p.buffer; +} + + +/* Parser core - when encountering text, process appropriately. */ +static const char *parse_value(cJSON *item,const char *value) +{ + if (!value) return 0; /* Fail on null. */ + if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } + if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } + if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } + if (*value=='\"') { return parse_string(item,value); } + if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } + if (*value=='[') { return parse_array(item,value); } + if (*value=='{') { return parse_object(item,value); } + + ep=value;return 0; /* failure. */ +} + +/* Render a value to text. */ +static char *print_value(cJSON *item,int depth,int fmt,printbuffer *p) +{ + char *out=0; + if (!item) return 0; + if (p) + { + switch ((item->type)&255) + { + case cJSON_NULL: {out=ensure(p,5); if (out) strcpy(out,"null"); break;} + case cJSON_False: {out=ensure(p,6); if (out) strcpy(out,"false"); break;} + case cJSON_True: {out=ensure(p,5); if (out) strcpy(out,"true"); break;} + case cJSON_Number: out=print_number(item,p);break; + case cJSON_String: out=print_string(item,p);break; + case cJSON_Array: out=print_array(item,depth,fmt,p);break; + case cJSON_Object: out=print_object(item,depth,fmt,p);break; + } + } + else + { + switch ((item->type)&255) + { + case cJSON_NULL: out=cJSON_strdup("null"); break; + case cJSON_False: out=cJSON_strdup("false");break; + case cJSON_True: out=cJSON_strdup("true"); break; + case cJSON_Number: out=print_number(item,0);break; + case cJSON_String: out=print_string(item,0);break; + case cJSON_Array: out=print_array(item,depth,fmt,0);break; + case cJSON_Object: out=print_object(item,depth,fmt,0);break; + } + } + return out; +} + +/* Build an array from input text. */ +static const char *parse_array(cJSON *item,const char *value) +{ + cJSON *child; + if (*value!='[') {ep=value;return 0;} /* not an array! */ + + item->type=cJSON_Array; + value=skip(value+1); + if (*value==']') return value+1; /* empty array. */ + + item->child=child=cJSON_New_Item(); + if (!item->child) return 0; /* memory fail */ + value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ + if (!value) return 0; + + while (*value==',') + { + cJSON *new_item; + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ + child->next=new_item;new_item->prev=child;child=new_item; + value=skip(parse_value(child,skip(value+1))); + if (!value) return 0; /* memory fail */ + } + + if (*value==']') return value+1; /* end of array */ + ep=value;return 0; /* malformed. */ +} + +/* Render an array to text */ +static char *print_array(cJSON *item,int depth,int fmt,printbuffer *p) +{ + char **entries; + char *out=0,*ptr,*ret;int len=5; + cJSON *child=item->child; + int numentries=0,i=0,fail=0; + size_t tmplen=0; + + /* How many entries in the array? */ + while (child) numentries++,child=child->next; + /* Explicitly handle numentries==0 */ + if (!numentries) + { + if (p) out=ensure(p,3); + else out=(char*)cJSON_malloc(3); + if (out) strcpy(out,"[]"); + return out; + } + + if (p) + { + /* Compose the output array. */ + i=p->offset; + ptr=ensure(p,1);if (!ptr) return 0; *ptr='['; p->offset++; + child=item->child; + while (child && !fail) + { + print_value(child,depth+1,fmt,p); + p->offset=update(p); + if (child->next) {len=fmt?2:1;ptr=ensure(p,len+1);if (!ptr) return 0;*ptr++=',';if(fmt)*ptr++=' ';*ptr=0;p->offset+=len;} + child=child->next; + } + ptr=ensure(p,2);if (!ptr) return 0; *ptr++=']';*ptr=0; + out=(p->buffer)+i; + } + else + { + /* Allocate an array to hold the values for each */ + entries=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!entries) return 0; + memset(entries,0,numentries*sizeof(char*)); + /* Retrieve all the results: */ + child=item->child; + while (child && !fail) + { + ret=print_value(child,depth+1,fmt,0); + entries[i++]=ret; + if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; + child=child->next; + } + + /* If we didn't fail, try to malloc the output string */ + if (!fail) out=(char*)cJSON_malloc(len); + /* If that fails, we fail. */ + if (!out) fail=1; + + /* Handle failure. */ + if (fail) + { + for (i=0;itype=cJSON_Object; + value=skip(value+1); + if (*value=='}') return value+1; /* empty array. */ + + item->child=child=cJSON_New_Item(); + if (!item->child) return 0; + value=skip(parse_string(child,skip(value))); + if (!value) return 0; + child->string=child->valuestring;child->valuestring=0; + if (*value!=':') {ep=value;return 0;} /* fail! */ + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ + if (!value) return 0; + + while (*value==',') + { + cJSON *new_item; + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ + child->next=new_item;new_item->prev=child;child=new_item; + value=skip(parse_string(child,skip(value+1))); + if (!value) return 0; + child->string=child->valuestring;child->valuestring=0; + if (*value!=':') {ep=value;return 0;} /* fail! */ + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ + if (!value) return 0; + } + + if (*value=='}') return value+1; /* end of array */ + ep=value;return 0; /* malformed. */ +} + +/* Render an object to text. */ +static char *print_object(cJSON *item,int depth,int fmt,printbuffer *p) +{ + char **entries=0,**names=0; + char *out=0,*ptr,*ret,*str;int len=7,i=0,j; + cJSON *child=item->child; + int numentries=0,fail=0; + size_t tmplen=0; + /* Count the number of entries. */ + while (child) numentries++,child=child->next; + /* Explicitly handle empty object case */ + if (!numentries) + { + if (p) out=ensure(p,fmt?depth+4:3); + else out=(char*)cJSON_malloc(fmt?depth+4:3); + if (!out) return 0; + ptr=out;*ptr++='{'; + if (fmt) {*ptr++='\n';for (i=0;ioffset; + len=fmt?2:1; ptr=ensure(p,len+1); if (!ptr) return 0; + *ptr++='{'; if (fmt) *ptr++='\n'; *ptr=0; p->offset+=len; + child=item->child;depth++; + while (child) + { + if (fmt) + { + ptr=ensure(p,depth); if (!ptr) return 0; + for (j=0;joffset+=depth; + } + print_string_ptr(child->string,p); + p->offset=update(p); + + len=fmt?2:1; + ptr=ensure(p,len); if (!ptr) return 0; + *ptr++=':';if (fmt) *ptr++='\t'; + p->offset+=len; + + print_value(child,depth,fmt,p); + p->offset=update(p); + + len=(fmt?1:0)+(child->next?1:0); + ptr=ensure(p,len+1); if (!ptr) return 0; + if (child->next) *ptr++=','; + if (fmt) *ptr++='\n';*ptr=0; + p->offset+=len; + child=child->next; + } + ptr=ensure(p,fmt?(depth+1):2); if (!ptr) return 0; + if (fmt) for (i=0;ibuffer)+i; + } + else + { + /* Allocate space for the names and the objects */ + entries=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!entries) return 0; + names=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!names) {cJSON_free(entries);return 0;} + memset(entries,0,sizeof(char*)*numentries); + memset(names,0,sizeof(char*)*numentries); + + /* Collect all the results into our arrays: */ + child=item->child;depth++;if (fmt) len+=depth; + while (child) + { + names[i]=str=print_string_ptr(child->string,0); + entries[i++]=ret=print_value(child,depth,fmt,0); + if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; + child=child->next; + } + + /* Try to allocate the output string */ + if (!fail) out=(char*)cJSON_malloc(len); + if (!out) fail=1; + + /* Handle failure */ + if (fail) + { + for (i=0;ichild;int i=0;while(c)i++,c=c->next;return i;} +cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} +cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;} +/* Utility for handling references. */ +static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;} + +/* Add item to array/object. */ +void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} +void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} +void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (!(item->type&cJSON_StringIsConst) && item->string) cJSON_free(item->string);item->string=(char*)string;item->type|=cJSON_StringIsConst;cJSON_AddItemToArray(object,item);} +void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} +void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} + +cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; + if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} +void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} +cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;} +void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));} + +/* Replace array/object items with new ones. */ +void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) {cJSON_AddItemToArray(array,newitem);return;} + newitem->next=c;newitem->prev=c->prev;c->prev=newitem;if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;} +void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; + newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; + if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} +void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} + +/* Create basic types: */ +cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} +cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} +cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} +cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} +cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} +cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} +cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} +cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} + +/* Create Arrays: */ +cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} + +/* Duplication */ +cJSON *cJSON_Duplicate(cJSON *item,int recurse) +{ + cJSON *newitem,*cptr,*nptr=0,*newchild; + /* Bail on bad ptr */ + if (!item) return 0; + /* Create new item */ + newitem=cJSON_New_Item(); + if (!newitem) return 0; + /* Copy over all vars */ + newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; + if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}} + if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}} + /* If non-recursive, then we're done! */ + if (!recurse) return newitem; + /* Walk the ->next chain for the child. */ + cptr=item->child; + while (cptr) + { + newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) {cJSON_Delete(newitem);return 0;} + if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */ + cptr=cptr->next; + } + return newitem; +} + +void cJSON_Minify(char *json) +{ + char *into=json; + while (*json) + { + if (*json==' ') json++; + else if (*json=='\t') json++; /* Whitespace characters. */ + else if (*json=='\r') json++; + else if (*json=='\n') json++; + else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; /* double-slash comments, to end of line. */ + else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} /* multiline comments. */ + else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} /* string literals, which are \" sensitive. */ + else *into++=*json++; /* All other characters. */ + } + *into=0; /* and null-terminate. */ +} diff --git a/src/left_over/auth/sycJson.h b/src/left_over/auth/sycJson.h new file mode 100644 index 0000000..466d10d --- /dev/null +++ b/src/left_over/auth/sycJson.h @@ -0,0 +1,149 @@ +/* + Copyright (c) 2009 Dave Gamble + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* cJSON Types: */ +#define cJSON_False 0 +#define cJSON_True 1 +#define cJSON_NULL 2 +#define cJSON_Number 3 +#define cJSON_String 4 +#define cJSON_Array 5 +#define cJSON_Object 6 + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON { + struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + + int type; /* The type of the item, as above. */ + + char *valuestring; /* The item's string, if type==cJSON_String */ + int valueint; /* The item's number, if type==cJSON_Number */ + double valuedouble; /* The item's number, if type==cJSON_Number */ + + char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ +} cJSON; + +typedef struct cJSON_Hooks { + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); +} cJSON_Hooks; + +/* Supply malloc, realloc and free functions to cJSON */ +extern void cJSON_InitHooks(cJSON_Hooks* hooks); + + +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. Call cJSON_Delete when finished. */ +extern cJSON *cJSON_Parse(const char *value); +/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */ +extern char *cJSON_Print(cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */ +extern char *cJSON_PrintUnformatted(cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +extern char *cJSON_PrintBuffered(cJSON *item,int prebuffer,int fmt); +/* Delete a cJSON entity and all subentities. */ +extern void cJSON_Delete(cJSON *c); + +/* Returns the number of items in an array (or object). */ +extern int cJSON_GetArraySize(cJSON *array); +/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */ +extern cJSON *cJSON_GetArrayItem(cJSON *array,int item); +/* Get item "string" from object. Case insensitive. */ +extern cJSON *cJSON_GetObjectItem(cJSON *object,const char *string); + +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +extern const char *cJSON_GetErrorPtr(void); + +/* These calls create a cJSON item of the appropriate type. */ +extern cJSON *cJSON_CreateNull(void); +extern cJSON *cJSON_CreateTrue(void); +extern cJSON *cJSON_CreateFalse(void); +extern cJSON *cJSON_CreateBool(int b); +extern cJSON *cJSON_CreateNumber(double num); +extern cJSON *cJSON_CreateString(const char *string); +extern cJSON *cJSON_CreateArray(void); +extern cJSON *cJSON_CreateObject(void); + +/* These utilities create an Array of count items. */ +extern cJSON *cJSON_CreateIntArray(const int *numbers,int count); +extern cJSON *cJSON_CreateFloatArray(const float *numbers,int count); +extern cJSON *cJSON_CreateDoubleArray(const double *numbers,int count); +extern cJSON *cJSON_CreateStringArray(const char **strings,int count); + +/* Append item to the specified array/object. */ +extern void cJSON_AddItemToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item); +extern void cJSON_AddItemToObjectCS(cJSON *object,const char *string,cJSON *item); /* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object */ +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +extern void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +extern void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item); + +/* Remove/Detatch items from Arrays/Objects. */ +extern cJSON *cJSON_DetachItemFromArray(cJSON *array,int which); +extern void cJSON_DeleteItemFromArray(cJSON *array,int which); +extern cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string); +extern void cJSON_DeleteItemFromObject(cJSON *object,const char *string); + +/* Update array items. */ +extern void cJSON_InsertItemInArray(cJSON *array,int which,cJSON *newitem); /* Shifts pre-existing items to the right. */ +extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem); +extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +extern cJSON *cJSON_Duplicate(cJSON *item,int recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will +need to be released. With recurse!=0, it will duplicate any children connected to the item. +The item->next and ->prev pointers are always zero on return from Duplicate. */ + +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +extern cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated); + +extern void cJSON_Minify(char *json); + +/* Macros for creating things quickly. */ +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) +#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b)) +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) +#define cJSON_SetNumberValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/src/left_over/head.h b/src/left_over/head.h deleted file mode 100644 index b633d90..0000000 --- a/src/left_over/head.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once -#include "sy_common.h" - -typedef struct rs_params -{ - int mode; //运行模式(DEVICE_GPU / DEVICE_CPU) - int gpuid; //指定显卡id - //其余算法参数 如长短边等 - - sy_img image; - int channel_deal; - bool filt_flag; - int min_area; - int max_area; - - rs_params() :mode(DEVICE_GPU), gpuid(0), min_area(0), max_area(1000000) {}; -}rs_params; diff --git a/src/left_over/left_over_det.h b/src/left_over/left_over_det.h index 775ce2f..6ae51b1 100644 --- a/src/left_over/left_over_det.h +++ b/src/left_over/left_over_det.h @@ -1,8 +1,8 @@ -锘/************************************************************************* -* Version: 閬楃暀鐗㏒DK_v0.0.0 -* CopyRight: 涓瑙嗚(鍖椾含)绉戞妧鏈夐檺鍏徃 -* UpdateDate锛20200319 -* Content: 閬楃暀鐗╂娴 +/************************************************************************* +* Version: 遗留物SDK_v0.0.0 +* CopyRight: 中科视语(北京)科技有限公司 +* UpdateDate:20200319 +* Content: 遗留物检测 *************************************************************************/ #pragma once #ifdef _MSC_VER @@ -16,65 +16,107 @@ #endif -#include "header.h" + #define m_BOUNDING_BOX_MIN 50 #define m_BOUNDING_BOX_MAX 500 #define m_BOUNDING_BOX_RATEMIN 0.001 #define m_BOUNDING_BOX_RATEMAX 100 -#define MAXROINUM 10 // 鏈澶OI鏁 +#define MAXROINUM 10 // 最大ROI数 #define MACDETECTOBJNUM 10 #ifdef __cplusplus extern "C" { #endif +//ImgData +//Point +#ifndef __SY_POINT__ +#define __SY_POINT__ +typedef struct sy_point +{ + int x_; + int y_; + sy_point(int m_x, int m_y) :x_(m_x), y_(m_y) {}; + sy_point() {}; +} sy_point; +#endif -#ifndef __RS_PARAM__ -#define __RS_PARAM__ +#ifndef __SY_IMG__ +#define __SY_IMG__ +typedef struct sy_img +{ + unsigned char * data_; + int w_; + int h_; + int c_; + void set_data(int m_w, int m_h, int m_c, unsigned char * m_data) + { + w_ = m_w; + h_ = m_h; + c_ = m_c; + data_ = m_data; //Shallow copy + } +} sy_img; +#endif +//Rect #ifndef __SY_RECT__ #define __SY_RECT__ - typedef struct sy_rect - { - int left_; - int top_; - int width_; - int height_; - sy_rect(int m_left, int m_top, int m_width, int m_height) :left_(m_left), top_(m_top), width_(m_width), height_(m_height) {}; - sy_rect() {}; - } sy_rect; +typedef struct sy_rect +{ + int left_; + int top_; + int width_; + int height_; + sy_rect(int m_left, int m_top, int m_width, int m_height) :left_(m_left), top_(m_top), width_(m_width), height_(m_height) {}; + sy_rect() {}; +} sy_rect; #endif +#ifndef __RS_PARAM__ +#define __RS_PARAM__ #define MAXVERTEXNUM 10 +#define MAXVERPATHLEN 128 +typedef struct rs_auth_config { + char url[MAXVERPATHLEN]; + int port; +}rs_auth_config; + +typedef enum rs_auth_type { + TIME = 0, + PRODUCT_ID = 1 +}rs_auth_type; typedef struct rs_param { - long frame_num; // 閫楃暀鏃堕棿 鍗曚綅甯ф暟 - double scale; //缂╁皬姣斾緥 - sy_rect rect[MAXVERTEXNUM]; //鏈夋晥鍖哄煙 - unsigned char rect_num; //鏈夋晥鍖哄煙鏁伴噺 + long frame_num; //逗留时间 单位帧数 + double scale; //缩小比例 + sy_rect rect[MAXVERTEXNUM]; //有效区域 + unsigned char rect_num; //有效区域数量 + rs_auth_config auth; + rs_auth_type type; }rs_param; #endif #ifndef __MS_TRACE__ #define __MS_TRACE__ -#include "sy_common.h" -// 杩愬姩鐩爣鍧愭爣鍙婅建杩 -#define MAXTRACENUM 200 //杞ㄨ抗鏈澶ч暱搴 + +// 运动目标坐标及轨迹 +#define MAXTRACENUM 200 //轨迹最大长度 typedef struct ms_trace { - int trace_num; // 杞ㄨ抗闀垮害锛屾弿杩皃ObjTrace鐨勯暱搴 - sy_point obj_trace[MAXTRACENUM]; // 杞ㄨ抗锛岀偣鍧愭爣 + int trace_num; // 轨迹长度,描述pObjTrace的长度 + sy_point obj_trace[MAXTRACENUM]; // 轨迹,点坐标 }ms_trace; #endif #ifndef __RS_INFO__ #define __RS_INFO__ typedef struct ms_object_info { - sy_point curPos; // 褰撳墠鍧愭爣 - ms_trace trace; // 杞ㄨ抗鍙婃姤璀︾姸鎬 - int unique_id; // 褰撳墠鐩爣鐨勭壒鐐笽D - sy_rect tar_box; // 鐩爣澶栨帴鐭╁舰 - bool pb_alarm_state[MAXROINUM]; // 瀵瑰簲鍖哄煙鏄惁鎶ヨ - int pb_alarm_type[MAXROINUM]; // 瀵瑰簲鍖哄煙鏄摢绉嶆姤璀 + sy_point curPos; // 当前坐标 + ms_trace trace; // 轨迹及报警状态 + int unique_id; // 当前目标的特点ID + sy_rect tar_box; // 目标外接矩形 + bool pb_alarm_state[MAXROINUM]; // 对应区域是否报警 + int pb_alarm_type[MAXROINUM]; // 对应区域是哪种报警 }ms_object_info; #endif @@ -90,45 +132,45 @@ typedef struct ms_trace { #endif /************************************************************************* * FUNCTION: rs_init - * PURPOSE: 鍒濆鍖 + * PURPOSE: 初始化 * PARAM: - [out] handle - 鍙ユ焺 - [in] hp_param - 鍒濆鍖栧弬鏁 + [out] handle - 句柄 + [in] hp_param - 初始化参数 * RETURN: - [out] int - 鍒濆鍖栨槸鍚︽垚鍔燂紙SUCCEEDED琛ㄧず鎴愬姛锛孎AILED琛ㄧず澶辫触锛 + [out] int - 初始化是否成功(SUCCEEDED表示成功,FAILED表示失败) * NOTES: *************************************************************************/ MSREGIONSURVEILANCE_API int rs_init(void **handle, rs_param param); /************************************************************************* * FUNCTION: rs_process - * PURPOSE: 閬楃暀鐗╂娴 + * PURPOSE: 遗留物检测 * PARAM: - [in] tools - 鍙ユ焺 - [in] img_data - 妫娴嬪浘鍍忔暟鎹 - [in] result - 妫娴嬬粨鏋 + [in] tools - 句柄 + [in] img_data - 检测图像数据 + [in] result - 检测结果 * RETURN: - [out] int - 妫娴嬫槸鍚︽垚鍔燂紙SUCCEED琛ㄧず鎴愬姛锛孎AILED琛ㄧず澶辫触锛 + [out] int - 检测是否成功(SUCCEED表示成功,FAILED表示失败) * NOTES: *************************************************************************/ MSREGIONSURVEILANCE_API int rs_process(void *handle, sy_img img_data, rs_result *result); /************************************************************************* * FUNCTION: rs_batch - * PURPOSE: 閬楃暀鐗╂娴 batch + * PURPOSE: 遗留物检测 batch * PARAM: - [in] tools - 鍙ユ焺 - [in] img_data - 妫娴嬪浘鍍忔暟鎹 - [in] batch_size - 妫娴嬪浘鍍忔暟鐩 - [in] result - 妫娴嬬粨鏋 + [in] tools - 句柄 + [in] img_data - 检测图像数据 + [in] batch_size - 检测图像数目 + [in] result - 检测结果 * RETURN: - [out] int - 妫娴嬫槸鍚︽垚鍔燂紙SUCCEED琛ㄧず鎴愬姛锛孎AILED琛ㄧず澶辫触锛 + [out] int - 检测是否成功(SUCCEED表示成功,FAILED表示失败) * NOTES: *************************************************************************/ MSREGIONSURVEILANCE_API int rs_batch(void *handle, sy_img *img_data, int batch_size, rs_result *result); /************************************************************************* *FUNCTION: rs_release - * PURPOSE : 璧勬簮閲婃斁 + * PURPOSE : 资源释放 * PARAM : - [in] handle - 澶勭悊鍙ユ焺 + [in] handle - 处理句柄 * RETURN : NULL * NOTES : **************************************************************************/ @@ -137,7 +179,7 @@ typedef struct ms_trace { * FUNCTION: rs_get_version * PURPOSE: * PARAM: NULL - * RETURN: 鐗堟湰鍙 + * RETURN: 版本号 * NOTES: *************************************************************************/ MSREGIONSURVEILANCE_API const char * rs_get_version(); diff --git a/src/left_over/ms_region_surveilance.cpp b/src/left_over/ms_region_surveilance.cpp index 3cde4b6..92b7fe8 100644 --- a/src/left_over/ms_region_surveilance.cpp +++ b/src/left_over/ms_region_surveilance.cpp @@ -4,18 +4,10 @@ #include #include #include -#include "head.h" -//#include "authority.h" #include "sy_errorinfo.h" #include -#ifdef _MSC_VER -#define productSN "50799D35A77C4D15ACB1A4D0018471D8" //windows 视频结构化-图片接口 -#else -#define productSN "212B61A819604F588DC421D947F3F344" //linux 视频结构化--图片接口 -#endif -//#define AUTHORIZATION - - +//#define productSN "D92CBC0CFBA54BD3846DEBD4A9D36FC1" +#define productSN "B5895C36B5304C9A9FE665A372BFFDA2" //void check_thread(RegionSurveillanceProcess* handle) //{ @@ -75,7 +67,7 @@ inline std::chrono::system_clock::time_point makeTimePoint(int year, int mon, in inline bool timecheck() { - std::chrono::system_clock::time_point limitTime = makeTimePoint(2020, 12, 31); + std::chrono::system_clock::time_point limitTime = makeTimePoint(2021, 7, 1); std::chrono::system_clock::time_point nowTime = std::chrono::system_clock::now(); if (nowTime > limitTime) { @@ -86,16 +78,30 @@ inline bool timecheck() return true; } } + + int rs_init(void **handle, rs_param param) { int ret = SUCCESS; - - if (timecheck()) + RegionSurveillanceProcess* regin = new IRegionSurveillanceCpu; + bool auth_type = false; + if (param.type == TIME) + { + auth_type = timecheck(); + } + else + { + char uuid[36] = {}; + FILE *Uuid = fopen("/proc/sys/kernel/random/uuid", "r"); + fgets(uuid, 36, Uuid); + //strcpy(uuid,"059bebb1-fca2-42e6-8cbd-6b3195641819"); + fclose(Uuid); + regin->auth = new CheckAuthor; + regin->auth->Init(param.auth.url, param.auth.port, uuid, productSN, 1); + auth_type = regin->auth->GetAuthorStatus(); + } + if (auth_type) { - - RegionSurveillanceProcess* regin = nullptr; - //if (param.mode == 0) - regin = new IRegionSurveillanceCpu; regin->frame_num = param.frame_num; if (!regin) { @@ -103,12 +109,6 @@ int rs_init(void **handle, rs_param param) return -1; } - - /* regin->long_side = param.long_side; - regin->short_side = param.short_side;*/ - regin->licence_status = 0; - - regin->thrd_status = 0; regin->scale = param.scale; regin->rect_num = param.rect_num; //有效区域数量 for (int i = 0; i < regin->rect_num; ++i) @@ -123,6 +123,7 @@ int rs_init(void **handle, rs_param param) } else { + delete regin; return AUTHOR_ERROR; } @@ -191,6 +192,12 @@ int rs_process(void *handle, sy_img img_data, rs_result *result) printf("handle is NULL \n"); return -1; } + if (regin->auth && 0 == regin->auth->GetAuthorStatus()) + { + printf("auth error \n"); + return -1; + } + region_info pRegionInfo; pRegionInfo.alarm_info = 6; pRegionInfo.frame_num = regin->frame_num; @@ -332,14 +339,10 @@ void rs_release(void **handle) printf("handle is NULL \n"); return; } - if (regin->thrd_status == 0) + if (regin->auth) { -#ifdef AUTHORIZATION - regin->thrd.interrupt(); - //regin->thrd_run = false; - regin->thrd.join(); -#endif - regin->thrd_status = -1; + regin->auth->Uninit(); + delete regin->auth; } delete regin; regin = nullptr; diff --git a/src/left_over/svibe.h b/src/left_over/svibe.h index 2627180..acbd2a0 100644 --- a/src/left_over/svibe.h +++ b/src/left_over/svibe.h @@ -113,8 +113,8 @@ public: left_flag = 1; // 逗留标志 0 遗留 1移除 left_flag_now_s = 1; left_flag_now_w = 1; - OBJECT_AREA_MIN = 1000000; //默认最大过滤面积为1,000,000 by zl 20160304 - OBJECT_AREA_MAX = 300; //默认最小过滤面积为300 by zl 20160304 + OBJECT_AREA_MAX = 1000000; //默认最大过滤面积为1,000,000 by zl 20160304 + OBJECT_AREA_MIN = 300; //默认最小过滤面积为300 by zl 20160304 stay_dis = 5; greyImgData = NULL; diff --git a/src/left_over/sy_errorinfo.h b/src/left_over/sy_errorinfo.h new file mode 100644 index 0000000..c57f446 --- /dev/null +++ b/src/left_over/sy_errorinfo.h @@ -0,0 +1,133 @@ +#ifndef __SY_ERRORINFO_H__ +#define __SY_ERRORINFO_H__ + + +//--------------------------------通用------------------------------------// + +#define SUCCESS 0 //成功 +#define FAILED -1 //失败 + +//1.通用错误 预留编号:(-199) - (-100) +#define PARAMS_NULL_ERROR -100 //参数为空 +#define FILE_NOTFOUND_ERROR -101 //文件找不到 +#define HANDLE_NULL_ERROR -102 //句柄为空 +#define TYPE_UNKNOWN -103 //未知类型 +#define IMG_DATA_ERROR -104 //图像数据错误 +#define IMG_PARAMS_ERROR -105 //图像参数(宽 高 或者 通道数)有错误 +#define AUTHOR_ERROR -106 //授权失败 +#define VERSION_EXPIRED -107 //时间限制下的版本过期 +#define VIDEOFILEERROR -108 //视频打开失败 +#define BUFFNOTENOUGH -109 //缓冲区太小 + +#define MEAN_ERROR -110 //均值错误 +#define NEW_DATA_ERROR -111 //内存申请失败 +#define GPUID_PARAM_ERROR -112 //显卡参数设置错误 +#define CODEC_FORMAT_ERROR -113 //不支持的解码格式 +#define PARAMS_INVALID_ERROR -114 //参数值无效 + +//------------------------------------------------------------------------// + + +//-----------------------------深度学习相关-------------------------------// + +//1.通用模块 预留编号:(-299) - (-200) + +//a. caffe部分 预留编号:(-239) - (-200) +#define BATCH_SIZE_NO_EQUAL_INPUT -200 //BATCH_SIZE不匹配 +#define LAYER_NO_REGISTER -201 //层未注册 + +//b. 网络和模型部分 预留编号:(-279) - (-240) +#define PROTOFILE_MODEL_MISMATCH -240 //网络和模型不匹配 +#define PROTOFILEORVECTOR_NOTFOUND -241 //网络文件或者数组找不到 +#define PROTOFILE_NOTFOUND -242 //网络文件找不到 +#define PROTOVECTOR_NOTFOUND -243 //网络数组找不到 +#define MODELFILE_NOTFOUND -244 //模型文件找不到 +#define MODELLENGTH_ERROE -245 //模型数组长度错误 +#define MODELVECTOR_ERROE -246 //模型数组错误 + +//c. 其他深度学习通用错误 预留编号:(-299) - (-280) + +//----------------------------------------// + + +//2.人脸模块 预留编号:(-349) - (-300) + +//a. 人脸检测错误返回 预留编号:(-319) - (-300) +#define QUALITY_INIT_ERROR -300 //质量检测初始化失败 +#define ROTATIONCUT_INIT_ERROR -301 //切割旋转初始化失败 +#define FACERECG_INITFAILD_ERROR -302 //人脸识别初始化失败 +#define FACECUT_INITFAILD_ERROR -303 //人脸切割旋转初始化失败 +#define LDMK_INIT_ERROR -304 //关键点检测初始化失败 +#define FACEDETECT_INIT_ERROR -305 //人脸检测初始化失败 +#define POSE_INIT_ERROR -306 //人脸角度初始化失败 +#define SCORE_INIT_ERROR -307 //人脸置信度初始化失败 +#define DB_OPEN_DB_ERROR -308 //数据库打开失败(数据库错误) +#define DB_OPEN_SYS_ERROR -309 //数据库打开失败(程序内部错误) +#define DB_ADD_DATA_EXIST_ERROR -310 //数据库插入数据失败(已存在) +#define DB_ADD_DATA_NOTFOUND -311 //数据库插入数据失败 +#define FACEATTRIBUTES_INITFAILD_ERROR -312 //人脸属性初始化失败 + + +//c. 其他人脸模块错误 预留编号:(-349) - (-340) + + +//----------------------------------------// + + +//3.跟踪模块 预留编号:(-399) - (-350) +#define TRACKER_INIT_ERROR -350 //轨迹跟踪初始化失败 + + +//----------------------------------------// + + +//4.快照模块 预留编号:(-449) - (-400) +#define SHAPSHOT_INIT_ERROR -400 //快照初始化失败 + + +//----------------------------------------// + + +//5.流量统计模块 预留编号:(-499) - (-450) +#define TRAFFICSTATISTICS_INIT_ERROR -450 //流量统计初始化失败 + +//------------------------------------------------------------------------// + + +//-----------------------------授权部分相关-------------------------------// + +//1.授权通用模块 预留编号:(-600) - (-500) +#define AUTHOR_TIMEEXPIRED_ERROR -500 //超出有效期 +#define AUTHOR_SERVER_ERROR -501 //服务器出错 +#define AUTHOR_NOAUTHORIZATION_ERROR -502 //未注册且没有装机剩余量 +#define AUTHOR_NOCOMMUNICATION_ERROR -503 //无法通信 +#define AUTHOR_NET_ERROR -504 //网络出错 +#define LICENCE_SERVICECHECK_ERROR -505 //服务检查未成功 +#define LICENCE_SERVICENOTRUNNING_ERROR -506 //服务未开启 +#define LICENCE_LICENCEDATA_ERROR -507 //授权文件数据错误 +#define LICENCE_LICENCEINVALID_ERROR -508 //授权文件无效 +#define LICENCE_LICENCENOTEXIST_ERROR -509 //授权文件不存在 + +//------------------------------------------------------------------------// + + +//--------------------------------sdk相关---------------------------------// + +//1.视频结构化模块 预留编号:(-699) - (-600) + + +//a.二次属性错误返回 预留编号:(-649) - (-600) + +#define HUMANPARSING_INIT_ERROR -600 //行人结构化初始化失败 +#define HUMANCARPARSING_INIT_ERROR -601 //人骑车结构化初始化失败 +#define VEHICLECOLOR_INIT_ERROR -602 //车颜色识别初始化失败 +#define VEHICLEPLATEDETECT_INIT_ERROR -603 //车牌检测初始化失败 +#define VEHICLEPLATERECOG_INIT_ERROR -604 //车牌识别初始化失败 +#define VEHICLERECOG_INIT_ERROR -605 //车型识别初始化失败 +#define VPT_DET_INIT_ERROR -606 //人车物检测初始化失败 +//c.其他模块错误 预留编号:(-699) - (-650) + +//------------------------------------------------------------------------// + + +#endif // __SY_ERRORINFO_H__ \ No newline at end of file diff --git a/src/test/CvxText.cpp b/src/test/CvxText.cpp deleted file mode 100644 index 6820210..0000000 --- a/src/test/CvxText.cpp +++ /dev/null @@ -1,211 +0,0 @@ -#include - -#include -#include - -#include "CvxText.h" - -//==================================================================== -//==================================================================== - -// 打开字库 - -CvxText::CvxText(const char *freeType) -{ - assert(freeType != NULL); - - // 打开字库文件, 创建一个字体 - - if (FT_Init_FreeType(&m_library)) throw; - if (FT_New_Face(m_library, freeType, 0, &m_face)) throw; - - // 设置字体输出参数 - - restoreFont(); - - // 设置C语言的字符集环境 - - setlocale(LC_ALL, ""); -} - -// 释放FreeType资源 - -CvxText::~CvxText() -{ - FT_Done_Face(m_face); - FT_Done_FreeType(m_library); -} - -// 设置字体参数: -// -// font - 字体类型, 目前不支持 -// size - 字体大小/空白比例/间隔比例/旋转角度 -// underline - 下画线 -// diaphaneity - 透明度 - -void CvxText::getFont(int *type, CvScalar *size, bool *underline, float *diaphaneity) -{ - if (type) *type = m_fontType; - if (size) *size = m_fontSize; - if (underline) *underline = m_fontUnderline; - if (diaphaneity) *diaphaneity = m_fontDiaphaneity; -} - -void CvxText::setFont(int *type, CvScalar *size, bool *underline, float *diaphaneity) -{ - // 参数合法性检查 - - if (type) - { - if (type >= 0) m_fontType = *type; - } - if (size) - { - m_fontSize.val[0] = fabs(size->val[0]); - m_fontSize.val[1] = fabs(size->val[1]); - m_fontSize.val[2] = fabs(size->val[2]); - m_fontSize.val[3] = fabs(size->val[3]); - FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0); - } - if (underline) - { - m_fontUnderline = *underline; - } - if (diaphaneity) - { - m_fontDiaphaneity = *diaphaneity; - } - //FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0); -} - -// 恢复原始的字体设置 - -void CvxText::restoreFont() -{ - m_fontType = 0; // 字体类型(不支持) - - m_fontSize.val[0] = 20; // 字体大小 - m_fontSize.val[1] = 0.5; // 空白字符大小比例 - m_fontSize.val[2] = 0.1; // 间隔大小比例 - m_fontSize.val[3] = 0; // 旋转角度(不支持) - - m_fontUnderline = false; // 下画线(不支持) - - m_fontDiaphaneity = 1.0; // 色彩比例(可产生透明效果) - - // 设置字符大小 - - FT_Set_Pixel_Sizes(m_face, (int)m_fontSize.val[0], 0); -} - -// 输出函数(颜色默认为黑色) - -int CvxText::putText(IplImage *img, const char *text, CvPoint pos) -{ - return putText(img, text, pos, CV_RGB(255, 255, 255)); -} -int CvxText::putText(IplImage *img, const wchar_t *text, CvPoint pos) -{ - return putText(img, text, pos, CV_RGB(255, 255, 255)); -} - -// - -int CvxText::putText(IplImage *img, const char *text, CvPoint pos, CvScalar color) -{ - if (img == NULL) return -1; - if (text == NULL) return -1; - - // - - int i; - for (i = 0; text[i] != '\0'; ++i) - { - wchar_t wc = text[i]; - - // 解析双字节符号 - - if (!isascii(wc)) mbtowc(&wc, &text[i++], 2); - - // 输出当前的字符 - - putWChar(img, wc, pos, color); - } - return i; -} -int CvxText::putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color) -{ - if (img == NULL) return -1; - if (text == NULL) return -1; - - // - - int i; - for (i = 0; text[i] != '\0'; ++i) - { - // 输出当前的字符 - - putWChar(img, text[i], pos, color); - } - return i; -} - -// 输出当前字符, 更新m_pos位置 - -void CvxText::putWChar(IplImage *img, wchar_t wc, CvPoint &pos, CvScalar color) -{ - // 根据unicode生成字体的二值位图 - - FT_UInt glyph_index = FT_Get_Char_Index(m_face, wc); - FT_Load_Glyph(m_face, glyph_index, FT_LOAD_DEFAULT); - FT_Render_Glyph(m_face->glyph, FT_RENDER_MODE_MONO); - - // - - FT_GlyphSlot slot = m_face->glyph; - - // 行列数 - - int rows = slot->bitmap.rows; - int cols = slot->bitmap.width; - - // - - for (int i = 0; i < rows; ++i) - { - for (int j = 0; j < cols; ++j) - { - int off = ((img->origin == 0) ? i : (rows - 1 - i)) - * slot->bitmap.pitch + j / 8; - - if (slot->bitmap.buffer[off] & (0xC0 >> (j % 8))) - { - int r = (img->origin == 0) ? pos.y - (rows - 1 - i) : pos.y + i;; - int c = pos.x + j; - - if (r >= 0 && r < img->height - && c >= 0 && c < img->width) - { - CvScalar scalar = cvGet2D(img, r, c); - - // 进行色彩融合 - - float p = m_fontDiaphaneity; - for (int k = 0; k < 4; ++k) - { - scalar.val[k] = scalar.val[k] * (1 - p) + color.val[k] * p; - } - - cvSet2D(img, r, c, scalar); - } - } - } // end for - } // end for - - // 修改下一个字的输出位置 - - double space = m_fontSize.val[0] * m_fontSize.val[1]; - double sep = m_fontSize.val[0] * m_fontSize.val[2]; - - pos.x += (int)((cols ? cols : space) + sep); -} \ No newline at end of file diff --git a/src/test/CvxText.h b/src/test/CvxText.h deleted file mode 100644 index 3047505..0000000 --- a/src/test/CvxText.h +++ /dev/null @@ -1,190 +0,0 @@ -//==================================================================== -//==================================================================== -// -// 文件: CvxText.h -// -// 说明: OpenCV汉字输出 -// -// 时间: -// -// 作者: chaishushan#gmail.com -// -//==================================================================== -//==================================================================== - -#ifndef OPENCV_CVX_TEXT_2007_08_31_H -#define OPENCV_CVX_TEXT_2007_08_31_H - -/** -* \file CvxText.h -* \brief OpenCV汉字输出接口 -* -* 实现了汉字输出功能。 -*/ - -#include -#include FT_FREETYPE_H - -#include - -/** -* \class CvxText -* \brief OpenCV中输出汉字 -* -* OpenCV中输出汉字。字库提取采用了开源的FreeFype库。由于FreeFype是 -* GPL版权发布的库,和OpenCV版权并不一致,因此目前还没有合并到OpenCV -* 扩展库中。 -* -* 显示汉字的时候需要一个汉字字库文件,字库文件系统一般都自带了。 -* 这里采用的是一个开源的字库:“文泉驿正黑体”。 -* -* 关于"OpenCV扩展库"的细节请访问 -* http://code.google.com/p/opencv-extension-library/ -* -* 关于FreeType的细节请访问 -* http://www.freetype.org/ -*/ - - -class CvxText -{ - // 禁止copy - - CvxText& operator=(const CvxText&); - - //================================================================ - //================================================================ - -public: - - /** - * 装载字库文件 - */ - - CvxText(const char *freeType); - virtual ~CvxText(); - - //================================================================ - //================================================================ - - /** - * 获取字体。目前有些参数尚不支持。 - * - * \param font 字体类型, 目前不支持 - * \param size 字体大小/空白比例/间隔比例/旋转角度 - * \param underline 下画线 - * \param diaphaneity 透明度 - * - * \sa setFont, restoreFont - */ - - void getFont(int *type, - CvScalar *size = NULL, bool *underline = NULL, float *diaphaneity = NULL); - - /** - * 设置字体。目前有些参数尚不支持。 - * - * \param font 字体类型, 目前不支持 - * \param size 字体大小/空白比例/间隔比例/旋转角度 - * \param underline 下画线 - * \param diaphaneity 透明度 - * - * \sa getFont, restoreFont - */ - - void setFont(int *type, - CvScalar *size = NULL, bool *underline = NULL, float *diaphaneity = NULL); - - /** - * 恢复原始的字体设置。 - * - * \sa getFont, setFont - */ - - void restoreFont(); - - //================================================================ - //================================================================ - - /** - * 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。 - * - * \param img 输出的影象 - * \param text 文本内容 - * \param pos 文本位置 - * - * \return 返回成功输出的字符长度,失败返回-1。 - */ - - int putText(IplImage *img, const char *text, CvPoint pos); - - /** - * 输出汉字(颜色默认为黑色)。遇到不能输出的字符将停止。 - * - * \param img 输出的影象 - * \param text 文本内容 - * \param pos 文本位置 - * - * \return 返回成功输出的字符长度,失败返回-1。 - */ - - int putText(IplImage *img, const wchar_t *text, CvPoint pos); - - /** - * 输出汉字。遇到不能输出的字符将停止。 - * - * \param img 输出的影象 - * \param text 文本内容 - * \param pos 文本位置 - * \param color 文本颜色 - * - * \return 返回成功输出的字符长度,失败返回-1。 - */ - - int putText(IplImage *img, const char *text, CvPoint pos, CvScalar color); - - /** - * 输出汉字。遇到不能输出的字符将停止。 - * - * \param img 输出的影象 - * \param text 文本内容 - * \param pos 文本位置 - * \param color 文本颜色 - * - * \return 返回成功输出的字符长度,失败返回-1。 - */ - int putText(IplImage *img, const wchar_t *text, CvPoint pos, CvScalar color); - - //================================================================ - //================================================================ - -private: - - // 输出当前字符, 更新m_pos位置 - - void putWChar(IplImage *img, wchar_t wc, CvPoint &pos, CvScalar color); - - //================================================================ - //================================================================ - -private: - - FT_Library m_library; // 字库 - FT_Face m_face; // 字体 - - //================================================================ - //================================================================ - - // 默认的字体输出参数 - - int m_fontType; - CvScalar m_fontSize; - bool m_fontUnderline; - float m_fontDiaphaneity; - - //================================================================ - //================================================================ -}; - -#endif // OPENCV_CVX_TEXT_2007_08_31_H - diff --git a/src/test/demo - 鍓湰.cpp b/src/test/demo - 鍓湰.cpp deleted file mode 100644 index 85999d5..0000000 --- a/src/test/demo - 鍓湰.cpp +++ /dev/null @@ -1,408 +0,0 @@ -#include -#include -#include -#include - -#include "MSRegionSurveilance.h" -#include "highgui.h" -#include "cv.h" -#include "RegionAssist.h" - -#include "time_debug.h" - -#include - - -using namespace std; -//using namespace cv; - -void imag_ana_1channels(); -void imag_ana_3channels(); - -int main() -{ - imag_ana_1channels(); - //imag_ana_3channels(); - - system("pause"); -} - - -void imag_ana_3channels() -{ - //AlarmInfo 1进入禁区 2离开禁区 3单向越界 4双向越界 5徘徊 6丢包 - int numROI = 1; - - debug_time_t stime, etime; - - RegionInfo* pRegionInfo = new RegionInfo[numROI]; - int LeftPointX = 1050; - int LeftPointY = 450; - int RightPointX = 1400; - int RightPointY = 600; - - // 进入禁区 - pRegionInfo[0].AlarmInfo = 1; - pRegionInfo[0].nPointNum = 4; - pRegionInfo[0].pROI[0].x = LeftPointX; - pRegionInfo[0].pROI[0].y = LeftPointY; - pRegionInfo[0].pROI[1].x = RightPointX; - pRegionInfo[0].pROI[1].y = LeftPointY; - pRegionInfo[0].pROI[2].x = RightPointX; - pRegionInfo[0].pROI[2].y = RightPointY; - pRegionInfo[0].pROI[3].x = LeftPointX; - pRegionInfo[0].pROI[3].y = RightPointY; - - //pRegionInfo[0].AlarmInfo = 1; - //pRegionInfo[0].nPointNum = 4; - //pRegionInfo[0].pROI[0].x = LeftPointX/*226*/; - //pRegionInfo[0].pROI[0].y = LeftPointY; - //pRegionInfo[0].pROI[1].x = RightPointX/*223*/; - //pRegionInfo[0].pROI[1].y = LeftPointY; - //pRegionInfo[0].pROI[2].x = LeftPointX/*223*/; - //pRegionInfo[0].pROI[2].y = RightPointY; - //pRegionInfo[0].pROI[3].x = RightPointX/*223*/; - //pRegionInfo[0].pROI[3].y = RightPointY; - //pRegionInfo[0].dirPoint.x = 200;//用于定义方向的点 位于合法方向指向的一侧 - //pRegionInfo[0].dirPoint.y = 109; - - // 定义 - MS_RegionSurveillance MS1; - IRegionSurveillance* test = MS1.GetMS_RS(); - if (!test) - { - printf("model initial failed"); - exit(0); - } - - CvCapture* video1 = cvCaptureFromFile("../../data/test1.mp4"); - // 用opencv函数读取视频的一帧 - IplImage * src = cvQueryFrame(video1); - IplImage * srcscale = cvCreateImage(cvSize(src->width, src->height), 8, 3); - cvResize(src, srcscale); - // 获得图像信息 - int width = srcscale->width; - int height = srcscale->height; - int widthstep = srcscale->widthStep; - int nChannel = srcscale->nChannels; - - int frameCount = 0; // 处理的图像序号 - MS_ObjectInfo *ObjInfo = NULL; // 结果结构体 - int ObjCount; - int error_flag; - - long total_t = 0; - // 循环处理视频的每一帧 - while (src) - { - src = cvQueryFrame(video1); - - if (!src) - break; - - cvResize(src, srcscale); - - // 如果当前处理的是第一帧,则要进行初始化 - if (frameCount == 0) - { - error_flag = test->RSinit(width, height, widthstep, (unsigned char*)(srcscale->imageData), nChannel, 3, 0, 10, 1000000); - if (error_flag == 0) - { - cout << "设置有问题!!!" << endl; - return; - } - - - error_flag = test->RSRegion(numROI, pRegionInfo, false); - if (error_flag == 0) - { - cout << "区域设置有问题!!!" << endl; - return; - } - - - } - GetTime(&stime); - - // 智能分析 - test->RSDetect((unsigned char*)(srcscale->imageData), pRegionInfo); - - GetTime(&etime); - total_t += CalcTimeDiff(&stime, &etime); - //printf("RSDetect %d:%ld fps\n", frameCount, cost_t); - - // 获取智能分析结果 - ObjCount = test->getObjectNum(); - ObjInfo = new MS_ObjectInfo[ObjCount]; - test->getObjectInfo(ObjCount, ObjInfo); - printf("alram:\n"); - for (int i = 0; i < ObjCount; i++) - { - if (ObjInfo[i].pbAlarmType[0]) - { - switch (ObjInfo[i].pbAlarmType[0]) - { - case 1: - printf("obj %d: 进入禁区\n", ObjInfo[i].UniqueID); - break; - case 2: - printf("obj %d: 离开禁区\n", ObjInfo[i].UniqueID); - break; - case 3: - printf("obj %d: 单向越界\n", ObjInfo[i].UniqueID); - break; - case 4: - printf("obj %d: 双向越界\n", ObjInfo[i].UniqueID); - break; - case 5: - printf("obj %d: 徘徊\n", ObjInfo[i].UniqueID); - break; - case 6: - printf("obj %d: 丢包\n", ObjInfo[i].UniqueID); - break; - } - } - - } - - cvRectangle(srcscale, cvPoint(LeftPointX, LeftPointY), cvPoint(RightPointX, RightPointY), cvScalar(0, 0, 0)); - - // 轨迹描绘 - Trajectory((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, width, height, widthstep); - - // 目标框描绘 - ExternalRectangle((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, widthstep, numROI); - //画出警报区域 - //disp area 1 - /*for (int i = 0; i < numROI; i++) - { - cvLine(srcscale, cvPoint(pRegionInfo[i].pROI[0].x, pRegionInfo[i].pROI[0].y), - cvPoint(pRegionInfo[i].pROI[1].x, pRegionInfo[i].pROI[1].y), cvScalar(255, 0, 255), 1); - //获取箭头端点坐标 - - if (pRegionInfo[i].AlarmInfo == 3) - { - cv::Point pStart, pEnd;//by zl - pStart.x = pRegionInfo[i].ArrowStartPoint.x; - pStart.y = pRegionInfo[i].ArrowStartPoint.y; - pEnd.x = pRegionInfo[i].ArrowEndPoint.x; - pEnd.y = pRegionInfo[i].ArrowEndPoint.y; - DrawArrow(srcscale, pStart, pEnd, 15, 30);//调用绘制箭头函数 - //显示dirPoint - cv::Point pt1; - pt1.x = pRegionInfo[i].dirPoint.x; - pt1.y = pRegionInfo[i].dirPoint.y; - cvLine(srcscale, pt1, pt1, cvScalar(255, 0, 255), 3); - } - // - }*/ - ++frameCount; - - - // 图像显示 - cvShowImage("3channels", srcscale); - - cvWaitKey(1); - - delete[] ObjInfo; - } //循环处理结束 - - - long aver_t = total_t / frameCount; - printf("aver time:%ld us", aver_t); - - delete[] pRegionInfo; - test->RSrelease(); - MS1.Destroy(); - cvReleaseCapture(&video1); - cvReleaseImage(&srcscale); -} - - - -void imag_ana_1channels() -{ - //AlarmInfo 1进入禁区 2离开禁区 3单向越界 4双向越界 5徘徊 6丢包 - int numROI = 1; - - debug_time_t stime, etime; - - RegionInfo* pRegionInfo = new RegionInfo[numROI]; - - int LeftPointX = 1050; - int LeftPointY = 450; - int RightPointX = 1400; - int RightPointY = 600; - - // 进入禁区 - int index = 0; - pRegionInfo[index].AlarmInfo = 1; - pRegionInfo[index].nPointNum = 4; - pRegionInfo[index].pROI[0].x = LeftPointX; - pRegionInfo[index].pROI[0].y = LeftPointY; - pRegionInfo[index].pROI[1].x = RightPointX; - pRegionInfo[index].pROI[1].y = LeftPointY; - pRegionInfo[index].pROI[2].x = RightPointX; - pRegionInfo[index].pROI[2].y = RightPointY; - pRegionInfo[index].pROI[3].x = LeftPointX; - pRegionInfo[index].pROI[3].y = RightPointY; - - - index = 0; - //离开禁区 - pRegionInfo[index].AlarmInfo = 2; - pRegionInfo[index].nPointNum = 4; - pRegionInfo[index].pROI[0].x = LeftPointX; - pRegionInfo[index].pROI[0].y = LeftPointY; - pRegionInfo[index].pROI[1].x = RightPointX; - pRegionInfo[index].pROI[1].y = LeftPointY; - pRegionInfo[index].pROI[2].x = RightPointX; - pRegionInfo[index].pROI[2].y = RightPointY; - pRegionInfo[index].pROI[3].x = LeftPointX; - pRegionInfo[index].pROI[3].y = RightPointY; - - - - // 定义 - MS_RegionSurveillance MS1; - IRegionSurveillance* test = MS1.GetMS_RS(); - if (!test) - { - printf("model initial failed"); - exit(0); - } - - CvCapture* video1 = cvCaptureFromFile("../../data/test1.mp4"); - // 用opencv函数读取视频的一帧 - IplImage * src = cvQueryFrame(video1); - IplImage * srcscale = cvCreateImage(cvSize(src->width, src->height), 8, 3); //用于缩放 当前先不缩放 - IplImage * gray = cvCreateImage(cvSize(srcscale->width, srcscale->height), 8, 1); - cvResize(src, srcscale); - cvCvtColor(srcscale, gray, CV_RGB2GRAY); - - - //cv::Mat saveImg = cv::cvarrToMat(src, true); - - //cv::rectangle(saveImg, cv::Rect(1000, 450, 1450-1000, 600-450), cv::Scalar(255, 255, 0), 2); - //cv::imwrite("img.jpg", saveImg); - //cv::imshow("image", saveImg); - //cv::waitKey(0); - - - CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 30, cvSize(srcscale->width, srcscale->height)); - - int frameCount = 0; // 处理的图像序号 - MS_ObjectInfo *ObjInfo = NULL; // 结果结构体 - int ObjCount; - int error_flag; - - long total_t = 0; - - printf("width = %d height = %d\n", gray->width, gray->height); - // 循环处理视频的每一帧 - while (src) - { - src = cvQueryFrame(video1); - if (!src) - break; - cvResize(src, srcscale); - cvCvtColor(srcscale, gray, CV_RGB2GRAY); - - // 如果当前处理的是第一帧,则要进行初始化 - if (frameCount == 0) - { - error_flag = test->RSinit(gray->width, gray->height, gray->widthStep, - (unsigned char*)(gray->imageData), gray->nChannels, 1, 0, 10, 1000000); - if (error_flag == 0) - { - cout << "设置有问题!!!" << endl; - return; - } - - error_flag = test->RSRegion(numROI, pRegionInfo, false); - if (error_flag == 0) - { - cout << "区域设置有问题!!!" << endl; - return; - } - - } - - GetTime(&stime); - - // 智能分析 - test->RSDetect((unsigned char*)(gray->imageData), pRegionInfo); - - GetTime(&etime); - total_t += CalcTimeDiff(&stime, &etime); - printf("detect time:%ld us\n", CalcTimeDiff(&stime, &etime)); - - // 获取智能分析结果 - ObjCount = test->getObjectNum(); - ObjInfo = new MS_ObjectInfo[ObjCount]; - test->getObjectInfo(ObjCount, ObjInfo); - - //报警区域 - cvRectangle(srcscale, cvPoint(LeftPointX, LeftPointY), cvPoint(RightPointX, RightPointY), cvScalar(0, 0, 0)); - - // 轨迹描绘 - Trajectory((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, srcscale->width, srcscale->height, srcscale->widthStep); - - // 目标框描绘 - ExternalRectangle((unsigned char*)(srcscale->imageData), ObjInfo, ObjCount, srcscale->widthStep, numROI); - - for (int i = 0; i < ObjCount; i++) - { - for (int j = 0; j < numROI; j++) - { - if (ObjInfo[i].pbAlarmType[j]) - { - switch (ObjInfo[i].pbAlarmType[j]) - { - case 1: - printf("obj %d: 进入禁区\n", ObjInfo[i].UniqueID); - break; - case 2: - printf("obj %d: 离开禁区\n", ObjInfo[i].UniqueID); - break; - case 3: - printf("obj %d: 单向越界\n", ObjInfo[i].UniqueID); - break; - case 4: - printf("obj %d: 双向越界\n", ObjInfo[i].UniqueID); - break; - case 5: - printf("obj %d: 徘徊\n", ObjInfo[i].UniqueID); - break; - case 6: - printf("obj %d: 丢包\n", ObjInfo[i].UniqueID); - break; - } - } - } - - - } - - ++frameCount; - cvWriteFrame(writer, srcscale); - // 图像显示 - cvShowImage("1channels", srcscale); - - cvWaitKey(1); - - delete[] ObjInfo; - } //循环处理结束 - - long aver_t = total_t / frameCount; - printf("aver time:%ld us", aver_t); - - cvReleaseVideoWriter(&writer); - delete[] pRegionInfo; - test->RSrelease(); - MS1.Destroy(); - cvReleaseCapture(&video1); - cvReleaseImage(&srcscale); - cvReleaseImage(&gray); - -} \ No newline at end of file diff --git a/src/test/demo.cpp b/src/test/demo.cpp index a44734a..1978918 100644 --- a/src/test/demo.cpp +++ b/src/test/demo.cpp @@ -13,7 +13,6 @@ #include #include "left_over_det.h" #include -#include #include "RegionAssist.h" using namespace std; @@ -23,25 +22,10 @@ void imag_ana_3channels(); void algorthim_thread1(); int main() { - //int test_count = 10; - - //while (test_count--) - //{ - // printf("begin test_count: %d\n", test_count); - - // boost::thread thrd1(boost::bind(algorthim_thread1)); - // boost::thread thrd2(boost::bind(algorthim_thread1)); - // boost::thread thrd3(boost::bind(algorthim_thread1)); - // boost::thread thrd4(boost::bind(algorthim_thread1)); - - // thrd1.join(); - // thrd2.join(); - // thrd3.join(); - // thrd4.join(); - - // printf("finish\n"); - //} - imag_ana_3channels(); + for(int i = 0;i < 10;++i) + { + imag_ana_3channels(); + } system("pause"); } @@ -78,63 +62,53 @@ void imag_ana_3channels() void *tools = nullptr; rs_param param; - param.frame_num = 100; - //param.long_side = 1920; - //param.short_side = 1080; - param.scale = 2; + param.frame_num = 10; + param.scale = 1; param.rect_num = 2; { - param.rect[0].left_ = 30; - param.rect[0].top_ = 0; - param.rect[0].width_ = 320; - param.rect[0].height_ = 480; - - param.rect[1].left_ = 320; + param.rect[1].left_ = 30; param.rect[1].top_ = 0; - param.rect[1].width_ = 319; - param.rect[1].height_ = 479; + param.rect[1].width_ = 930; + param.rect[1].height_ = 1080; + + param.rect[0].left_ = 900; + param.rect[0].top_ = 0; + param.rect[0].width_ = 960; + param.rect[0].height_ = 960; } + strcpy(param.auth.url, "192.168.10.4"); + param.auth.port = 8888; + param.type = PRODUCT_ID; if (rs_init(&tools, param) != 0) - cout << "hp_init ailed!" << endl; + { + cout << "hp_init ailed!" << endl; + return; + } + else + { + printf("hp_init suceed!\n"); + } + char imgpath[260]; - //CvCapture* video1 = cvCaptureFromFile("D:\\weixin\\ATM遗留物\\20200928\\192.0.0.209_8000_1_4_-1\\20200928_20200928103418_20200928104058_103413.mp4"); - //CvCapture* video1 = cvCaptureFromFile("E:\\vpt_pic\\MSRegion.git\\win\\MSRegionDemo\\test1.mp4"); - CvCapture* video1 = cvCaptureFromFile("D:\\ruijinVideo\\192.168.1.10_01_2020072911472348.mp4"); + CvCapture* video1 = cvCaptureFromFile("./test.mp4"); // 用opencv函数读取视频的一帧 - IplImage * src = cvQueryFrame(video1); - - //int long_side = (src->width > src->height ? src->width : src->height); - //int short_side = (src->width <= src->height ? src->width : src->height); - //double scale_l = (double)long_side / (double)param.long_side; - //double scale_s = (double)short_side / (double)param.short_side; - //double scale = (scale_l > scale_s ? scale_l : scale_s); - double scale = 1.0; - int width = src->width / scale; - int height = src->height / scale; - //width = 1912; - IplImage * srcscale = cvCreateImage(cvSize(width, height), 8, 3); //用于缩放 当前先不缩放 - CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, cvSize(srcscale->width, srcscale->height)); - /************************************************/ - //int long_side = (srcscale->width > srcscale->height ? srcscale->width : srcscale->height); - //int short_side = (srcscale->width <= srcscale->height ? srcscale->width : srcscale->height); - //double scale_l = (double)long_side / (double)param.long_side; - //double scale_s = (double)short_side / (double)param.short_side; - //double scale = (scale_l > scale_s ? scale_l : scale_s); - //scale = 1.6; - - //int width = srcscale->width / scale; - //int height = srcscale->height / scale; - //CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, cvSize(width, height)); - //IplImage * srcscale1 = cvCreateImage(cvSize(width, height), 8, 3); //用于缩放 当前先不缩放 - /***********************************************************************/ - cvResize(src, srcscale); + //IplImage * src = cvQueryFrame(video1); + IplImage *src = cvQueryFrame(video1); while (src) { src = cvQueryFrame(video1); + //auto frame = cvCloneImage(src); if (!src) break; + double scale = 1.0; + int width = src->width / scale; + int height = src->height / scale; + //width = 1912; + IplImage * srcscale = cvCreateImage(cvSize(width, height), 8, 3); //用于缩放 当前先不缩放 + //CvVideoWriter *writer = cvCreateVideoWriter("result_2019_9_23.avi", CV_FOURCC('M', 'J', 'P', 'G'), 25, cvSize(srcscale->width, srcscale->height)); + cvResize(src, srcscale); sy_img syimg; syimg.set_data(srcscale->width, srcscale->height, srcscale->nChannels, (unsigned char *)srcscale->imageData); @@ -150,18 +124,9 @@ void imag_ana_3channels() } } - - /********************************************/ - - - //cvResize(src, srcscale1); - //ExternalRectangle((unsigned char*)(srcscale1->imageData), srcscale1->width, srcscale1->height, result.obj_infos, result.obj_count, srcscale1->widthStep, 1); - - /*****************************************************/ ExternalRectangle((unsigned char*)(srcscale->imageData), srcscale->width, srcscale->height, result.obj_infos, result.obj_count, srcscale->widthStep,1); CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX, 0.5, 0.5, 0, 2, 8); - //cvPutText(srcscale, "1Hello World !", cvPoint(80, 40), &font, cvScalar(255, 0, 0, 1)); std::string str; std::string alarm; for (int i = 0; i < result.obj_count; i++) @@ -211,18 +176,19 @@ void imag_ana_3channels() } - cvWriteFrame(writer, srcscale); + //cvWriteFrame(writer, srcscale); // 图像显示 - cvShowImage("1channels", srcscale); - - cvWaitKey(1); + //cvShowImage("1channels", srcscale); + cvReleaseImage(&srcscale); + //cvReleaseImage(&frame); + //cvWaitKey(1); + //break; } rs_release(&tools); - //cvReleaseImage(&srcscale1); - //cvReleaseImage(&gray); + //cvReleaseImage(&src); cvReleaseCapture(&video1); - cvReleaseImage(&srcscale); + } diff --git a/src/test/regionassist.h b/src/test/regionassist.h index d67d9cb..fa16d9c 100644 --- a/src/test/regionassist.h +++ b/src/test/regionassist.h @@ -5,7 +5,7 @@ //using namespace cv; //描绘区域 -void DrawRegion(unsigned char* pRGBIn, region_info* pRegionInfo, int numROI, int widthStep); +//void DrawRegion(unsigned char* pRGBIn, region_info* pRegionInfo, int numROI, int widthStep); //画线 void DrawLine(unsigned char* pRGBIn, int widthStep, const sy_point & p_roi, const sy_point & dir_point); //外接矩形描绘