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.

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