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.

2211 lines
90 KiB

4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #include "kernelModuleEmbedVideo.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 ) kernelModule::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. kernelModule::m_pLog->Log( "MOD_EVIDEO", this, _LOG_ERROR, _tBfrErrMSG2w34 );\
  36. }
  37. #else
  38. #define LOG_ERROR( X ) kernelModule::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. kernelModuleEmbedVideo::kernelModuleEmbedVideo( uint32_t moduleID ): kernelModule( moduleID, KERNEL_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. kernelModuleEmbedVideo::~kernelModuleEmbedVideo(){
  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 *kernelModuleEmbedVideo::webClientProc( void *ptr ){
  146. WEB_CLIENT_CTX * CTX = (WEB_CLIENT_CTX *) ptr;
  147. kernelModuleEmbedVideo * 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 kernelModuleEmbedVideo::m_fThreadProc( void ){
  366. if( !m_bEnabled ) {
  367. #ifdef DEBUG
  368. LOG("Module is Disabled!");
  369. #endif
  370. return;
  371. };
  372. #ifdef DEBUG
  373. LOG("Module Started!");
  374. #endif
  375. struct pollfd pfd[1];
  376. pfd->fd = m_nSocketDescriptor;
  377. pfd->events = POLLIN | POLLHUP;
  378. m_bThreadStatus = TH_WORKING;
  379. while( m_bThreadStatus < TH_ENDED ) {
  380. if( !m_bEnabled ) {
  381. m_bThreadStatus = TH_ENDED;
  382. continue;
  383. };
  384. int RetVal = poll( pfd, 1, 1000 );
  385. if( RetVal < 0 ){
  386. if( EINTR == errno ) continue;
  387. LOG_ERROR("Unrecoverable error");
  388. m_bThreadStatus = TH_ENDED;
  389. continue;
  390. };
  391. // Handle Connections
  392. if( RetVal != 0 ){
  393. if ( pfd[0].revents & POLLIN ) {
  394. #ifdef DEBUG_EXTRA
  395. LOG("Handle New Client");
  396. #endif
  397. int tSID = accept( pfd[0].fd, NULL, NULL);
  398. if( tSID < 0 ){
  399. char tBuf[CTEXT];
  400. sprintf(tBuf, "Accept() error: %s", strerror(errno));
  401. LOG_ERROR(tBuf);
  402. } else {
  403. #ifdef DEBUG_EXTRA
  404. LOG("Accept OK");
  405. #endif
  406. WEB_CLIENT_CTX *tCTX = (WEB_CLIENT_CTX *) malloc(sizeof(WEB_CLIENT_CTX));
  407. if( tCTX ) {
  408. #ifdef DEBUG_EXTRA
  409. LOG("CTX OK");
  410. #endif
  411. WEB_HANDLER *tHANDLER = (WEB_HANDLER *) malloc(sizeof(WEB_HANDLER));
  412. if( tHANDLER ) {
  413. #ifdef DEBUG_EXTRA
  414. LOG("HANDLER OK");
  415. #endif
  416. memset( tCTX, 0, sizeof(WEB_CLIENT_CTX) );
  417. memset( tHANDLER, 0, sizeof(WEB_HANDLER) );
  418. tCTX->m_iSocketFID = tSID;
  419. tCTX->m_iEncoderPipe[0] = -1;
  420. tCTX->m_iEncoderPipe[1] = -1;
  421. tCTX->mediaStreamId = 0;
  422. tCTX->bValid = true;
  423. tCTX->ModulePtr = this;
  424. #ifdef DEBUG_EXTRA
  425. LOG("Before Thread Create");
  426. #endif
  427. int RetVal = pthread_create( &tHANDLER->m_hThreadHandle, NULL, webClientProc, ( void * ) tCTX );
  428. if( RetVal == -1 ) {
  429. free(tCTX);
  430. free(tHANDLER);
  431. LOG_ERROR("Thread Creation Faled.");
  432. shutdown( tSID, SHUT_RDWR );
  433. close( tSID );
  434. } else {
  435. tHANDLER->CTX = tCTX;
  436. m_mHandlersProtector.lock();
  437. m_vHandlersPool.push_back( tHANDLER );
  438. m_mHandlersProtector.unlock();
  439. #ifdef DEBUG_EXTRA
  440. LOG("Handler Pushed to a Pool");
  441. #endif
  442. };
  443. } else { //https://stackoverflow.com/questions/18545077/image-fullscreen-on-click
  444. free(tCTX);
  445. LOG_ERROR("CL_HANDLER Mem Allocation Failure!");
  446. shutdown( tSID, SHUT_RDWR );
  447. close( tSID );
  448. };
  449. } else {
  450. LOG_ERROR("CL_CTX Mem Allocation Failure!");
  451. shutdown( tSID, SHUT_RDWR );
  452. close( tSID );
  453. };
  454. };
  455. };
  456. };
  457. // Handle Dead Clients
  458. if( m_vHandlersPool.size() ) {
  459. for( vectorHANDLERS::iterator idx = m_vHandlersPool.begin(); idx < m_vHandlersPool.end(); idx++ ) {
  460. if( !( (*idx)->CTX->bValid ) ) {
  461. pthread_join( (*idx)->m_hThreadHandle, NULL );
  462. //close( (*idx)->CTX->m_iEncoderPipe[0] );
  463. close( (*idx)->CTX->m_iEncoderPipe[1] );
  464. free( (*idx)->CTX );
  465. free( (*idx) );
  466. m_mHandlersProtector.lock();
  467. m_vHandlersPool.erase(idx);
  468. m_mHandlersProtector.unlock();
  469. #ifdef DEBUG_EXTRA
  470. LOG("Web Handler Ripped!");
  471. #endif
  472. };
  473. };
  474. };
  475. // validate active streams ?
  476. SLEEP( 50 );
  477. };
  478. };
  479. #define ENABLE_SOCKOPT(sd, level, opt) \
  480. do { \
  481. int val = 1; \
  482. if (setsockopt(sd, level, opt, &val, sizeof(val)) < 0) \
  483. warn("Failed enabling %s for web service", #opt); \
  484. } while (0);
  485. bool kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::getWidh( void ){
  858. if( m_sEmbedVideoData.width ) return m_sEmbedVideoData.width;
  859. return -1;
  860. };
  861. int kernelModuleEmbedVideo::getHeight( void ){
  862. if( m_sEmbedVideoData.height ) return m_sEmbedVideoData.height;
  863. return -1;
  864. };
  865. bool kernelModuleEmbedVideo::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 kernelModuleEmbedVideo::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( m_pDBC, streamID );
  907. };
  908. return false;
  909. };
  910. bool kernelModuleEmbedVideo::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( kernelModuleEmbedVideo *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( dataBinder *ptr, uint32_t stremID ){
  967. if ( ptr == NULL ) return false;
  968. m_pDBC = ptr;
  969. if (stremID) {
  970. DBC_MEDIA_STREAM_DATA *tData = m_pDBC->getMediaStreamData( stremID );
  971. if ( tData ) {
  972. memcpy( &m_sStreamData, tData, sizeof(DBC_MEDIA_STREAM_DATA));
  973. free(tData);
  974. DBC_CAM_DATA *tCAM = m_pDBC->getCamData( m_sStreamData.source_id );
  975. if( tCAM ){
  976. CSTR tNAM = m_pDBC->getNodeName( tCAM->node_id );
  977. m_sSourceDesc.mediaStreamId = stremID;
  978. m_sSourceDesc.mediaSourceId = m_sStreamData.source_id;
  979. if ( tNAM!= NULL ) {
  980. strncpy(m_sSourceDesc.mediaName, tNAM, 127 );
  981. m_sSourceDesc.mediaName[127] = (char)0;
  982. free( tNAM );
  983. } else {
  984. sprintf(m_sSourceDesc.mediaName, "No Name Cam");
  985. };
  986. switch( m_sStreamData.source_type[0] ) {
  987. case 'A': m_pSource = (basicMediaSource *) new videoAVLIBSource( &m_sSourceDesc ); break;
  988. case 'D': m_pSource = (basicMediaSource *) new videoLIVE555Source( &m_sSourceDesc ); break;
  989. };
  990. if( m_pSource != NULL ) {
  991. char tMRL[1024];
  992. #ifdef DEBUG
  993. LOG("Source OK");
  994. #endif
  995. int tW = m_pMaster->getWidh();
  996. int tH = m_pMaster->getHeight();
  997. int pix = -1;
  998. bool in_16_9 = (((m_sStreamData.width*100) / m_sStreamData.height ) > 140 );
  999. bool out_16_9 = (((tW*100) / tH ) > 140 );
  1000. //if( tW > 0 ){
  1001. // //m_pSource->setProportionalByWidth( tW );
  1002. // m_pSource->setSize( tW, tH );
  1003. //};
  1004. if( in_16_9 != out_16_9 ){
  1005. if( in_16_9 ){
  1006. tH = ((( tW * 1000 ) / 16 ) * 9 ) / 1000;
  1007. } else {
  1008. tW = ((( tH * 1000 ) / 3 ) * 4 ) / 1000;
  1009. };
  1010. };
  1011. //export PATH=/usr/sbin:$PATH
  1012. if (strncmp( m_sStreamData.mrl_proto, "v4l2", 4) == 0) {
  1013. sprintf( tMRL, m_sStreamData.mrl );
  1014. } else {
  1015. 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 );
  1016. };
  1017. LOG( tMRL );
  1018. if( m_pSource->_open( tMRL, false, -1.0f, pix, m_sStreamData.width, m_sStreamData.height, tW, tH ) ){
  1019. if( !m_pSource->attachDestination( this ) ){
  1020. delete( m_pSource );
  1021. m_pSource = NULL;
  1022. } else {
  1023. #ifdef DEBUG
  1024. LOG("Source is Connected to Output.");
  1025. #endif
  1026. };
  1027. } else {
  1028. LOG_ERROR("Can not Open Video Source!");
  1029. delete( m_pSource );
  1030. m_pSource = NULL;
  1031. };
  1032. } else {
  1033. LOG_ERROR("Video Source Stream Failure!");
  1034. };
  1035. free( tCAM );
  1036. } else {
  1037. LOG_ERROR("Error Getting CAM Data!");
  1038. m_pSource = NULL;
  1039. return false;
  1040. };
  1041. };
  1042. };
  1043. if( m_pSource ){
  1044. #ifdef EVE_ENABLE_VIDEO
  1045. return initVideoOutput();
  1046. #else
  1047. return true;
  1048. #endif // EVE_ENABLE_VIDEO
  1049. };
  1050. return false;
  1051. };
  1052. bool streamHandler::pushFrame( AVFrame *Frame, void* src){
  1053. if( m_pMaster == NULL ) return false;
  1054. MEDIA_SOURCE_DESC *tMD = (MEDIA_SOURCE_DESC *)src;
  1055. if( tMD ) {
  1056. };
  1057. return true;
  1058. };
  1059. bool streamHandler::pushFrame( cv::Mat &Frame, void* src ){
  1060. if( m_pMaster == NULL ) return false;
  1061. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  1062. char tBuffer[128];
  1063. if( tMD ) {
  1064. float mK, oK;
  1065. cv::Rect ROI;
  1066. m_pMaster->m_mPictureProtector.lock();
  1067. if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) {
  1068. LOG("First Frame Enqueued");
  1069. sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId );
  1070. LOG( tBuffer );
  1071. m_pMaster->m_mapMATS[tMD->mediaStreamId].create(
  1072. m_pMaster->m_sEmbedVideoData.height,
  1073. m_pMaster->m_sEmbedVideoData.width,
  1074. CV_8UC3
  1075. );
  1076. cv::rectangle(
  1077. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1078. cv::Point( 0, 0 ),
  1079. cv::Point(
  1080. m_pMaster->m_sEmbedVideoData.height,
  1081. m_pMaster->m_sEmbedVideoData.width
  1082. ),
  1083. cv::Scalar( 0, 0, 0 ),
  1084. cv::FILLED
  1085. );
  1086. };
  1087. #ifdef USE_SCALING_IN
  1088. oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width);
  1089. mK = ((float)Frame.rows )/ ((float)Frame.cols);
  1090. //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK );
  1091. if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) {
  1092. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1093. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1094. ROI.x = (int) 0;
  1095. ROI.y = (int) 0;
  1096. } else {
  1097. if( mK < oK ) {
  1098. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1099. ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK );
  1100. ROI.x = (int) 0;
  1101. ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1;
  1102. } else {
  1103. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1104. ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK );
  1105. ROI.y = (int) 0;
  1106. ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1;
  1107. };
  1108. };
  1109. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1110. cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR );
  1111. #else
  1112. if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){
  1113. Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] );
  1114. } else {
  1115. //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows));
  1116. //src.copyTo(dst_roi);
  1117. if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) {
  1118. ROI.width = Frame.cols;
  1119. ROI.height = Frame.rows;
  1120. ROI.x = 0;
  1121. ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1;
  1122. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1123. Frame.copyTo(mROI);
  1124. } else {
  1125. ROI.width = Frame.cols;
  1126. ROI.height = Frame.rows;
  1127. ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1;
  1128. ROI.y = 0;
  1129. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1130. Frame.copyTo(mROI);
  1131. };
  1132. };
  1133. #endif
  1134. if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) {
  1135. cv::rectangle(
  1136. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1137. cv::Rect( 10, 10, 20, 20 ),
  1138. cv::Scalar( m_bCamMoveCounter, 0, 0 ),
  1139. cv::FILLED
  1140. );
  1141. m_bCamMoveCounter -=4;
  1142. if ( m_bCamMoveCounter < 4 ) m_bCamMoveCounter = 0;
  1143. } else {
  1144. if ( m_bEvtMarkerCounter ) {
  1145. m_bCamMoveCounter = 0;
  1146. cv::rectangle(
  1147. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1148. cv::Rect( 10, 10, 20, 20 ),
  1149. cv::Scalar( 0, 0, m_bEvtMarkerCounter ),
  1150. cv::FILLED
  1151. );
  1152. m_bEvtMarkerCounter -=4;
  1153. if ( m_bEvtMarkerCounter < 4 ) m_bEvtMarkerCounter = 0;
  1154. };
  1155. };
  1156. if (m_pMaster->m_sEmbedVideoData.show_label) {
  1157. time_t t = time( NULL );
  1158. struct tm * tmp = gmtime( &t );
  1159. if( tmp ){
  1160. char tsb[64];
  1161. if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){
  1162. sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb );
  1163. int baseline=0;
  1164. cv::Size textSize = cv::getTextSize( tBuffer,
  1165. m_pMaster->m_sEmbedVideoData.label_font_face,
  1166. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1167. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1168. &baseline
  1169. );
  1170. int x = m_pMaster->m_sEmbedVideoData.label_x;
  1171. int y = m_pMaster->m_sEmbedVideoData.label_y;
  1172. if( x < 0 ) {
  1173. x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width;
  1174. };
  1175. if( y < 0 ) {
  1176. y = m_pMaster->m_sEmbedVideoData.height+y-baseline;//
  1177. };
  1178. if( !m_pMaster->m_sEmbedVideoData.label_transperant ) {
  1179. cv::rectangle(
  1180. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1181. cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ),
  1182. cv::Scalar( 0, 0, 0 ),
  1183. cv::FILLED
  1184. );
  1185. };
  1186. cv::putText(
  1187. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1188. tBuffer,
  1189. cv::Point( x, y ),
  1190. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face,
  1191. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1192. cv::Scalar( 0, 255, 0 ),
  1193. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1194. m_pMaster->m_sEmbedVideoData.label_line_type
  1195. );
  1196. };
  1197. };
  1198. } else {
  1199. if( m_pMaster->m_sEmbedVideoData.show_ts ){
  1200. time_t t = time( NULL );
  1201. struct tm * tmp = gmtime( &t );
  1202. if( tmp ){
  1203. if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){
  1204. uint8_t shift_x = 0;
  1205. uint8_t shift_y = 15;
  1206. if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) {
  1207. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1208. shift_y = 15;
  1209. cv::rectangle(
  1210. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1211. cv::Point(
  1212. m_pMaster->m_sEmbedVideoData.ts_x,
  1213. m_pMaster->m_sEmbedVideoData.ts_y
  1214. ),
  1215. cv::Point( 490, 60 ),
  1216. cv::Scalar( 0, 0, 0 ),
  1217. cv::FILLED
  1218. );
  1219. } else {
  1220. shift_y = 23;
  1221. cv::rectangle(
  1222. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1223. cv::Point(
  1224. m_pMaster->m_sEmbedVideoData.ts_x,
  1225. m_pMaster->m_sEmbedVideoData.ts_y
  1226. ),
  1227. cv::Point( 490, 60 ),
  1228. cv::Scalar( 0, 0, 0 ),
  1229. cv::FILLED
  1230. );
  1231. };
  1232. cv::putText(
  1233. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1234. tBuffer,
  1235. cv::Point(
  1236. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1237. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1238. ),
  1239. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1240. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1241. cv::Scalar( 0, 255, 255 ),
  1242. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1243. m_pMaster->m_sEmbedVideoData.ts_line_type
  1244. );
  1245. } else {
  1246. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1247. shift_y = 15;
  1248. } else {
  1249. shift_y = 23;
  1250. };
  1251. cv::putText(
  1252. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1253. tBuffer,
  1254. cv::Point(
  1255. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1256. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1257. ),
  1258. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1259. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1260. cv::Scalar( 0, 0, 0 ),
  1261. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1262. m_pMaster->m_sEmbedVideoData.ts_line_type
  1263. );
  1264. cv::putText(
  1265. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1266. tBuffer,
  1267. cv::Point(
  1268. m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1,
  1269. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1270. ),
  1271. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1272. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1273. cv::Scalar( 0, 0, 0 ),
  1274. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1275. m_pMaster->m_sEmbedVideoData.ts_line_type
  1276. );
  1277. cv::putText(
  1278. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1279. tBuffer,
  1280. cv::Point(
  1281. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1282. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1
  1283. ),
  1284. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1285. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1286. cv::Scalar( 0, 0, 0 ),
  1287. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1288. m_pMaster->m_sEmbedVideoData.ts_line_type
  1289. );
  1290. cv::putText(
  1291. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1292. tBuffer,
  1293. cv::Point(
  1294. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1295. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2
  1296. ),
  1297. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1298. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1299. cv::Scalar( 0, 0, 0 ),
  1300. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1301. m_pMaster->m_sEmbedVideoData.ts_line_type
  1302. );
  1303. cv::putText(
  1304. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1305. tBuffer,
  1306. cv::Point(
  1307. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1308. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1309. ),
  1310. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1311. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1312. cv::Scalar( 0, 255, 255 ),
  1313. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1314. m_pMaster->m_sEmbedVideoData.ts_line_type
  1315. );
  1316. }
  1317. };
  1318. };
  1319. };
  1320. };
  1321. if( m_pMaster->m_sEmbedVideoData.show_logo ){
  1322. cv::Rect roi(
  1323. cv::Point(
  1324. m_pMaster->m_sEmbedVideoData.logo_x,
  1325. m_pMaster->m_sEmbedVideoData.logo_y
  1326. ),
  1327. cv::Size(
  1328. m_pMaster->m_sEmbedVideoData.logo_w,
  1329. m_pMaster->m_sEmbedVideoData.logo_h
  1330. )
  1331. );
  1332. cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi );
  1333. m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask );
  1334. };
  1335. vector<int> compression_params;
  1336. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  1337. //compression_params.push_back(9);
  1338. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  1339. compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality );
  1340. m_pMaster->m_mEncodedProtector.lock();
  1341. m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear();
  1342. cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  1343. m_pMaster->m_mEncodedProtector.unlock();
  1344. #ifdef EVE_ENABLE_VIDEO
  1345. // encode Video Stream
  1346. //m_nPreAlarmFrames
  1347. //m_nPostAlarmFrames
  1348. //m_nNoAlarmSegmentFrames
  1349. //m_nSegmentLimitFrames
  1350. //m_nHardLimitFrames
  1351. if ( m_bSegAActive || m_bSegBActive ) {
  1352. m_mFrameCounterProtector.lock();
  1353. if( m_bSegAActive ){
  1354. do {
  1355. //In Any Case Close Stream if it Long enough
  1356. if( m_nSegAFrameCounter > m_nHardLimitFrames ){
  1357. LOG("HardLimit Reached!(A)");
  1358. closeSegmentA();
  1359. break;
  1360. };
  1361. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1362. if ( !m_bSegBActive ){
  1363. LOG("Start Alt!(A)");
  1364. openSegmentB();
  1365. };
  1366. };
  1367. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){
  1368. LOG("Swap Active!(A)");
  1369. swapActiveStreams();
  1370. break;
  1371. };
  1372. } while ( 0 );
  1373. };
  1374. if( m_bSegBActive ) {
  1375. do {
  1376. //In Any Case Close Stream if it Long enough
  1377. if( m_nSegBFrameCounter > m_nHardLimitFrames ){
  1378. LOG("HardLimit Reached!(B)");
  1379. closeSegmentB();
  1380. break;
  1381. };
  1382. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1383. if ( !m_bSegAActive ){
  1384. LOG("Start Alt!(B)");
  1385. openSegmentA();
  1386. };
  1387. };
  1388. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){
  1389. LOG("Swap Active!(B)");
  1390. swapActiveStreams();
  1391. break;
  1392. };
  1393. } while ( 0 );
  1394. };
  1395. m_mFrameCounterProtector.unlock();
  1396. ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER));
  1397. if ( tData ) {
  1398. tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize();
  1399. tData->linesize[1] = 0;
  1400. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  1401. tData->size = tData->linesize[0]*tData->rows;
  1402. tData->data[1] = NULL;
  1403. tData->data[0] = (uint8_t *)malloc( tData->size );
  1404. if ( tData->data[0] ) {
  1405. memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size );
  1406. m_mEncodingQueueProtector.lock();
  1407. m_qEncodingQueue.push( tData );
  1408. m_mEncodingQueueProtector.unlock();
  1409. } else {
  1410. LOG_ERROR("MAT_CPY malloc Error!");
  1411. free( tData );
  1412. };
  1413. } else LOG_ERROR("ENC_BUF malloc Error!");
  1414. };
  1415. #endif // EVE_ENABLE_VIDEO
  1416. m_pMaster->m_mPictureProtector.unlock();
  1417. } else {
  1418. LOG_ERROR("No PayLoad!");
  1419. };
  1420. return true;
  1421. };
  1422. void streamHandler::closeSegmentA( void ){
  1423. m_mCurrentOperationProtector.lock();
  1424. if ( m_bCOP == 0 ) m_bCOP = 0x01;
  1425. m_mCurrentOperationProtector.unlock();
  1426. LOG("Closing Stream A");
  1427. };
  1428. void streamHandler::closeSegmentB( void ){
  1429. m_mCurrentOperationProtector.lock();
  1430. if ( m_bCOP == 0 ) m_bCOP = 0x02;
  1431. m_mCurrentOperationProtector.unlock();
  1432. LOG("Closing Stream B");
  1433. };
  1434. void streamHandler::closeAll(){
  1435. waitThreadEnd( true );
  1436. avcodec_send_frame( m_pCodecCtx, NULL );
  1437. int ret = 0;
  1438. AVPacket *avp = av_packet_alloc();
  1439. if ( avp ) {
  1440. do {
  1441. av_packet_unref( avp );
  1442. ret = avcodec_receive_packet( m_pCodecCtx, avp );
  1443. if ( !ret ) {
  1444. if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp );
  1445. if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp );
  1446. };
  1447. } while ( !ret );
  1448. av_packet_unref( avp );
  1449. av_packet_free( &avp );
  1450. };
  1451. if ( m_bSegAActive ) {
  1452. av_write_trailer(m_pFormatCtxA);
  1453. avformat_close_input( &m_pFormatCtxA );
  1454. m_bSegAActive = false;
  1455. };
  1456. if ( m_bSegBActive ) {
  1457. av_write_trailer(m_pFormatCtxB);
  1458. avformat_close_input( &m_pFormatCtxB );
  1459. m_bSegBActive = false;
  1460. };
  1461. };
  1462. bool streamHandler::openSegmentA( void ){
  1463. if( !m_bSegAActive ){
  1464. CSTR tAM = getUniqID_MD5();
  1465. if ( tAM ) {
  1466. sprintf( m_cSegNameA, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER );
  1467. strncpy( m_cSegMD5A, tAM, 32 );
  1468. m_cSegMD5A[32] = (char)0;
  1469. free( tAM );
  1470. #ifdef DEBUG
  1471. LOG("Opening Stream A");
  1472. LOG(m_cSegNameA);
  1473. char tB[128];
  1474. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  1475. LOG( tB );
  1476. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  1477. LOG( tB );
  1478. #endif
  1479. m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1;
  1480. if (m_pVideoStrA->nb_frames) {
  1481. m_pVideoStrA->nb_frames = 0;
  1482. m_pVideoStrA->start_time = 0;
  1483. m_pVideoStrA->first_dts = 0;
  1484. m_pFormatCtxA->start_time = 0;
  1485. };
  1486. if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  1487. LOG_ERROR("Could not open output file.");
  1488. return m_bSegAActive;
  1489. };
  1490. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  1491. LOG_ERROR("Error occurred when writing header to output file.");
  1492. return m_bSegAActive;
  1493. };
  1494. //m_mFrameCounterProtector.lock();
  1495. m_nSegAFrameCounter = 0;
  1496. m_nSegAShiftFrames = 0;
  1497. m_bSegAActive = true;
  1498. m_bSegADelete = true;
  1499. //m_mFrameCounterProtector.unlock();
  1500. #ifdef DEBUG
  1501. LOG("Stream A Opened");
  1502. #endif
  1503. };
  1504. };
  1505. return m_bSegAActive;
  1506. };
  1507. bool streamHandler::openSegmentB( void ){
  1508. if( !m_bSegBActive ){
  1509. CSTR tAM = getUniqID_MD5();
  1510. if ( tAM ) {
  1511. sprintf( m_cSegNameB, "data/reports/%s.%s", tAM, VIDEO_OUTPUT_CONTAINER );
  1512. strncpy( m_cSegMD5B, tAM, 32 );
  1513. m_cSegMD5B[32] = (char)0;
  1514. free( tAM );
  1515. #ifdef DEBUG
  1516. LOG("Opening Stream B");
  1517. LOG(m_cSegNameB);
  1518. char tB[128];
  1519. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts );
  1520. LOG( tB );
  1521. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration );
  1522. LOG( tB );
  1523. #endif
  1524. m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1;
  1525. if (m_pVideoStrB->nb_frames) {
  1526. m_pVideoStrB->nb_frames = 0;
  1527. m_pVideoStrB->start_time = 0;
  1528. m_pVideoStrB->first_dts = 0;
  1529. m_pFormatCtxB->start_time = 0;
  1530. };
  1531. if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  1532. LOG_ERROR("Could not open output file.");
  1533. return m_bSegBActive;
  1534. };
  1535. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  1536. LOG_ERROR("Error occurred when writing header to output file.");
  1537. return m_bSegBActive;
  1538. };
  1539. //m_mFrameCounterProtector.lock();
  1540. m_nSegBFrameCounter = 0;
  1541. m_nSegBShiftFrames = 0;
  1542. m_bSegBActive = true;
  1543. m_bSegBDelete = true;
  1544. //m_mFrameCounterProtector.unlock();
  1545. #ifdef DEBUG
  1546. LOG("Stream B Opened");
  1547. #endif
  1548. };
  1549. };
  1550. return m_bSegBActive;
  1551. };
  1552. bool streamHandler::initVideoOutput(){
  1553. m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1554. m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1555. m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1556. m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1557. if( !initLibAV() ) return false;
  1558. m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL );
  1559. if ( m_pFormat == NULL ) {
  1560. LOG_ERROR("Out VideoFormat Not Found!");
  1561. return false;
  1562. #ifdef DEBUG
  1563. } else {
  1564. LOG("Output video Format");
  1565. LOG( VIDEO_OUTPUT_CONTAINER );
  1566. #endif
  1567. };
  1568. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1569. LOG_ERROR("Format CTX A alloc error!");
  1570. av_free( m_pFormat );
  1571. return false;
  1572. } else {
  1573. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  1574. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1575. };
  1576. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1577. LOG_ERROR("Format CTX B alloc error!");
  1578. avformat_free_context( m_pFormatCtxA );
  1579. //av_free( m_pFormat );
  1580. return false;
  1581. } else {
  1582. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  1583. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1584. };
  1585. m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  1586. if( m_pVideoCodec == NULL ){
  1587. LOG_ERROR("Out VideoCodec Not Found!");
  1588. avformat_free_context( m_pFormatCtxA );
  1589. avformat_free_context( m_pFormatCtxB );
  1590. //av_free( m_pFormat );
  1591. return false;
  1592. #ifdef DEBUG
  1593. } else {
  1594. LOG("Out Video Codec Found");
  1595. #endif
  1596. };
  1597. m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec );
  1598. if ( m_pCodecCtx == NULL){
  1599. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  1600. av_free( m_pVideoCodec );
  1601. avformat_free_context( m_pFormatCtxA );
  1602. avformat_free_context( m_pFormatCtxB );
  1603. //av_free( m_pFormat );
  1604. return false;
  1605. #ifdef DEBUG
  1606. } else {
  1607. LOG("Out Codec Context3 Allocated");
  1608. #endif
  1609. };
  1610. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec );
  1611. if ( m_pVideoStrA == NULL){
  1612. LOG_ERROR("VideoStream A Not Created!");
  1613. avcodec_free_context( &m_pCodecCtx );
  1614. av_free( m_pCodecCtx );
  1615. av_free( m_pVideoCodec );
  1616. avformat_free_context( m_pFormatCtxA );
  1617. avformat_free_context( m_pFormatCtxB );
  1618. //av_free( m_pFormat );
  1619. return false;
  1620. #ifdef DEBUG
  1621. } else {
  1622. LOG("VideoStream A is Created");
  1623. #endif
  1624. };
  1625. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec );
  1626. if ( m_pVideoStrB == NULL){
  1627. LOG_ERROR("VideoStream B Not Created!");
  1628. avcodec_free_context( &m_pCodecCtx );
  1629. av_free( m_pCodecCtx );
  1630. av_free( m_pVideoCodec );
  1631. avformat_free_context( m_pFormatCtxA );
  1632. avformat_free_context( m_pFormatCtxB );
  1633. av_free( m_pFormat );
  1634. return false;
  1635. #ifdef DEBUG
  1636. } else {
  1637. LOG("VideoStream B is Created");
  1638. #endif
  1639. };
  1640. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  1641. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  1642. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1643. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  1644. //m_pCodecCtx->thread_count = 1;
  1645. //m_pCodecCtx->bit_rate_tolerance = 1;
  1646. //m_pCodecCtx->global_quality = 100;
  1647. //m_pCodecCtx->compression_level = 2;
  1648. m_pCodecCtx->max_b_frames=1;
  1649. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  1650. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  1651. m_pCodecCtx->time_base.num = 1;
  1652. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  1653. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  1654. m_pCodecCtx->framerate.den = 1;
  1655. //https://pastebin.com/yG37YhWW
  1656. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  1657. //G@ avcodec encode NALU mp4
  1658. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  1659. m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  1660. #endif
  1661. m_pFormatOpts = NULL;
  1662. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  1663. if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){
  1664. #ifdef DEBUG
  1665. LOG("Begin Options!");
  1666. #endif
  1667. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  1668. //Set format's privater options, to be passed to avformat_write_header()
  1669. /*
  1670. mp4 muxer AVOptions:
  1671. -movflags E..... MOV muxer flags (default 0)
  1672. rtphint E..... Add RTP hint tracks
  1673. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  1674. frag_keyframe E..... Fragment at video keyframes
  1675. separate_moof E..... Write separate moof/mdat atoms for each track
  1676. frag_custom E..... Flush fragments on caller requests
  1677. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  1678. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  1679. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  1680. delay_moov ??
  1681. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  1682. -rtpflags E..... RTP muxer flags (default 0)
  1683. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  1684. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  1685. skip_rtcp E..... Don't send RTCP sender reports
  1686. h264_mode0 E..... Use mode 0 for H264 in RTP
  1687. send_bye E..... Send RTCP BYE packets when finishing
  1688. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  1689. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  1690. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  1691. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  1692. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  1693. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  1694. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  1695. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  1696. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  1697. */
  1698. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  1699. LOG_ERROR( "av_dict_set movflags!");
  1700. #ifdef DEBUG
  1701. } else {
  1702. LOG("MOV FLAG SET!");
  1703. #endif
  1704. };
  1705. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  1706. // LOG_ERROR( "av_dict_set live!" );
  1707. //};
  1708. //default brand is "isom", which fails on some devices
  1709. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  1710. LOG_ERROR( "av_dict_set brand!" );
  1711. };
  1712. //m_pCodecCtx->max_b_frames = 1;
  1713. //m_pCodecCtx->level = 31;
  1714. m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  1715. /// P-frames, generated by referencing data from prev and future frames.
  1716. /// [Compression up, CPU usage up]
  1717. /// [use 3/gop]
  1718. m_pCodecCtx->max_b_frames = 5;
  1719. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  1720. /// [use 3�5 ref per P]
  1721. m_pCodecCtx->refs = 3;
  1722. /// Compression efficiency (slower -> better quality + higher cpu%)
  1723. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  1724. /// Set this option to "ultrafast" is critical for realtime encoding
  1725. av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  1726. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  1727. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  1728. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  1729. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  1730. av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0);
  1731. /// Change settings based upon the specifics of input
  1732. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  1733. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  1734. av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  1735. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  1736. /// Because Quicktime (ie. iOS) doesn't support this option
  1737. av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
  1738. #ifdef DEBUG
  1739. LOG("End Options!");
  1740. #endif
  1741. } else {
  1742. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1743. };
  1744. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  1745. #ifdef DEBUG
  1746. char TB[129];
  1747. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den );
  1748. LOG(TB);
  1749. #endif
  1750. m_pVideoStrA->time_base = m_pCodecCtx->time_base;
  1751. m_pVideoStrB->time_base = m_pCodecCtx->time_base;
  1752. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  1753. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1754. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1755. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1756. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1757. m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1758. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  1759. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  1760. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  1761. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  1762. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  1763. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1764. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1765. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  1766. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx );
  1767. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1768. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  1769. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1770. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx );
  1771. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  1772. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  1773. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  1774. if ( avcodec_is_open( m_pCodecCtx ) == 0 ) {
  1775. LOG("output codec context is closed, opening");
  1776. if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) {
  1777. LOG_ERROR("Error opening2 encoder");
  1778. return false;
  1779. #ifdef DEBUG
  1780. } else {
  1781. LOG("output codec context is opened");
  1782. };
  1783. #endif
  1784. #ifdef DEBUG
  1785. } else {
  1786. LOG("output codec context is already opened");
  1787. #endif
  1788. };
  1789. m_pConvertCtx = sws_getContext(
  1790. m_pMaster->m_sEmbedVideoData.width,
  1791. m_pMaster->m_sEmbedVideoData.height,
  1792. AV_PIX_FMT_BGR24,
  1793. m_pMaster->m_sEmbedVideoData.width,
  1794. m_pMaster->m_sEmbedVideoData.height,
  1795. VIDEO_OUTPUT_PIX_FMT,
  1796. SWS_FAST_BILINEAR,
  1797. NULL,
  1798. NULL,
  1799. NULL
  1800. );
  1801. if ( m_pConvertCtx == NULL ) {
  1802. return false;
  1803. }
  1804. m_pAVFrame = av_frame_alloc();
  1805. if ( m_pAVFrame == NULL ) {
  1806. return false;
  1807. };
  1808. 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));
  1809. if( m_pOutBuffer == NULL ) {
  1810. return false;
  1811. };
  1812. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  1813. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  1814. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  1815. //av_frame_get_buffer( m_pAVFrame, 0 );
  1816. 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 );
  1817. //av_frame_make_writable( m_pAVFrame );
  1818. return init();
  1819. };
  1820. //encoding thread
  1821. void streamHandler::m_fThreadProc( void ){
  1822. AVPacket mPacket;
  1823. int bGotPacket;
  1824. int rVal = 0;
  1825. char tB[128];
  1826. av_init_packet( &mPacket );
  1827. while( m_bThreadStatus != TH_ENDED ){
  1828. //At the begining All streams are closed --> try to Open
  1829. if( m_bThreadStatus < TH_WORKING ){
  1830. if( !openSegmentA() ){
  1831. m_bThreadStatus = TH_ENDED;
  1832. continue;
  1833. };
  1834. //if( !openSegmentB() ){
  1835. // m_bThreadStatus = TH_ENDED;
  1836. // continue;
  1837. //};
  1838. m_bThreadStatus = TH_WORKING;
  1839. continue;
  1840. };
  1841. m_mEncodingQueueProtector.lock();
  1842. if ( m_qEncodingQueue.size() ) {
  1843. ENCODING_BUFFER *tData = m_qEncodingQueue.front();
  1844. if( tData ){
  1845. //av_frame_make_writable( m_pAVFrame );
  1846. sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize );
  1847. free( tData->data[0] );
  1848. free( tData );
  1849. m_qEncodingQueue.pop();
  1850. /*
  1851. AV_PICTURE_TYPE_NONE Undefined.
  1852. AV_PICTURE_TYPE_I Intra.
  1853. AV_PICTURE_TYPE_P Predicted.
  1854. AV_PICTURE_TYPE_B Bi-dir predicted.
  1855. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4.
  1856. AV_PICTURE_TYPE_SI Switching Intra.
  1857. AV_PICTURE_TYPE_SP Switching Predicted.
  1858. AV_PICTURE_TYPE_BI BI type.
  1859. */
  1860. if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) {
  1861. m_pAVFrame->key_frame = 1;
  1862. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I;
  1863. } else {
  1864. m_pAVFrame->key_frame = 0;
  1865. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
  1866. };
  1867. m_pAVFrame->pts = m_nGlobalFrameCounter + 1;
  1868. rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame );
  1869. m_mFrameCounterProtector.lock();
  1870. m_nGlobalFrameCounter++;
  1871. if ( m_bSegAActive ) m_nSegAFrameCounter++;
  1872. if ( m_bSegBActive ) m_nSegBFrameCounter++;
  1873. m_mFrameCounterProtector.unlock();
  1874. };
  1875. m_mEncodingQueueProtector.unlock();
  1876. } else {
  1877. m_mEncodingQueueProtector.unlock();
  1878. // If No Encode Job -> Test Commands!
  1879. m_mCurrentOperationProtector.lock();
  1880. switch ( m_bCOP ) {
  1881. case 0x01:{
  1882. m_bSegAActive = false;
  1883. if ( !m_bSegADelete ) {
  1884. av_write_trailer( m_pFormatCtxA );
  1885. avio_close( m_pFormatCtxA->pb );
  1886. #ifdef DEBUG
  1887. LOG("Stream A is Closed");
  1888. #endif
  1889. } else {
  1890. #ifdef EVE_DONT_DELETE_SEGMENTS
  1891. av_write_trailer( m_pFormatCtxA );
  1892. #endif
  1893. avio_close( m_pFormatCtxA->pb );
  1894. #ifndef EVE_DONT_DELETE_SEGMENTS
  1895. unlink( m_cSegNameA );
  1896. #endif
  1897. #ifdef DEBUG
  1898. LOG("Stream A is Deleted!");
  1899. #endif
  1900. };
  1901. break;
  1902. };
  1903. case 0x02:{
  1904. m_bSegBActive = false;
  1905. if ( !m_bSegBDelete ) {
  1906. av_write_trailer( m_pFormatCtxB );
  1907. avio_close( m_pFormatCtxB->pb );
  1908. #ifdef DEBUG
  1909. LOG("Stream B is Closed");
  1910. #endif
  1911. } else {
  1912. #ifdef EVE_DONT_DELETE_SEGMENTS
  1913. av_write_trailer( m_pFormatCtxB );
  1914. #endif
  1915. avio_close( m_pFormatCtxB->pb );
  1916. #ifndef EVE_DONT_DELETE_SEGMENTS
  1917. unlink( m_cSegNameB );
  1918. #endif
  1919. #ifdef DEBUG
  1920. LOG("Stream B is Deleted!");
  1921. #endif
  1922. };
  1923. break;
  1924. };
  1925. };
  1926. m_bCOP = 0;
  1927. m_mCurrentOperationProtector.unlock();
  1928. };
  1929. do {
  1930. mPacket.data = NULL;
  1931. mPacket.size = 0;
  1932. rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket );
  1933. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  1934. break;
  1935. } else if( rVal < 0 ){
  1936. LOG_ERROR( "Error during encoding " );
  1937. m_bThreadStatus = TH_ENDED;
  1938. break;
  1939. };
  1940. if( !rVal ){
  1941. if ( m_bSegAActive ) {
  1942. mPacket.stream_index = m_pVideoStrA->index;
  1943. mPacket.duration = 1;
  1944. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1945. //mPacket.pts = AV_NOPTS_VALUE;
  1946. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1947. mPacket.dts = mPacket.pts;
  1948. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  1949. if( rc < 0 ){
  1950. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  1951. m_bThreadStatus = TH_ENDED;
  1952. LOG_ERROR("Trouble with Video Output A!");
  1953. av_strerror( rc, tB, 128 );
  1954. LOG_ERROR( tB );
  1955. break; //continue (changed since embed into do-while)
  1956. };
  1957. };
  1958. if ( m_bSegBActive ) {
  1959. mPacket.stream_index = m_pVideoStrB->index;
  1960. mPacket.duration = 1;
  1961. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  1962. //mPacket.pts = AV_NOPTS_VALUE;
  1963. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  1964. mPacket.dts = mPacket.pts;
  1965. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  1966. if( rc < 0 ) {
  1967. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  1968. m_bThreadStatus = TH_ENDED;
  1969. LOG_ERROR( "Trouble with Video Output B!" );
  1970. av_strerror( rc, tB, 128 );
  1971. LOG_ERROR( tB );
  1972. break; //continue (changed since embed into do-while)
  1973. };
  1974. };
  1975. av_packet_unref( &mPacket );
  1976. };
  1977. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  1978. };
  1979. #ifdef DEBUG
  1980. LOG("Encoder Loop Ended!");
  1981. #endif
  1982. if ( m_bSegAActive ) {
  1983. m_bSegAActive = false;
  1984. av_write_trailer( m_pFormatCtxA );
  1985. avio_close( m_pFormatCtxA->pb );
  1986. };
  1987. if ( m_bSegBActive ) {
  1988. m_bSegBActive = false;
  1989. av_write_trailer( m_pFormatCtxB );
  1990. avio_close( m_pFormatCtxB->pb );
  1991. };
  1992. #ifdef DEBUG
  1993. LOG("Encoder Streams are Closed!");
  1994. #endif
  1995. };
  1996. void streamHandler::swapActiveStreams( void ){
  1997. //m_mFrameCounterProtector.lock();
  1998. if ( !m_bActiveEncoderStream ) {
  1999. m_bActiveEncoderStream = 1;
  2000. m_nVideoRegisteredDBID = 0;
  2001. // No need to continue Stream A if no Events
  2002. if ( m_bSegADelete ) closeSegmentA();
  2003. } else {
  2004. m_bActiveEncoderStream = 0;
  2005. m_nVideoRegisteredDBID = 0;
  2006. // No need to continue Stream B if no Events
  2007. if ( m_bSegBDelete ) closeSegmentB();
  2008. };
  2009. //m_mFrameCounterProtector.unlock();
  2010. };
  2011. bool streamHandler::triggerEvent( uint32_t &dbid, uint32_t &frame ){
  2012. m_mFrameCounterProtector.lock();
  2013. // To Mark Events Frames
  2014. m_bEvtMarkerCounter = 255;
  2015. if ( m_nVideoRegisteredDBID == 0 ) {
  2016. LOG("New Event!");
  2017. PF_TIMESTAMP ts;
  2018. getPFTS( &ts );
  2019. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  2020. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  2021. m_sStreamData.id,
  2022. m_cSegMD5A,
  2023. VIDEO_OUTPUT_CONTAINER,
  2024. ts.seconds,
  2025. ts.milliseconds,
  2026. m_sStreamData.fps
  2027. );
  2028. m_bSegADelete = false;
  2029. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  2030. } else { // Stream B is Active
  2031. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  2032. m_sStreamData.id,
  2033. m_cSegMD5B,
  2034. VIDEO_OUTPUT_CONTAINER,
  2035. ts.seconds,
  2036. ts.milliseconds,
  2037. m_sStreamData.fps
  2038. );
  2039. m_bSegBDelete = false;
  2040. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  2041. };
  2042. };
  2043. if ( m_nVideoRegisteredDBID == 0 ) return false;
  2044. dbid = m_nVideoRegisteredDBID;
  2045. LOG("Event Registered!");
  2046. m_mFrameCounterProtector.unlock();
  2047. return true;
  2048. };
  2049. bool streamHandler::triggerCamMove( void ){
  2050. m_bCamMoveCounter = 255;
  2051. return true;
  2052. };
  2053. bool streamHandler::validate( void ){
  2054. if ( m_pSource )
  2055. #ifdef EVE_ENABLE_VIDEO
  2056. if( m_bThreadStatus < TH_ENDED )
  2057. #endif
  2058. return true;
  2059. return false;
  2060. };
  2061. #undef LOG
  2062. #undef LOG_ERROR
  2063. #undef TLOG
  2064. #undef TLOG_ERROR