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.

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