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.

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