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.

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