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.

4019 lines
174 KiB

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