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.

3591 lines
157 KiB

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