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.

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