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.

4236 lines
178 KiB

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