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.

3766 lines
144 KiB

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