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.

2291 lines
91 KiB

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