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.

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