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.

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