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.

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