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.

5141 lines
139 KiB

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