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.

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