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.

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