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.

2209 lines
89 KiB

4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
12 months ago
4 years ago
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
4 years ago
​
​
​
​
​
​
4 years ago
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
4 years ago
​
​
​
​
​
​
​
4 years ago
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
  1. #include "rgooseModuleEmbedVideo.h"
  2. //#include "rgooseHardwareResourceNetworkProvider.h"
  3. #include "mojoKernel.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(); ) {
  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. } else idx++;
  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(0, 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_MOVE_TO:{
  746. uint32_t sid = m_pDBC->getNodeAuxParam( Evt->m_nSourceNodeID );
  747. if ( sid ) {
  748. mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find(sid);
  749. if( hnd != m_mapHANDLERS.end() ){
  750. (*hnd).second->triggerCamMove();
  751. };
  752. }
  753. break;
  754. };
  755. case EVT_CAMERA_ON_POSITION:{
  756. #ifdef DEBUG
  757. LOG("Cam On Position After Event -> Capture Picture");
  758. #endif
  759. DBC_SNAPSHOT_DATA *tData = (DBC_SNAPSHOT_DATA *) Evt->m_pEvtData;
  760. if( tData ){
  761. if( !saveStreamPicture( tData ) ) LOG_ERROR("Save Error!");
  762. tData->assoc_event_ids.clear();
  763. delete( tData );
  764. Evt->m_pEvtData = NULL;
  765. } else LOG_ERROR("No Evt Data!");
  766. break;
  767. };
  768. };
  769. break;
  770. };
  771. };
  772. };
  773. };
  774. //https://www.ps2-home.com/forum/viewtopic.php?t=98
  775. //https://www.mikekohn.net/software/playstation2.php
  776. bool argusModuleEmbedVideo::saveStreamPicture( DBC_SNAPSHOT_DATA *ptr ){
  777. if( ptr == NULL ) return false;
  778. if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){
  779. LOG("Saving Picture!");
  780. if( ptr->assoc_event_ids.size() ){
  781. if( m_mapCAPTURES.find( ptr->stream_id ) != m_mapCAPTURES.end() ){
  782. m_mPictureProtector.lock();
  783. ptr->data = (uint8_t *) malloc( m_mapCAPTURES[ptr->stream_id].size() );
  784. if( ptr->data ){
  785. ptr->data_size = m_mapCAPTURES[ptr->stream_id].size();
  786. memcpy( ptr->data, m_mapCAPTURES[ptr->stream_id].data(), ptr->data_size );
  787. m_mPictureProtector.unlock();
  788. CSTR MD5 = MD5Binary( ptr->data, ptr->data_size );
  789. if( MD5 ){
  790. strncpy( ptr->md5, MD5, 32 );
  791. free( MD5 );
  792. if( !m_pDBC->addPicture( ptr, "jpg" ) ) LOG_ERROR("Database Error to consume capture!");
  793. } else LOG_ERROR("no MD5 Hash!");
  794. free( ptr->data );
  795. } else {
  796. m_mPictureProtector.unlock();
  797. LOG_ERROR("No memory to allocate!");
  798. };
  799. #ifdef DEBUG
  800. } else {
  801. LOG("No apropriate Stream Found!");
  802. #endif
  803. };
  804. };
  805. };
  806. if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_VIDEO ){
  807. LOG("Saving Video!");
  808. if( ptr->assoc_event_ids.size() ){
  809. mapSTREAMHANDLERS::iterator hnd = m_mapHANDLERS.find( ptr->stream_id );
  810. if( hnd != m_mapHANDLERS.end() ){
  811. uint32_t db_id;
  812. uint32_t cfrm;
  813. if( (*hnd).second->triggerEvent( db_id, cfrm ) ){
  814. for( DBC_INT_LIST::iterator idx = ptr->assoc_event_ids.begin(); idx < ptr->assoc_event_ids.end(); idx++ ){
  815. m_pDBC->addVideoEvent( (*idx), db_id, cfrm );
  816. };
  817. };
  818. };
  819. };
  820. };
  821. return true;
  822. };
  823. bool argusModuleEmbedVideo::saveStreamPicture( uint32_t id ){
  824. if( !id ) return false;
  825. if( m_sEmbedVideoData.output_mode & EVE_OUTPUT_PICTURES ){
  826. if( m_mapCAPTURES.find(id) != m_mapCAPTURES.end() ){
  827. FILE * tFD;
  828. m_mPictureProtector.lock();
  829. size_t tBufferSize = m_mapCAPTURES[id].size();
  830. uint8_t * tBuffer = (uint8_t *) malloc( tBufferSize );
  831. if( tBuffer ){
  832. memcpy( tBuffer, m_mapCAPTURES[id].data(), tBufferSize );
  833. m_mPictureProtector.unlock();
  834. CSTR MD5 = MD5Binary( tBuffer, tBufferSize );
  835. if( MD5 ){
  836. char tFileName[MAX_PATH];
  837. if( generateSavePicPath( MD5, tFileName ) ){
  838. FILE *fd = fopen( tFileName, "wb+" );
  839. if( fd ){
  840. fwrite(tBuffer, 1, tBufferSize, fd );
  841. fclose(fd);
  842. chown( tFileName, "nobody", "nogroup" );
  843. //retVal = m_pDBC->addPicture( id, MD5, "jpg" );
  844. } else LOG_ERROR("Can not open picture file!");
  845. } else LOG_ERROR("Can not generate file name!");
  846. free(MD5);
  847. } else LOG_ERROR("no MD5 Hash!");
  848. free(tBuffer);
  849. } else {
  850. m_mPictureProtector.unlock();
  851. LOG_ERROR("no memory to allocate!");
  852. };
  853. };
  854. }
  855. return true;
  856. };
  857. int argusModuleEmbedVideo::getWidh( void ){
  858. if( m_sEmbedVideoData.width ) return m_sEmbedVideoData.width;
  859. return -1;
  860. };
  861. int argusModuleEmbedVideo::getHeight( void ){
  862. if( m_sEmbedVideoData.height ) return m_sEmbedVideoData.height;
  863. return -1;
  864. };
  865. bool argusModuleEmbedVideo::generateSavePicPath( CSTR MD5, CSTR Output ){
  866. if( MD5 == NULL ) return false;
  867. if( Output == NULL ) return false;
  868. if( !fileExist( m_pBaseSavePath ) ) {
  869. LOG_ERROR("No Base Picture Save Path Defined!");
  870. return false;
  871. };
  872. if( strlen(MD5) < 4 ) return false;
  873. char test[MAX_PATH];
  874. sprintf( test, "%s/%c%c", m_pBaseSavePath, MD5[0], MD5[1] );
  875. if( !fileExist( test ) ) {
  876. #ifdef __linux__
  877. mkdir( test, STORAGE_DIR_MODE );
  878. #else
  879. _mkdir( test );
  880. #endif
  881. chown( test, "nobody", "nogroup" );
  882. };
  883. sprintf( test, "%s/%c%c/%c%c", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3] );
  884. if( !fileExist( test ) ) {
  885. #ifdef __linux__
  886. mkdir( test, STORAGE_DIR_MODE );
  887. #else
  888. _mkdir( test );
  889. #endif
  890. chown( test, "nobody", "nogroup" );
  891. };
  892. sprintf( Output, "%s/%c%c/%c%c/%s.jpg", m_pBaseSavePath, MD5[0], MD5[1], MD5[2], MD5[3], MD5 );
  893. return true;
  894. };
  895. bool argusModuleEmbedVideo::registerStream( uint32_t streamID ){
  896. //Check if stream is not allready exists
  897. //for ( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ){
  898. // if ( (*idx)->CTX->mediaStreamId == streamID ) return true;
  899. //};
  900. try {
  901. streamHandler * tData = m_mapHANDLERS.at( streamID );
  902. if( tData!= NULL ) return true;
  903. } catch (const std::out_of_range& oor ) {
  904. //std::cerr << "Out of Range error: " << oor.what() << '\n';
  905. m_mapHANDLERS[streamID] = new streamHandler( this );
  906. if ( m_mapHANDLERS[streamID] != NULL ) return m_mapHANDLERS[streamID]->create( streamID );
  907. };
  908. return false;
  909. };
  910. bool argusModuleEmbedVideo::unregisterStream( uint32_t streamID ){
  911. return true;
  912. };
  913. #undef LOG
  914. #undef LOG_ERROR
  915. #define LOG( X ) streamHandler::m_pLog->Log( "MEV_STR", this, X )
  916. #ifdef DEBUG
  917. #define LOG_ERROR( X ) {\
  918. char _tBfrErrMSG2w34[256];\
  919. sprintf( _tBfrErrMSG2w34, "In file %s[%d] in func:%s %s",__FILE__, __LINE__, __func__, X );\
  920. streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
  921. }
  922. #else
  923. #define LOG_ERROR( X ) streamHandler::m_pLog->Log( "MEV_STR", this, _LOG_ERROR, X );
  924. #endif
  925. streamHandler::streamHandler( argusModuleEmbedVideo *ptr, MS_WORK_MODE M ): m_pMaster( ptr ), m_eWM( M ), basicMediaDestination() {
  926. m_pLog = basicLogCollection::getInstance( );
  927. memset( &m_sStreamData, 0, sizeof( DBC_MEDIA_STREAM_DATA ) );
  928. m_pSource = NULL;
  929. m_bEvtMarkerCounter = 0;
  930. m_bCamMoveCounter = 0;
  931. #ifdef EVE_ENABLE_VIDEO
  932. m_nPreAlarmFrames = 0;
  933. m_nPostAlarmFrames = 0;
  934. m_nSegAFrameCounter = 0;
  935. m_nSegBFrameCounter = 0;
  936. m_nGlobalFrameCounter = 0;
  937. m_nVideoRegisteredDBID = 0;
  938. m_nSegAShiftFrames = 0;
  939. m_nSegBShiftFrames = 0;
  940. m_nSegASkippedFrames = m_nSegBSkippedFrames = 0;
  941. m_nSegmentLimitFrames = 0;
  942. m_nHardLimitFrames = 0;
  943. m_bActiveEncoderStream = 0;
  944. m_bSegAActive = false;
  945. m_bSegADelete = true;
  946. m_bSegBActive = false;
  947. m_bSegBDelete = true;
  948. m_bCOP = 0;
  949. #endif //EVE_ENABLE_VIDEO
  950. };
  951. streamHandler::~streamHandler(){
  952. LOG("DESTRUCT!");
  953. if ( m_sStreamData.id ) {
  954. if (m_pMaster != NULL) m_pMaster->unregisterStream(m_sStreamData.id);
  955. if ( m_pSource != NULL ) {
  956. switch( m_sStreamData.source_type[0] ) {
  957. case 'D': delete( ( videoLIVE555Source *) m_pSource ); break;
  958. case 'A': delete( ( videoAVLIBSource *) m_pSource ); break;
  959. };
  960. };
  961. #ifdef EVE_ENABLE_VIDEO
  962. closeAll();
  963. #endif //EVE_ENABLE_VIDEO
  964. };
  965. };
  966. bool streamHandler::create( uint32_t stremID ){
  967. if( stremID ) {
  968. DBC_MEDIA_STREAM_DATA *tData = mojoDBC::getInstance()->getMediaStreamData( stremID );
  969. if ( tData ) {
  970. memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA));
  971. free(tData);
  972. DBC_CAM_DATA *tCAM = mojoDBC::getInstance()->getCamData( m_sStreamData.source_id );
  973. if( tCAM ){
  974. CSTR tNAM = mojoDBC::getInstance()->getNodeName( tCAM->node_id );
  975. m_sSourceDesc.mediaStreamId = stremID;
  976. m_sSourceDesc.mediaSourceId = m_sStreamData.source_id;
  977. if ( tNAM!= NULL ) {
  978. strncpy(m_sSourceDesc.mediaName, tNAM, 127 );
  979. m_sSourceDesc.mediaName[127] = (char)0;
  980. free( tNAM );
  981. } else {
  982. sprintf(m_sSourceDesc.mediaName, "No Name Cam");
  983. };
  984. switch( m_sStreamData.source_type[0] ) {
  985. case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource( &m_sSourceDesc ); break;
  986. case 'D': m_pSource = (basicMediaSource *) new videoLIVE555Source( &m_sSourceDesc ); break;
  987. };
  988. if( m_pSource != NULL ) {
  989. char tMRL[1024];
  990. #ifdef DEBUG
  991. LOG("Source OK");
  992. #endif
  993. int tW = m_pMaster->getWidh();
  994. int tH = m_pMaster->getHeight();
  995. int pix = -1;
  996. bool in_16_9 = (((m_sStreamData.width*100) / m_sStreamData.height ) > 140 );
  997. bool out_16_9 = (((tW*100) / tH ) > 140 );
  998. //if( tW > 0 ){
  999. // //m_pSource->setProportionalByWidth( tW );
  1000. // m_pSource->setSize( tW, tH );
  1001. //};
  1002. if( in_16_9 != out_16_9 ){
  1003. if( in_16_9 ){
  1004. tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000;
  1005. } else {
  1006. tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000;
  1007. };
  1008. };
  1009. if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) {
  1010. sprintf( tMRL, m_sStreamData.mrl );
  1011. } else {
  1012. 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 );
  1013. };
  1014. LOG( tMRL );
  1015. if( m_pSource->_open( tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH ) ){
  1016. if( !m_pSource->attachDestination( this ) ){
  1017. delete( m_pSource );
  1018. m_pSource = NULL;
  1019. } else {
  1020. #ifdef DEBUG
  1021. LOG("Source is Connected to Output.");
  1022. #endif
  1023. };
  1024. } else {
  1025. LOG_ERROR("Can not Open Video Source!");
  1026. delete( m_pSource );
  1027. m_pSource = NULL;
  1028. };
  1029. } else {
  1030. LOG_ERROR("Video Source Stream Failure!");
  1031. };
  1032. free( tCAM );
  1033. } else {
  1034. LOG_ERROR("Error Getting CAM Data!");
  1035. m_pSource = NULL;
  1036. return false;
  1037. };
  1038. };
  1039. };
  1040. if( m_pSource ){
  1041. #ifdef EVE_ENABLE_VIDEO
  1042. return initVideoOutput();
  1043. #else
  1044. return true;
  1045. #endif // EVE_ENABLE_VIDEO
  1046. };
  1047. return false;
  1048. };
  1049. bool streamHandler::pushFrame( AVFrame *Frame, void* src){
  1050. if( m_pMaster == NULL ) return false;
  1051. MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src;
  1052. if( tMD ) {
  1053. };
  1054. return true;
  1055. };
  1056. bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){
  1057. if( m_pMaster == NULL ) return false;
  1058. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  1059. char tBuffer[128];
  1060. if( tMD ) {
  1061. float mK, oK;
  1062. cv::Rect ROI;
  1063. m_pMaster->m_mPictureProtector.lock();
  1064. if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) {
  1065. LOG("First Frame Enqueued");
  1066. sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId );
  1067. LOG( tBuffer );
  1068. m_pMaster->m_mapMATS[tMD->mediaStreamId].create(
  1069. m_pMaster->m_sEmbedVideoData.height,
  1070. m_pMaster->m_sEmbedVideoData.width,
  1071. CV_8UC3
  1072. );
  1073. cv::rectangle(
  1074. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1075. cv::Point( 0, 0 ),
  1076. cv::Point(
  1077. m_pMaster->m_sEmbedVideoData.height,
  1078. m_pMaster->m_sEmbedVideoData.width
  1079. ),
  1080. cv::Scalar( 0, 0, 0 ),
  1081. cv::FILLED
  1082. );
  1083. };
  1084. #ifdef USE_SCALING_IN
  1085. oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width);
  1086. mK = ((float)Frame.rows )/ ((float)Frame.cols);
  1087. //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK );
  1088. if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) {
  1089. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1090. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1091. ROI.x = (int) 0;
  1092. ROI.y = (int) 0;
  1093. } else {
  1094. if( mK < oK ) {
  1095. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1096. ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK );
  1097. ROI.x = (int) 0;
  1098. ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1;
  1099. } else {
  1100. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1101. ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK );
  1102. ROI.y = (int) 0;
  1103. ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1;
  1104. };
  1105. };
  1106. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1107. cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR );
  1108. #else
  1109. if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){
  1110. Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] );
  1111. } else {
  1112. //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows));
  1113. //src.copyTo(dst_roi);
  1114. if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) {
  1115. ROI.width = Frame.cols;
  1116. ROI.height = Frame.rows;
  1117. ROI.x = 0;
  1118. ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1;
  1119. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1120. Frame.copyTo(mROI);
  1121. } else {
  1122. ROI.width = Frame.cols;
  1123. ROI.height = Frame.rows;
  1124. ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1;
  1125. ROI.y = 0;
  1126. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1127. Frame.copyTo(mROI);
  1128. };
  1129. };
  1130. #endif
  1131. if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) {
  1132. cv::rectangle(
  1133. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1134. cv::Rect( 10, 10, 20, 20 ),
  1135. cv::Scalar( m_bCamMoveCounter, 0, 0 ),
  1136. cv::FILLED
  1137. );
  1138. m_bCamMoveCounter -=4;
  1139. if ( m_bCamMoveCounter < 4 ) m_bCamMoveCounter = 0;
  1140. } else {
  1141. if ( m_bEvtMarkerCounter ) {
  1142. m_bCamMoveCounter = 0;
  1143. cv::rectangle(
  1144. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1145. cv::Rect( 10, 10, 20, 20 ),
  1146. cv::Scalar( 0, 0, m_bEvtMarkerCounter ),
  1147. cv::FILLED
  1148. );
  1149. m_bEvtMarkerCounter -=4;
  1150. if ( m_bEvtMarkerCounter < 4 ) m_bEvtMarkerCounter = 0;
  1151. };
  1152. };
  1153. if (m_pMaster->m_sEmbedVideoData.show_label) {
  1154. time_t t = time( NULL );
  1155. struct tm * tmp = gmtime( &t );
  1156. if( tmp ){
  1157. char tsb[64];
  1158. if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){
  1159. sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb );
  1160. int baseline=0;
  1161. cv::Size textSize = cv::getTextSize( tBuffer,
  1162. m_pMaster->m_sEmbedVideoData.label_font_face,
  1163. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1164. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1165. &baseline
  1166. );
  1167. int x = m_pMaster->m_sEmbedVideoData.label_x;
  1168. int y = m_pMaster->m_sEmbedVideoData.label_y;
  1169. if( x < 0 ) {
  1170. x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width;
  1171. };
  1172. if( y < 0 ) {
  1173. y = m_pMaster->m_sEmbedVideoData.height+y-baseline;//
  1174. };
  1175. if( !m_pMaster->m_sEmbedVideoData.label_transperant ) {
  1176. cv::rectangle(
  1177. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1178. cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ),
  1179. cv::Scalar( 0, 0, 0 ),
  1180. cv::FILLED
  1181. );
  1182. };
  1183. cv::putText(
  1184. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1185. tBuffer,
  1186. cv::Point( x, y ),
  1187. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face,
  1188. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1189. cv::Scalar( 0, 255, 0 ),
  1190. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1191. m_pMaster->m_sEmbedVideoData.label_line_type
  1192. );
  1193. };
  1194. };
  1195. } else {
  1196. if( m_pMaster->m_sEmbedVideoData.show_ts ){
  1197. time_t t = time( NULL );
  1198. struct tm * tmp = gmtime( &t );
  1199. if( tmp ){
  1200. if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){
  1201. uint8_t shift_x = 0;
  1202. uint8_t shift_y = 15;
  1203. if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) {
  1204. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1205. shift_y = 15;
  1206. cv::rectangle(
  1207. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1208. cv::Point(
  1209. m_pMaster->m_sEmbedVideoData.ts_x,
  1210. m_pMaster->m_sEmbedVideoData.ts_y
  1211. ),
  1212. cv::Point( 490, 60 ),
  1213. cv::Scalar( 0, 0, 0 ),
  1214. cv::FILLED
  1215. );
  1216. } else {
  1217. shift_y = 23;
  1218. cv::rectangle(
  1219. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1220. cv::Point(
  1221. m_pMaster->m_sEmbedVideoData.ts_x,
  1222. m_pMaster->m_sEmbedVideoData.ts_y
  1223. ),
  1224. cv::Point( 490, 60 ),
  1225. cv::Scalar( 0, 0, 0 ),
  1226. cv::FILLED
  1227. );
  1228. };
  1229. cv::putText(
  1230. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1231. tBuffer,
  1232. cv::Point(
  1233. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1234. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1235. ),
  1236. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1237. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1238. cv::Scalar( 0, 255, 255 ),
  1239. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1240. m_pMaster->m_sEmbedVideoData.ts_line_type
  1241. );
  1242. } else {
  1243. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1244. shift_y = 15;
  1245. } else {
  1246. shift_y = 23;
  1247. };
  1248. cv::putText(
  1249. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1250. tBuffer,
  1251. cv::Point(
  1252. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1253. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1254. ),
  1255. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1256. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1257. cv::Scalar( 0, 0, 0 ),
  1258. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1259. m_pMaster->m_sEmbedVideoData.ts_line_type
  1260. );
  1261. cv::putText(
  1262. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1263. tBuffer,
  1264. cv::Point(
  1265. m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1,
  1266. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1267. ),
  1268. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1269. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1270. cv::Scalar( 0, 0, 0 ),
  1271. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1272. m_pMaster->m_sEmbedVideoData.ts_line_type
  1273. );
  1274. cv::putText(
  1275. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1276. tBuffer,
  1277. cv::Point(
  1278. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1279. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1
  1280. ),
  1281. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1282. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1283. cv::Scalar( 0, 0, 0 ),
  1284. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1285. m_pMaster->m_sEmbedVideoData.ts_line_type
  1286. );
  1287. cv::putText(
  1288. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1289. tBuffer,
  1290. cv::Point(
  1291. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1292. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2
  1293. ),
  1294. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1295. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1296. cv::Scalar( 0, 0, 0 ),
  1297. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1298. m_pMaster->m_sEmbedVideoData.ts_line_type
  1299. );
  1300. cv::putText(
  1301. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1302. tBuffer,
  1303. cv::Point(
  1304. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1305. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1306. ),
  1307. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1308. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1309. cv::Scalar( 0, 255, 255 ),
  1310. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1311. m_pMaster->m_sEmbedVideoData.ts_line_type
  1312. );
  1313. }
  1314. };
  1315. };
  1316. };
  1317. };
  1318. if( m_pMaster->m_sEmbedVideoData.show_logo ){
  1319. cv::Rect roi(
  1320. cv::Point(
  1321. m_pMaster->m_sEmbedVideoData.logo_x,
  1322. m_pMaster->m_sEmbedVideoData.logo_y
  1323. ),
  1324. cv::Size(
  1325. m_pMaster->m_sEmbedVideoData.logo_w,
  1326. m_pMaster->m_sEmbedVideoData.logo_h
  1327. )
  1328. );
  1329. cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi );
  1330. m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask );
  1331. };
  1332. vector<int> compression_params;
  1333. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  1334. //compression_params.push_back(9);
  1335. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  1336. compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality );
  1337. m_pMaster->m_mEncodedProtector.lock();
  1338. m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear();
  1339. cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  1340. m_pMaster->m_mEncodedProtector.unlock();
  1341. #ifdef EVE_ENABLE_VIDEO
  1342. // encode Video Stream
  1343. //m_nPreAlarmFrames
  1344. //m_nPostAlarmFrames
  1345. //m_nNoAlarmSegmentFrames
  1346. //m_nSegmentLimitFrames
  1347. //m_nHardLimitFrames
  1348. if ( m_bSegAActive || m_bSegBActive ) {
  1349. m_mFrameCounterProtector.lock();
  1350. if( m_bSegAActive ){
  1351. do {
  1352. //In Any Case Close Stream if it Long enough
  1353. if( m_nSegAFrameCounter > m_nHardLimitFrames ){
  1354. LOG("HardLimit Reached!(A)");
  1355. closeSegmentA();
  1356. break;
  1357. };
  1358. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1359. if ( !m_bSegBActive ){
  1360. LOG("Start Alt!(A)");
  1361. openSegmentB();
  1362. };
  1363. };
  1364. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){
  1365. LOG("Swap Active!(A)");
  1366. swapActiveStreams();
  1367. break;
  1368. };
  1369. } while ( 0 );
  1370. };
  1371. if( m_bSegBActive ) {
  1372. do {
  1373. //In Any Case Close Stream if it Long enough
  1374. if( m_nSegBFrameCounter > m_nHardLimitFrames ){
  1375. LOG("HardLimit Reached!(B)");
  1376. closeSegmentB();
  1377. break;
  1378. };
  1379. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1380. if ( !m_bSegAActive ){
  1381. LOG("Start Alt!(B)");
  1382. openSegmentA();
  1383. };
  1384. };
  1385. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){
  1386. LOG("Swap Active!(B)");
  1387. swapActiveStreams();
  1388. break;
  1389. };
  1390. } while ( 0 );
  1391. };
  1392. m_mFrameCounterProtector.unlock();
  1393. /// @todo this tData pointer is never freed according to Valgrind
  1394. ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER));
  1395. if ( tData ) {
  1396. tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize();
  1397. tData->linesize[1] = 0;
  1398. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  1399. tData->size = tData->linesize[0]*tData->rows;
  1400. tData->data[1] = NULL;
  1401. tData->data[0] = (uint8_t *)malloc( tData->size );
  1402. if ( tData->data[0] ) {
  1403. memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size );
  1404. m_mEncodingQueueProtector.lock();
  1405. m_qEncodingQueue.push( tData );
  1406. m_mEncodingQueueProtector.unlock();
  1407. } else {
  1408. LOG_ERROR("MAT_CPY malloc Error!");
  1409. free( tData );
  1410. };
  1411. } else LOG_ERROR("ENC_BUF malloc Error!");
  1412. };
  1413. #endif // EVE_ENABLE_VIDEO
  1414. m_pMaster->m_mPictureProtector.unlock();
  1415. } else {
  1416. LOG_ERROR("No PayLoad!");
  1417. };
  1418. return true;
  1419. };
  1420. void streamHandler::closeSegmentA( void ){
  1421. m_mCurrentOperationProtector.lock();
  1422. if ( m_bCOP == 0 ) m_bCOP = 0x01;
  1423. m_mCurrentOperationProtector.unlock();
  1424. LOG("Closing Stream A");
  1425. };
  1426. void streamHandler::closeSegmentB( void ){
  1427. m_mCurrentOperationProtector.lock();
  1428. if ( m_bCOP == 0 ) m_bCOP = 0x02;
  1429. m_mCurrentOperationProtector.unlock();
  1430. LOG("Closing Stream B");
  1431. };
  1432. void streamHandler::closeAll(){
  1433. waitThreadEnd( true );
  1434. avcodec_send_frame( m_pCodecCtx, NULL );
  1435. int ret = 0;
  1436. AVPacket *avp = av_packet_alloc();
  1437. if ( avp ) {
  1438. do {
  1439. av_packet_unref( avp );
  1440. ret = avcodec_receive_packet( m_pCodecCtx, avp );
  1441. if ( !ret ) {
  1442. if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp );
  1443. if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp );
  1444. };
  1445. } while ( !ret );
  1446. av_packet_unref( avp );
  1447. av_packet_free( &avp );
  1448. };
  1449. if ( m_bSegAActive ) {
  1450. av_write_trailer(m_pFormatCtxA);
  1451. avformat_close_input( &m_pFormatCtxA );
  1452. m_bSegAActive = false;
  1453. };
  1454. if ( m_bSegBActive ) {
  1455. av_write_trailer(m_pFormatCtxB);
  1456. avformat_close_input( &m_pFormatCtxB );
  1457. m_bSegBActive = false;
  1458. };
  1459. };
  1460. bool streamHandler::openSegmentA( void ){
  1461. if( !m_bSegAActive ){
  1462. CSTR tAM = getUniqID_MD5();
  1463. if ( tAM ) {
  1464. sprintf( m_cSegNameA, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER );
  1465. strncpy( m_cSegMD5A, tAM, 32 );
  1466. m_cSegMD5A[32] = (char)0;
  1467. free( tAM );
  1468. #ifdef DEBUG
  1469. LOG("Opening Stream A");
  1470. LOG(m_cSegNameA);
  1471. char tB[128];
  1472. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  1473. LOG( tB );
  1474. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  1475. LOG( tB );
  1476. #endif
  1477. m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1;
  1478. if (m_pVideoStrA->nb_frames) {
  1479. m_pVideoStrA->nb_frames = 0;
  1480. m_pVideoStrA->start_time = 0;
  1481. m_pVideoStrA->first_dts = 0;
  1482. m_pFormatCtxA->start_time = 0;
  1483. };
  1484. if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  1485. LOG_ERROR("Could not open output file.");
  1486. return m_bSegAActive;
  1487. };
  1488. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  1489. LOG_ERROR("Error occurred when writing header to output file.");
  1490. return m_bSegAActive;
  1491. };
  1492. //m_mFrameCounterProtector.lock();
  1493. m_nSegAFrameCounter = 0;
  1494. m_nSegAShiftFrames = 0;
  1495. m_bSegAActive = true;
  1496. m_bSegADelete = true;
  1497. //m_mFrameCounterProtector.unlock();
  1498. #ifdef DEBUG
  1499. LOG("Stream A Opened");
  1500. #endif
  1501. };
  1502. };
  1503. return m_bSegAActive;
  1504. };
  1505. bool streamHandler::openSegmentB( void ){
  1506. if( !m_bSegBActive ){
  1507. CSTR tAM = getUniqID_MD5();
  1508. if ( tAM ) {
  1509. sprintf( m_cSegNameB, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER );
  1510. strncpy( m_cSegMD5B, tAM, 32 );
  1511. m_cSegMD5B[32] = (char)0;
  1512. free( tAM );
  1513. #ifdef DEBUG
  1514. LOG("Opening Stream B");
  1515. LOG(m_cSegNameB);
  1516. char tB[128];
  1517. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts );
  1518. LOG( tB );
  1519. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration );
  1520. LOG( tB );
  1521. #endif
  1522. m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1;
  1523. if (m_pVideoStrB->nb_frames) {
  1524. m_pVideoStrB->nb_frames = 0;
  1525. m_pVideoStrB->start_time = 0;
  1526. m_pVideoStrB->first_dts = 0;
  1527. m_pFormatCtxB->start_time = 0;
  1528. };
  1529. if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  1530. LOG_ERROR("Could not open output file.");
  1531. return m_bSegBActive;
  1532. };
  1533. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  1534. LOG_ERROR("Error occurred when writing header to output file.");
  1535. return m_bSegBActive;
  1536. };
  1537. //m_mFrameCounterProtector.lock();
  1538. m_nSegBFrameCounter = 0;
  1539. m_nSegBShiftFrames = 0;
  1540. m_bSegBActive = true;
  1541. m_bSegBDelete = true;
  1542. //m_mFrameCounterProtector.unlock();
  1543. #ifdef DEBUG
  1544. LOG("Stream B Opened");
  1545. #endif
  1546. };
  1547. };
  1548. return m_bSegBActive;
  1549. };
  1550. bool streamHandler::initVideoOutput(){
  1551. m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1552. m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1553. m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1554. m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1555. if( !initLibAV() ) return false;
  1556. m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL );
  1557. if ( m_pFormat == NULL ) {
  1558. LOG_ERROR("Out VideoFormat Not Found!");
  1559. return false;
  1560. #ifdef DEBUG
  1561. } else {
  1562. LOG("Output video Format");
  1563. LOG( VIDEO_OUTPUT_CONTAINER );
  1564. #endif
  1565. };
  1566. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1567. LOG_ERROR("Format CTX A alloc error!");
  1568. av_free( m_pFormat );
  1569. return false;
  1570. } else {
  1571. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  1572. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1573. };
  1574. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1575. LOG_ERROR("Format CTX B alloc error!");
  1576. avformat_free_context( m_pFormatCtxA );
  1577. //av_free( m_pFormat );
  1578. return false;
  1579. } else {
  1580. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  1581. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1582. };
  1583. m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  1584. if( m_pVideoCodec == NULL ){
  1585. LOG_ERROR("Out VideoCodec Not Found!");
  1586. avformat_free_context( m_pFormatCtxA );
  1587. avformat_free_context( m_pFormatCtxB );
  1588. //av_free( m_pFormat );
  1589. return false;
  1590. #ifdef DEBUG
  1591. } else {
  1592. LOG("Out Video Codec Found");
  1593. #endif
  1594. };
  1595. m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec );
  1596. if ( m_pCodecCtx == NULL){
  1597. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  1598. av_free( m_pVideoCodec );
  1599. avformat_free_context( m_pFormatCtxA );
  1600. avformat_free_context( m_pFormatCtxB );
  1601. //av_free( m_pFormat );
  1602. return false;
  1603. #ifdef DEBUG
  1604. } else {
  1605. LOG("Out Codec Context3 Allocated");
  1606. #endif
  1607. };
  1608. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec );
  1609. if ( m_pVideoStrA == NULL){
  1610. LOG_ERROR("VideoStream A Not Created!");
  1611. avcodec_free_context( &m_pCodecCtx );
  1612. av_free( m_pCodecCtx );
  1613. av_free( m_pVideoCodec );
  1614. avformat_free_context( m_pFormatCtxA );
  1615. avformat_free_context( m_pFormatCtxB );
  1616. //av_free( m_pFormat );
  1617. return false;
  1618. #ifdef DEBUG
  1619. } else {
  1620. LOG("VideoStream A is Created");
  1621. #endif
  1622. };
  1623. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec );
  1624. if ( m_pVideoStrB == NULL){
  1625. LOG_ERROR("VideoStream B Not Created!");
  1626. avcodec_free_context( &m_pCodecCtx );
  1627. av_free( m_pCodecCtx );
  1628. av_free( m_pVideoCodec );
  1629. avformat_free_context( m_pFormatCtxA );
  1630. avformat_free_context( m_pFormatCtxB );
  1631. av_free( m_pFormat );
  1632. return false;
  1633. #ifdef DEBUG
  1634. } else {
  1635. LOG("VideoStream B is Created");
  1636. #endif
  1637. };
  1638. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  1639. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  1640. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1641. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  1642. //m_pCodecCtx->thread_count = 1;
  1643. //m_pCodecCtx->bit_rate_tolerance = 1;
  1644. //m_pCodecCtx->global_quality = 100;
  1645. //m_pCodecCtx->compression_level = 2;
  1646. m_pCodecCtx->max_b_frames=1;
  1647. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  1648. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  1649. m_pCodecCtx->time_base.num = 1;
  1650. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  1651. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  1652. m_pCodecCtx->framerate.den = 1;
  1653. //https://pastebin.com/yG37YhWW
  1654. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  1655. //G@ avcodec encode NALU mp4
  1656. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  1657. m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  1658. #endif
  1659. m_pFormatOpts = NULL;
  1660. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  1661. if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){
  1662. #ifdef DEBUG
  1663. LOG("Begin Options!");
  1664. #endif
  1665. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  1666. //Set format's privater options, to be passed to avformat_write_header()
  1667. /*
  1668. mp4 muxer AVOptions:
  1669. -movflags E..... MOV muxer flags (default 0)
  1670. rtphint E..... Add RTP hint tracks
  1671. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  1672. frag_keyframe E..... Fragment at video keyframes
  1673. separate_moof E..... Write separate moof/mdat atoms for each track
  1674. frag_custom E..... Flush fragments on caller requests
  1675. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  1676. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  1677. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  1678. delay_moov ??
  1679. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  1680. -rtpflags E..... RTP muxer flags (default 0)
  1681. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  1682. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  1683. skip_rtcp E..... Don't send RTCP sender reports
  1684. h264_mode0 E..... Use mode 0 for H264 in RTP
  1685. send_bye E..... Send RTCP BYE packets when finishing
  1686. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  1687. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  1688. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  1689. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  1690. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  1691. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  1692. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  1693. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  1694. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  1695. */
  1696. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  1697. LOG_ERROR( "av_dict_set movflags!");
  1698. #ifdef DEBUG
  1699. } else {
  1700. LOG("MOV FLAG SET!");
  1701. #endif
  1702. };
  1703. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  1704. // LOG_ERROR( "av_dict_set live!" );
  1705. //};
  1706. //default brand is "isom", which fails on some devices
  1707. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  1708. LOG_ERROR( "av_dict_set brand!" );
  1709. };
  1710. //m_pCodecCtx->max_b_frames = 1;
  1711. //m_pCodecCtx->level = 31;
  1712. m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  1713. /// P-frames, generated by referencing data from prev and future frames.
  1714. /// [Compression up, CPU usage up]
  1715. /// [use 3/gop]
  1716. m_pCodecCtx->max_b_frames = 5;
  1717. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  1718. /// [use 3�5 ref per P]
  1719. m_pCodecCtx->refs = 3;
  1720. /// Compression efficiency (slower -> better quality + higher cpu%)
  1721. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  1722. /// Set this option to "ultrafast" is critical for realtime encoding
  1723. av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  1724. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  1725. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  1726. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  1727. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  1728. av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0);
  1729. /// Change settings based upon the specifics of input
  1730. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  1731. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  1732. av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  1733. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  1734. /// Because Quicktime (ie. iOS) doesn't support this option
  1735. av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
  1736. #ifdef DEBUG
  1737. LOG("End Options!");
  1738. #endif
  1739. } else {
  1740. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1741. };
  1742. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  1743. #ifdef DEBUG
  1744. char TB[129];
  1745. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den );
  1746. LOG(TB);
  1747. #endif
  1748. m_pVideoStrA->time_base = m_pCodecCtx->time_base;
  1749. m_pVideoStrB->time_base = m_pCodecCtx->time_base;
  1750. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  1751. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1752. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1753. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1754. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1755. m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1756. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  1757. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1758. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1759. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1760. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1761. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1762. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1763. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1764. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx );
  1765. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1766. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  1767. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1768. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx );
  1769. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1770. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  1771. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1772. if ( avcodec_is_open( m_pCodecCtx ) == 0 ) {
  1773. LOG("output codec context is closed, opening");
  1774. if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) {
  1775. LOG_ERROR("Error opening2 encoder");
  1776. return false;
  1777. #ifdef DEBUG
  1778. } else {
  1779. LOG("output codec context is opened");
  1780. };
  1781. #endif
  1782. #ifdef DEBUG
  1783. } else {
  1784. LOG("output codec context is already opened");
  1785. #endif
  1786. };
  1787. m_pConvertCtx = sws_getContext(
  1788. m_pMaster->m_sEmbedVideoData.width,
  1789. m_pMaster->m_sEmbedVideoData.height,
  1790. AV_PIX_FMT_BGR24,
  1791. m_pMaster->m_sEmbedVideoData.width,
  1792. m_pMaster->m_sEmbedVideoData.height,
  1793. VIDEO_OUTPUT_PIX_FMT,
  1794. SWS_FAST_BILINEAR,
  1795. NULL,
  1796. NULL,
  1797. NULL
  1798. );
  1799. if ( m_pConvertCtx == NULL ) {
  1800. return false;
  1801. }
  1802. m_pAVFrame = av_frame_alloc();
  1803. if ( m_pAVFrame == NULL ) {
  1804. return false;
  1805. };
  1806. 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));
  1807. if( m_pOutBuffer == NULL ) {
  1808. return false;
  1809. };
  1810. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  1811. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  1812. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  1813. //av_frame_get_buffer( m_pAVFrame, 0 );
  1814. 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 );
  1815. //av_frame_make_writable( m_pAVFrame );
  1816. return init();
  1817. };
  1818. //encoding thread
  1819. void streamHandler::m_fThreadProc( void ){
  1820. AVPacket mPacket;
  1821. int bGotPacket;
  1822. int rVal = 0;
  1823. char tB[128];
  1824. av_init_packet( &mPacket );
  1825. while( m_bThreadStatus != TH_ENDED ){
  1826. //At the begining All streams are closed --> try to Open
  1827. if( m_bThreadStatus < TH_WORKING ){
  1828. if( !openSegmentA() ){
  1829. m_bThreadStatus = TH_ENDED;
  1830. continue;
  1831. };
  1832. //if( !openSegmentB() ){
  1833. // m_bThreadStatus = TH_ENDED;
  1834. // continue;
  1835. //};
  1836. m_bThreadStatus = TH_WORKING;
  1837. continue;
  1838. };
  1839. m_mEncodingQueueProtector.lock();
  1840. if ( m_qEncodingQueue.size() ) {
  1841. ENCODING_BUFFER *tData = m_qEncodingQueue.front();
  1842. if( tData ){
  1843. //av_frame_make_writable( m_pAVFrame );
  1844. sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize );
  1845. free( tData->data[0] );
  1846. free( tData );
  1847. m_qEncodingQueue.pop();
  1848. /*
  1849. AV_PICTURE_TYPE_NONE Undefined.
  1850. AV_PICTURE_TYPE_I Intra.
  1851. AV_PICTURE_TYPE_P Predicted.
  1852. AV_PICTURE_TYPE_B Bi-dir predicted.
  1853. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4.
  1854. AV_PICTURE_TYPE_SI Switching Intra.
  1855. AV_PICTURE_TYPE_SP Switching Predicted.
  1856. AV_PICTURE_TYPE_BI BI type.
  1857. */
  1858. if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) {
  1859. m_pAVFrame->key_frame = 1;
  1860. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I;
  1861. } else {
  1862. m_pAVFrame->key_frame = 0;
  1863. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
  1864. };
  1865. m_pAVFrame->pts = m_nGlobalFrameCounter + 1;
  1866. rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame );
  1867. m_mFrameCounterProtector.lock();
  1868. m_nGlobalFrameCounter++;
  1869. if ( m_bSegAActive ) m_nSegAFrameCounter++;
  1870. if ( m_bSegBActive ) m_nSegBFrameCounter++;
  1871. m_mFrameCounterProtector.unlock();
  1872. };
  1873. m_mEncodingQueueProtector.unlock();
  1874. } else {
  1875. m_mEncodingQueueProtector.unlock();
  1876. // If No Encode Job -> Test Commands!
  1877. m_mCurrentOperationProtector.lock();
  1878. switch ( m_bCOP ) {
  1879. case 0x01:{
  1880. m_bSegAActive = false;
  1881. if ( !m_bSegADelete ) {
  1882. av_write_trailer( m_pFormatCtxA );
  1883. avio_close( m_pFormatCtxA->pb );
  1884. #ifdef DEBUG
  1885. LOG("Stream A is Closed");
  1886. #endif
  1887. } else {
  1888. #ifdef EVE_DONT_DELETE_SEGMENTS
  1889. av_write_trailer( m_pFormatCtxA );
  1890. #endif
  1891. avio_close( m_pFormatCtxA->pb );
  1892. #ifndef EVE_DONT_DELETE_SEGMENTS
  1893. unlink( m_cSegNameA );
  1894. #endif
  1895. #ifdef DEBUG
  1896. LOG("Stream A is Deleted!");
  1897. #endif
  1898. };
  1899. break;
  1900. };
  1901. case 0x02:{
  1902. m_bSegBActive = false;
  1903. if ( !m_bSegBDelete ) {
  1904. av_write_trailer( m_pFormatCtxB );
  1905. avio_close( m_pFormatCtxB->pb );
  1906. #ifdef DEBUG
  1907. LOG("Stream B is Closed");
  1908. #endif
  1909. } else {
  1910. #ifdef EVE_DONT_DELETE_SEGMENTS
  1911. av_write_trailer( m_pFormatCtxB );
  1912. #endif
  1913. avio_close( m_pFormatCtxB->pb );
  1914. #ifndef EVE_DONT_DELETE_SEGMENTS
  1915. unlink( m_cSegNameB );
  1916. #endif
  1917. #ifdef DEBUG
  1918. LOG("Stream B is Deleted!");
  1919. #endif
  1920. };
  1921. break;
  1922. };
  1923. };
  1924. m_bCOP = 0;
  1925. m_mCurrentOperationProtector.unlock();
  1926. };
  1927. do {
  1928. mPacket.data = NULL;
  1929. mPacket.size = 0;
  1930. rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket );
  1931. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  1932. break;
  1933. } else if( rVal < 0 ){
  1934. LOG_ERROR( "Error during encoding " );
  1935. m_bThreadStatus = TH_ENDED;
  1936. break;
  1937. };
  1938. if( !rVal ){
  1939. if ( m_bSegAActive ) {
  1940. mPacket.stream_index = m_pVideoStrA->index;
  1941. mPacket.duration = 1;
  1942. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1943. //mPacket.pts = AV_NOPTS_VALUE;
  1944. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1945. mPacket.dts = mPacket.pts;
  1946. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  1947. if( rc < 0 ){
  1948. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  1949. m_bThreadStatus = TH_ENDED;
  1950. LOG_ERROR("Trouble with Video Output A!");
  1951. av_strerror( rc, tB, 128 );
  1952. LOG_ERROR( tB );
  1953. break; //continue (changed since embed into do-while)
  1954. };
  1955. };
  1956. if ( m_bSegBActive ) {
  1957. mPacket.stream_index = m_pVideoStrB->index;
  1958. mPacket.duration = 1;
  1959. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1960. //mPacket.pts = AV_NOPTS_VALUE;
  1961. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  1962. mPacket.dts = mPacket.pts;
  1963. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  1964. if( rc < 0 ) {
  1965. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  1966. m_bThreadStatus = TH_ENDED;
  1967. LOG_ERROR( "Trouble with Video Output B!" );
  1968. av_strerror( rc, tB, 128 );
  1969. LOG_ERROR( tB );
  1970. break; //continue (changed since embed into do-while)
  1971. };
  1972. };
  1973. av_packet_unref( &mPacket );
  1974. };
  1975. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  1976. };
  1977. #ifdef DEBUG
  1978. LOG("Encoder Loop Ended!");
  1979. #endif
  1980. if ( m_bSegAActive ) {
  1981. m_bSegAActive = false;
  1982. av_write_trailer( m_pFormatCtxA );
  1983. avio_close( m_pFormatCtxA->pb );
  1984. };
  1985. if ( m_bSegBActive ) {
  1986. m_bSegBActive = false;
  1987. av_write_trailer( m_pFormatCtxB );
  1988. avio_close( m_pFormatCtxB->pb );
  1989. };
  1990. #ifdef DEBUG
  1991. LOG("Encoder Streams are Closed!");
  1992. #endif
  1993. };
  1994. void streamHandler::swapActiveStreams( void ){
  1995. //m_mFrameCounterProtector.lock();
  1996. if ( !m_bActiveEncoderStream ) {
  1997. m_bActiveEncoderStream = 1;
  1998. m_nVideoRegisteredDBID = 0;
  1999. // No need to continue Stream A if no Events
  2000. if ( m_bSegADelete ) closeSegmentA();
  2001. } else {
  2002. m_bActiveEncoderStream = 0;
  2003. m_nVideoRegisteredDBID = 0;
  2004. // No need to continue Stream B if no Events
  2005. if ( m_bSegBDelete ) closeSegmentB();
  2006. };
  2007. //m_mFrameCounterProtector.unlock();
  2008. };
  2009. bool streamHandler::triggerEvent( uint32_t &dbid, uint32_t &frame ){
  2010. m_mFrameCounterProtector.lock();
  2011. // To Mark Events Frames
  2012. m_bEvtMarkerCounter = 255;
  2013. if ( m_nVideoRegisteredDBID == 0 ) {
  2014. LOG("New Event!");
  2015. PF_TIMESTAMP ts;
  2016. getPFTS( &ts );
  2017. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  2018. m_nVideoRegisteredDBID = mojoDBC::getInstance()->addVideoRecord(
  2019. m_sStreamData.id,
  2020. m_cSegMD5A,
  2021. VIDEO_OUTPUT_CONTAINER,
  2022. ts.seconds,
  2023. ts.milliseconds,
  2024. m_sStreamData.fps
  2025. );
  2026. m_bSegADelete = false;
  2027. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  2028. } else { // Stream B is Active
  2029. m_nVideoRegisteredDBID = mojoDBC::getInstance()->addVideoRecord(
  2030. m_sStreamData.id,
  2031. m_cSegMD5B,
  2032. VIDEO_OUTPUT_CONTAINER,
  2033. ts.seconds,
  2034. ts.milliseconds,
  2035. m_sStreamData.fps
  2036. );
  2037. m_bSegBDelete = false;
  2038. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  2039. };
  2040. };
  2041. if ( m_nVideoRegisteredDBID == 0 ) return false;
  2042. dbid = m_nVideoRegisteredDBID;
  2043. LOG("Event Registered!");
  2044. m_mFrameCounterProtector.unlock();
  2045. return true;
  2046. };
  2047. bool streamHandler::triggerCamMove( void ){
  2048. m_bCamMoveCounter = 255;
  2049. return true;
  2050. };
  2051. bool streamHandler::validate( void ){
  2052. if ( m_pSource )
  2053. #ifdef EVE_ENABLE_VIDEO
  2054. if( m_bThreadStatus < TH_ENDED )
  2055. #endif
  2056. return true;
  2057. return false;
  2058. };
  2059. #undef LOG
  2060. #undef LOG_ERROR
  2061. #undef TLOG
  2062. #undef TLOG_ERROR