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.

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