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.

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