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.

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