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.

3445 lines
147 KiB

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