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.

3436 lines
146 KiB

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