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.

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