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.

3901 lines
144 KiB

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