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.

3903 lines
147 KiB

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