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.

2166 lines
88 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
5 years ago
​
​
​
5 years ago
​
5 years ago
​
​
​
5 years ago
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
4 years ago
5 years ago
​
​
4 years ago
​
​
​
​
​
​
5 years ago
​
​
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
4 years ago
​
5 years ago
​
​
​
​
​
5 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "rgooseModuleEmbedVideo.h"
  2. #include "rgooseHardwareResourceNetworkProvider.h"
  3. #include "rgooseKernel.h"
  4. #include "../alg/generic/base64.h"
  5. #include "../data/media/video/videoAVLIBSource.h"
  6. #include "../data/media/video/videoLive555AVLibSource.h"
  7. #include <ctype.h>
  8. #include <err.h>
  9. #include <errno.h>
  10. #include <getopt.h>
  11. #include <ifaddrs.h>
  12. #include <netdb.h>
  13. #include <paths.h>
  14. #include <poll.h>
  15. #include <stdio.h>
  16. #include <signal.h>
  17. #include <stdint.h>
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #include <time.h>
  21. #include <unistd.h>
  22. #include <arpa/inet.h>
  23. #include <netinet/ip.h>
  24. #include <netinet/udp.h>
  25. #include <sys/param.h> /* MIN() */
  26. #include <sys/socket.h>
  27. #include <openssl/sha.h>
  28. #define STORAGE_DIR_MODE 0x1FF
  29. #define STORAGE_FILE_MODE 0x1B6
  30. #define LOG( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, X )
  31. #ifdef DEBUG
  32. #define LOG_ERROR( X ) {\
  33. char _tBfrErrMSG2w34[256];\
  34. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  35. argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
  36. }
  37. #else
  38. #define LOG_ERROR( X ) argusKernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, X );
  39. #endif
  40. #define TLOG( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, X )
  41. #ifdef DEBUG
  42. #define TLOG_ERROR( X ) {\
  43. char _tBfrErrMSG2w34[256];\
  44. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  45. basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, _tBfrErrMSG2w34 );\
  46. }
  47. #else
  48. #define TLOG_ERROR( X ) basicLogCollection::getInstance()->Log( "MOD_EVIDEO_T", CTX, _LOG_ERROR, X );
  49. #endif
  50. enum {
  51. WEBRTC_REQ_SIGNIN = 0,
  52. WEBRTC_REQ_WAIT = 1,
  53. WEBRTC_REQ_SIGNOUT = 2,
  54. WEBRTC_REQ_MESSAGE = 3
  55. };
  56. static const char* kRequestPaths[] = { "/stream", "/sign_in", "/wait", "/sign_out", "/message" };
  57. //buffer_data bd[1]={0};
  58. argusModuleEmbedVideo::argusModuleEmbedVideo( uint32_t moduleID ): argusKernelModule( moduleID, ARGUS_MODULE_EMBED_VIDEO ), basicThread(){
  59. m_pEventHeap = basicEventHeap::getInstance();
  60. if( m_pDBC ){
  61. DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID );
  62. if( tDATA ) {
  63. memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) );
  64. free( tDATA );
  65. } else {
  66. memset( &m_sEmbedVideoData, 0, sizeof(DBC_MODULE_EMBED_VIDEO_DATA) );
  67. m_sEmbedVideoData.port = 8972;
  68. };
  69. } else {
  70. LOG_ERROR( "DB Error!" );
  71. };
  72. n_pNoSignalData = NULL;
  73. m_nNoSignalSize = 0;
  74. char tBuff[1024];
  75. sprintf( m_pBaseSavePath, "%s/data/reports", getcwd(tBuff, 1024) );
  76. #ifdef DEBUG
  77. char tB[64];
  78. sprintf( tB, "Web Streams Port: %d", m_sEmbedVideoData.port );
  79. LOG( tB );
  80. sprintf( tB, "Frame: [%dx%d]", m_sEmbedVideoData.width, m_sEmbedVideoData.height );
  81. LOG( tB );
  82. if( m_sEmbedVideoData.show_ts ) LOG("Show TimeStamp");
  83. if( m_sEmbedVideoData.show_label ) LOG("Show Label");
  84. if( m_sEmbedVideoData.show_logo ) LOG("Show Logo");
  85. #endif
  86. if( m_sEmbedVideoData.show_logo ){
  87. LOG( m_sEmbedVideoData.logo_md5 );
  88. char tPath[MAX_PATH];
  89. sprintf( tPath, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 );
  90. if( !fileExist( tPath ) ){
  91. LOG_ERROR("Logo File Missed!");
  92. m_sEmbedVideoData.show_logo = false;
  93. }
  94. #ifdef DEBUG
  95. else LOG("Logo File is OK");
  96. #endif
  97. ;
  98. };
  99. };
  100. argusModuleEmbedVideo::~argusModuleEmbedVideo(){
  101. m_bEnabled = false;
  102. waitThreadEnd( true );
  103. if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes
  104. #ifdef DEBUG
  105. char tB[200];
  106. sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() );
  107. LOG( tB );
  108. #endif
  109. for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) pthread_cancel( (*index)->m_hThreadHandle );
  110. m_vHandlersPool.clear();
  111. };
  112. #ifdef DEBUG
  113. LOG("No More Client Handlers!");
  114. #endif
  115. if( m_mapHANDLERS.size() ){
  116. for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) delete( (*idx).second );
  117. m_mapHANDLERS.clear();
  118. };
  119. if( m_mapCAPTURES.size() ) m_mapCAPTURES.clear();
  120. if( m_mapMATS.size() ) m_mapMATS.clear();
  121. if( n_pNoSignalData ) free(n_pNoSignalData);
  122. };
  123. static const char * ht_head = "HTTP/1.1 200 OK\r\n"
  124. "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n"
  125. "Pragma: no-cache\r\n"
  126. "MIME-version: 1.0\r\n"
  127. "Connection: close\r\n"
  128. //"Keep-Alive: timeout=5, max=1\r\n"
  129. //"Connection: Keep-Alive\r\n"
  130. //"Content-Type: video/mp4\r\n"
  131. "Content-Transfer-Encoding: BINARY\r\n"
  132. //"Transfer-Encoding: chunked\r\n"
  133. "Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n"
  134. "\r\n";
  135. static const char * ht_abort = "HTTP/1.1 404 OK\r\n"
  136. "Cache-Control: no-store, no-cache, post-check=0, pre-check=0\r\n"
  137. "Pragma: no-cache\r\n"
  138. "Connection: close\r\n\r\n";
  139. static const char * ht_no_signal = "HTTP/1.1 200 OK\r\n"
  140. "MIME-version: 1.0\r\n"
  141. "Connection: close\r\n"
  142. "Content-Transfer-Encoding: BINARY\r\n"
  143. //"Content-type: multipart/x-mixed-replace;boundary=MPFrame\r\n\r\n"
  144. "Content-Type: image/jpeg\r\nContent-length: %d\r\n\r\n";
  145. void *argusModuleEmbedVideo::webClientProc( void *ptr ){
  146. WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr;
  147. argusModuleEmbedVideo * MODULE = CTX->ModulePtr;
  148. uint32_t msgSize;
  149. uint8_t tBuf[FILESTREAMBUFFERSZ];
  150. int retVal;
  151. if( CTX ) {
  152. char mesg[1024];
  153. size_t RecvSize;
  154. struct pollfd pfd[1];
  155. char cGetURI[1024];
  156. bool m_bDeflatePerMessage = false;
  157. bool m_pInit;
  158. #ifdef DEBUG_EXTRA
  159. pid_t pid = gettid();
  160. char pidBuf[16];
  161. sprintf( pidBuf, "pid:%d", pid);
  162. TLOG( pidBuf );
  163. #endif
  164. pfd->fd = CTX->m_iSocketFID;
  165. pfd->events = POLLIN | POLLHUP;
  166. while( CTX->bValid ) {
  167. if( !CTX->initDone ){
  168. int RetVal;
  169. char * reqline[256];
  170. RetVal = poll( pfd, 1, 1000 );
  171. if( RetVal <= 0 ){
  172. if ( EINTR == errno ) continue;
  173. TLOG_ERROR("Unrecoverable error");
  174. CTX->bValid = false;
  175. continue;
  176. };
  177. memset( mesg, 0, sizeof(mesg) );
  178. RetVal = recv( CTX->m_iSocketFID, mesg, sizeof(mesg), 0 );
  179. if ( RetVal <= 0 ) {
  180. sprintf( mesg, "web recv() error: %s", strerror(errno));
  181. TLOG_ERROR( mesg );
  182. CTX->bValid = false;
  183. continue;
  184. };
  185. #ifdef DEBUG_EXTRA
  186. TLOG( mesg );
  187. #endif
  188. uint32_t index = 0;
  189. reqline[index] = strtok( mesg, "\n" );
  190. if( strncmp( reqline[index], "GET", 3 ) == 0 ) {
  191. char * pPartURI;
  192. char * pPartPROTO;
  193. pPartURI = strstr( reqline[index], " " );
  194. if( pPartURI != NULL ) {
  195. pPartURI++;
  196. pPartPROTO = strstr( pPartURI, " " );
  197. pPartPROTO++;
  198. int URILen = pPartPROTO - pPartURI;
  199. strncpy( cGetURI, pPartURI, URILen );
  200. cGetURI[URILen] = (char)0;
  201. if(strncmp( pPartPROTO, "HTTP/1.0", 8) != 0 && strncmp( pPartPROTO, "HTTP/1.1", 8) != 0) {
  202. TLOG_ERROR("No HTTP version supplied in request!");
  203. if( write( CTX->m_iSocketFID, "HTTP/1.1 400 Bad Request\r\n", 26) < 0 ){
  204. sprintf( mesg, "Failed returning status 400 to client: %s", strerror(errno));
  205. TLOG_ERROR(mesg);
  206. };
  207. CTX->bValid = false;
  208. continue;
  209. };
  210. };
  211. #ifdef DEBUG_EXTRA
  212. TLOG( cGetURI );
  213. #endif
  214. };
  215. if( strncmp( cGetURI, "/stream", 7 ) == 0 ) {
  216. uint32_t tStreamID = 0;
  217. CSTR tP;
  218. if( tP = strstr( cGetURI, "?" ) ) {
  219. CSTR tB;
  220. tP++;
  221. if( tB = strstr( tP, "id=" ) ) {
  222. tStreamID = atoi( tB+3 );
  223. };
  224. };
  225. if( tStreamID ) {
  226. #ifdef DEBUG_EXTRA
  227. char tB[64];
  228. sprintf(tB,"StremID: %d", tStreamID );
  229. TLOG( tB );
  230. #endif
  231. if( CTX->ModulePtr->registerForMediaStream( tStreamID, CTX ) ){
  232. // Send Header
  233. if( send( CTX->m_iSocketFID, ht_head, strlen(ht_head), 0 ) < 0 ){
  234. #ifdef DEBUG_EXTRA
  235. sprintf( mesg, "Failed sending file to client: %s", strerror(errno));
  236. TLOG_ERROR(mesg);
  237. #endif
  238. CTX->bValid = false;
  239. };
  240. CTX->initDone = true;
  241. continue;
  242. }
  243. #ifdef DEBUG_EXTRA
  244. else {
  245. TLOG("Stream id Not Online");
  246. }
  247. #endif
  248. ;
  249. }
  250. #ifdef DEBUG_EXTRA
  251. else TLOG("No Stream ID")
  252. #endif
  253. ;
  254. };
  255. if( CTX->ModulePtr->n_pNoSignalData ) {
  256. //Send Dummy Picture
  257. sprintf( mesg, ht_no_signal, CTX->ModulePtr->m_nNoSignalSize );
  258. send( CTX->m_iSocketFID, mesg, strlen(mesg), 0 );
  259. send( CTX->m_iSocketFID, CTX->ModulePtr->n_pNoSignalData, CTX->ModulePtr->m_nNoSignalSize, 0 );
  260. send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 );
  261. #ifdef DEBUG_EXTRA
  262. TLOG("Sent No Signal Image!");
  263. #endif
  264. } else {
  265. // Send 404 Header
  266. send( CTX->m_iSocketFID, ht_abort, strlen(ht_abort), 0 );
  267. #ifdef DEBUG_EXTRA
  268. TLOG("Aborted!");
  269. #endif
  270. };
  271. CTX->bValid = false;
  272. continue;
  273. } else {
  274. /*
  275. retVal = read( CTX->m_iEncoderPipe[0], &msgSize, sizeof(uint32_t));
  276. if( retVal == -1 ){
  277. if( errno == EAGAIN || errno == EWOULDBLOCK ){
  278. continue;
  279. };
  280. TLOG_ERROR("Pipe Communication Error[1]!");
  281. CTX->bValid = false;
  282. continue;
  283. };
  284. if( msgSize < FILESTREAMBUFFERSZ ) {
  285. retVal = read( CTX->m_iEncoderPipe[0], tBuf, msgSize );
  286. } else {
  287. TLOG_ERROR("Data too Big in Pipe Transfer!");
  288. CTX->bValid = false;
  289. continue;
  290. };
  291. if( retVal == -1 ){
  292. //free( tBuf );
  293. if( errno == EAGAIN || errno == EWOULDBLOCK ){
  294. continue;
  295. };
  296. TLOG_ERROR("Pipe Communication Error[2]!");
  297. CTX->bValid = false;
  298. continue;
  299. };
  300. */
  301. /**************/
  302. CTX->ModulePtr->m_mEncodedProtector.lock();
  303. if( CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size() ) {
  304. msgSize = CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].size();
  305. if( msgSize < FILESTREAMBUFFERSZ ) {
  306. memcpy( tBuf, CTX->ModulePtr->m_mapCAPTURES[CTX->mediaStreamId].data(), msgSize );
  307. CTX->ModulePtr->m_mEncodedProtector.unlock();
  308. } else {
  309. CTX->ModulePtr->m_mEncodedProtector.unlock();
  310. TLOG_ERROR("Data too Big in Pipe Transfer!");
  311. CTX->bValid = false;
  312. continue;
  313. };
  314. } else {
  315. CTX->ModulePtr->m_mEncodedProtector.unlock();
  316. if( CTX->ModulePtr->n_pNoSignalData ){
  317. msgSize = CTX->ModulePtr->m_nNoSignalSize;
  318. memcpy( tBuf, CTX->ModulePtr->n_pNoSignalData, msgSize );
  319. } else {
  320. TLOG_ERROR("Data too Big in Pipe Transfer!");
  321. CTX->bValid = false;
  322. continue;
  323. };
  324. };
  325. /*********/
  326. sprintf( mesg, "--MPFrame\r\nContent-type: image/jpeg\r\nContent-length: %d\r\n\r\n", msgSize );
  327. if( send( CTX->m_iSocketFID, mesg, strlen( mesg ), 0 )< 0 ){
  328. #ifdef DEBUG_EXTRA
  329. sprintf( mesg, "[1]Failed sending file to client: %s", strerror(errno));
  330. TLOG_ERROR(mesg);
  331. #endif
  332. CTX->bValid = false;
  333. continue;
  334. };
  335. if( send( CTX->m_iSocketFID, tBuf, msgSize, 0 ) < 0 ){
  336. #ifdef DEBUG_EXTRA
  337. sprintf( mesg, "[2]Failed sending file to client: %s", strerror(errno));
  338. TLOG_ERROR(mesg);
  339. #endif
  340. CTX->bValid = false;
  341. continue;
  342. };
  343. if( send( CTX->m_iSocketFID, "\r\n\r\n", 4, 0 )< 0 ){
  344. #ifdef DEBUG_EXTRA
  345. sprintf( mesg, "[3]Failed sending file to client: %s", strerror(errno));
  346. TLOG_ERROR(mesg);
  347. #endif
  348. CTX->bValid = false;
  349. continue;
  350. };
  351. SLEEP( 80 );
  352. };
  353. };
  354. };
  355. CTX->bValid = false;
  356. #ifdef DEBUG_EXTRA
  357. TLOG("WEB Client Handler Ended!");
  358. #endif
  359. close( CTX->m_iEncoderPipe[0] );
  360. shutdown( CTX->m_iSocketFID, SHUT_RDWR);
  361. close( CTX->m_iSocketFID );
  362. //pthread_exit( NULL );
  363. return NULL;
  364. };
  365. void argusModuleEmbedVideo::m_fThreadProc( void ){
  366. if( !m_bEnabled ) {
  367. #ifdef DEBUG
  368. LOG("Module is Disabled!");
  369. #endif
  370. return;
  371. };
  372. #ifdef DEBUG
  373. LOG("Module Started!");
  374. #endif
  375. struct pollfd pfd[1];
  376. pfd->fd = m_nSocketDescriptor;
  377. pfd->events = POLLIN | POLLHUP;
  378. m_bThreadStatus = TH_WORKING;
  379. while( m_bThreadStatus < TH_ENDED ) {
  380. if( !m_bEnabled ) {
  381. m_bThreadStatus = TH_ENDED;
  382. continue;
  383. };
  384. int RetVal = poll( pfd, 1, 1000 );
  385. if( RetVal < 0 ){
  386. if( EINTR == errno ) continue;
  387. LOG_ERROR("Unrecoverable error");
  388. m_bThreadStatus = TH_ENDED;
  389. continue;
  390. };
  391. // Handle Connections
  392. if( RetVal != 0 ){
  393. if ( pfd[0].revents & POLLIN ) {
  394. #ifdef DEBUG_EXTRA
  395. LOG("Handle New Client");
  396. #endif
  397. int tSID = accept( pfd[0].fd, NULL, NULL);
  398. if( tSID < 0 ){
  399. char tBuf[CTEXT];
  400. sprintf(tBuf, "Accept() error: %s", strerror(errno));
  401. LOG_ERROR(tBuf);
  402. } else {
  403. #ifdef DEBUG_EXTRA
  404. LOG("Accept OK");
  405. #endif
  406. WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX));
  407. if( tCTX ) {
  408. #ifdef DEBUG_EXTRA
  409. LOG("CTX OK");
  410. #endif
  411. WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER));
  412. if( tHANDLER ) {
  413. #ifdef DEBUG_EXTRA
  414. LOG("HANDLER OK");
  415. #endif
  416. memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) );
  417. memset( tHANDLER, 0, sizeof(WEB_HANDLER) );
  418. tCTX->m_iSocketFID = tSID;
  419. tCTX->m_iEncoderPipe[0] = -1;
  420. tCTX->m_iEncoderPipe[1] = -1;
  421. tCTX->mediaStreamId = 0;
  422. tCTX->bValid = true;
  423. tCTX->ModulePtr = this;
  424. #ifdef DEBUG_EXTRA
  425. LOG("Before Thread Create");
  426. #endif
  427. int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX );
  428. if( RetVal == -1 ) {
  429. free(tCTX);
  430. free(tHANDLER);
  431. LOG_ERROR("Thread Creation Faled.");
  432. shutdown( tSID, SHUT_RDWR );
  433. close( tSID );
  434. } else {
  435. tHANDLER->CTX = tCTX;
  436. m_mHandlersProtector.lock();
  437. m_vHandlersPool.push_back( tHANDLER );
  438. m_mHandlersProtector.unlock();
  439. #ifdef DEBUG_EXTRA
  440. LOG("Handler Pushed to a Pool");
  441. #endif
  442. };
  443. } else { //https://stackoverflow.com/questions/18545077/image-fullscreen-on-click
  444. free(tCTX);
  445. LOG_ERROR("CL_HANDLER Mem Allocation Failure!");
  446. shutdown( tSID, SHUT_RDWR );
  447. close( tSID );
  448. };
  449. } else {
  450. LOG_ERROR("CL_CTX Mem Allocation Failure!");
  451. shutdown( tSID, SHUT_RDWR );
  452. close( tSID );
  453. };
  454. };
  455. };
  456. };
  457. // Handle Dead Clients
  458. if( m_vHandlersPool.size() ) {
  459. for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) {
  460. if( !( (*idx)->CTX->bValid ) ) {
  461. pthread_join( (*idx)->m_hThreadHandle, NULL );
  462. //close( (*idx)->CTX->m_iEncoderPipe[0] );
  463. close( (*idx)->CTX->m_iEncoderPipe[1] );
  464. free( (*idx)->CTX );
  465. free( (*idx) );
  466. m_mHandlersProtector.lock();
  467. m_vHandlersPool.erase(idx);
  468. m_mHandlersProtector.unlock();
  469. #ifdef DEBUG_EXTRA
  470. LOG("Web Handler Ripped!");
  471. #endif
  472. };
  473. };
  474. };
  475. // validate active streams ?
  476. SLEEP( 50 );
  477. };
  478. };
  479. #define ENABLE_SOCKOPT(sd, level, opt) \
  480. do { \
  481. int val = 1; \
  482. if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \
  483. warn("Failed enabling %s for web service", #opt); \
  484. } while (0);
  485. bool argusModuleEmbedVideo::startService(){
  486. m_bEnabled = true;
  487. //Create NoSignal Image
  488. cv::Mat tMat( m_sEmbedVideoData.height, m_sEmbedVideoData.width, CV_8UC3 );
  489. cv::rectangle( tMat, cv::Point( 0, 0 ), cv::Point( m_sEmbedVideoData.width, m_sEmbedVideoData.height ), cv::Scalar( 255, 0, 0 ), cv::FILLED );
  490. cv::putText( tMat, "NO SIGNAL", cv::Point( 10, 30 ), cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar( 0, 255, 255 ), 3 );
  491. if( m_sEmbedVideoData.show_logo ) {
  492. int a_x, a_y;
  493. if( m_sEmbedVideoData.logo_x < 0 ) {
  494. a_x = m_sEmbedVideoData.width + m_sEmbedVideoData.logo_x - m_sEmbedVideoData.logo_w;
  495. if( a_x < 0 ) a_x = 0;
  496. } else a_x = m_sEmbedVideoData.logo_x;
  497. if( ( a_x + m_sEmbedVideoData.logo_w ) > m_sEmbedVideoData.width ) a_x = m_sEmbedVideoData.width - m_sEmbedVideoData.logo_w;
  498. if( m_sEmbedVideoData.logo_y < 0 ) {
  499. a_y = m_sEmbedVideoData.height + m_sEmbedVideoData.logo_y - m_sEmbedVideoData.logo_h;
  500. if( a_y < 0 ) a_y = 0;
  501. } else a_y = m_sEmbedVideoData.logo_y;
  502. if( ( a_y + m_sEmbedVideoData.logo_h ) > m_sEmbedVideoData.height ) a_y = m_sEmbedVideoData.height - m_sEmbedVideoData.logo_h;
  503. if( ( a_x > -1 ) && ( a_y > -1 ) ) {
  504. char tName[256];
  505. m_sEmbedVideoData.logo_x = a_x;
  506. m_sEmbedVideoData.logo_y = a_y;
  507. sprintf( tName, "data/assets/images/%s.png", m_sEmbedVideoData.logo_md5 );
  508. cv::Mat T = cv::imread( tName, cv::IMREAD_UNCHANGED );
  509. if( T.cols > 0 ) {
  510. cv::Mat mask;
  511. vector<cv::Mat> layers;
  512. #ifdef DEBUG
  513. LOG("Logo Loaded OK");
  514. #endif
  515. cv::split( T, layers); // seperate channels
  516. cv::Mat rgb[3] = { layers[0], layers[1], layers[2] };
  517. mask = layers[3]; // png's alpha channel used as mask
  518. cv::merge( rgb, 3, T ); // put together the RGB channels, now transp insn't transparent
  519. cv::resize( T, m_mLogoPic, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC );
  520. cv::resize( mask, m_mLogoMask, cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ), cv::INTER_CUBIC );
  521. cv::Rect roi(cv::Point( m_sEmbedVideoData.logo_x, m_sEmbedVideoData.logo_y ), cv::Size( m_sEmbedVideoData.logo_w, m_sEmbedVideoData.logo_h ));
  522. cv::Mat destinationROI = tMat( roi );
  523. m_mLogoPic.copyTo( destinationROI, m_mLogoMask );
  524. //m_sEmbedVideoData.show_logo = false;
  525. } else {
  526. LOG("Logo Disabled - No Picture is Loaded");
  527. m_sEmbedVideoData.show_logo = false;
  528. };
  529. } else {
  530. LOG("Logo Disabled - Wrong Coords");
  531. m_sEmbedVideoData.show_logo = false;
  532. };
  533. LOG("Logo Draw OK");
  534. };
  535. try{
  536. vector<int> compression_params;
  537. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  538. //compression_params.push_back(9);
  539. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  540. compression_params.push_back( m_sEmbedVideoData.compression_quality );
  541. vector<uchar> buf;
  542. cv::imencode( ".jpg", tMat, buf, compression_params );
  543. m_nNoSignalSize = buf.size();
  544. n_pNoSignalData = (uint8_t *) malloc( m_nNoSignalSize );
  545. if( n_pNoSignalData ) {
  546. memcpy( n_pNoSignalData, buf.data(), m_nNoSignalSize );
  547. } else m_nNoSignalSize =0;
  548. buf.clear();
  549. } catch (cv::Exception & e) {
  550. LOG_ERROR(e.msg.c_str());
  551. };
  552. // Socket
  553. struct sockaddr sa;
  554. struct sockaddr_in *sin;
  555. memset(&sa, 0, sizeof(struct sockaddr));
  556. sa.sa_family = AF_INET;
  557. sin = (struct sockaddr_in *)&sa;
  558. sin->sin_addr.s_addr = htonl( INADDR_ANY );
  559. sin->sin_port = htons( m_sEmbedVideoData.port );
  560. m_nSocketDescriptor = socket( sa.sa_family, SOCK_STREAM | SOCK_NONBLOCK, 0);
  561. if( m_nSocketDescriptor == -1 ){
  562. LOG_ERROR("Failed creating ACC socket");
  563. return false;
  564. };
  565. ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEADDR);
  566. #ifdef SO_REUSEPORT
  567. ENABLE_SOCKOPT( m_nSocketDescriptor, SOL_SOCKET, SO_REUSEPORT);
  568. #endif
  569. if( bind( m_nSocketDescriptor, &sa, sizeof(sa)) < 0 ){
  570. LOG_ERROR("Failed binding Socket");
  571. close( m_nSocketDescriptor );
  572. return false;
  573. } else {
  574. LOG("Bind Socessfull");
  575. };
  576. if( listen( m_nSocketDescriptor, 10) != 0 ){
  577. LOG_ERROR("Failed setting web listen backlog");
  578. close( m_nSocketDescriptor );
  579. return false;
  580. } else {
  581. LOG("Listen OK");
  582. };
  583. LOG("Start Thread");
  584. m_bEnabled = init();
  585. return m_bEnabled;
  586. };
  587. bool argusModuleEmbedVideo::stopService( bool force ){
  588. m_bEnabled = false;
  589. m_bDetached = uninit();
  590. #ifdef DEBUG
  591. LOG("Service Thread ended!");
  592. #endif
  593. if( m_vHandlersPool.size() ) { // Kill-Wait Started Probes
  594. #ifdef DEBUG
  595. char tB[200];
  596. sprintf(tB, "Have to Wait Client Handlers[%d]!", m_vHandlersPool.size() );
  597. LOG( tB );
  598. #endif
  599. for( vectorHANDLERS::iterator index = m_vHandlersPool.begin(); index < m_vHandlersPool.end(); index++ ) {
  600. if( force ) {
  601. #ifdef DEBUG
  602. LOG("Force Client Handler to Stop!");
  603. #endif
  604. pthread_cancel( (*index)->m_hThreadHandle );
  605. } else {
  606. #ifdef DEBUG
  607. LOG("Waiting Client Handler to End!");
  608. #endif
  609. pthread_join( (*index)->m_hThreadHandle, NULL );
  610. }
  611. };
  612. m_vHandlersPool.clear();
  613. };
  614. #ifdef DEBUG
  615. LOG("No More Client Handlers!");
  616. #endif
  617. if( m_mapCAPTURES.size() ){
  618. m_mapCAPTURES.clear();
  619. //for( mapSTREAMCAPS::iterator idx = m_mapCAPTURES.begin(); idx < m_mapCAPTURES.end(); idx++ ) {
  620. //};
  621. };
  622. if( m_mapMATS.size() ){
  623. m_mapMATS.clear();
  624. //for( mapSTREAMMAPS::iterator idx = m_mapMATS.begin(); idx < m_mapMATS.end(); idx++ ) {
  625. //};
  626. };
  627. if ( n_pNoSignalData ) {
  628. free( n_pNoSignalData );
  629. n_pNoSignalData = NULL;
  630. m_nNoSignalSize = 0;
  631. };
  632. return m_bDetached;
  633. };
  634. bool argusModuleEmbedVideo::reloadSettings(){
  635. LOG("Reload Service");
  636. if( m_pDBC ){
  637. DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID );
  638. if( tDATA ) {
  639. if( stopService() ){
  640. LOG("Stoped!");
  641. memcpy( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA));
  642. free( tDATA );
  643. LOG("Starting...");
  644. return startService();
  645. } else {
  646. free( tDATA );
  647. };
  648. };
  649. };
  650. return false;
  651. };
  652. bool argusModuleEmbedVideo::validate(){
  653. bool RetVal = true;
  654. if( m_pDBC ){
  655. DBC_MODULE_EMBED_VIDEO_DATA *tDATA = m_pDBC->getEmbedVideoData( m_nDBAUXID );
  656. if( tDATA ) {
  657. if( memcmp( &m_sEmbedVideoData, tDATA, sizeof(DBC_MODULE_EMBED_VIDEO_DATA)) != 0 ){
  658. free( tDATA );
  659. LOG("Module Settings Changed!");
  660. return reloadSettings();
  661. };
  662. free( tDATA );
  663. } else {
  664. RetVal = false;
  665. };
  666. if ( RetVal ) {
  667. DBC_INT_LIST *tList = m_pDBC->listMediaStreams(m_pKernel->getSiteId(), LIST_VALID_RECORDS);
  668. if ( tList != NULL ) {
  669. for( DBC_INT_LIST::iterator idx = tList->begin(); idx < tList->end(); idx++ ){
  670. if( !registerStream( *idx ) ){
  671. RetVal = false;
  672. break;
  673. };
  674. };
  675. delete ( tList );
  676. };
  677. };
  678. if ( RetVal ) {
  679. for( mapSTREAMHANDLERS::iterator idx = m_mapHANDLERS.begin(); idx != m_mapHANDLERS.end(); idx++ ) {
  680. if ( !(*idx).second->validate() ) {
  681. RetVal = false;
  682. };
  683. };
  684. };
  685. } else {
  686. LOG_ERROR( "DB Error!" );
  687. RetVal = false;
  688. };
  689. return RetVal;
  690. };
  691. bool argusModuleEmbedVideo::registerForMediaStream( uint32_t id, WEB_CLIENT_CTX *&CTX ){
  692. if( CTX ){
  693. if( id ){
  694. //Check if its Valid!
  695. DBC_MEDIA_STREAM_DATA *tSD = m_pDBC->getMediaStreamData( id );
  696. if( tSD ) {
  697. //if( !tSD->valid ) {
  698. // free( tSD );
  699. // return false;
  700. //};
  701. free( tSD );
  702. //if( pipe( CTX->m_iEncoderPipe ) == -1 ){
  703. // CTX->bValid = false;
  704. // return false;
  705. //};
  706. CTX->mediaStreamId = id;
  707. return true;
  708. };
  709. };
  710. } else LOG_ERROR("Client Context error!");
  711. return false;
  712. };
  713. void argusModuleEmbedVideo::dispatchEvent( EVENT_CONTAINER *Evt ){
  714. if( Evt ) {
  715. switch( Evt->m_eClass ) {
  716. case EVT_CLASS_IMAGE:
  717. case EVT_CLASS_VIDEO:{
  718. switch( Evt->m_eType ) {
  719. case EVT_CAPTURE_START:{
  720. #ifdef DEBUG
  721. LOG("Capture Event");
  722. #endif
  723. if( Evt->m_ref_id && Evt->m_db_id ){
  724. uint32_t tPicID = saveStreamPicture( Evt->m_ref_id );
  725. if( tPicID ){
  726. //
  727. //m_pDBC->addPictureEvent( Evt->m_db_id, tPicID );
  728. } else {
  729. #ifdef DEBUG
  730. LOG_ERROR("No Picture is Saved!");
  731. #endif
  732. };
  733. } else {
  734. #ifdef DEBUG
  735. LOG_ERROR("No Stream ID or Event ID in Event Data!");
  736. #endif
  737. };
  738. break;
  739. };
  740. };
  741. break;
  742. };
  743. case EVT_CLASS_CAMERA_CTRL:{
  744. switch ( Evt->m_eType ) {
  745. case EVT_CAMERA_ON_POSITION:{
  746. #ifdef DEBUG
  747. LOG("Cam On Position After Event -> Capture Picture");
  748. #endif
  749. DBC_SNAPSHOT_DATA *tData = (DBC_SNAPSHOT_DATA *) Evt->m_pEvtData;
  750. if( tData ){
  751. if( !saveStreamPicture( tData ) ) LOG_ERROR("Save Error!");
  752. tData->assoc_event_ids.clear();
  753. delete( tData );
  754. Evt->m_pEvtData = NULL;
  755. } else LOG_ERROR("No Evt Data!");
  756. break;
  757. };
  758. };
  759. break;
  760. };
  761. };
  762. };
  763. };
  764. //https://www.ps2-home.com/forum/viewtopic.php?t=98
  765. //https://www.mikekohn.net/software/playstation2.php
  766. bool argusModuleEmbedVideo::saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ){
  767. if( ptr == NULL ) return false;
  768. if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){
  769. LOG("Saving Picture!");
  770. if( ptr->assoc_event_ids.size() ){
  771. if( m_mapCAPTURES.find( ptr->stream_id ) != m_mapCAPTURES.end() ){
  772. m_mPictureProtector.lock();
  773. ptr->data = (uint8_t *) malloc( m_mapCAPTURES[ptr->stream_id].size() );
  774. if( ptr->data ){
  775. ptr->data_size = m_mapCAPTURES[ptr->stream_id].size();
  776. memcpy( ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size );
  777. m_mPictureProtector.unlock();
  778. CSTR MD5 = MD5Binary( ptr->data, ptr->data_size );
  779. if( MD5 ){
  780. strncpy( ptr->md5, MD5, 32 );
  781. free( MD5 );
  782. if( !m_pDBC->addPicture( ptr, "jpg" ) ) LOG_ERROR("Database Error to consume capture!");
  783. } else LOG_ERROR("no MD5 Hash!");
  784. free( ptr->data );
  785. } else {
  786. m_mPictureProtector.unlock();
  787. LOG_ERROR("No memory to allocate!");
  788. };
  789. #ifdef DEBUG
  790. } else {
  791. LOG("No apropriate Stream Found!");
  792. #endif
  793. };
  794. };
  795. };
  796. if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO ){
  797. LOG("Saving Video!");
  798. if( ptr->assoc_event_ids.size() ){
  799. mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find( ptr->stream_id );
  800. if( hnd != m_mapHANDLERS.end() ){
  801. uint32_t db_id;
  802. uint32_t cfrm;
  803. if( (*hnd).second->triggerEvent( db_id, cfrm ) ){
  804. for( DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++ ){
  805. m_pDBC->addVideoEvent( (*idx), db_id, cfrm );
  806. };
  807. };
  808. };
  809. };
  810. };
  811. return true;
  812. };
  813. bool argusModuleEmbedVideo::saveStreamPicture( uint32_t id ){
  814. if( !id ) return false;
  815. if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){
  816. if( m_mapCAPTURES.find(id) != m_mapCAPTURES.end() ){
  817. FILE * tFD;
  818. m_mPictureProtector.lock();
  819. size_t tBufferSize = m_mapCAPTURES[id].size();
  820. uint8_t * tBuffer = (uint8_t *) malloc( tBufferSize );
  821. if( tBuffer ){
  822. memcpy( tBuffer, m_mapCAPTURES[id].data(), tBufferSize );
  823. m_mPictureProtector.unlock();
  824. CSTR MD5 = MD5Binary( tBuffer, tBufferSize );
  825. if( MD5 ){
  826. char tFileName[MAX_PATH];
  827. if( generateSavePicPath( MD5, tFileName ) ){
  828. FILE *fd = fopen( tFileName, "wb+" );
  829. if( fd ){
  830. fwrite(tBuffer, 1, tBufferSize, fd );
  831. fclose(fd);
  832. chown( tFileName, "nobody", "nogroup" );
  833. //retVal = m_pDBC->addPicture( id, MD5, "jpg" );
  834. } else LOG_ERROR("Can not open picture file!");
  835. } else LOG_ERROR("Can not generate file name!");
  836. free(MD5);
  837. } else LOG_ERROR("no MD5 Hash!");
  838. free(tBuffer);
  839. } else {
  840. m_mPictureProtector.unlock();
  841. LOG_ERROR("no memory to allocate!");
  842. };
  843. };
  844. }
  845. return true;
  846. };
  847. int argusModuleEmbedVideo::getWidh( void ){
  848. if( m_sEmbedVideoData.width ) return m_sEmbedVideoData.width;
  849. return -1;
  850. };
  851. int argusModuleEmbedVideo::getHeight( void ){
  852. if( m_sEmbedVideoData.height ) return m_sEmbedVideoData.height;
  853. return -1;
  854. };
  855. bool argusModuleEmbedVideo::generateSavePicPath( CSTR MD5, CSTR Output ){
  856. if( MD5 == NULL ) return false;
  857. if( Output == NULL ) return false;
  858. if( !fileExist( m_pBaseSavePath ) ) {
  859. LOG_ERROR("No Base Picture Save Path Defined!");
  860. return false;
  861. };
  862. if( strlen(MD5) < 4 ) return false;
  863. char test[MAX_PATH];
  864. sprintf( test, "%s/%c%c", m_pBaseSavePath, MD5[0], MD5[1] );
  865. if( !fileExist( test ) ) {
  866. #ifdef __linux__
  867. mkdir( test, STORAGE_DIR_MODE );
  868. #else
  869. _mkdir( test );
  870. #endif
  871. chown( test, "nobody", "nogroup" );
  872. };
  873. sprintf( test, "%s/%c%c/%c%c", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3] );
  874. if( !fileExist( test ) ) {
  875. #ifdef __linux__
  876. mkdir( test, STORAGE_DIR_MODE );
  877. #else
  878. _mkdir( test );
  879. #endif
  880. chown( test, "nobody", "nogroup" );
  881. };
  882. sprintf( Output, "%s/%c%c/%c%c/%s.jpg", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3], MD5 );
  883. return true;
  884. };
  885. bool argusModuleEmbedVideo::registerStream( uint32_t streamID ){
  886. //Check if stream is not allready exists
  887. //for ( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ){
  888. // if ( (*idx)->CTX->mediaStreamId == streamID ) return true;
  889. //};
  890. try {
  891. streamHandler * tData = m_mapHANDLERS.at( streamID );
  892. if( tData!= NULL ) return true;
  893. } catch (const std::out_of_range& oor ) {
  894. //std::cerr << "Out of Range error: " << oor.what() << '\n';
  895. m_mapHANDLERS[streamID] = new streamHandler( this );
  896. if ( m_mapHANDLERS[streamID] != NULL ) return m_mapHANDLERS[streamID]->create( streamID );
  897. };
  898. return false;
  899. };
  900. bool argusModuleEmbedVideo::unregisterStream( uint32_t streamID ){
  901. return true;
  902. };
  903. #undef LOG
  904. #undef LOG_ERROR
  905. #define LOG( X ) streamHandler::m_pLog->Log( "MEV_STR", this, X )
  906. #ifdef DEBUG
  907. #define LOG_ERROR( X ) {\
  908. char _tBfrErrMSG2w34[256];\
  909. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  910. streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
  911. }
  912. #else
  913. #define LOG_ERROR( X ) streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, X );
  914. #endif
  915. streamHandler::streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() {
  916. m_pLog = basicLogCollection::getInstance( );
  917. memset( &m_sStreamData, 0, sizeof( DBC_MEDIA_STREAM_DATA ) );
  918. m_pSource = NULL;
  919. #ifdef EVE_ENABLE_VIDEO
  920. m_nPreAlarmFrames = 0;
  921. m_nPostAlarmFrames = 0;
  922. m_nSegAFrameCounter = 0;
  923. m_nSegBFrameCounter = 0;
  924. m_nGlobalFrameCounter = 0;
  925. m_nVideoRegisteredDBID = 0;
  926. m_nSegAShiftFrames = 0;
  927. m_nSegBShiftFrames = 0;
  928. m_nSegASkippedFrames = m_nSegBSkippedFrames = 0;
  929. m_nSegmentLimitFrames = 0;
  930. m_nHardLimitFrames = 0;
  931. m_bActiveEncoderStream = 0;
  932. m_bSegAActive = false;
  933. m_bSegADelete = true;
  934. m_bSegBActive = false;
  935. m_bSegBDelete = true;
  936. m_bCOP = 0;
  937. #endif //EVE_ENABLE_VIDEO
  938. };
  939. streamHandler::~streamHandler(){
  940. LOG("DESTRUCT!");
  941. if ( m_sStreamData.id ) {
  942. if (m_pMaster != NULL) m_pMaster->unregisterStream(m_sStreamData.id);
  943. if ( m_pSource != NULL ) {
  944. switch( m_sStreamData.source_type[0] ) {
  945. case 'D': delete( ( videoLIVE555Source *) m_pSource ); break;
  946. case 'A': delete( ( videoAVLIBSource *) m_pSource ); break;
  947. };
  948. };
  949. #ifdef EVE_ENABLE_VIDEO
  950. closeAll();
  951. #endif //EVE_ENABLE_VIDEO
  952. };
  953. };
  954. bool streamHandler::create( uint32_t stremID ){
  955. if( stremID ) {
  956. DBC_MEDIA_STREAM_DATA *tData = argusDBC::getInstance()->getMediaStreamData( stremID );
  957. if ( tData ) {
  958. memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA));
  959. free(tData);
  960. DBC_CAM_DATA *tCAM = argusDBC::getInstance()->getCamData( m_sStreamData.source_id );
  961. if( tCAM ){
  962. CSTR tNAM = argusDBC::getInstance()->getNodeName( tCAM->node_id );
  963. m_sSourceDesc.mediaStreamId = stremID;
  964. m_sSourceDesc.mediaSourceId = m_sStreamData.source_id;
  965. if ( tNAM!= NULL ) {
  966. strncpy(m_sSourceDesc.mediaName, tNAM, 127 );
  967. m_sSourceDesc.mediaName[127] = (char)0;
  968. free( tNAM );
  969. } else {
  970. sprintf(m_sSourceDesc.mediaName, "No Name Cam");
  971. };
  972. switch( m_sStreamData.source_type[0] ) {
  973. case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource( &m_sSourceDesc ); break;
  974. case 'D': m_pSource = (basicMediaSource *) new videoLIVE555Source( &m_sSourceDesc ); break;
  975. };
  976. if( m_pSource != NULL ) {
  977. char tMRL[1024];
  978. #ifdef DEBUG
  979. LOG("Source OK");
  980. #endif
  981. int tW = m_pMaster->getWidh();
  982. int tH = m_pMaster->getHeight();
  983. int pix = -1;
  984. bool in_16_9 = (((m_sStreamData.width*100) / m_sStreamData.height ) > 140 );
  985. bool out_16_9 = (((tW*100) / tH ) > 140 );
  986. //if( tW > 0 ){
  987. // //m_pSource->setProportionalByWidth( tW );
  988. // m_pSource->setSize( tW, tH );
  989. //};
  990. if( in_16_9 != out_16_9 ){
  991. if( in_16_9 ){
  992. tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000;
  993. } else {
  994. tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000;
  995. };
  996. };
  997. if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) {
  998. sprintf( tMRL, m_sStreamData.mrl );
  999. } else {
  1000. sprintf( tMRL, "%s://%s:%s@%s:%d%s", m_sStreamData.mrl_proto, tCAM->username, tCAM->password, tCAM->ip, m_sStreamData.mrl_port, m_sStreamData.mrl );
  1001. };
  1002. LOG( tMRL );
  1003. if( m_pSource->_open( tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH ) ){
  1004. if( !m_pSource->attachDestination( this ) ){
  1005. delete( m_pSource );
  1006. m_pSource = NULL;
  1007. } else {
  1008. #ifdef DEBUG
  1009. LOG("Source is Connected to Output.");
  1010. #endif
  1011. };
  1012. } else {
  1013. LOG_ERROR("Can not Open Video Source!");
  1014. delete( m_pSource );
  1015. m_pSource = NULL;
  1016. };
  1017. } else {
  1018. LOG_ERROR("Video Source Stream Failure!");
  1019. };
  1020. free( tCAM );
  1021. } else {
  1022. LOG_ERROR("Error Getting CAM Data!");
  1023. m_pSource = NULL;
  1024. return false;
  1025. };
  1026. };
  1027. };
  1028. if( m_pSource ){
  1029. #ifdef EVE_ENABLE_VIDEO
  1030. return initVideoOutput();
  1031. #else
  1032. return true;
  1033. #endif // EVE_ENABLE_VIDEO
  1034. };
  1035. return false;
  1036. };
  1037. bool streamHandler::pushFrame( AVFrame *Frame, void* src){
  1038. if( m_pMaster == NULL ) return false;
  1039. MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src;
  1040. if( tMD ) {
  1041. };
  1042. return true;
  1043. };
  1044. bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){
  1045. if( m_pMaster == NULL ) return false;
  1046. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  1047. char tBuffer[128];
  1048. if( tMD ) {
  1049. float mK, oK;
  1050. cv::Rect ROI;
  1051. m_pMaster->m_mPictureProtector.lock();
  1052. if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) {
  1053. LOG("First Frame Enqueued");
  1054. sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId );
  1055. LOG( tBuffer );
  1056. m_pMaster->m_mapMATS[tMD->mediaStreamId].create(
  1057. m_pMaster->m_sEmbedVideoData.height,
  1058. m_pMaster->m_sEmbedVideoData.width,
  1059. CV_8UC3
  1060. );
  1061. cv::rectangle(
  1062. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1063. cv::Point( 0, 0 ),
  1064. cv::Point(
  1065. m_pMaster->m_sEmbedVideoData.height,
  1066. m_pMaster->m_sEmbedVideoData.width
  1067. ),
  1068. cv::Scalar( 0, 0, 0 ),
  1069. cv::FILLED
  1070. );
  1071. };
  1072. #ifdef USE_SCALING_IN
  1073. oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width);
  1074. mK = ((float)Frame.rows )/ ((float)Frame.cols);
  1075. //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK );
  1076. if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) {
  1077. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1078. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1079. ROI.x = (int) 0;
  1080. ROI.y = (int) 0;
  1081. } else {
  1082. if( mK < oK ) {
  1083. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1084. ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK );
  1085. ROI.x = (int) 0;
  1086. ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1;
  1087. } else {
  1088. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1089. ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK );
  1090. ROI.y = (int) 0;
  1091. ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1;
  1092. };
  1093. };
  1094. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1095. cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR );
  1096. #else
  1097. if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){
  1098. Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] );
  1099. } else {
  1100. //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows));
  1101. //src.copyTo(dst_roi);
  1102. if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) {
  1103. ROI.width = Frame.cols;
  1104. ROI.height = Frame.rows;
  1105. ROI.x = 0;
  1106. ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1;
  1107. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1108. Frame.copyTo(mROI);
  1109. } else {
  1110. ROI.width = Frame.cols;
  1111. ROI.height = Frame.rows;
  1112. ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1;
  1113. ROI.y = 0;
  1114. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1115. Frame.copyTo(mROI);
  1116. };
  1117. };
  1118. #endif
  1119. if( m_pMaster->m_sEmbedVideoData.show_label ){
  1120. time_t t = time( NULL );
  1121. struct tm * tmp = gmtime( &t );
  1122. if( tmp ){
  1123. char tsb[64];
  1124. if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){
  1125. sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb );
  1126. int baseline=0;
  1127. cv::Size textSize = cv::getTextSize( tBuffer,
  1128. m_pMaster->m_sEmbedVideoData.label_font_face,
  1129. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1130. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1131. &baseline
  1132. );
  1133. int x = m_pMaster->m_sEmbedVideoData.label_x;
  1134. int y = m_pMaster->m_sEmbedVideoData.label_y;
  1135. if( x < 0 ) {
  1136. x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width;
  1137. };
  1138. if( y < 0 ) {
  1139. y = m_pMaster->m_sEmbedVideoData.height+y-baseline;//
  1140. };
  1141. if( !m_pMaster->m_sEmbedVideoData.label_transperant ) {
  1142. cv::rectangle(
  1143. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1144. cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ),
  1145. cv::Scalar( 0, 0, 0 ),
  1146. cv::FILLED
  1147. );
  1148. };
  1149. cv::putText(
  1150. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1151. tBuffer,
  1152. cv::Point( x, y ),
  1153. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face,
  1154. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1155. cv::Scalar( 0, 255, 0 ),
  1156. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1157. m_pMaster->m_sEmbedVideoData.label_line_type
  1158. );
  1159. };
  1160. };
  1161. } else {
  1162. if( m_pMaster->m_sEmbedVideoData.show_ts ){
  1163. time_t t = time( NULL );
  1164. struct tm * tmp = gmtime( &t );
  1165. if( tmp ){
  1166. if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){
  1167. uint8_t shift_x = 0;
  1168. uint8_t shift_y = 15;
  1169. if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) {
  1170. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1171. shift_y = 15;
  1172. cv::rectangle(
  1173. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1174. cv::Point(
  1175. m_pMaster->m_sEmbedVideoData.ts_x,
  1176. m_pMaster->m_sEmbedVideoData.ts_y
  1177. ),
  1178. cv::Point( 490, 60 ),
  1179. cv::Scalar( 0, 0, 0 ),
  1180. cv::FILLED
  1181. );
  1182. } else {
  1183. shift_y = 23;
  1184. cv::rectangle(
  1185. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1186. cv::Point(
  1187. m_pMaster->m_sEmbedVideoData.ts_x,
  1188. m_pMaster->m_sEmbedVideoData.ts_y
  1189. ),
  1190. cv::Point( 490, 60 ),
  1191. cv::Scalar( 0, 0, 0 ),
  1192. cv::FILLED
  1193. );
  1194. };
  1195. cv::putText(
  1196. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1197. tBuffer,
  1198. cv::Point(
  1199. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1200. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1201. ),
  1202. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1203. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1204. cv::Scalar( 0, 255, 255 ),
  1205. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1206. m_pMaster->m_sEmbedVideoData.ts_line_type
  1207. );
  1208. } else {
  1209. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1210. shift_y = 15;
  1211. } else {
  1212. shift_y = 23;
  1213. };
  1214. cv::putText(
  1215. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1216. tBuffer,
  1217. cv::Point(
  1218. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1219. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1220. ),
  1221. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1222. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1223. cv::Scalar( 0, 0, 0 ),
  1224. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1225. m_pMaster->m_sEmbedVideoData.ts_line_type
  1226. );
  1227. cv::putText(
  1228. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1229. tBuffer,
  1230. cv::Point(
  1231. m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1,
  1232. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1233. ),
  1234. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1235. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1236. cv::Scalar( 0, 0, 0 ),
  1237. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1238. m_pMaster->m_sEmbedVideoData.ts_line_type
  1239. );
  1240. cv::putText(
  1241. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1242. tBuffer,
  1243. cv::Point(
  1244. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1245. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1
  1246. ),
  1247. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1248. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1249. cv::Scalar( 0, 0, 0 ),
  1250. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1251. m_pMaster->m_sEmbedVideoData.ts_line_type
  1252. );
  1253. cv::putText(
  1254. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1255. tBuffer,
  1256. cv::Point(
  1257. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1258. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2
  1259. ),
  1260. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1261. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1262. cv::Scalar( 0, 0, 0 ),
  1263. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1264. m_pMaster->m_sEmbedVideoData.ts_line_type
  1265. );
  1266. cv::putText(
  1267. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1268. tBuffer,
  1269. cv::Point(
  1270. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1271. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1272. ),
  1273. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1274. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1275. cv::Scalar( 0, 255, 255 ),
  1276. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1277. m_pMaster->m_sEmbedVideoData.ts_line_type
  1278. );
  1279. }
  1280. };
  1281. };
  1282. };
  1283. };
  1284. if( m_pMaster->m_sEmbedVideoData.show_logo ){
  1285. cv::Rect roi(
  1286. cv::Point(
  1287. m_pMaster->m_sEmbedVideoData.logo_x,
  1288. m_pMaster->m_sEmbedVideoData.logo_y
  1289. ),
  1290. cv::Size(
  1291. m_pMaster->m_sEmbedVideoData.logo_w,
  1292. m_pMaster->m_sEmbedVideoData.logo_h
  1293. )
  1294. );
  1295. cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi );
  1296. m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask );
  1297. };
  1298. vector<int> compression_params;
  1299. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  1300. //compression_params.push_back(9);
  1301. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  1302. compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality );
  1303. m_pMaster->m_mEncodedProtector.lock();
  1304. m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear();
  1305. cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  1306. m_pMaster->m_mEncodedProtector.unlock();
  1307. #ifdef EVE_ENABLE_VIDEO
  1308. // encode Video Stream
  1309. //m_nPreAlarmFrames
  1310. //m_nPostAlarmFrames
  1311. //m_nNoAlarmSegmentFrames
  1312. //m_nSegmentLimitFrames
  1313. //m_nHardLimitFrames
  1314. if ( m_bSegAActive || m_bSegBActive ) {
  1315. m_mFrameCounterProtector.lock();
  1316. if( m_bSegAActive ){
  1317. do {
  1318. //In Any Case Close Stream if it Long enough
  1319. if( m_nSegAFrameCounter > m_nHardLimitFrames ){
  1320. LOG("HardLimit Reached!(A)");
  1321. closeSegmentA();
  1322. break;
  1323. };
  1324. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1325. if ( !m_bSegBActive ){
  1326. LOG("Start Alt!(A)");
  1327. openSegmentB();
  1328. };
  1329. };
  1330. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){
  1331. LOG("Swap Active!(A)");
  1332. swapActiveStreams();
  1333. break;
  1334. };
  1335. } while ( 0 );
  1336. };
  1337. if( m_bSegBActive ) {
  1338. do {
  1339. //In Any Case Close Stream if it Long enough
  1340. if( m_nSegBFrameCounter > m_nHardLimitFrames ){
  1341. LOG("HardLimit Reached!(B)");
  1342. closeSegmentB();
  1343. break;
  1344. };
  1345. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1346. if ( !m_bSegAActive ){
  1347. LOG("Start Alt!(B)");
  1348. openSegmentA();
  1349. };
  1350. };
  1351. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){
  1352. LOG("Swap Active!(B)");
  1353. swapActiveStreams();
  1354. break;
  1355. };
  1356. } while ( 0 );
  1357. };
  1358. m_mFrameCounterProtector.unlock();
  1359. ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER));
  1360. if ( tData ) {
  1361. tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize();
  1362. tData->linesize[1] = 0;
  1363. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  1364. tData->size = tData->linesize[0]*tData->rows;
  1365. tData->data[1] = NULL;
  1366. tData->data[0] = (uint8_t *)malloc( tData->size );
  1367. if ( tData->data[0] ) {
  1368. memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size );
  1369. m_mEncodingQueueProtector.lock();
  1370. m_qEncodingQueue.push( tData );
  1371. m_mEncodingQueueProtector.unlock();
  1372. } else {
  1373. LOG_ERROR("MAT_CPY malloc Error!");
  1374. free( tData );
  1375. };
  1376. } else LOG_ERROR("ENC_BUF malloc Error!");
  1377. };
  1378. #endif // EVE_ENABLE_VIDEO
  1379. m_pMaster->m_mPictureProtector.unlock();
  1380. } else {
  1381. LOG_ERROR("No PayLoad!");
  1382. };
  1383. return true;
  1384. };
  1385. void streamHandler::closeSegmentA( void ){
  1386. m_mCurrentOperationProtector.lock();
  1387. if ( m_bCOP == 0 ) m_bCOP = 0x01;
  1388. m_mCurrentOperationProtector.unlock();
  1389. LOG("Closing Stream A");
  1390. };
  1391. void streamHandler::closeSegmentB( void ){
  1392. m_mCurrentOperationProtector.lock();
  1393. if ( m_bCOP == 0 ) m_bCOP = 0x02;
  1394. m_mCurrentOperationProtector.unlock();
  1395. LOG("Closing Stream B");
  1396. };
  1397. void streamHandler::closeAll(){
  1398. waitThreadEnd( true );
  1399. avcodec_send_frame( m_pCodecCtx, NULL );
  1400. int ret = 0;
  1401. AVPacket *avp = av_packet_alloc();
  1402. if ( avp ) {
  1403. do {
  1404. av_packet_unref( avp );
  1405. ret = avcodec_receive_packet( m_pCodecCtx, avp );
  1406. if ( !ret ) {
  1407. if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp );
  1408. if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp );
  1409. };
  1410. } while ( !ret );
  1411. av_packet_unref( avp );
  1412. av_packet_free( &avp );
  1413. };
  1414. if ( m_bSegAActive ) {
  1415. av_write_trailer(m_pFormatCtxA);
  1416. avformat_close_input( &m_pFormatCtxA );
  1417. m_bSegAActive = false;
  1418. };
  1419. if ( m_bSegBActive ) {
  1420. av_write_trailer(m_pFormatCtxB);
  1421. avformat_close_input( &m_pFormatCtxB );
  1422. m_bSegBActive = false;
  1423. };
  1424. };
  1425. bool streamHandler::openSegmentA( void ){
  1426. if( !m_bSegAActive ){
  1427. CSTR tAM = getUniqID_MD5();
  1428. if ( tAM ) {
  1429. sprintf( m_cSegNameA, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER );
  1430. strncpy( m_cSegMD5A, tAM, 32 );
  1431. m_cSegMD5A[32] = (char)0;
  1432. free( tAM );
  1433. #ifdef DEBUG
  1434. LOG("Opening Stream A");
  1435. LOG(m_cSegNameA);
  1436. char tB[128];
  1437. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  1438. LOG( tB );
  1439. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  1440. LOG( tB );
  1441. #endif
  1442. m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1;
  1443. //if (m_pVideoStrA->nb_frames) {
  1444. // m_pVideoStrA->nb_frames = 0;
  1445. // m_pVideoStrA->start_time = 0;
  1446. // m_pVideoStrA->first_dts = 0;
  1447. // m_pFormatCtxA->start_time = 0;
  1448. //};
  1449. if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  1450. LOG_ERROR("Could not open output file.");
  1451. return m_bSegAActive;
  1452. };
  1453. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  1454. LOG_ERROR("Error occurred when writing header to output file.");
  1455. return m_bSegAActive;
  1456. };
  1457. //m_mFrameCounterProtector.lock();
  1458. m_nSegAFrameCounter = 0;
  1459. m_nSegAShiftFrames = 0;
  1460. m_bSegAActive = true;
  1461. m_bSegADelete = true;
  1462. //m_mFrameCounterProtector.unlock();
  1463. #ifdef DEBUG
  1464. LOG("Stream A Opened");
  1465. #endif
  1466. };
  1467. };
  1468. return m_bSegAActive;
  1469. };
  1470. bool streamHandler::openSegmentB( void ){
  1471. if( !m_bSegBActive ){
  1472. CSTR tAM = getUniqID_MD5();
  1473. if ( tAM ) {
  1474. sprintf( m_cSegNameB, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER );
  1475. strncpy( m_cSegMD5B, tAM, 32 );
  1476. m_cSegMD5B[32] = (char)0;
  1477. free( tAM );
  1478. #ifdef DEBUG
  1479. LOG("Opening Stream B");
  1480. LOG(m_cSegNameB);
  1481. char tB[128];
  1482. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts );
  1483. LOG( tB );
  1484. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration );
  1485. LOG( tB );
  1486. #endif
  1487. m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1;
  1488. //if (m_pVideoStrB->nb_frames) {
  1489. // m_pVideoStrB->nb_frames = 0;
  1490. // m_pVideoStrB->start_time = 0;
  1491. // m_pVideoStrB->first_dts = 0;
  1492. // m_pFormatCtxB->start_time = 0;
  1493. //};
  1494. if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  1495. LOG_ERROR("Could not open output file.");
  1496. return m_bSegBActive;
  1497. };
  1498. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  1499. LOG_ERROR("Error occurred when writing header to output file.");
  1500. return m_bSegBActive;
  1501. };
  1502. //m_mFrameCounterProtector.lock();
  1503. m_nSegBFrameCounter = 0;
  1504. m_nSegBShiftFrames = 0;
  1505. m_bSegBActive = true;
  1506. m_bSegBDelete = true;
  1507. //m_mFrameCounterProtector.unlock();
  1508. #ifdef DEBUG
  1509. LOG("Stream B Opened");
  1510. #endif
  1511. };
  1512. };
  1513. return m_bSegBActive;
  1514. };
  1515. bool streamHandler::initVideoOutput(){
  1516. m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1517. m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1518. m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1519. m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1520. if( !initLibAV() ) return false;
  1521. m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL );
  1522. if ( m_pFormat == NULL ) {
  1523. LOG_ERROR("Out VideoFormat Not Found!");
  1524. return false;
  1525. #ifdef DEBUG
  1526. } else {
  1527. LOG("Output video Format");
  1528. LOG( VIDEO_OUTPUT_CONTAINER );
  1529. #endif
  1530. };
  1531. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1532. LOG_ERROR("Format CTX A alloc error!");
  1533. av_free( m_pFormat );
  1534. return false;
  1535. } else {
  1536. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  1537. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1538. };
  1539. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1540. LOG_ERROR("Format CTX B alloc error!");
  1541. avformat_free_context( m_pFormatCtxA );
  1542. //av_free( m_pFormat );
  1543. return false;
  1544. } else {
  1545. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  1546. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1547. };
  1548. m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  1549. if( m_pVideoCodec == NULL ){
  1550. LOG_ERROR("Out VideoCodec Not Found!");
  1551. avformat_free_context( m_pFormatCtxA );
  1552. avformat_free_context( m_pFormatCtxB );
  1553. //av_free( m_pFormat );
  1554. return false;
  1555. #ifdef DEBUG
  1556. } else {
  1557. LOG("Out Video Codec Found");
  1558. #endif
  1559. };
  1560. m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec );
  1561. if ( m_pCodecCtx == NULL){
  1562. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  1563. av_free( m_pVideoCodec );
  1564. avformat_free_context( m_pFormatCtxA );
  1565. avformat_free_context( m_pFormatCtxB );
  1566. //av_free( m_pFormat );
  1567. return false;
  1568. #ifdef DEBUG
  1569. } else {
  1570. LOG("Out Codec Context3 Allocated");
  1571. #endif
  1572. };
  1573. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec );
  1574. if ( m_pVideoStrA == NULL){
  1575. LOG_ERROR("VideoStream A Not Created!");
  1576. avcodec_free_context( &m_pCodecCtx );
  1577. av_free( m_pCodecCtx );
  1578. av_free( m_pVideoCodec );
  1579. avformat_free_context( m_pFormatCtxA );
  1580. avformat_free_context( m_pFormatCtxB );
  1581. //av_free( m_pFormat );
  1582. return false;
  1583. #ifdef DEBUG
  1584. } else {
  1585. LOG("VideoStream A is Created");
  1586. #endif
  1587. };
  1588. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec );
  1589. if ( m_pVideoStrB == NULL){
  1590. LOG_ERROR("VideoStream B Not Created!");
  1591. avcodec_free_context( &m_pCodecCtx );
  1592. av_free( m_pCodecCtx );
  1593. av_free( m_pVideoCodec );
  1594. avformat_free_context( m_pFormatCtxA );
  1595. avformat_free_context( m_pFormatCtxB );
  1596. av_free( m_pFormat );
  1597. return false;
  1598. #ifdef DEBUG
  1599. } else {
  1600. LOG("VideoStream B is Created");
  1601. #endif
  1602. };
  1603. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  1604. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  1605. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1606. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  1607. //m_pCodecCtx->thread_count = 1;
  1608. //m_pCodecCtx->bit_rate_tolerance = 1;
  1609. //m_pCodecCtx->global_quality = 100;
  1610. //m_pCodecCtx->compression_level = 2;
  1611. m_pCodecCtx->max_b_frames=1;
  1612. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  1613. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  1614. m_pCodecCtx->time_base.num = 1;
  1615. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  1616. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  1617. m_pCodecCtx->framerate.den = 1;
  1618. //https://pastebin.com/yG37YhWW
  1619. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  1620. //G@ avcodec encode NALU mp4
  1621. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  1622. m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  1623. #endif
  1624. m_pFormatOpts = NULL;
  1625. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  1626. if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){
  1627. #ifdef DEBUG
  1628. LOG("Begin Options!");
  1629. #endif
  1630. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  1631. //Set format's privater options, to be passed to avformat_write_header()
  1632. /*
  1633. mp4 muxer AVOptions:
  1634. -movflags E..... MOV muxer flags (default 0)
  1635. rtphint E..... Add RTP hint tracks
  1636. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  1637. frag_keyframe E..... Fragment at video keyframes
  1638. separate_moof E..... Write separate moof/mdat atoms for each track
  1639. frag_custom E..... Flush fragments on caller requests
  1640. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  1641. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  1642. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  1643. delay_moov ??
  1644. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  1645. -rtpflags E..... RTP muxer flags (default 0)
  1646. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  1647. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  1648. skip_rtcp E..... Don't send RTCP sender reports
  1649. h264_mode0 E..... Use mode 0 for H264 in RTP
  1650. send_bye E..... Send RTCP BYE packets when finishing
  1651. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  1652. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  1653. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  1654. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  1655. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  1656. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  1657. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  1658. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  1659. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  1660. */
  1661. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  1662. LOG_ERROR( "av_dict_set movflags!");
  1663. #ifdef DEBUG
  1664. } else {
  1665. LOG("MOV FLAG SET!");
  1666. #endif
  1667. };
  1668. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  1669. // LOG_ERROR( "av_dict_set live!" );
  1670. //};
  1671. //default brand is "isom", which fails on some devices
  1672. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  1673. LOG_ERROR( "av_dict_set brand!" );
  1674. };
  1675. //m_pCodecCtx->max_b_frames = 1;
  1676. //m_pCodecCtx->level = 31;
  1677. m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  1678. /// P-frames, generated by referencing data from prev and future frames.
  1679. /// [Compression up, CPU usage up]
  1680. /// [use 3/gop]
  1681. m_pCodecCtx->max_b_frames = 5;
  1682. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  1683. /// [use 3�5 ref per P]
  1684. m_pCodecCtx->refs = 3;
  1685. /// Compression efficiency (slower -> better quality + higher cpu%)
  1686. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  1687. /// Set this option to "ultrafast" is critical for realtime encoding
  1688. av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  1689. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  1690. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  1691. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  1692. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  1693. av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0);
  1694. /// Change settings based upon the specifics of input
  1695. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  1696. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  1697. av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  1698. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  1699. /// Because Quicktime (ie. iOS) doesn't support this option
  1700. av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
  1701. #ifdef DEBUG
  1702. LOG("End Options!");
  1703. #endif
  1704. } else {
  1705. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1706. };
  1707. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  1708. #ifdef DEBUG
  1709. char TB[129];
  1710. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den );
  1711. LOG(TB);
  1712. #endif
  1713. m_pVideoStrA->time_base = m_pCodecCtx->time_base;
  1714. m_pVideoStrB->time_base = m_pCodecCtx->time_base;
  1715. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  1716. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1717. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1718. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1719. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1720. m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1721. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  1722. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1723. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1724. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1725. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1726. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1727. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1728. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1729. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx );
  1730. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1731. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  1732. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1733. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx );
  1734. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1735. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  1736. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1737. if ( avcodec_is_open( m_pCodecCtx ) == 0 ) {
  1738. LOG("output codec context is closed, opening");
  1739. if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) {
  1740. LOG_ERROR("Error opening2 encoder");
  1741. return false;
  1742. #ifdef DEBUG
  1743. } else {
  1744. LOG("output codec context is opened");
  1745. };
  1746. #endif
  1747. #ifdef DEBUG
  1748. } else {
  1749. LOG("output codec context is already opened");
  1750. #endif
  1751. };
  1752. m_pConvertCtx = sws_getContext(
  1753. m_pMaster->m_sEmbedVideoData.width,
  1754. m_pMaster->m_sEmbedVideoData.height,
  1755. AV_PIX_FMT_BGR24,
  1756. m_pMaster->m_sEmbedVideoData.width,
  1757. m_pMaster->m_sEmbedVideoData.height,
  1758. VIDEO_OUTPUT_PIX_FMT,
  1759. SWS_FAST_BILINEAR,
  1760. NULL,
  1761. NULL,
  1762. NULL
  1763. );
  1764. if ( m_pConvertCtx == NULL ) {
  1765. return false;
  1766. }
  1767. m_pAVFrame = av_frame_alloc();
  1768. if ( m_pAVFrame == NULL ) {
  1769. return false;
  1770. };
  1771. m_pOutBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, BUFFER_ALIGN));
  1772. if( m_pOutBuffer == NULL ) {
  1773. return false;
  1774. };
  1775. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  1776. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  1777. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  1778. //av_frame_get_buffer( m_pAVFrame, 0 );
  1779. av_image_fill_arrays ( m_pAVFrame->data, m_pAVFrame->linesize, m_pOutBuffer, VIDEO_OUTPUT_PIX_FMT, m_pMaster->m_sEmbedVideoData.width, m_pMaster->m_sEmbedVideoData.height, 1 );
  1780. //av_frame_make_writable( m_pAVFrame );
  1781. return init();
  1782. };
  1783. //encoding thread
  1784. void streamHandler::m_fThreadProc( void ){
  1785. AVPacket mPacket;
  1786. int bGotPacket;
  1787. int rVal = 0;
  1788. char tB[128];
  1789. av_init_packet( &mPacket );
  1790. while( m_bThreadStatus != TH_ENDED ){
  1791. //At the begining All streams are closed --> try to Open
  1792. if( m_bThreadStatus < TH_WORKING ){
  1793. if( !openSegmentA() ){
  1794. m_bThreadStatus = TH_ENDED;
  1795. continue;
  1796. };
  1797. //if( !openSegmentB() ){
  1798. // m_bThreadStatus = TH_ENDED;
  1799. // continue;
  1800. //};
  1801. m_bThreadStatus = TH_WORKING;
  1802. continue;
  1803. };
  1804. m_mEncodingQueueProtector.lock();
  1805. if ( m_qEncodingQueue.size() ) {
  1806. ENCODING_BUFFER *tData = m_qEncodingQueue.front();
  1807. if( tData ){
  1808. //av_frame_make_writable( m_pAVFrame );
  1809. sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize );
  1810. free( tData->data[0] );
  1811. free( tData );
  1812. m_qEncodingQueue.pop();
  1813. /*
  1814. AV_PICTURE_TYPE_NONE Undefined.
  1815. AV_PICTURE_TYPE_I Intra.
  1816. AV_PICTURE_TYPE_P Predicted.
  1817. AV_PICTURE_TYPE_B Bi-dir predicted.
  1818. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4.
  1819. AV_PICTURE_TYPE_SI Switching Intra.
  1820. AV_PICTURE_TYPE_SP Switching Predicted.
  1821. AV_PICTURE_TYPE_BI BI type.
  1822. */
  1823. if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) {
  1824. m_pAVFrame->key_frame = 1;
  1825. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I;
  1826. } else {
  1827. m_pAVFrame->key_frame = 0;
  1828. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
  1829. };
  1830. m_pAVFrame->pts = m_nGlobalFrameCounter + 1;
  1831. rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame );
  1832. m_mFrameCounterProtector.lock();
  1833. m_nGlobalFrameCounter++;
  1834. if ( m_bSegAActive ) m_nSegAFrameCounter++;
  1835. if ( m_bSegBActive ) m_nSegBFrameCounter++;
  1836. m_mFrameCounterProtector.unlock();
  1837. };
  1838. m_mEncodingQueueProtector.unlock();
  1839. } else {
  1840. m_mEncodingQueueProtector.unlock();
  1841. // If No Encode Job -> Test Commands!
  1842. m_mCurrentOperationProtector.lock();
  1843. switch ( m_bCOP ) {
  1844. case 0x01:{
  1845. m_bSegAActive = false;
  1846. if ( !m_bSegADelete ) {
  1847. av_write_trailer( m_pFormatCtxA );
  1848. avio_close( m_pFormatCtxA->pb );
  1849. #ifdef DEBUG
  1850. LOG("Stream A is Closed");
  1851. #endif
  1852. } else {
  1853. #ifdef EVE_DONT_DELETE_SEGMENTS
  1854. av_write_trailer( m_pFormatCtxA );
  1855. #endif
  1856. avio_close( m_pFormatCtxA->pb );
  1857. #ifndef EVE_DONT_DELETE_SEGMENTS
  1858. unlink( m_cSegNameA );
  1859. #endif
  1860. #ifdef DEBUG
  1861. LOG("Stream A is Deleted!");
  1862. #endif
  1863. };
  1864. break;
  1865. };
  1866. case 0x02:{
  1867. m_bSegBActive = false;
  1868. if ( !m_bSegBDelete ) {
  1869. av_write_trailer( m_pFormatCtxB );
  1870. avio_close( m_pFormatCtxB->pb );
  1871. #ifdef DEBUG
  1872. LOG("Stream B is Closed");
  1873. #endif
  1874. } else {
  1875. #ifdef EVE_DONT_DELETE_SEGMENTS
  1876. av_write_trailer( m_pFormatCtxB );
  1877. #endif
  1878. avio_close( m_pFormatCtxB->pb );
  1879. #ifndef EVE_DONT_DELETE_SEGMENTS
  1880. unlink( m_cSegNameB );
  1881. #endif
  1882. #ifdef DEBUG
  1883. LOG("Stream B is Deleted!");
  1884. #endif
  1885. };
  1886. break;
  1887. };
  1888. };
  1889. m_bCOP = 0;
  1890. m_mCurrentOperationProtector.unlock();
  1891. };
  1892. do {
  1893. mPacket.data = NULL;
  1894. mPacket.size = 0;
  1895. rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket );
  1896. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  1897. break;
  1898. } else if( rVal < 0 ){
  1899. LOG_ERROR( "Error during encoding " );
  1900. m_bThreadStatus = TH_ENDED;
  1901. break;
  1902. };
  1903. if( !rVal ){
  1904. if ( m_bSegAActive ) {
  1905. mPacket.stream_index = m_pVideoStrA->index;
  1906. mPacket.duration = 1;
  1907. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1908. //mPacket.pts = AV_NOPTS_VALUE;
  1909. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1910. mPacket.dts = mPacket.pts;
  1911. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  1912. if( rc < 0 ){
  1913. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  1914. m_bThreadStatus = TH_ENDED;
  1915. LOG_ERROR("Trouble with Video Output A!");
  1916. av_strerror( rc, tB, 128 );
  1917. LOG_ERROR( tB );
  1918. break; //continue (changed since embed into do-while)
  1919. };
  1920. };
  1921. if ( m_bSegBActive ) {
  1922. mPacket.stream_index = m_pVideoStrB->index;
  1923. mPacket.duration = 1;
  1924. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1925. //mPacket.pts = AV_NOPTS_VALUE;
  1926. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  1927. mPacket.dts = mPacket.pts;
  1928. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  1929. if( rc < 0 ) {
  1930. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  1931. m_bThreadStatus = TH_ENDED;
  1932. LOG_ERROR( "Trouble with Video Output B!" );
  1933. av_strerror( rc, tB, 128 );
  1934. LOG_ERROR( tB );
  1935. break; //continue (changed since embed into do-while)
  1936. };
  1937. };
  1938. av_packet_unref( &mPacket );
  1939. };
  1940. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  1941. };
  1942. #ifdef DEBUG
  1943. LOG("Encoder Loop Ended!");
  1944. #endif
  1945. if ( m_bSegAActive ) {
  1946. m_bSegAActive = false;
  1947. av_write_trailer( m_pFormatCtxA );
  1948. avio_close( m_pFormatCtxA->pb );
  1949. };
  1950. if ( m_bSegBActive ) {
  1951. m_bSegBActive = false;
  1952. av_write_trailer( m_pFormatCtxB );
  1953. avio_close( m_pFormatCtxB->pb );
  1954. };
  1955. #ifdef DEBUG
  1956. LOG("Encoder Streams are Closed!");
  1957. #endif
  1958. };
  1959. void streamHandler::swapActiveStreams( void ){
  1960. //m_mFrameCounterProtector.lock();
  1961. if ( !m_bActiveEncoderStream ) {
  1962. m_bActiveEncoderStream = 1;
  1963. m_nVideoRegisteredDBID = 0;
  1964. // No need to continue Stream A if no Events
  1965. if ( m_bSegADelete ) closeSegmentA();
  1966. } else {
  1967. m_bActiveEncoderStream = 0;
  1968. m_nVideoRegisteredDBID = 0;
  1969. // No need to continue Stream B if no Events
  1970. if ( m_bSegBDelete ) closeSegmentB();
  1971. };
  1972. //m_mFrameCounterProtector.unlock();
  1973. };
  1974. bool streamHandler::triggerEvent( uint32_t &dbid, uint32_t &frame ){
  1975. m_mFrameCounterProtector.lock();
  1976. if ( m_nVideoRegisteredDBID == 0 ) {
  1977. LOG("New Event!");
  1978. PF_TIMESTAMP ts;
  1979. getPFTS( &ts );
  1980. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  1981. m_nVideoRegisteredDBID = argusDBC::getInstance()->addVideoRecord(
  1982. m_sStreamData.id,
  1983. m_cSegMD5A,
  1984. VIDEO_OUTPUT_CONTAINER,
  1985. ts.seconds,
  1986. ts.milliseconds,
  1987. m_sStreamData.fps
  1988. );
  1989. m_bSegADelete = false;
  1990. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  1991. } else { // Stream B is Active
  1992. m_nVideoRegisteredDBID = argusDBC::getInstance()->addVideoRecord(
  1993. m_sStreamData.id,
  1994. m_cSegMD5B,
  1995. VIDEO_OUTPUT_CONTAINER,
  1996. ts.seconds,
  1997. ts.milliseconds,
  1998. m_sStreamData.fps
  1999. );
  2000. m_bSegBDelete = false;
  2001. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  2002. };
  2003. };
  2004. if ( m_nVideoRegisteredDBID == 0 ) return false;
  2005. dbid = m_nVideoRegisteredDBID;
  2006. LOG("Event Registered!");
  2007. m_mFrameCounterProtector.unlock();
  2008. return true;
  2009. };
  2010. bool streamHandler::validate( void ){
  2011. if ( m_pSource )
  2012. #ifdef EVE_ENABLE_VIDEO
  2013. if( m_bThreadStatus < TH_ENDED )
  2014. #endif
  2015. return true;
  2016. return false;
  2017. };
  2018. #undef LOG
  2019. #undef LOG_ERROR
  2020. #undef TLOG
  2021. #undef TLOG_ERROR