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.

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