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.

3161 lines
136 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
​
​
​
4 years ago
4 years ago
​
​
​
​
4 years ago
​
4 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
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. sprintf( tBuffer, ">>>%s>%s>", tMD->mediaName, tsb );
  1328. int baseline=0;
  1329. cv::Size textSize = cv::getTextSize( tBuffer,
  1330. m_pMaster->m_sEmbedVideoData.label_font_face,
  1331. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1332. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1333. &baseline
  1334. );
  1335. int x = m_pMaster->m_sEmbedVideoData.label_x;
  1336. int y = m_pMaster->m_sEmbedVideoData.label_y;
  1337. if( x < 0 ) {
  1338. x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width;
  1339. };
  1340. if( y < 0 ) {
  1341. y = m_pMaster->m_sEmbedVideoData.height+y-baseline;//
  1342. };
  1343. if( !m_pMaster->m_sEmbedVideoData.label_transperant ) {
  1344. cv::rectangle(
  1345. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1346. cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ),
  1347. cv::Scalar( 0, 0, 0 ),
  1348. cv::FILLED
  1349. );
  1350. };
  1351. cv::putText(
  1352. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1353. tBuffer,
  1354. cv::Point( x, y ),
  1355. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face,
  1356. m_pMaster->m_sEmbedVideoData.label_font_scale,
  1357. cv::Scalar( 0, 255, 0 ),
  1358. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  1359. m_pMaster->m_sEmbedVideoData.label_line_type
  1360. );
  1361. };
  1362. };
  1363. } else {
  1364. if( m_pMaster->m_sEmbedVideoData.show_ts ){
  1365. time_t t = time( NULL );
  1366. struct tm * tmp = gmtime( &t );
  1367. if( tmp ){
  1368. if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){
  1369. uint8_t shift_x = 0;
  1370. uint8_t shift_y = 15;
  1371. if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) {
  1372. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1373. shift_y = 15;
  1374. cv::rectangle(
  1375. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1376. cv::Point(
  1377. m_pMaster->m_sEmbedVideoData.ts_x,
  1378. m_pMaster->m_sEmbedVideoData.ts_y
  1379. ),
  1380. cv::Point( 490, 60 ),
  1381. cv::Scalar( 0, 0, 0 ),
  1382. cv::FILLED
  1383. );
  1384. } else {
  1385. shift_y = 23;
  1386. cv::rectangle(
  1387. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1388. cv::Point(
  1389. m_pMaster->m_sEmbedVideoData.ts_x,
  1390. m_pMaster->m_sEmbedVideoData.ts_y
  1391. ),
  1392. cv::Point( 490, 60 ),
  1393. cv::Scalar( 0, 0, 0 ),
  1394. cv::FILLED
  1395. );
  1396. };
  1397. cv::putText(
  1398. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1399. tBuffer,
  1400. cv::Point(
  1401. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1402. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1403. ),
  1404. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1405. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1406. cv::Scalar( 0, 255, 255 ),
  1407. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1408. m_pMaster->m_sEmbedVideoData.ts_line_type
  1409. );
  1410. } else {
  1411. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  1412. shift_y = 15;
  1413. } else {
  1414. shift_y = 23;
  1415. };
  1416. cv::putText(
  1417. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1418. tBuffer,
  1419. cv::Point(
  1420. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1421. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1422. ),
  1423. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1424. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1425. cv::Scalar( 0, 0, 0 ),
  1426. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1427. m_pMaster->m_sEmbedVideoData.ts_line_type
  1428. );
  1429. cv::putText(
  1430. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1431. tBuffer,
  1432. cv::Point(
  1433. m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1,
  1434. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  1435. ),
  1436. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1437. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1438. cv::Scalar( 0, 0, 0 ),
  1439. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1440. m_pMaster->m_sEmbedVideoData.ts_line_type
  1441. );
  1442. cv::putText(
  1443. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1444. tBuffer,
  1445. cv::Point(
  1446. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1447. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1
  1448. ),
  1449. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1450. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1451. cv::Scalar( 0, 0, 0 ),
  1452. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1453. m_pMaster->m_sEmbedVideoData.ts_line_type
  1454. );
  1455. cv::putText(
  1456. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1457. tBuffer,
  1458. cv::Point(
  1459. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  1460. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2
  1461. ),
  1462. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1463. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1464. cv::Scalar( 0, 0, 0 ),
  1465. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1466. m_pMaster->m_sEmbedVideoData.ts_line_type
  1467. );
  1468. cv::putText(
  1469. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1470. tBuffer,
  1471. cv::Point(
  1472. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  1473. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  1474. ),
  1475. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  1476. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  1477. cv::Scalar( 0, 255, 255 ),
  1478. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  1479. m_pMaster->m_sEmbedVideoData.ts_line_type
  1480. );
  1481. }
  1482. };
  1483. };
  1484. };
  1485. };
  1486. if( m_pMaster->m_sEmbedVideoData.show_logo ){
  1487. cv::Rect roi(
  1488. cv::Point(
  1489. m_pMaster->m_sEmbedVideoData.logo_x,
  1490. m_pMaster->m_sEmbedVideoData.logo_y
  1491. ),
  1492. cv::Size(
  1493. m_pMaster->m_sEmbedVideoData.logo_w,
  1494. m_pMaster->m_sEmbedVideoData.logo_h
  1495. )
  1496. );
  1497. cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi );
  1498. m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask );
  1499. };
  1500. vector<int> compression_params;
  1501. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  1502. //compression_params.push_back(9);
  1503. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  1504. compression_params.push_back( m_pMaster->m_sEmbedVideoData.compression_quality );
  1505. m_pMaster->m_mEncodedProtector.lock();
  1506. m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear();
  1507. cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  1508. m_pMaster->m_mEncodedProtector.unlock();
  1509. #ifdef EVE_ENABLE_VIDEO
  1510. // encode Video Stream
  1511. //m_nPreAlarmFrames
  1512. //m_nPostAlarmFrames
  1513. //m_nNoAlarmSegmentFrames
  1514. //m_nSegmentLimitFrames
  1515. //m_nHardLimitFrames
  1516. if ( m_bSegAActive || m_bSegBActive ) {
  1517. m_mFrameCounterProtector.lock();
  1518. if( m_bSegAActive ){
  1519. do {
  1520. //In Any Case Close Stream if it Long enough
  1521. if( m_nSegAFrameCounter > m_nHardLimitFrames ){
  1522. #ifdef DEBUG
  1523. LOG("HardLimit Reached!(A)");
  1524. #endif
  1525. closeSegmentA();
  1526. break;
  1527. };
  1528. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1529. if ( !m_bSegBActive ){
  1530. #ifdef DEBUG
  1531. LOG("Start Alt!(A)");
  1532. #endif
  1533. openSegmentB();
  1534. };
  1535. };
  1536. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){
  1537. #ifdef DEBUG
  1538. LOG("Swap Active!(A)");
  1539. #endif
  1540. swapActiveStreams();
  1541. break;
  1542. };
  1543. } while ( 0 );
  1544. };
  1545. if( m_bSegBActive ) {
  1546. do {
  1547. //In Any Case Close Stream if it Long enough
  1548. if( m_nSegBFrameCounter > m_nHardLimitFrames ){
  1549. #ifdef DEBUG
  1550. LOG("HardLimit Reached!(B)");
  1551. #endif
  1552. closeSegmentB();
  1553. break;
  1554. };
  1555. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  1556. if ( !m_bSegAActive ){
  1557. #ifdef DEBUG
  1558. LOG("Start Alt!(B)");
  1559. #endif
  1560. openSegmentA();
  1561. };
  1562. };
  1563. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){
  1564. #ifdef DEBUG
  1565. LOG("Swap Active!(B)");
  1566. #endif
  1567. swapActiveStreams();
  1568. break;
  1569. };
  1570. } while ( 0 );
  1571. };
  1572. m_mFrameCounterProtector.unlock();
  1573. ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER));
  1574. if ( tData ) {
  1575. #ifdef OPENCV_VIDEO_OUTPUT
  1576. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  1577. tData->cols = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols;
  1578. tData->size = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize()*tData->rows;
  1579. tData->data = (uint8_t *)malloc( tData->size );
  1580. if ( tData->data ) {
  1581. memcpy( tData->data, m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size );
  1582. #else //OPENCV_VIDEO_OUTPUT
  1583. tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize();
  1584. tData->linesize[1] = 0;
  1585. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  1586. tData->size = tData->linesize[0]*tData->rows;
  1587. tData->data[1] = NULL;
  1588. tData->data[0] = (uint8_t *)malloc( tData->size );
  1589. if ( tData->data[0] ) {
  1590. memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size );
  1591. #endif //OPENCV_VIDEO_OUTPUT
  1592. m_mEncodingQueueProtector.lock();
  1593. m_qEncodingQueue.push( tData );
  1594. m_mEncodingQueueProtector.unlock();
  1595. } else {
  1596. LOG_ERROR("MAT_CPY malloc Error!");
  1597. free( tData );
  1598. };
  1599. } else LOG_ERROR("ENC_BUF malloc Error!");
  1600. };
  1601. #endif // EVE_ENABLE_VIDEO
  1602. m_pMaster->m_mPictureProtector.unlock();
  1603. } else {
  1604. LOG_ERROR("No PayLoad!");
  1605. };
  1606. return true;
  1607. };
  1608. #ifdef EVE_ENABLE_VIDEO
  1609. void streamHandler::closeSegmentA( void ){
  1610. m_mCurrentOperationProtector.lock();
  1611. if ( m_bCOP == 0 ) m_bCOP = 0x01;
  1612. m_mCurrentOperationProtector.unlock();
  1613. #ifdef DEBUG
  1614. LOG("Closing Stream A");
  1615. #endif
  1616. };
  1617. void streamHandler::closeSegmentB( void ){
  1618. m_mCurrentOperationProtector.lock();
  1619. if ( m_bCOP == 0 ) m_bCOP = 0x02;
  1620. m_mCurrentOperationProtector.unlock();
  1621. #ifdef DEBUG
  1622. LOG("Closing Stream B");
  1623. #endif
  1624. };
  1625. void streamHandler::closeAll(){
  1626. waitThreadEnd( true );
  1627. #ifdef OPENCV_VIDEO_OUTPUT
  1628. if( m_pEncoderA ){
  1629. if ( m_pEncoderA->isOpened() ) {
  1630. m_pEncoderA->release();
  1631. };
  1632. delete(m_pEncoderA);
  1633. };
  1634. if( m_pEncoderB ){
  1635. if ( m_pEncoderB->isOpened() ) {
  1636. m_pEncoderB->release();
  1637. };
  1638. delete( m_pEncoderB );
  1639. };
  1640. #else //OPENCV_VIDEO_OUTPUT
  1641. #ifdef SEPARATED_VIDEO_ENCODERS
  1642. if( ( m_pCodecACtx != NULL || m_pCodecBCtx != NULL ) && (m_bSegAActive || m_bSegBActive )) {
  1643. if( m_pCodecACtx != NULL ) {
  1644. avcodec_send_frame(m_pCodecACtx, NULL);
  1645. int ret = 0;
  1646. AVPacket *avp = av_packet_alloc();
  1647. if ( avp ) {
  1648. do {
  1649. av_packet_unref( avp );
  1650. ret = avcodec_receive_packet( m_pCodecACtx, avp );
  1651. if ( !ret ) {
  1652. if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp );
  1653. };
  1654. } while ( !ret );
  1655. av_packet_unref( avp );
  1656. av_packet_free( &avp );
  1657. };
  1658. };
  1659. if( m_pCodecBCtx != NULL ) {
  1660. avcodec_send_frame(m_pCodecBCtx, NULL);
  1661. int ret = 0;
  1662. AVPacket *avp = av_packet_alloc();
  1663. if ( avp ) {
  1664. do {
  1665. av_packet_unref( avp );
  1666. ret = avcodec_receive_packet( m_pCodecBCtx, avp );
  1667. if ( !ret ) {
  1668. if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp );
  1669. };
  1670. } while ( !ret );
  1671. av_packet_unref( avp );
  1672. av_packet_free( &avp );
  1673. };
  1674. };
  1675. if ( m_bSegAActive ) {
  1676. av_write_trailer(m_pFormatCtxA);
  1677. avformat_close_input( &m_pFormatCtxA );
  1678. m_bSegAActive = false;
  1679. };
  1680. if ( m_bSegBActive ) {
  1681. av_write_trailer(m_pFormatCtxB);
  1682. avformat_close_input( &m_pFormatCtxB );
  1683. m_bSegBActive = false;
  1684. };
  1685. };
  1686. #else // ! SEPARATED_VIDEO_ENCODERS
  1687. if( m_pCodecCtx != NULL && (m_bSegAActive || m_bSegBActive )) {
  1688. avcodec_send_frame( m_pCodecCtx, NULL );
  1689. int ret = 0;
  1690. AVPacket *avp = av_packet_alloc();
  1691. if ( avp ) {
  1692. do {
  1693. av_packet_unref( avp );
  1694. ret = avcodec_receive_packet( m_pCodecCtx, avp );
  1695. if ( !ret ) {
  1696. if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp );
  1697. if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp );
  1698. };
  1699. } while ( !ret );
  1700. av_packet_unref( avp );
  1701. av_packet_free( &avp );
  1702. };
  1703. if ( m_bSegAActive ) {
  1704. av_write_trailer(m_pFormatCtxA);
  1705. avformat_close_input( &m_pFormatCtxA );
  1706. m_bSegAActive = false;
  1707. };
  1708. if ( m_bSegBActive ) {
  1709. av_write_trailer(m_pFormatCtxB);
  1710. avformat_close_input( &m_pFormatCtxB );
  1711. m_bSegBActive = false;
  1712. };
  1713. };
  1714. #endif // SEPARATED_VIDEO_ENCODERS
  1715. //if( m_pFormat != NULL ) {
  1716. //av_free( m_pFormat );
  1717. //};
  1718. #endif // OPENCV_VIDEO_OUTPUT
  1719. };
  1720. bool streamHandler::openSegmentA( void ){
  1721. if( !m_bSegAActive ){
  1722. CSTR tAM = getUniqID_MD5();
  1723. if ( tAM ) {
  1724. //sprintf( m_cSegNameA, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER );
  1725. sprintf( m_sStreamSegmentInfo[0].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER );
  1726. strncpy( m_sStreamSegmentInfo[0].recordMD5, tAM, 32 );
  1727. m_sStreamSegmentInfo[0].recordMD5[32] = (char)0;
  1728. free( tAM );
  1729. m_sStreamSegmentInfo[0].stream_id = m_sStreamData.id;
  1730. PF_TIMESTAMP ts;
  1731. getPFTS( &ts );
  1732. m_sStreamSegmentInfo[0].streamTSS = ts.seconds;
  1733. m_sStreamSegmentInfo[0].streamTMS = ts.milliseconds;
  1734. strncpy( m_sStreamSegmentInfo[0].recordEXT, VIDEO_OUTPUT_CONTAINER, 4 );
  1735. m_sStreamSegmentInfo[0].streamFPS = m_sStreamData.fps;
  1736. m_sStreamSegmentInfo[0].eventIDS.clear();
  1737. m_sStreamSegmentInfo[0].eventTSS.clear();
  1738. m_sStreamSegmentInfo[0].eventTMS.clear();
  1739. m_sStreamSegmentInfo[0].eventFrames.clear();
  1740. m_sStreamSegmentInfo[0].dataSize = 0;
  1741. m_sStreamSegmentInfo[0].db_id = 0;
  1742. #ifdef OPENCV_VIDEO_OUTPUT
  1743. if ( m_pEncoderA ) {
  1744. int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  1745. double fps = m_sStreamData.fps;
  1746. cv::String mn( m_sStreamSegmentInfo[0].scratchPath );
  1747. cv::Size fz( m_sStreamData.width, m_sStreamData.height );
  1748. //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  1749. if( !m_pEncoderA->open( mn, fourcc, fps, fz ) ){
  1750. LOG_ERROR("Cannot Open Output Segment A!");
  1751. return false;
  1752. #ifdef DEBUG
  1753. } else {
  1754. LOG("VideoStream A is Created");
  1755. LOG( m_sStreamSegmentInfo[0].scratchPath );
  1756. #endif
  1757. };
  1758. m_bSegAActive = true;
  1759. m_bSegADelete = true;
  1760. m_nSegAFrameCounter = 0;
  1761. m_nSegAShiftFrames = 0;
  1762. } else {
  1763. LOG_ERROR("No Encoder(A) Object!");
  1764. return false;
  1765. };
  1766. #else
  1767. //Check if Encoder is Ready
  1768. if ( m_pFormat == NULL ) return false;
  1769. #ifdef SEPARATED_VIDEO_ENCODERS
  1770. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1771. LOG_ERROR("Format CTX A alloc error!");
  1772. return false;
  1773. } else {
  1774. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  1775. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1776. };
  1777. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoACodec );
  1778. if ( m_pVideoStrA == NULL){
  1779. avformat_free_context( m_pFormatCtxA );
  1780. return false;
  1781. #ifdef DEBUG_EXTRA
  1782. } else {
  1783. LOG("VideoStream A is Created");
  1784. #endif
  1785. };
  1786. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  1787. m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps;
  1788. m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  1789. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecACtx );
  1790. #ifdef DEBUG_EXTRA
  1791. LOG("Opening Stream A");
  1792. LOG(m_cSegNameA);
  1793. char tB[128];
  1794. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  1795. LOG( tB );
  1796. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  1797. LOG( tB );
  1798. #endif
  1799. //if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  1800. if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, AVIO_FLAG_WRITE) < 0) {
  1801. LOG_ERROR("Could not open output file.");
  1802. return m_bSegAActive;
  1803. };
  1804. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  1805. LOG_ERROR("Error occurred when writing header to output file.");
  1806. return m_bSegAActive;
  1807. };
  1808. //m_mFrameCounterProtector.lock();
  1809. m_nSegAFrameCounter = 0;
  1810. m_nSegAShiftFrames = 0;
  1811. m_bSegAActive = true;
  1812. m_bSegADelete = true;
  1813. //m_mFrameCounterProtector.unlock();
  1814. #else // SEPARATED_VIDEO_ENCODERS
  1815. m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1;
  1816. if (m_pVideoStrA->nb_frames) {
  1817. m_pVideoStrA->nb_frames = 0;
  1818. m_pVideoStrA->start_time = 0;
  1819. m_pVideoStrA->first_dts = 0;
  1820. m_pFormatCtxA->start_time = 0;
  1821. };
  1822. #ifdef DEBUG_EXTRA
  1823. LOG("Opening Stream A");
  1824. LOG(m_cSegNameA);
  1825. char tB[128];
  1826. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  1827. LOG( tB );
  1828. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  1829. LOG( tB );
  1830. #endif
  1831. if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  1832. LOG_ERROR("Could not open output file.");
  1833. return m_bSegAActive;
  1834. };
  1835. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  1836. LOG_ERROR("Error occurred when writing header to output file.");
  1837. return m_bSegAActive;
  1838. };
  1839. //m_mFrameCounterProtector.lock();
  1840. m_nSegAFrameCounter = 0;
  1841. m_nSegAShiftFrames = 0;
  1842. m_bSegAActive = true;
  1843. m_bSegADelete = true;
  1844. //m_mFrameCounterProtector.unlock();
  1845. #endif // SEPARATED_VIDEO_ENCODERS
  1846. #ifdef DEBUG_EXTRA
  1847. LOG("Stream A Opened");
  1848. #endif
  1849. #endif //OPENCV_VIDEO_OUTPUT
  1850. };
  1851. };
  1852. return m_bSegAActive;
  1853. };
  1854. bool streamHandler::openSegmentB( void ){
  1855. if( !m_bSegBActive ){
  1856. CSTR tAM = getUniqID_MD5();
  1857. if ( tAM ) {
  1858. sprintf( m_sStreamSegmentInfo[1].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER );
  1859. strncpy( m_sStreamSegmentInfo[1].recordMD5, tAM, 32 );
  1860. m_sStreamSegmentInfo[1].recordMD5[32] = (char)0;
  1861. free( tAM );
  1862. m_sStreamSegmentInfo[1].stream_id = m_sStreamData.id;
  1863. PF_TIMESTAMP ts;
  1864. getPFTS( &ts );
  1865. m_sStreamSegmentInfo[1].streamTSS = ts.seconds;
  1866. m_sStreamSegmentInfo[1].streamTMS = ts.milliseconds;
  1867. strncpy( m_sStreamSegmentInfo[1].recordEXT, VIDEO_OUTPUT_CONTAINER, 4 );
  1868. m_sStreamSegmentInfo[1].streamFPS = m_sStreamData.fps;
  1869. m_sStreamSegmentInfo[1].eventIDS.clear();
  1870. m_sStreamSegmentInfo[1].eventTSS.clear();
  1871. m_sStreamSegmentInfo[1].eventTMS.clear();
  1872. m_sStreamSegmentInfo[1].eventFrames.clear();
  1873. m_sStreamSegmentInfo[1].dataSize = 0;
  1874. m_sStreamSegmentInfo[1].db_id = 0;
  1875. #ifdef OPENCV_VIDEO_OUTPUT
  1876. if ( m_pEncoderB ) {
  1877. int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  1878. double fps = m_sStreamData.fps;
  1879. cv::String mn( m_sStreamSegmentInfo[1].scratchPath );
  1880. cv::Size fz( m_sStreamData.width, m_sStreamData.height );
  1881. //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  1882. if( !m_pEncoderB->open( mn, fourcc, fps, fz ) ){
  1883. LOG_ERROR("Cannot Open Output Segment B!");
  1884. return false;
  1885. #ifdef DEBUG
  1886. } else {
  1887. LOG("VideoStream B is Created");
  1888. LOG( m_sStreamSegmentInfo[1].scratchPath );
  1889. #endif
  1890. };
  1891. m_bSegBActive = true;
  1892. m_bSegBDelete = true;
  1893. m_nSegBFrameCounter = 0;
  1894. m_nSegBShiftFrames = 0;
  1895. } else {
  1896. LOG_ERROR("No Encoder(B) Object!");
  1897. return false;
  1898. };
  1899. #else
  1900. //Check if Encoder is Ready
  1901. if ( m_pFormat == NULL ) return false;
  1902. #ifdef SEPARATED_VIDEO_ENCODERS
  1903. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  1904. LOG_ERROR("Format CTX B alloc error!");
  1905. return false;
  1906. } else {
  1907. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  1908. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  1909. };
  1910. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoBCodec );
  1911. if ( m_pVideoStrB == NULL){
  1912. avformat_free_context( m_pFormatCtxB );
  1913. return false;
  1914. #ifdef DEBUG_EXTRA
  1915. } else {
  1916. LOG("VideoStream B is Created");
  1917. #endif
  1918. };
  1919. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  1920. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  1921. m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  1922. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecBCtx );
  1923. #ifdef DEBUG_EXTRA
  1924. LOG("Opening Stream B");
  1925. LOG( m_cSegNameB );
  1926. char tB[128];
  1927. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts );
  1928. LOG( tB );
  1929. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration );
  1930. LOG( tB );
  1931. #endif
  1932. //if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  1933. if ( avio_open( &m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE ) < 0 ){
  1934. LOG_ERROR("Could not open output file.");
  1935. avformat_free_context( m_pFormatCtxB );
  1936. return false;
  1937. };
  1938. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  1939. LOG_ERROR("Error occurred when writing header to output file.");
  1940. avio_close( m_pFormatCtxB->pb );
  1941. avformat_free_context( m_pFormatCtxB );
  1942. return false;
  1943. };
  1944. //m_mFrameCounterProtector.lock();
  1945. m_nSegBFrameCounter = 0;
  1946. m_nSegBShiftFrames = 0;
  1947. m_bSegBActive = true;
  1948. m_bSegBDelete = true;
  1949. //m_mFrameCounterProtector.unlock();
  1950. #else // SEPARATED_VIDEO_ENCODERS
  1951. m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1;
  1952. if (m_pVideoStrB->nb_frames) {
  1953. m_pVideoStrB->nb_frames = 0;
  1954. m_pVideoStrB->start_time = 0;
  1955. m_pVideoStrB->first_dts = 0;
  1956. m_pFormatCtxB->start_time = 0;
  1957. };
  1958. if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  1959. LOG_ERROR("Could not open output file.");
  1960. return m_bSegBActive;
  1961. };
  1962. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  1963. LOG_ERROR("Error occurred when writing header to output file.");
  1964. return m_bSegBActive;
  1965. };
  1966. //m_mFrameCounterProtector.lock();
  1967. m_nSegBFrameCounter = 0;
  1968. m_nSegBShiftFrames = 0;
  1969. m_bSegBActive = true;
  1970. m_bSegBDelete = true;
  1971. //m_mFrameCounterProtector.unlock();
  1972. #endif // SEPARATED_VIDEO_ENCODERS
  1973. #ifdef DEBUG_EXTRA
  1974. LOG("Stream B Opened");
  1975. #endif
  1976. #endif //OPENCV_VIDEO_OUTPUT
  1977. };
  1978. };
  1979. return m_bSegBActive;
  1980. };
  1981. bool streamHandler::initVideoOutput(){
  1982. m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1983. m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  1984. m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1985. m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000;
  1986. #ifdef OPENCV_VIDEO_OUTPUT
  1987. m_pEncoderA = new cv::VideoWriter();
  1988. if ( m_pEncoderA == NULL ) {
  1989. LOG_ERROR("Encoder A Create Failure!");
  1990. return false;
  1991. };
  1992. m_pEncoderB = new cv::VideoWriter();
  1993. if ( m_pEncoderA == NULL ) {
  1994. LOG_ERROR("Encoder B Create Failure!");
  1995. return false;
  1996. };
  1997. #else
  1998. if( !initLibAV() ) return false;
  1999. m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL );
  2000. if ( m_pFormat == NULL ) {
  2001. LOG_ERROR("Out VideoFormat Not Found!");
  2002. return false;
  2003. #ifdef DEBUG_EXTRA
  2004. } else {
  2005. LOG("Output video Format");
  2006. LOG( VIDEO_OUTPUT_CONTAINER );
  2007. #endif
  2008. };
  2009. #ifdef SEPARATED_VIDEO_ENCODERS
  2010. /* Stream A */
  2011. m_pVideoACodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  2012. if( m_pVideoACodec == NULL ){
  2013. LOG_ERROR("Encoder Video Codec Not Found!");
  2014. return false;
  2015. #ifdef DEBUG_EXTRA
  2016. } else {
  2017. LOG("Video Encoder A Created");
  2018. #endif
  2019. };
  2020. m_pCodecACtx = avcodec_alloc_context3( m_pVideoACodec );
  2021. if ( m_pCodecACtx == NULL){
  2022. LOG_ERROR("Video Encoder A Context Memory Allocation Error!");
  2023. av_free( m_pVideoACodec );
  2024. avformat_free_context( m_pFormatCtxA );
  2025. return false;
  2026. #ifdef DEBUG_EXTRA
  2027. } else {
  2028. LOG("Video Encoder Context A Allocated");
  2029. #endif
  2030. };
  2031. /* Stream B */
  2032. m_pVideoBCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  2033. if( m_pVideoBCodec == NULL ){
  2034. LOG_ERROR("Out VideoCodec Not Found!");
  2035. av_free( m_pVideoACodec );
  2036. return false;
  2037. #ifdef DEBUG_EXTRA
  2038. } else {
  2039. LOG("Video Encoder B Created");
  2040. #endif
  2041. };
  2042. m_pCodecBCtx = avcodec_alloc_context3( m_pVideoBCodec );
  2043. if ( m_pCodecBCtx == NULL){
  2044. LOG_ERROR("Video Encoder B Context Memory Allocation Error!");
  2045. av_free( m_pVideoACodec );
  2046. av_free( m_pVideoBCodec );
  2047. avformat_free_context( m_pFormatCtxA );
  2048. avformat_free_context( m_pFormatCtxB );
  2049. return false;
  2050. #ifdef DEBUG_EXTRA
  2051. } else {
  2052. LOG("Video Encoder Context B Allocated");
  2053. #endif
  2054. };
  2055. m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC;
  2056. m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO;
  2057. m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2058. m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  2059. m_pCodecACtx->max_b_frames=1;
  2060. m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width;
  2061. m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height;
  2062. m_pCodecACtx->time_base.num = 1;
  2063. m_pCodecACtx->time_base.den = m_sStreamData.fps;
  2064. m_pCodecACtx->framerate.num = m_sStreamData.fps;
  2065. m_pCodecACtx->framerate.den = 1;
  2066. m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC;
  2067. m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  2068. m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2069. m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  2070. m_pCodecBCtx->max_b_frames=1;
  2071. m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width;
  2072. m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height;
  2073. m_pCodecBCtx->time_base.num = 1;
  2074. m_pCodecBCtx->time_base.den = m_sStreamData.fps;
  2075. m_pCodecBCtx->framerate.num = m_sStreamData.fps;
  2076. m_pCodecBCtx->framerate.den = 1;
  2077. //https://pastebin.com/yG37YhWW
  2078. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  2079. //G@ avcodec encode NALU mp4
  2080. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2081. ////m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  2082. #endif
  2083. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2084. ////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  2085. #endif
  2086. m_pFormatOpts = NULL;
  2087. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  2088. if( ( m_pCodecACtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecACtx->codec_id == AV_CODEC_ID_H265 ) ){
  2089. #ifdef DEBUG_EXTRA
  2090. LOG("Begin Options!");
  2091. #endif
  2092. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  2093. //Set format's privater options, to be passed to avformat_write_header()
  2094. /*
  2095. mp4 muxer AVOptions:
  2096. -movflags E..... MOV muxer flags (default 0)
  2097. rtphint E..... Add RTP hint tracks
  2098. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  2099. frag_keyframe E..... Fragment at video keyframes
  2100. separate_moof E..... Write separate moof/mdat atoms for each track
  2101. frag_custom E..... Flush fragments on caller requests
  2102. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  2103. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  2104. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  2105. delay_moov ??
  2106. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  2107. -rtpflags E..... RTP muxer flags (default 0)
  2108. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  2109. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  2110. skip_rtcp E..... Don't send RTCP sender reports
  2111. h264_mode0 E..... Use mode 0 for H264 in RTP
  2112. send_bye E..... Send RTCP BYE packets when finishing
  2113. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  2114. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  2115. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  2116. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  2117. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  2118. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  2119. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  2120. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  2121. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  2122. */
  2123. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  2124. LOG_ERROR( "av_dict_set movflags!");
  2125. #ifdef DEBUG_EXTRA
  2126. } else {
  2127. LOG("MOV FLAG SET!");
  2128. #endif
  2129. };
  2130. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  2131. // LOG_ERROR( "av_dict_set live!" );
  2132. //};
  2133. //default brand is "isom", which fails on some devices
  2134. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  2135. LOG_ERROR( "av_dict_set brand!" );
  2136. };
  2137. //m_pCodecCtx->max_b_frames = 1;
  2138. //m_pCodecCtx->level = 31;
  2139. m_pCodecACtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  2140. /// P-frames, generated by referencing data from prev and future frames.
  2141. /// [Compression up, CPU usage up]
  2142. /// [use 3/gop]
  2143. m_pCodecACtx->max_b_frames = 5;
  2144. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  2145. /// [use 3�5 ref per P]
  2146. m_pCodecACtx->refs = 3;
  2147. /// Compression efficiency (slower -> better quality + higher cpu%)
  2148. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  2149. /// Set this option to "ultrafast" is critical for realtime encoding
  2150. av_opt_set( m_pCodecACtx->priv_data, "preset", "ultrafast", 0);
  2151. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  2152. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  2153. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  2154. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  2155. av_opt_set( m_pCodecACtx->priv_data, "crf", "32", 0);
  2156. /// Change settings based upon the specifics of input
  2157. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  2158. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  2159. av_opt_set( m_pCodecACtx->priv_data, "tune", "zerolatency", 0);
  2160. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  2161. /// Because Quicktime (ie. iOS) doesn't support this option
  2162. av_opt_set( m_pCodecACtx->priv_data, "b-pyramid", "0", 0 );
  2163. #ifdef DEBUG_EXTRA
  2164. LOG("End Options!");
  2165. #endif
  2166. } else {
  2167. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2168. };
  2169. if( ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H265 ) ){
  2170. #ifdef DEBUG_EXTRA
  2171. LOG("Begin Options!");
  2172. #endif
  2173. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  2174. //Set format's privater options, to be passed to avformat_write_header()
  2175. /*
  2176. mp4 muxer AVOptions:
  2177. -movflags E..... MOV muxer flags (default 0)
  2178. rtphint E..... Add RTP hint tracks
  2179. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  2180. frag_keyframe E..... Fragment at video keyframes
  2181. separate_moof E..... Write separate moof/mdat atoms for each track
  2182. frag_custom E..... Flush fragments on caller requests
  2183. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  2184. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  2185. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  2186. delay_moov ??
  2187. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  2188. -rtpflags E..... RTP muxer flags (default 0)
  2189. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  2190. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  2191. skip_rtcp E..... Don't send RTCP sender reports
  2192. h264_mode0 E..... Use mode 0 for H264 in RTP
  2193. send_bye E..... Send RTCP BYE packets when finishing
  2194. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  2195. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  2196. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  2197. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  2198. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  2199. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  2200. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  2201. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  2202. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  2203. */
  2204. //m_pCodecCtx->max_b_frames = 1;
  2205. //m_pCodecCtx->level = 31;
  2206. m_pCodecBCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  2207. /// P-frames, generated by referencing data from prev and future frames.
  2208. /// [Compression up, CPU usage up]
  2209. /// [use 3/gop]
  2210. m_pCodecBCtx->max_b_frames = 5;
  2211. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  2212. /// [use 3�5 ref per P]
  2213. m_pCodecBCtx->refs = 3;
  2214. /// Compression efficiency (slower -> better quality + higher cpu%)
  2215. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  2216. /// Set this option to "ultrafast" is critical for realtime encoding
  2217. av_opt_set( m_pCodecBCtx->priv_data, "preset", "ultrafast", 0);
  2218. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  2219. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  2220. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  2221. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  2222. av_opt_set( m_pCodecBCtx->priv_data, "crf", "32", 0);
  2223. /// Change settings based upon the specifics of input
  2224. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  2225. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  2226. av_opt_set( m_pCodecBCtx->priv_data, "tune", "zerolatency", 0);
  2227. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  2228. /// Because Quicktime (ie. iOS) doesn't support this option
  2229. av_opt_set( m_pCodecBCtx->priv_data, "b-pyramid", "0", 0 );
  2230. #ifdef DEBUG_EXTRA
  2231. LOG("End Options!");
  2232. #endif
  2233. } else {
  2234. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2235. };
  2236. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  2237. #ifdef DEBUG_EXTRA
  2238. char TB[129];
  2239. sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den );
  2240. LOG(TB);
  2241. sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den );
  2242. LOG(TB);
  2243. #endif
  2244. ////m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  2245. ////m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  2246. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  2247. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2248. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2249. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2250. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2251. //// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate =
  2252. ////dst_fps;
  2253. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  2254. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2255. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2256. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2257. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2258. //// m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate =
  2259. ////dst_fps;
  2260. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2261. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2262. //// avcodec_parameters_from_context( m_pVideoStrA->codecpar,
  2263. ////m_pCodecACtx );
  2264. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2265. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  2266. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2267. //// avcodec_parameters_from_context( m_pVideoStrB->codecpar,
  2268. ////m_pCodecBCtx );
  2269. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2270. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  2271. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2272. if ( avcodec_is_open( m_pCodecACtx ) == 0 ) {
  2273. LOG("output codec context is closed, opening");
  2274. if ( avcodec_open2( m_pCodecACtx, m_pVideoACodec, NULL) < 0 ) {
  2275. LOG_ERROR("Error opening2 encoder");
  2276. return false;
  2277. #ifdef DEBUG_EXTRA
  2278. } else {
  2279. LOG("output codec context is opened");
  2280. #endif
  2281. };
  2282. #ifdef DEBUG_EXTRA
  2283. } else {
  2284. LOG("output codec context is already opened");
  2285. #endif
  2286. };
  2287. if ( avcodec_is_open( m_pCodecBCtx ) == 0 ) {
  2288. LOG("output codec context is closed, opening");
  2289. if ( avcodec_open2( m_pCodecBCtx, m_pVideoBCodec, NULL) < 0 ) {
  2290. LOG_ERROR("Error opening2 encoder");
  2291. return false;
  2292. #ifdef DEBUG_EXTRA
  2293. } else {
  2294. LOG("output codec context is opened");
  2295. #endif
  2296. };
  2297. #ifdef DEBUG
  2298. } else {
  2299. LOG("output codec context is already opened");
  2300. #endif
  2301. };
  2302. #else // SEPARATED_VIDEO_ENCODERS
  2303. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  2304. LOG_ERROR("Format CTX A alloc error!");
  2305. return false;
  2306. } else {
  2307. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  2308. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2309. };
  2310. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  2311. LOG_ERROR("Format CTX B alloc error!");
  2312. avformat_free_context( m_pFormatCtxA );
  2313. return false;
  2314. } else {
  2315. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  2316. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2317. };
  2318. m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  2319. if( m_pVideoCodec == NULL ){
  2320. LOG_ERROR("Out VideoCodec Not Found!");
  2321. avformat_free_context( m_pFormatCtxA );
  2322. avformat_free_context( m_pFormatCtxB );
  2323. return false;
  2324. #ifdef DEBUG_EXTRA
  2325. } else {
  2326. LOG("Out Video Codec Found");
  2327. #endif
  2328. };
  2329. m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec );
  2330. if ( m_pCodecCtx == NULL){
  2331. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  2332. av_free( m_pVideoCodec );
  2333. avformat_free_context( m_pFormatCtxA );
  2334. avformat_free_context( m_pFormatCtxB );
  2335. return false;
  2336. #ifdef DEBUG_EXTRA
  2337. } else {
  2338. LOG("Out Codec Context3 Allocated");
  2339. #endif
  2340. };
  2341. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec );
  2342. if ( m_pVideoStrA == NULL){
  2343. LOG_ERROR("VideoStream A Not Created!");
  2344. avcodec_free_context( &m_pCodecCtx );
  2345. av_free( m_pCodecCtx );
  2346. av_free( m_pVideoCodec );
  2347. //avformat_close_input ( &m_pFormatCtxA );
  2348. //avformat_close_input ( &m_pFormatCtxB );
  2349. avformat_free_context( m_pFormatCtxA );
  2350. avformat_free_context( m_pFormatCtxB );
  2351. return false;
  2352. #ifdef DEBUG_EXTRA
  2353. } else {
  2354. LOG("VideoStream A is Created");
  2355. #endif
  2356. };
  2357. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec );
  2358. if ( m_pVideoStrB == NULL){
  2359. LOG_ERROR("VideoStream B Not Created!");
  2360. avcodec_free_context( &m_pCodecCtx );
  2361. av_free( m_pCodecCtx );
  2362. av_free( m_pVideoCodec );
  2363. //avformat_close_input ( &m_pFormatCtxA );
  2364. //avformat_close_input ( &m_pFormatCtxB );
  2365. avformat_free_context( m_pFormatCtxA );
  2366. avformat_free_context( m_pFormatCtxB );
  2367. return false;
  2368. #ifdef DEBUG_EXTRA
  2369. } else {
  2370. LOG("VideoStream B is Created");
  2371. #endif
  2372. };
  2373. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  2374. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  2375. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2376. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  2377. //m_pCodecCtx->thread_count = 1;
  2378. //m_pCodecCtx->bit_rate_tolerance = 1;
  2379. //m_pCodecCtx->global_quality = 100;
  2380. //m_pCodecCtx->compression_level = 2;
  2381. m_pCodecCtx->max_b_frames=1;
  2382. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  2383. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  2384. m_pCodecCtx->time_base.num = 1;
  2385. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  2386. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  2387. m_pCodecCtx->framerate.den = 1;
  2388. //https://pastebin.com/yG37YhWW
  2389. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  2390. //G@ avcodec encode NALU mp4
  2391. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2392. m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  2393. #endif
  2394. m_pFormatOpts = NULL;
  2395. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  2396. if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){
  2397. #ifdef DEBUG_EXTRA
  2398. LOG("Begin Options!");
  2399. #endif
  2400. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  2401. //Set format's privater options, to be passed to avformat_write_header()
  2402. /*
  2403. mp4 muxer AVOptions:
  2404. -movflags E..... MOV muxer flags (default 0)
  2405. rtphint E..... Add RTP hint tracks
  2406. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  2407. frag_keyframe E..... Fragment at video keyframes
  2408. separate_moof E..... Write separate moof/mdat atoms for each track
  2409. frag_custom E..... Flush fragments on caller requests
  2410. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  2411. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  2412. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  2413. delay_moov ??
  2414. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  2415. -rtpflags E..... RTP muxer flags (default 0)
  2416. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  2417. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  2418. skip_rtcp E..... Don't send RTCP sender reports
  2419. h264_mode0 E..... Use mode 0 for H264 in RTP
  2420. send_bye E..... Send RTCP BYE packets when finishing
  2421. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  2422. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  2423. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  2424. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  2425. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  2426. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  2427. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  2428. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  2429. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  2430. */
  2431. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  2432. LOG_ERROR( "av_dict_set movflags!");
  2433. #ifdef DEBUG_EXTRA
  2434. } else {
  2435. LOG("MOV FLAG SET!");
  2436. #endif
  2437. };
  2438. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  2439. // LOG_ERROR( "av_dict_set live!" );
  2440. //};
  2441. //default brand is "isom", which fails on some devices
  2442. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  2443. LOG_ERROR( "av_dict_set brand!" );
  2444. };
  2445. //m_pCodecCtx->max_b_frames = 1;
  2446. //m_pCodecCtx->level = 31;
  2447. m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  2448. /// P-frames, generated by referencing data from prev and future frames.
  2449. /// [Compression up, CPU usage up]
  2450. /// [use 3/gop]
  2451. m_pCodecCtx->max_b_frames = 5;
  2452. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  2453. /// [use 3�5 ref per P]
  2454. m_pCodecCtx->refs = 3;
  2455. /// Compression efficiency (slower -> better quality + higher cpu%)
  2456. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  2457. /// Set this option to "ultrafast" is critical for realtime encoding
  2458. av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  2459. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  2460. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  2461. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  2462. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  2463. av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0);
  2464. /// Change settings based upon the specifics of input
  2465. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  2466. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  2467. av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  2468. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  2469. /// Because Quicktime (ie. iOS) doesn't support this option
  2470. av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
  2471. #ifdef DEBUG_EXTRA
  2472. LOG("End Options!");
  2473. #endif
  2474. } else {
  2475. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2476. };
  2477. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  2478. #ifdef DEBUG_EXTRA
  2479. char TB[129];
  2480. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den );
  2481. LOG(TB);
  2482. #endif
  2483. m_pVideoStrA->time_base = m_pCodecCtx->time_base;
  2484. m_pVideoStrB->time_base = m_pCodecCtx->time_base;
  2485. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  2486. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2487. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2488. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2489. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2490. m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  2491. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  2492. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  2493. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  2494. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2495. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  2496. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  2497. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2498. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  2499. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx );
  2500. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2501. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  2502. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2503. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx );
  2504. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  2505. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  2506. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  2507. if ( avcodec_is_open( m_pCodecCtx ) == 0 ) {
  2508. LOG("output codec context is closed, opening");
  2509. if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) {
  2510. LOG_ERROR("Error opening2 encoder");
  2511. return false;
  2512. #ifdef DEBUG_EXTRA
  2513. } else {
  2514. LOG("output codec context is opened");
  2515. #endif
  2516. };
  2517. #ifdef DEBUG_EXTRA
  2518. } else {
  2519. LOG("output codec context is already opened");
  2520. #endif
  2521. };
  2522. #endif // SEPARATED_VIDEO_ENCODERS
  2523. m_pConvertCtx = sws_getContext(
  2524. m_pMaster->m_sEmbedVideoData.width,
  2525. m_pMaster->m_sEmbedVideoData.height,
  2526. AV_PIX_FMT_BGR24,
  2527. m_pMaster->m_sEmbedVideoData.width,
  2528. m_pMaster->m_sEmbedVideoData.height,
  2529. VIDEO_OUTPUT_PIX_FMT,
  2530. SWS_FAST_BILINEAR,
  2531. NULL,
  2532. NULL,
  2533. NULL
  2534. );
  2535. if ( m_pConvertCtx == NULL ) {
  2536. return false;
  2537. }
  2538. m_pAVFrame = av_frame_alloc();
  2539. if ( m_pAVFrame == NULL ) {
  2540. return false;
  2541. };
  2542. 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));
  2543. if( m_pOutBuffer == NULL ) {
  2544. return false;
  2545. };
  2546. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  2547. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  2548. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  2549. //av_frame_get_buffer( m_pAVFrame, 0 );
  2550. 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 );
  2551. //av_frame_make_writable( m_pAVFrame );
  2552. #endif //OPENCV_VIDEO_OUTPUT
  2553. return init();
  2554. };
  2555. //encoding thread
  2556. void streamHandler::m_fThreadProc( void ){
  2557. char tB[128];
  2558. #ifndef OPENCV_VIDEO_OUTPUT
  2559. AVPacket mPacket;
  2560. int bGotPacket;
  2561. int rVal = 0;
  2562. av_init_packet( &mPacket );
  2563. #endif
  2564. while( m_bThreadStatus != TH_ENDED ){
  2565. //At the begining All streams are closed --> try to Open
  2566. if( m_bThreadStatus < TH_WORKING ){
  2567. if( !openSegmentA() ){
  2568. m_bThreadStatus = TH_ENDED;
  2569. continue;
  2570. };
  2571. //if( !openSegmentB() ){
  2572. // m_bThreadStatus = TH_ENDED;
  2573. // continue;
  2574. //};
  2575. m_bThreadStatus = TH_WORKING;
  2576. continue;
  2577. };
  2578. m_mEncodingQueueProtector.lock();
  2579. if ( m_qEncodingQueue.size() ) {
  2580. ENCODING_BUFFER *tData = m_qEncodingQueue.front();
  2581. if( tData ){
  2582. m_qEncodingQueue.pop();
  2583. m_mEncodingQueueProtector.unlock();
  2584. #ifdef OPENCV_VIDEO_OUTPUT
  2585. cv::Mat image( tData->rows, tData->cols, CV_8UC3 );
  2586. memcpy( image.data, tData->data, tData->size );
  2587. free( tData->data );
  2588. free( tData );
  2589. if ( m_bSegAActive ) {
  2590. if ( m_pEncoderA->isOpened() ) {
  2591. m_pEncoderA->write( image );
  2592. m_mFrameCounterProtector.lock();
  2593. m_nSegAFrameCounter++;
  2594. m_mFrameCounterProtector.unlock();
  2595. };
  2596. };
  2597. if ( m_bSegBActive ) {
  2598. if ( m_pEncoderB->isOpened() ) {
  2599. m_pEncoderB->write( image );
  2600. m_mFrameCounterProtector.lock();
  2601. m_nSegBFrameCounter++;
  2602. m_mFrameCounterProtector.unlock();
  2603. };
  2604. };
  2605. #else
  2606. //av_frame_make_writable( m_pAVFrame );
  2607. //m_qEncodingQueue.pop();
  2608. //m_mEncodingQueueProtector.unlock();
  2609. sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize );
  2610. free( tData->data[0] );
  2611. free( tData );
  2612. /*
  2613. AV_PICTURE_TYPE_NONE Undefined.
  2614. AV_PICTURE_TYPE_I Intra.
  2615. AV_PICTURE_TYPE_P Predicted.
  2616. AV_PICTURE_TYPE_B Bi-dir predicted.
  2617. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4.
  2618. AV_PICTURE_TYPE_SI Switching Intra.
  2619. AV_PICTURE_TYPE_SP Switching Predicted.
  2620. AV_PICTURE_TYPE_BI BI type.
  2621. */
  2622. if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) {
  2623. m_pAVFrame->key_frame = 1;
  2624. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I;
  2625. } else {
  2626. m_pAVFrame->key_frame = 0;
  2627. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
  2628. };
  2629. m_pAVFrame->pts = m_nGlobalFrameCounter + 1;
  2630. #ifdef SEPARATED_VIDEO_ENCODERS
  2631. //if( m_bSegAActive ) {
  2632. rVal = avcodec_send_frame(m_pCodecACtx, m_pAVFrame );
  2633. //};
  2634. //if( m_bSegBActive ) {
  2635. // rVal = avcodec_send_frame(m_pCodecBCtx, m_pAVFrame );
  2636. //};
  2637. #else // SEPARATED_VIDEO_ENCODERS
  2638. rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame );
  2639. #endif // SEPARATED_VIDEO_ENCODERS
  2640. #endif // OPENCV_VIDEO_OUTPUT
  2641. m_mFrameCounterProtector.lock();
  2642. m_nGlobalFrameCounter++;
  2643. m_mFrameCounterProtector.unlock();
  2644. } else m_mEncodingQueueProtector.unlock();
  2645. } else {
  2646. m_mEncodingQueueProtector.unlock();
  2647. // If No Encode Job -> Test Commands!
  2648. m_mCurrentOperationProtector.lock();
  2649. switch ( m_bCOP ) {
  2650. case 0x01:{
  2651. LOG( m_sStreamSegmentInfo[0].scratchPath );
  2652. m_bSegAActive = false;
  2653. if ( !m_bSegADelete ) {
  2654. #ifdef OPENCV_VIDEO_OUTPUT
  2655. if ( m_pEncoderA->isOpened() ) {
  2656. m_pEncoderA->release();
  2657. };
  2658. #else
  2659. av_write_trailer( m_pFormatCtxA );
  2660. avio_close( m_pFormatCtxA->pb );
  2661. #endif //OPENCV_VIDEO_OUTPUT
  2662. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0] );
  2663. if ( bEVT ) {
  2664. basicEventHeap::getInstance()->broadcast( bEVT );
  2665. } else LOG_ERROR( "Event Creation failure!");
  2666. #ifdef DEBUG
  2667. LOG("Stream A is Saved");
  2668. #endif
  2669. } else {
  2670. #ifdef OPENCV_VIDEO_OUTPUT
  2671. if ( m_pEncoderA->isOpened() ) {
  2672. m_pEncoderA->release();
  2673. };
  2674. #else
  2675. #ifdef EVE_DONT_DELETE_SEGMENTS
  2676. av_write_trailer( m_pFormatCtxA );
  2677. #endif
  2678. avio_close( m_pFormatCtxA->pb );
  2679. #endif //OPENCV_VIDEO_OUTPUT
  2680. #ifndef EVE_DONT_DELETE_SEGMENTS
  2681. unlink( m_sStreamSegmentInfo[0].scratchPath );
  2682. #endif
  2683. #ifdef DEBUG
  2684. LOG("Stream A is Closed!");
  2685. #endif
  2686. };
  2687. #ifdef OPENCV_VIDEO_OUTPUT
  2688. #else
  2689. #ifdef SEPARATED_VIDEO_ENCODERS
  2690. #ifdef DEBUG_EXTRA
  2691. LOG("Del FCTX");
  2692. #endif
  2693. avformat_free_context( m_pFormatCtxA );
  2694. m_pVideoStrA = NULL;
  2695. #ifdef DEBUG_EXTRA
  2696. LOG("Del FCTX DONE");
  2697. #endif
  2698. #endif // SEPARATED_VIDEO_ENCODERS
  2699. #endif
  2700. break;
  2701. };
  2702. case 0x02:{
  2703. LOG( m_sStreamSegmentInfo[1].scratchPath );
  2704. m_bSegBActive = false;
  2705. if ( !m_bSegBDelete ) {
  2706. #ifdef OPENCV_VIDEO_OUTPUT
  2707. if ( m_pEncoderB->isOpened() ) {
  2708. m_pEncoderB->release();
  2709. };
  2710. #else
  2711. av_write_trailer( m_pFormatCtxB );
  2712. avio_close( m_pFormatCtxB->pb );
  2713. #endif //OPENCV_VIDEO_OUTPUT
  2714. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1] );
  2715. if ( bEVT ) {
  2716. basicEventHeap::getInstance()->broadcast( bEVT );
  2717. } else LOG_ERROR( "Event Creation failure!");
  2718. #ifdef DEBUG
  2719. LOG("Stream B is Saved");
  2720. #endif
  2721. } else {
  2722. #ifdef OPENCV_VIDEO_OUTPUT
  2723. if ( m_pEncoderB->isOpened() ) {
  2724. m_pEncoderB->release();
  2725. };
  2726. #else
  2727. #ifdef EVE_DONT_DELETE_SEGMENTS
  2728. av_write_trailer( m_pFormatCtxB );
  2729. #endif
  2730. avio_close( m_pFormatCtxB->pb );
  2731. #endif // OPENCV_VIDEO_OUTPUT
  2732. #ifndef EVE_DONT_DELETE_SEGMENTS
  2733. unlink( m_sStreamSegmentInfo[1].scratchPath );
  2734. #endif
  2735. #ifdef DEBUG
  2736. LOG("Stream B is Closed!");
  2737. #endif
  2738. };
  2739. #ifdef OPENCV_VIDEO_OUTPUT
  2740. #else
  2741. #ifdef SEPARATED_VIDEO_ENCODERS
  2742. avformat_free_context( m_pFormatCtxB );
  2743. m_pVideoStrB = NULL;
  2744. #endif // SEPARATED_VIDEO_ENCODERS
  2745. #endif
  2746. break;
  2747. };
  2748. };
  2749. m_bCOP = 0;
  2750. m_mCurrentOperationProtector.unlock();
  2751. };
  2752. #ifdef OPENCV_VIDEO_OUTPUT
  2753. #else // OPENCV_VIDEO_OUTPUT
  2754. #ifdef SEPARATED_VIDEO_ENCODERS
  2755. do {
  2756. mPacket.data = NULL;
  2757. mPacket.size = 0;
  2758. rVal = avcodec_receive_packet( m_pCodecACtx, &mPacket );
  2759. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  2760. break;
  2761. } else if( rVal < 0 ){
  2762. LOG_ERROR( "Error during encoding " );
  2763. m_bThreadStatus = TH_ENDED;
  2764. break;
  2765. };
  2766. if( !rVal ){
  2767. if ( m_bSegAActive ) {
  2768. mPacket.stream_index = m_pVideoStrA->index;
  2769. mPacket.duration = 1;
  2770. m_mFrameCounterProtector.lock();
  2771. m_nSegAFrameCounter++;
  2772. m_mFrameCounterProtector.unlock();
  2773. mPacket.pts = av_rescale_q( m_nSegAFrameCounter, m_pCodecACtx->time_base, m_pVideoStrA->time_base );
  2774. //mPacket.pts = AV_NOPTS_VALUE;
  2775. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  2776. mPacket.dts = mPacket.pts;
  2777. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  2778. if( rc < 0 ){
  2779. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  2780. m_bThreadStatus = TH_ENDED;
  2781. LOG_ERROR("Trouble with Video Output A!");
  2782. av_strerror( rc, tB, 128 );
  2783. LOG_ERROR( tB );
  2784. break; //continue (changed since embed into do-while)
  2785. };
  2786. };
  2787. if ( m_bSegBActive ) {
  2788. mPacket.stream_index = m_pVideoStrB->index;
  2789. mPacket.duration = 1;
  2790. m_mFrameCounterProtector.lock();
  2791. m_nSegBFrameCounter++;
  2792. m_mFrameCounterProtector.unlock();
  2793. mPacket.pts = av_rescale_q( m_nSegBFrameCounter, m_pCodecBCtx->time_base, m_pVideoStrB->time_base );
  2794. //mPacket.pts = AV_NOPTS_VALUE;
  2795. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  2796. mPacket.dts = mPacket.pts;
  2797. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  2798. if( rc < 0 ) {
  2799. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  2800. m_bThreadStatus = TH_ENDED;
  2801. LOG_ERROR( "Trouble with Video Output B!" );
  2802. av_strerror( rc, tB, 128 );
  2803. LOG_ERROR( tB );
  2804. break; //continue (changed since embed into do-while)
  2805. };
  2806. };
  2807. av_packet_unref( &mPacket );
  2808. };
  2809. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  2810. #else // ! SEPARATED_VIDEO_ENCODERS
  2811. do {
  2812. mPacket.data = NULL;
  2813. mPacket.size = 0;
  2814. rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket );
  2815. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  2816. break;
  2817. } else if( rVal < 0 ){
  2818. LOG_ERROR( "Error during encoding " );
  2819. m_bThreadStatus = TH_ENDED;
  2820. break;
  2821. };
  2822. if( !rVal ){
  2823. if ( m_bSegAActive ) {
  2824. mPacket.stream_index = m_pVideoStrA->index;
  2825. mPacket.duration = 1;
  2826. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  2827. //mPacket.pts = AV_NOPTS_VALUE;
  2828. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  2829. mPacket.dts = mPacket.pts;
  2830. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  2831. if( rc < 0 ){
  2832. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  2833. m_bThreadStatus = TH_ENDED;
  2834. LOG_ERROR("Trouble with Video Output A!");
  2835. av_strerror( rc, tB, 128 );
  2836. LOG_ERROR( tB );
  2837. break; //continue (changed since embed into do-while)
  2838. };
  2839. };
  2840. if ( m_bSegBActive ) {
  2841. mPacket.stream_index = m_pVideoStrB->index;
  2842. mPacket.duration = 1;
  2843. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  2844. //mPacket.pts = AV_NOPTS_VALUE;
  2845. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  2846. mPacket.dts = mPacket.pts;
  2847. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  2848. if( rc < 0 ) {
  2849. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  2850. m_bThreadStatus = TH_ENDED;
  2851. LOG_ERROR( "Trouble with Video Output B!" );
  2852. av_strerror( rc, tB, 128 );
  2853. LOG_ERROR( tB );
  2854. break; //continue (changed since embed into do-while)
  2855. };
  2856. };
  2857. av_packet_unref( &mPacket );
  2858. };
  2859. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  2860. #endif // ! SEPARATED_VIDEO_ENCODERS
  2861. #endif // OPENCV_VIDEO_OUTPUT
  2862. };
  2863. #ifdef DEBUG_EXTRA
  2864. LOG("Encoder Loop Ended!");
  2865. #endif
  2866. };
  2867. void streamHandler::swapActiveStreams( void ){
  2868. //m_mFrameCounterProtector.lock();
  2869. m_bActiveEncoderStream = 1 - m_bActiveEncoderStream;
  2870. if ( m_bActiveEncoderStream ) {
  2871. if ( m_bSegADelete ) closeSegmentA();
  2872. } else {
  2873. if ( m_bSegBDelete ) closeSegmentB();
  2874. };
  2875. //m_mFrameCounterProtector.unlock();
  2876. };
  2877. #endif // EVE_ENABLE_VIDEO
  2878. bool streamHandler::triggerEvent( uint32_t eid, uint32_t &dbid, uint32_t &frame ){
  2879. LOG("Trig Evt");
  2880. #ifdef EVE_ENABLE_VIDEO
  2881. m_mFrameCounterProtector.lock();
  2882. // To Mark Events Frames
  2883. m_bEvtMarkerCounter = 255;
  2884. PF_TIMESTAMP ts;
  2885. getPFTS( &ts );
  2886. /*
  2887. if ( m_nVideoRegisteredDBID == 0 ) {
  2888. LOG("New Event!");
  2889. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  2890. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  2891. m_sStreamData.id,
  2892. m_cSegMD5A,
  2893. VIDEO_OUTPUT_CONTAINER,
  2894. ts.seconds,
  2895. ts.milliseconds,
  2896. m_sStreamData.fps
  2897. );
  2898. m_bSegADelete = false;
  2899. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  2900. } else { // Stream B is Active
  2901. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  2902. m_sStreamData.id,
  2903. m_cSegMD5B,
  2904. VIDEO_OUTPUT_CONTAINER,
  2905. ts.seconds,
  2906. ts.milliseconds,
  2907. m_sStreamData.fps
  2908. );
  2909. m_bSegBDelete = false;
  2910. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  2911. };
  2912. };
  2913. */
  2914. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  2915. m_bSegADelete = false;
  2916. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  2917. } else { // Stream B is Active
  2918. m_bSegBDelete = false;
  2919. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  2920. };
  2921. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventIDS.push_back( eid );
  2922. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTSS.push_back( ts.seconds );
  2923. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTMS.push_back( ts.milliseconds );
  2924. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventFrames.push_back( frame );
  2925. //dbid = m_sStreamSegmentInfo[m_bActiveEncoderStream].db_id;// = m_nVideoRegisteredDBID;
  2926. m_mFrameCounterProtector.unlock();
  2927. //if ( dbid == 0 ) return false;
  2928. //dbid = m_nVideoRegisteredDBID;
  2929. LOG("Event Registered!");
  2930. #endif // EVE_ENABLE_VIDEO
  2931. return true;
  2932. };
  2933. bool streamHandler::triggerCamMove( void ){
  2934. LOG("Trig Cammove");
  2935. m_bCamMoveCounter = 255;
  2936. return true;
  2937. };
  2938. bool streamHandler::validate( void ){
  2939. if ( m_pSource ) {
  2940. if( m_pSource->getStatus() < MS_CLOSING )
  2941. #ifdef EVE_ENABLE_VIDEO
  2942. if( m_bThreadStatus < TH_ENDED )
  2943. #endif
  2944. return true;
  2945. };
  2946. return false;
  2947. };
  2948. #undef LOG
  2949. #undef LOG_ERROR
  2950. #undef TLOG
  2951. #undef TLOG_ERROR