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.

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