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.

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