You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

861 lines
35 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "rgooseModuleEmbedVideo.h"
  2. #include "rgooseHardwareResourceNetworkProvider.h"
  3. #include "../alg/generic/base64.h"
  4. #include <ctype.h>
  5. #include <err.h>
  6. #include <errno.h>
  7. #include <getopt.h>
  8. #include <ifaddrs.h>
  9. #include <netdb.h>
  10. #include <paths.h>
  11. #include <poll.h>
  12. #include <stdio.h>
  13. #include <signal.h>
  14. #include <stdint.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <time.h>
  18. #include <unistd.h>
  19. #include <arpa/inet.h>
  20. #include <netinet/ip.h>
  21. #include <netinet/udp.h>
  22. #include <sys/param.h> /* MIN() */
  23. #include <sys/socket.h>
  24. #include <openssl/sha.h>
  25. #define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, X )
  26. #ifdef DEBUG
  27. #define LOG_ERROR( X ) {\
  28. char _tBfrErrMSG2w34[256];\
  29. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  30. argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
  31. }
  32. #else
  33. #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, X );
  34. #endif
  35. #define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X )
  36. #ifdef DEBUG
  37. #define TLOG_ERROR( X ) {\
  38. char _tBfrErrMSG2w34[256];\
  39. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  40. basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34 );\
  41. }
  42. #else
  43. #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X );
  44. #endif
  45. enum {
  46. WEBRTC_REQ_SIGNIN = 0,
  47. WEBRTC_REQ_WAIT = 1,
  48. WEBRTC_REQ_SIGNOUT = 2,
  49. WEBRTC_REQ_MESSAGE = 3
  50. };
  51. static const char* kRequestPaths[] = { "/stream", "/sign_in", "/wait", "/sign_out", "/message" };
  52. //buffer_data bd[1]={0};
  53. argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicMediaDestination(), basicThread(){
  54. LOG( "Begin C" );
  55. m_pEventHeap = basicEventHeap::getInstance();
  56. LOG( "Evt Heap" );
  57. if( m_pDBC ){
  58. LOG( "DB OK!" );
  59. DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID );
  60. LOG( "Query DB!" );
  61. if( tDATA ) {
  62. LOG( "Data fetched from DB!" );
  63. memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) );
  64. free( tDATA );
  65. } else {
  66. LOG( "No Data fetched from DB!" );
  67. memset( &m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) );
  68. m_sEmbedVideoData.port = 8972;
  69. };
  70. } else {
  71. LOG_ERROR( "DB Error!" );
  72. };
  73. LOG( "DB data" );
  74. char tB[64];
  75. sprintf( tB, "Web Streams Port: %d", m_sEmbedVideoData.port );
  76. LOG( tB );
  77. sprintf( tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height );
  78. LOG( tB );
  79. n_pNoSignalData = NULL;
  80. m_nNoSignalSize = 0;
  81. if( m_sEmbedVideoData.show_ts ) LOG("Show TimeStamp");
  82. if( m_sEmbedVideoData.show_label ) LOG("Show Label");
  83. if( m_sEmbedVideoData.show_logo ){
  84. LOG("Show Logo");
  85. LOG( m_sEmbedVideoData.logo_md5 );
  86. char tPath[256];
  87. sprintf( tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5);
  88. if(!fileExist(tPath)){
  89. LOG_ERROR("Logo File Missed!");
  90. m_sEmbedVideoData.show_logo = false;
  91. }
  92. #ifdef DEBUG
  93. else LOG("Logo File is OK");
  94. #endif
  95. ;
  96. };
  97. LOG( "End C" );
  98. };
  99. argusModuleEmbedVideo::~argusModuleEmbedVideo(){
  100. if( n_pNoSignalData ) free( n_pNoSignalData );
  101. m_bEnabled = false;
  102. stopService();
  103. };
  104. void *argusModuleEmbedVideo::webClientProc( void *ptr ){
  105. static char *head = "HTTP/1.1 200 OK\r\n"
  106. "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n"
  107. "Pragma: no-cache\r\n"
  108. "MIME-version: 1.0\r\n"
  109. "Connection: close\r\n"
  110. //"Keep-Alive: timeout=5, max=1\r\n"
  111. //"Connection: Keep-Alive\r\n"
  112. //"Content-Type: video/mp4\r\n"
  113. "Content-Transfer-Encoding: BINARY\r\n"
  114. //"Transfer-Encoding: chunked\r\n"
  115. "Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n"
  116. "\r\n";
  117. static char *abort = "HTTP/1.1 404 OK\r\n"
  118. "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n"
  119. "Pragma: no-cache\r\n"
  120. "Connection: close\r\n\r\n";
  121. static char *no_signal ="HTTP/1.1 200 OK\r\n"
  122. "MIME-version: 1.0\r\n"
  123. "Connection: close\r\n"
  124. "Content-Transfer-Encoding: BINARY\r\n"
  125. //"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n\r\n"
  126. "Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n";
  127. WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr;
  128. argusModuleEmbedVideo * MODULE = CTX->ModulePtr;
  129. uint32_t msgSize;
  130. uint8_t tBuf[FILESTREAMBUFFERSZ];
  131. int retVal;
  132. if( CTX ) {
  133. char mesg[1024];
  134. size_t RecvSize;
  135. struct pollfd pfd[1];
  136. char cGetURI[1024];
  137. bool m_bDeflatePerMessage = false;
  138. bool m_pInit;
  139. #ifdef DEBUG_EXTRA
  140. pid_t pid = gettid();
  141. char pidBuf[16];
  142. sprintf( pidBuf, "pid:%d", pid);
  143. TLOG( pidBuf );
  144. #endif
  145. pfd->fd = CTX->m_iSocketFID;
  146. pfd->events = POLLIN | POLLHUP;
  147. while( CTX->bValid ) {
  148. if( !CTX->initDone ){
  149. int RetVal;
  150. char * reqline[256];
  151. RetVal = poll( pfd, 1, 1000 );
  152. if( RetVal <= 0 ){
  153. if ( EINTR == errno ) continue;
  154. TLOG_ERROR("Unrecoverable error");
  155. CTX->bValid = false;
  156. continue;
  157. };
  158. memset( mesg, 0, sizeof(mesg) );
  159. RetVal = recv( CTX->m_iSocketFID, mesg, sizeof(mesg), 0 );
  160. if ( RetVal <= 0 ) {
  161. sprintf( mesg, "web recv() error: %s", strerror(errno));
  162. TLOG_ERROR( mesg );
  163. CTX->bValid = false;
  164. continue;
  165. };
  166. #ifdef DEBUG_EXTRA
  167. TLOG( mesg );
  168. #endif
  169. uint32_t index = 0;
  170. reqline[index] = strtok( mesg, "\n" );
  171. if( strncmp( reqline[index], "GET", 3 ) == 0 ) {
  172. char * pPartURI;
  173. char * pPartPROTO;
  174. pPartURI = strstr( reqline[index], " " );
  175. if( pPartURI != NULL ) {
  176. pPartURI++;
  177. pPartPROTO = strstr( pPartURI, " " );
  178. pPartPROTO++;
  179. int URILen = pPartPROTO - pPartURI;
  180. strncpy( cGetURI, pPartURI, URILen );
  181. cGetURI[URILen] = (char)0;
  182. if(strncmp( pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp( pPartPROTO, "HTTP/1.1", 8) != 0) {
  183. TLOG_ERROR("No HTTP version supplied in request!");
  184. if( write( CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0 ){
  185. sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno));
  186. TLOG_ERROR(mesg);
  187. };
  188. CTX->bValid = false;
  189. continue;
  190. };
  191. };
  192. #ifdef DEBUG_EXTRA
  193. TLOG( cGetURI );
  194. #endif
  195. };
  196. // parse rest of request
  197. while( ( reqline[++index] = strtok( NULL, "\n" ) )!= NULL ) {
  198. if( strncmp( reqline[index], "Connection:", 11 ) == 0 ) {
  199. char * pPart;
  200. pPart = strcasestr( reqline[index], "Upgrade" );
  201. if( pPart != NULL ) {
  202. #ifdef DEBUG_EXTRA
  203. TLOG("Upgrade Mode ON");
  204. #endif
  205. //bUpgradeMode = true;
  206. };
  207. };
  208. if( strncmp( reqline[index], "Upgrade:", 8 ) == 0 ) {
  209. /*
  210. if( bUpgradeMode ) {
  211. char * pPart;
  212. pPart = strcasestr( reqline[index], "websocket" );
  213. if( pPart != NULL ) {
  214. TLOG("WebSocket Mode ON");
  215. //bWebSocketMode = true;
  216. };
  217. };
  218. */
  219. };
  220. if( strncmp( reqline[index], "Sec-WebSocket-Version:", 22 ) == 0 ) {
  221. char * pPart;
  222. pPart = strstr( reqline[index], " " );
  223. if( pPart != NULL ) {
  224. char tBuf[CTEXT];
  225. //nWebSocketVersion = atoi(pPart+1);
  226. #ifdef DEBUG_EXTRA
  227. sprintf( tBuf,"Web Socket Version: %d", 0 );//nWebSocketVersion );
  228. TLOG( tBuf );
  229. #endif
  230. };
  231. };
  232. if( strncmp( reqline[index], "Sec-WebSocket-Key:", 18 ) == 0 ) {
  233. /*char * pPart;
  234. pPart = strstr( reqline[index], " " );
  235. if( pPart != NULL ) {
  236. char tGenStr[256];
  237. unsigned char * tBase64;
  238. size_t nBase64;
  239. int kLen;
  240. unsigned char hash[SHA_DIGEST_LENGTH]; // == 20
  241. pPart++;
  242. kLen = strstr(pPart,"\r") - pPart;
  243. strncpy(cWSKey,pPart,kLen);
  244. cWSKey[kLen]=(char)0;
  245. TLOG( cWSKey );
  246. sprintf( tGenStr, "%s%s", cWSKey, ws_guid );
  247. SHA1( (const unsigned char*)tGenStr, strlen(tGenStr), hash );
  248. tBase64 = base64_encode( hash, SHA_DIGEST_LENGTH, &nBase64 );
  249. strncpy( cWSRep, (const char*)tBase64, nBase64 );
  250. free( tBase64 );
  251. cWSRep[nBase64] = (char)0;
  252. TLOG( cWSRep );
  253. };
  254. */
  255. };
  256. if( strncmp( reqline[index], "Sec-WebSocket-Protocol:", 23 ) == 0 ) {
  257. char * pPart;
  258. pPart = strstr( reqline[index], " " );
  259. if( pPart != NULL ) {
  260. // Check for protos
  261. };
  262. };
  263. if( strncmp( reqline[index], "Sec-WebSocket-Extensions:", 25 ) == 0 ) {
  264. char * pPart;
  265. pPart = strstr( reqline[index], " " );
  266. if( pPart != NULL ) {
  267. pPart++;
  268. if(strncmp( pPart, "permessage-deflate", 18 ) == 0 ) {
  269. m_bDeflatePerMessage = true;
  270. #ifdef DEBUG_EXTRA
  271. TLOG("Using Deflate");
  272. #endif
  273. };
  274. };
  275. };
  276. if( strncmp( reqline[index],"Accept-Encoding:", 16 ) == 0 ){
  277. char * pPart;
  278. pPart = strstr( reqline[index], " " );
  279. if( pPart != NULL ) {
  280. pPart++;
  281. if(strncmp( pPart, "gzip, deflate", 13 ) == 0 ) {
  282. m_bDeflatePerMessage = true;
  283. #ifdef DEBUG_EXTRA
  284. TLOG("Using Deflate");
  285. #endif
  286. };
  287. };
  288. };
  289. };
  290. if( strncmp( cGetURI, "/stream", 7 ) == 0 ) {
  291. uint32_t tStreamID = 0;
  292. CSTR tP;
  293. if( tP = strstr( cGetURI, "?" ) ) {
  294. CSTR tB;
  295. tP++;
  296. if( tB = strstr( tP, "id=" ) ) {
  297. tStreamID = atoi( tB+3 );
  298. };
  299. };
  300. if( tStreamID ) {
  301. #ifdef DEBUG_EXTRA
  302. char tB[64];
  303. sprintf(tB,"StremID: %d", tStreamID );
  304. TLOG( tB );
  305. #endif
  306. if( CTX->ModulePtr->registerForMediaStream( tStreamID, CTX ) ){
  307. // Send Header
  308. if( send( CTX->m_iSocketFID, head, strlen(head), 0 ) < 0 ){
  309. sprintf( mesg, "Failed sending file to client: %s", strerror(errno));
  310. TLOG_ERROR(mesg);
  311. CTX->bValid = false;
  312. };
  313. CTX->initDone = true;
  314. continue;
  315. } else {
  316. #ifdef DEBUG_EXTRA
  317. TLOG("Stream id Not Online");
  318. #endif
  319. };
  320. }
  321. #ifdef DEBUG_EXTRA
  322. else TLOG("No Stream ID")
  323. #endif
  324. ;
  325. };
  326. if( CTX->ModulePtr->n_pNoSignalData ) {
  327. sprintf( mesg, no_signal, CTX->ModulePtr->m_nNoSignalSize );
  328. send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 );
  329. send( CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0 );
  330. send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 );
  331. #ifdef DEBUG_EXTRA
  332. TLOG("Sent No Signal Image!");
  333. #endif
  334. } else {
  335. // Send 404 Header
  336. send( CTX->m_iSocketFID, abort, strlen(abort), 0 );
  337. #ifdef DEBUG_EXTRA
  338. TLOG("Aborted!");
  339. #endif
  340. };
  341. CTX->bValid = false;
  342. continue;
  343. } else {
  344. retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t));
  345. if( retVal == -1 ){
  346. if( errno == EAGAIN || errno == EWOULDBLOCK ){
  347. continue;
  348. };
  349. TLOG_ERROR("Pipe Communication Error[1]!");
  350. CTX->bValid = false;
  351. continue;
  352. };
  353. //uint8_t *tBuf = (uint8_t *) malloc(msgSize);
  354. //if( tBuf ){
  355. retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize );
  356. if( retVal == -1 ){
  357. //free( tBuf );
  358. if( errno == EAGAIN || errno == EWOULDBLOCK ){
  359. continue;
  360. };
  361. TLOG_ERROR("Pipe Communication Error[2]!");
  362. CTX->bValid = false;
  363. continue;
  364. };
  365. sprintf( mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize );
  366. if( send( CTX->m_iSocketFID, mesg, strlen( mesg ), 0 )< 0 ){
  367. sprintf( mesg, "[1]Failed sending file to client: %s", strerror(errno));
  368. TLOG_ERROR(mesg);
  369. CTX->bValid = false;
  370. continue;
  371. };
  372. if( send( CTX->m_iSocketFID, tBuf, msgSize, 0 ) < 0 ){
  373. sprintf( mesg, "[2]Failed sending file to client: %s", strerror(errno));
  374. TLOG_ERROR(mesg);
  375. CTX->bValid = false;
  376. continue;
  377. };
  378. if( send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 )< 0 ){
  379. sprintf( mesg, "[3]Failed sending file to client: %s", strerror(errno));
  380. TLOG_ERROR(mesg);
  381. CTX->bValid = false;
  382. continue;
  383. };
  384. // free( tBuf );
  385. //} else {
  386. // TLOG_ERROR("Mem Alloc Error!");
  387. // CTX->bValid = false;
  388. //};
  389. };
  390. };
  391. };
  392. CTX->bValid = false;
  393. #ifdef DEBUG_EXTRA
  394. TLOG("WEB Client Handler Ended!");
  395. #endif
  396. close( CTX->m_iEncoderPipe[0] );
  397. shutdown( CTX->m_iSocketFID, SHUT_RDWR);
  398. close( CTX->m_iSocketFID );
  399. //pthread_exit( NULL );
  400. return NULL;
  401. };
  402. void argusModuleEmbedVideo::m_fThreadProc( void ){
  403. if( !m_bEnabled ) {
  404. #ifdef DEBUG
  405. LOG("Module is Disabled!");
  406. #endif
  407. return;
  408. };
  409. #ifdef DEBUG
  410. LOG("Module Started!");
  411. #endif
  412. struct pollfd pfd[1];
  413. pfd->fd = m_nSocketDescriptor;
  414. pfd->events = POLLIN | POLLHUP;
  415. m_bThreadStatus = TH_WORKING;
  416. while( m_bThreadStatus < TH_ENDED ) {
  417. if( !m_bEnabled ) {
  418. m_bThreadStatus = TH_ENDED;
  419. continue;
  420. };
  421. int RetVal = poll( pfd, 1, 1000 );
  422. if( RetVal < 0 ){
  423. if( EINTR == errno ) continue;
  424. LOG_ERROR("Unrecoverable error");
  425. m_bThreadStatus = TH_ENDED;
  426. continue;
  427. };
  428. // Handle Connections
  429. if( RetVal != 0 ){
  430. if ( pfd[0].revents & POLLIN ) {
  431. #ifdef DEBUG_EXTRA
  432. LOG("Handle New Client");
  433. #endif
  434. int tSID = accept( pfd[0].fd, NULL, NULL);
  435. if( tSID < 0 ){
  436. char tBuf[CTEXT];
  437. sprintf(tBuf, "Accept() error: %s", strerror(errno));
  438. LOG_ERROR(tBuf);
  439. } else {
  440. #ifdef DEBUG_EXTRA
  441. LOG("Accept OK");
  442. #endif
  443. WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX));
  444. if( tCTX ) {
  445. #ifdef DEBUG_EXTRA
  446. LOG("CTX OK");
  447. #endif
  448. WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER));
  449. if( tHANDLER ) {
  450. #ifdef DEBUG_EXTRA
  451. LOG("HANDLER OK");
  452. #endif
  453. memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) );
  454. memset( tHANDLER, 0, sizeof(WEB_HANDLER) );
  455. tCTX->m_iSocketFID = tSID;
  456. tCTX->m_iEncoderPipe[0] = -1;
  457. tCTX->m_iEncoderPipe[1] = -1;
  458. tCTX->mediaStreamId = 0;
  459. tCTX->bValid = true;
  460. tCTX->ModulePtr = this;
  461. #ifdef DEBUG_EXTRA
  462. LOG("Before Thread Create");
  463. #endif
  464. int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX );
  465. if( RetVal == -1 ) {
  466. free(tCTX);
  467. free(tHANDLER);
  468. LOG_ERROR("Thread Creation Faled.");
  469. shutdown( tSID, SHUT_RDWR );
  470. close( tSID );
  471. } else {
  472. tHANDLER->CTX = tCTX;
  473. m_mHandlersProtector.lock();
  474. m_vHandlersPool.push_back( tHANDLER );
  475. m_mHandlersProtector.unlock();
  476. #ifdef DEBUG_EXTRA
  477. LOG("Handler Pushed to a Pool");
  478. #endif
  479. };
  480. } else { //https://stackoverflow.com/questions/18545077/image-fullscreen-on-click
  481. free(tCTX);
  482. LOG_ERROR("CL_HANDLER Mem Allocation Failure!");
  483. shutdown( tSID, SHUT_RDWR );
  484. close( tSID );
  485. };
  486. } else {
  487. LOG_ERROR("CL_CTX Mem Allocation Failure!");
  488. shutdown( tSID, SHUT_RDWR );
  489. close( tSID );
  490. };
  491. };
  492. };
  493. };
  494. // Handle Dead Clients
  495. if( m_vHandlersPool.size() ) {
  496. for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) {
  497. if( !( (*idx)->CTX->bValid ) ) {
  498. pthread_join( (*idx)->m_hThreadHandle, NULL );
  499. //close( (*idx)->CTX->m_iEncoderPipe[0] );
  500. close( (*idx)->CTX->m_iEncoderPipe[1] );
  501. free( (*idx)->CTX );
  502. free( (*idx) );
  503. m_mHandlersProtector.lock();
  504. m_vHandlersPool.erase(idx);
  505. m_mHandlersProtector.unlock();
  506. #ifdef DEBUG_EXTRA
  507. LOG("Web Handler Ripped!");
  508. #endif
  509. };
  510. };
  511. };
  512. SLEEP( 50 );
  513. };
  514. };
  515. #define ENABLE_SOCKOPT(sd, level, opt) \
  516. do { \
  517. int val = 1; \
  518. if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \
  519. warn("Failed enabling %s for web service", #opt); \
  520. } while (0);
  521. bool argusModuleEmbedVideo::startService(){
  522. //Create NoSignal Image
  523. cv::Mat tMat( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 );
  524. cv::rectangle( tMat, cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.width, m_sEmbedVideoData.height ), cv::Scalar( 255, 0, 0 ), cv::FILLED );
  525. cv::putText( tMat, "NO SIGNAL", cv::Point( 10, 30 ), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar( 0, 255, 255 ), 3 );
  526. if( m_sEmbedVideoData.show_logo ) {
  527. int a_x, a_y;
  528. if( m_sEmbedVideoData.logo_x < 0 ) {
  529. a_x = m_sEmbedVideoData.width + m_sEmbedVideoData.logo_x - m_sEmbedVideoData.logo_w;
  530. if( a_x < 0 ) a_x = 0;
  531. } else a_x = m_sEmbedVideoData.logo_x;
  532. if( ( a_x + m_sEmbedVideoData.logo_w ) > m_sEmbedVideoData.width ) a_x = m_sEmbedVideoData.width - m_sEmbedVideoData.logo_w;
  533. if( m_sEmbedVideoData.logo_y < 0 ) {
  534. a_y = m_sEmbedVideoData.height + m_sEmbedVideoData.logo_y - m_sEmbedVideoData.logo_h;
  535. if( a_y < 0 ) a_y = 0;
  536. } else a_y = m_sEmbedVideoData.logo_y;
  537. if( ( a_y + m_sEmbedVideoData.logo_h ) > m_sEmbedVideoData.height ) a_y = m_sEmbedVideoData.height - m_sEmbedVideoData.logo_h;
  538. if( ( a_x > -1 ) && ( a_y > -1 ) ) {
  539. char tName[256];
  540. m_sEmbedVideoData.logo_x = a_x;
  541. m_sEmbedVideoData.logo_y = a_y;
  542. sprintf( tName, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 );
  543. cv::Mat T = cv::imread( tName, cv::IMREAD_UNCHANGED );
  544. if( T.cols > 0 ) {
  545. cv::Mat mask;
  546. vector<cv::Mat> layers;
  547. #ifdef DEBUG
  548. LOG("Logo Loaded OK");
  549. #endif
  550. cv::split( T, layers); // seperate channels
  551. cv::Mat rgb[3] = { layers[0], layers[1], layers[2] };
  552. mask = layers[3]; // png's alpha channel used as mask
  553. cv::merge( rgb, 3, T ); // put together the RGB channels, now transp insn't transparent
  554. cv::resize( T, m_mLogoPic, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC );
  555. cv::resize( mask, m_mLogoMask, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC );
  556. cv::Rect roi(cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ));
  557. cv::Mat destinationROI = tMat( roi );
  558. m_mLogoPic.copyTo( destinationROI, m_mLogoMask );
  559. //m_sEmbedVideoData.show_logo = false;
  560. } else {
  561. LOG("Logo Disabled - No Picture is Loaded");
  562. m_sEmbedVideoData.show_logo = false;
  563. };
  564. } else {
  565. LOG("Logo Disabled - Wrong Coords");
  566. m_sEmbedVideoData.show_logo = false;
  567. };
  568. LOG("Logo Draw OK");
  569. };
  570. try{
  571. vector<int> compression_params;
  572. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  573. //compression_params.push_back(9);
  574. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  575. compression_params.push_back( m_sEmbedVideoData.compression_quality );
  576. vector<uchar> buf;
  577. cv::imencode( ".jpg", tMat, buf, compression_params );
  578. m_nNoSignalSize = buf.size();
  579. n_pNoSignalData = (uint8_t *) malloc( m_nNoSignalSize );
  580. if( n_pNoSignalData ) {
  581. memcpy( n_pNoSignalData, buf.data(), m_nNoSignalSize );
  582. } else m_nNoSignalSize =0;
  583. buf.clear();
  584. } catch (cv::Exception & e) {
  585. LOG_ERROR(e.msg.c_str());
  586. };
  587. // Socket
  588. struct sockaddr sa;
  589. struct sockaddr_in *sin;
  590. memset(&sa, 0, sizeof(struct sockaddr));
  591. sa.sa_family = AF_INET;
  592. sin = (struct sockaddr_in *)&sa;
  593. sin->sin_addr.s_addr = htonl( INADDR_ANY );
  594. sin->sin_port = htons( m_sEmbedVideoData.port );
  595. m_nSocketDescriptor = socket( sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
  596. if( m_nSocketDescriptor == -1 ){
  597. LOG_ERROR("Failed creating ACC socket");
  598. return false;
  599. };
  600. ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR);
  601. #ifdef SO_REUSEPORT
  602. ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT);
  603. #endif
  604. if( bind( m_nSocketDescriptor, &sa, sizeof(sa)) < 0 ){
  605. LOG_ERROR("Failed binding Socket");
  606. close( m_nSocketDescriptor );
  607. return false;
  608. } else {
  609. LOG("Bind Socessfull");
  610. };
  611. if( listen( m_nSocketDescriptor, 10) != 0 ){
  612. LOG_ERROR("Failed setting web listen backlog");
  613. close( m_nSocketDescriptor );
  614. return false;
  615. } else {
  616. LOG("Listen OK");
  617. };
  618. LOG("Start Thread");
  619. return init();
  620. };
  621. bool argusModuleEmbedVideo::stopService( bool force ){
  622. waitThreadEnd( true );
  623. if( m_vThreads.size() ) { // Kill-Wait Started Probes
  624. #ifdef DEBUG
  625. LOG("Have to Wait Client Handlers!");
  626. #endif
  627. for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) {
  628. if( force ) {
  629. pthread_cancel( (*index)->m_hThreadHandle );
  630. } else {
  631. pthread_join( (*index)->m_hThreadHandle, NULL );
  632. }
  633. };
  634. m_vHandlersPool.clear();
  635. };
  636. #ifdef DEBUG
  637. LOG("No More Client Handlers!");
  638. #endif
  639. if (m_vResultPool.size()){ // Clear structures
  640. for( vectorOBSERVER_RESULT::iterator index = m_vResultPool.begin(); index < m_vResultPool.end(); index++){
  641. free(*index);
  642. };
  643. m_vResultPool.clear();
  644. };
  645. #ifdef DEBUG
  646. LOG("Data is Cleared!");
  647. #endif
  648. */
  649. return true;
  650. };
  651. bool argusModuleEmbedVideo::reloadSettings(){
  652. return true;
  653. };
  654. bool argusModuleEmbedVideo::validate(){
  655. return true;
  656. };
  657. void argusModuleEmbedVideo::pushFrame( AVFrame *Frame, void* src){
  658. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  659. if( tMD ) {
  660. };
  661. };
  662. void argusModuleEmbedVideo::pushFrame( cv::Mat &Frame, void* src ){
  663. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  664. char tBuffer[128];
  665. if( tMD ) {
  666. float mK, oK;
  667. cv::Rect ROI;
  668. if( !m_mPictureProtector.try_lock() ) return;
  669. oK = ((float)m_sEmbedVideoData.height )/ ((float)m_sEmbedVideoData.width);
  670. mK = ((float)Frame.rows )/ ((float)Frame.cols);
  671. //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK );
  672. if( m_mapMATS[tMD->mediaStreamId].cols == 0 ) {
  673. LOG("First Frame Enqueued");
  674. sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId );
  675. LOG( tBuffer );
  676. m_mapMATS[tMD->mediaStreamId].create( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 );
  677. cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.height, m_sEmbedVideoData.width ), cv::Scalar( 0, 0, 0 ), cv::FILLED );
  678. };
  679. if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) {
  680. ROI.width = (int) m_sEmbedVideoData.width;
  681. ROI.height = (int) m_sEmbedVideoData.height;
  682. ROI.x = (int) 0;
  683. ROI.y = (int) 0;
  684. } else {
  685. if( mK < oK ) {
  686. ROI.width = (int) m_sEmbedVideoData.width;
  687. ROI.height = (int) (((float)m_sEmbedVideoData.width) * mK );
  688. ROI.x = (int) 0;
  689. ROI.y = (int)( m_sEmbedVideoData.height - ROI.height ) >> 1;
  690. } else {
  691. ROI.height = (int) m_sEmbedVideoData.height;
  692. ROI.width = (int) (((float)m_sEmbedVideoData.height) / mK );
  693. ROI.y = (int) 0;
  694. ROI.x = (int) ( m_sEmbedVideoData.width - ROI.width ) >> 1;
  695. };
  696. }
  697. cv::Mat mROI = m_mapMATS[tMD->mediaStreamId]( ROI );
  698. cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR );
  699. /*
  700. cv::putText( m_mapMATS[tMD->mediaStreamId], tBuffer, cv::Point( 30, 45 ),
  701. (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face,
  702. m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ),
  703. m_sEmbedVideoData.ts_font_thickness,
  704. m_sEmbedVideoData.ts_line_type
  705. );
  706. */
  707. if( m_sEmbedVideoData.show_ts ){
  708. char DateStr[200];
  709. time_t t = time( NULL );
  710. struct tm * tmp = gmtime( &t );
  711. if( tmp ){
  712. if( strftime( DateStr, sizeof(DateStr), "%F %T GMT", tmp )!=0 ){
  713. cv::rectangle( m_mapMATS[tMD->mediaStreamId], cv::Point( 10, 10 ), cv::Point( 490, 60 ), cv::Scalar( 0, 0, 0 ), cv::FILLED );
  714. cv::putText( m_mapMATS[tMD->mediaStreamId], DateStr, cv::Point( 30, 45 ),
  715. (cv::HersheyFonts) m_sEmbedVideoData.ts_font_face,
  716. m_sEmbedVideoData.ts_font_scale, cv::Scalar( 0, 255, 255 ),
  717. m_sEmbedVideoData.ts_font_thickness,
  718. m_sEmbedVideoData.ts_line_type
  719. );
  720. };
  721. };
  722. };
  723. if( m_sEmbedVideoData.show_logo ){
  724. cv::Rect roi( cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ));
  725. cv::Mat destinationROI = m_mapMATS[tMD->mediaStreamId]( roi );
  726. m_mLogoPic.copyTo( destinationROI, m_mLogoMask );
  727. };
  728. vector<int> compression_params;
  729. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  730. //compression_params.push_back(9);
  731. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  732. compression_params.push_back( m_sEmbedVideoData.compression_quality );
  733. //vector<uchar> buf;
  734. uint32_t DataSize;
  735. //m_mPictureProtector.lock();
  736. m_mapCAPTURES[tMD->mediaStreamId].clear();
  737. cv::imencode( ".jpg", m_mapMATS[tMD->mediaStreamId], m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  738. DataSize = m_mapCAPTURES[tMD->mediaStreamId].size(); //buf.size();
  739. if( DataSize ) {
  740. uint8_t *pData = m_mapCAPTURES[tMD->mediaStreamId].data(); //buf.data();
  741. if( m_vHandlersPool.size() ) {
  742. for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) {
  743. if( (*idx)->CTX->mediaStreamId == tMD->mediaStreamId ) {
  744. write( (*idx)->CTX->m_iEncoderPipe[1], &DataSize, sizeof(uint32_t));
  745. write( (*idx)->CTX->m_iEncoderPipe[1], pData, DataSize );
  746. };
  747. };
  748. };
  749. };
  750. m_mPictureProtector.unlock();
  751. };
  752. };
  753. bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){
  754. if( CTX ){
  755. if( id ){
  756. //Check if its Valid!
  757. DBC_MEDIA_STREAM_DATA *tSD = m_pDBC->getMediaStreamData( id );
  758. if( tSD ) {
  759. if( ! tSD->valid ) {
  760. free( tSD );
  761. return false;
  762. };
  763. free( tSD );
  764. if( pipe( CTX->m_iEncoderPipe ) == -1 ){
  765. CTX->bValid = false;
  766. return false;
  767. };
  768. CTX->mediaStreamId = id;
  769. return true;
  770. };
  771. };
  772. } else LOG_ERROR("Client Context error!");
  773. return false;
  774. };
  775. void argusModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){
  776. if( Evt ) {
  777. switch( Evt->m_eClass ) {
  778. case EVT_CLASS_IMAGE:
  779. case EVT_CLASS_VIDEO:{
  780. switch( Evt->m_eType ) {
  781. case EVT_CAPTURE_START:{
  782. #ifdef DEBUG
  783. LOG("Capture Event");
  784. #endif
  785. //cam_id
  786. //parent_evt_id
  787. char MD5[33];
  788. uint32_t id = 0;
  789. if( saveStreamPicture( id, (CSTR*)&MD5) ) {
  790. };
  791. break;
  792. };
  793. };
  794. break;
  795. };
  796. };
  797. };
  798. };
  799. bool argusModuleEmbedVideo::saveStreamPicture( uint32_t id, CSTR *MD5 ){
  800. if( m_mapCAPTURES.find( id ) != m_mapCAPTURES.end() ){
  801. CSTR cMD5 = NULL;
  802. FILE *tFD;
  803. m_mPictureProtector.lock();
  804. if( cMD5 ) {
  805. strncpy( *MD5, cMD5, 32 );
  806. (*MD5)[32]=(char)0;
  807. };
  808. m_mPictureProtector.unlock();
  809. };
  810. return false;
  811. };
  812. #undef LOG
  813. #undef LOG_ERROR
  814. #undef TLOG
  815. #undef TLOG_ERROR