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.

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