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.

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