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.

3737 lines
143 KiB

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