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. char tB[128];
  2544. sprintf( tB, "A opened %d.%d", m_sStreamSegmentInfo[0].streamTSS, m_sStreamSegmentInfo[0].streamTMS );
  2545. LOG( tB );
  2546. strncpy( m_sStreamSegmentInfo[0].recordEXT, VIDEO_OUTPUT_CONTAINER, 6 );
  2547. m_sStreamSegmentInfo[0].streamFPS = m_sStreamData.fps;
  2548. m_sStreamSegmentInfo[0].streamWidth = m_pMaster->getWidh();
  2549. m_sStreamSegmentInfo[0].streamHeight = m_pMaster->getHeight();
  2550. m_sStreamSegmentInfo[0].eventIDS.clear();
  2551. m_sStreamSegmentInfo[0].eventTSS.clear();
  2552. m_sStreamSegmentInfo[0].eventTMS.clear();
  2553. m_sStreamSegmentInfo[0].eventFrames.clear();
  2554. m_sStreamSegmentInfo[0].dataSize = 0;
  2555. m_sStreamSegmentInfo[0].db_id = 0;
  2556. #ifdef DIRECT_MJPEG_COMPOSING
  2557. m_pOutputFD[0] = fopen( m_sStreamSegmentInfo[0].scratchPath, "wb+" );
  2558. m_nSegAFrameCounter = 0;
  2559. m_nSegAShiftFrames = 0;
  2560. m_bSegAActive = true;
  2561. m_bSegADelete = true;
  2562. #else // !DIRECT_MJPEG_COMPOSING
  2563. #ifdef OPENCV_VIDEO_OUTPUT
  2564. if ( m_pEncoderA ) {
  2565. //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  2566. int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  2567. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2568. m_bAFrameSkeepDivider = m_bWebFrameSkeepDivider;
  2569. m_bAOutputFPS = m_bInitialOutputFPS / m_bAFrameSkeepDivider;
  2570. double fps = m_bAOutputFPS;
  2571. #else
  2572. double fps = m_sStreamData.fps;
  2573. #endif
  2574. cv::String mn( m_sStreamSegmentInfo[0].scratchPath );
  2575. cv::Size fz( m_sStreamData.width, m_sStreamData.height );
  2576. //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  2577. if( !m_pEncoderA->open( mn, fourcc, fps, fz ) ){
  2578. LOG_ERROR("Cannot Open Output Segment A!");
  2579. return false;
  2580. #ifdef DEBUG_EXTRA
  2581. } else {
  2582. char tB[256];
  2583. sprintf( tB,"VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps );
  2584. LOG( tB );
  2585. #endif
  2586. };
  2587. m_bSegAActive = true;
  2588. m_bSegADelete = true;
  2589. m_nSegAFrameCounter = 0;
  2590. m_nSegAShiftFrames = 0;
  2591. } else {
  2592. LOG_ERROR("No Encoder(A) Object!");
  2593. return false;
  2594. };
  2595. #else// !OPENCV_VIDEO_OUTPUT
  2596. //Check if Encoder is Ready
  2597. if ( m_pFormat == NULL ) return false;
  2598. #ifdef SEPARATED_VIDEO_ENCODERS
  2599. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  2600. LOG_ERROR("Format CTX A alloc error!");
  2601. return false;
  2602. } else {
  2603. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  2604. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2605. };
  2606. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoACodec );
  2607. if ( m_pVideoStrA == NULL){
  2608. avformat_free_context( m_pFormatCtxA );
  2609. return false;
  2610. #ifdef DEBUG_EXTRA
  2611. } else {
  2612. LOG("VideoStream A is Created");
  2613. #endif
  2614. };
  2615. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  2616. m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps;
  2617. m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  2618. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecACtx );
  2619. #ifdef DEBUG_EXTRA
  2620. LOG("Opening Stream A");
  2621. LOG(m_cSegNameA);
  2622. char tB[128];
  2623. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  2624. LOG( tB );
  2625. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  2626. LOG( tB );
  2627. #endif
  2628. //if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  2629. if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, AVIO_FLAG_WRITE) < 0) {
  2630. LOG_ERROR("Could not open output file.");
  2631. return m_bSegAActive;
  2632. };
  2633. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  2634. LOG_ERROR("Error occurred when writing header to output file.");
  2635. return m_bSegAActive;
  2636. };
  2637. //m_mFrameCounterProtector.lock();
  2638. m_nSegAFrameCounter = 0;
  2639. m_nSegAShiftFrames = 0;
  2640. m_bSegAActive = true;
  2641. m_bSegADelete = true;
  2642. //m_mFrameCounterProtector.unlock();
  2643. #else // SEPARATED_VIDEO_ENCODERS
  2644. m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1;
  2645. if (m_pVideoStrA->nb_frames) {
  2646. m_pVideoStrA->nb_frames = 0;
  2647. m_pVideoStrA->start_time = 0;
  2648. m_pVideoStrA->first_dts = 0;
  2649. m_pFormatCtxA->start_time = 0;
  2650. };
  2651. #ifdef DEBUG_EXTRA
  2652. LOG("Opening Stream A");
  2653. LOG(m_cSegNameA);
  2654. char tB[128];
  2655. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  2656. LOG( tB );
  2657. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  2658. LOG( tB );
  2659. #endif
  2660. if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  2661. LOG_ERROR("Could not open output file.");
  2662. return m_bSegAActive;
  2663. };
  2664. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  2665. LOG_ERROR("Error occurred when writing header to output file.");
  2666. return m_bSegAActive;
  2667. };
  2668. //m_mFrameCounterProtector.lock();
  2669. m_nSegAFrameCounter = 0;
  2670. m_nSegAShiftFrames = 0;
  2671. m_bSegAActive = true;
  2672. m_bSegADelete = true;
  2673. //m_mFrameCounterProtector.unlock();
  2674. #endif // SEPARATED_VIDEO_ENCODERS
  2675. #ifdef DEBUG_EXTRA
  2676. LOG("Stream A Opened");
  2677. #endif
  2678. #endif // !OPENCV_VIDEO_OUTPUT
  2679. #endif // !DIRECT_MJPEG_COMPOSING
  2680. };
  2681. };
  2682. return m_bSegAActive;
  2683. };
  2684. bool streamHandler::openSegmentB( void ){
  2685. if( !m_bSegBActive ){
  2686. CSTR tAM = getUniqID_MD5();
  2687. if ( tAM ) {
  2688. sprintf( m_sStreamSegmentInfo[1].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER );
  2689. strncpy( m_sStreamSegmentInfo[1].recordMD5, tAM, 32 );
  2690. m_sStreamSegmentInfo[1].recordMD5[32] = (char)0;
  2691. free( tAM );
  2692. m_sStreamSegmentInfo[1].stream_id = m_sStreamData.id;
  2693. PF_TIMESTAMP ts;
  2694. getPFTS( &ts );
  2695. m_sStreamSegmentInfo[1].streamTSS = ts.seconds;
  2696. m_sStreamSegmentInfo[1].streamTMS = ts.milliseconds;
  2697. char tB[128];
  2698. sprintf( tB, "B opened %d.%d", m_sStreamSegmentInfo[1].streamTSS, m_sStreamSegmentInfo[1].streamTMS );
  2699. LOG( tB );
  2700. strncpy( m_sStreamSegmentInfo[1].recordEXT, VIDEO_OUTPUT_CONTAINER, 6 );
  2701. m_sStreamSegmentInfo[1].streamFPS = m_sStreamData.fps;
  2702. m_sStreamSegmentInfo[1].streamWidth = m_pMaster->getWidh();
  2703. m_sStreamSegmentInfo[1].streamHeight = m_pMaster->getHeight();
  2704. m_sStreamSegmentInfo[1].eventIDS.clear();
  2705. m_sStreamSegmentInfo[1].eventTSS.clear();
  2706. m_sStreamSegmentInfo[1].eventTMS.clear();
  2707. m_sStreamSegmentInfo[1].eventFrames.clear();
  2708. m_sStreamSegmentInfo[1].dataSize = 0;
  2709. m_sStreamSegmentInfo[1].db_id = 0;
  2710. #ifdef DIRECT_MJPEG_COMPOSING
  2711. m_pOutputFD[1] = fopen( m_sStreamSegmentInfo[1].scratchPath, "wb+" );
  2712. m_nSegBFrameCounter = 0;
  2713. m_nSegBShiftFrames = 0;
  2714. m_bSegBActive = true;
  2715. m_bSegBDelete = true;
  2716. #else // !DIRECT_MJPEG_COMPOSING
  2717. #ifdef OPENCV_VIDEO_OUTPUT
  2718. if ( m_pEncoderB ) {
  2719. //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  2720. int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  2721. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2722. m_bBFrameSkeepDivider = m_bWebFrameSkeepDivider;
  2723. m_bBOutputFPS = m_bInitialOutputFPS / m_bBFrameSkeepDivider;
  2724. double fps = m_bBOutputFPS;
  2725. #else
  2726. double fps = m_sStreamData.fps;
  2727. #endif
  2728. cv::String mn( m_sStreamSegmentInfo[1].scratchPath );
  2729. cv::Size fz( m_sStreamData.width, m_sStreamData.height );
  2730. //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  2731. if( !m_pEncoderB->open( mn, fourcc, fps, fz ) ){
  2732. LOG_ERROR("Cannot Open Output Segment B!");
  2733. return false;
  2734. #ifdef DEBUG_EXTRA
  2735. } else {
  2736. char tB[256];
  2737. sprintf( tB,"VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps );
  2738. LOG( tB );
  2739. #endif
  2740. };
  2741. m_bSegBActive = true;
  2742. m_bSegBDelete = true;
  2743. m_nSegBFrameCounter = 0;
  2744. m_nSegBShiftFrames = 0;
  2745. } else {
  2746. LOG_ERROR("No Encoder(B) Object!");
  2747. return false;
  2748. };
  2749. #else // !OPENCV
  2750. //Check if Encoder is Ready
  2751. if ( m_pFormat == NULL ) return false;
  2752. #ifdef SEPARATED_VIDEO_ENCODERS
  2753. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  2754. LOG_ERROR("Format CTX B alloc error!");
  2755. return false;
  2756. } else {
  2757. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  2758. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2759. };
  2760. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoBCodec );
  2761. if ( m_pVideoStrB == NULL){
  2762. avformat_free_context( m_pFormatCtxB );
  2763. return false;
  2764. #ifdef DEBUG_EXTRA
  2765. } else {
  2766. LOG("VideoStream B is Created");
  2767. #endif
  2768. };
  2769. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  2770. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  2771. m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  2772. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecBCtx );
  2773. #ifdef DEBUG_EXTRA
  2774. LOG("Opening Stream B");
  2775. LOG( m_cSegNameB );
  2776. char tB[128];
  2777. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts );
  2778. LOG( tB );
  2779. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration );
  2780. LOG( tB );
  2781. #endif
  2782. //if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  2783. if ( avio_open( &m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE ) < 0 ){
  2784. LOG_ERROR("Could not open output file.");
  2785. avformat_free_context( m_pFormatCtxB );
  2786. return false;
  2787. };
  2788. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  2789. LOG_ERROR("Error occurred when writing header to output file.");
  2790. avio_close( m_pFormatCtxB->pb );
  2791. avformat_free_context( m_pFormatCtxB );
  2792. return false;
  2793. };
  2794. //m_mFrameCounterProtector.lock();
  2795. m_nSegBFrameCounter = 0;
  2796. m_nSegBShiftFrames = 0;
  2797. m_bSegBActive = true;
  2798. m_bSegBDelete = true;
  2799. //m_mFrameCounterProtector.unlock();
  2800. #else // SEPARATED_VIDEO_ENCODERS
  2801. m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1;
  2802. if (m_pVideoStrB->nb_frames) {
  2803. m_pVideoStrB->nb_frames = 0;
  2804. m_pVideoStrB->start_time = 0;
  2805. m_pVideoStrB->first_dts = 0;
  2806. m_pFormatCtxB->start_time = 0;
  2807. };
  2808. if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  2809. LOG_ERROR("Could not open output file.");
  2810. return m_bSegBActive;
  2811. };
  2812. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  2813. LOG_ERROR("Error occurred when writing header to output file.");
  2814. return m_bSegBActive;
  2815. };
  2816. //m_mFrameCounterProtector.lock();
  2817. m_nSegBFrameCounter = 0;
  2818. m_nSegBShiftFrames = 0;
  2819. m_bSegBActive = true;
  2820. m_bSegBDelete = true;
  2821. //m_mFrameCounterProtector.unlock();
  2822. #endif // SEPARATED_VIDEO_ENCODERS
  2823. #ifdef DEBUG_EXTRA
  2824. LOG("Stream B Opened");
  2825. #endif
  2826. #endif // !OPENCV_VIDEO_OUTPUT
  2827. #endif // !DIRECT_MJPEG_COMPOSING
  2828. };
  2829. };
  2830. return m_bSegBActive;
  2831. };
  2832. bool streamHandler::initVideoOutput(){
  2833. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2834. m_bAFrameSkeepDivider = m_bBFrameSkeepDivider = 1;
  2835. m_bAFrameSkeepDividerCounter = m_bBFrameSkeepDividerCounter = 0;
  2836. m_bCurrentOutputFPS = m_bInitialOutputFPS = m_sStreamData.fps;
  2837. m_nAPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_bAOutputFPS ) / 1000;
  2838. m_nAPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_bAOutputFPS ) / 1000;
  2839. m_nASegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_bAOutputFPS ) / 1000;
  2840. m_nAHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bAOutputFPS ) / 1000;
  2841. m_nBPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_bBOutputFPS ) / 1000;
  2842. m_nBPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_bBOutputFPS ) / 1000;
  2843. m_nBSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_bBOutputFPS ) / 1000;
  2844. m_nBHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bBOutputFPS ) / 1000;
  2845. #else
  2846. m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  2847. m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  2848. m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000;
  2849. m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000;
  2850. #endif
  2851. #ifndef DIRECT_MJPEG_COMPOSING
  2852. #ifdef OPENCV_VIDEO_OUTPUT
  2853. m_pEncoderA = new cv::VideoWriter();
  2854. if ( m_pEncoderA == NULL ) {
  2855. LOG_ERROR("Encoder A Create Failure!");
  2856. return false;
  2857. };
  2858. m_pEncoderA->set( cv::VIDEOWRITER_PROP_QUALITY, 10.0 );
  2859. m_pEncoderA->set( cv::VIDEOWRITER_PROP_NSTRIPES, -1.0 );
  2860. m_pEncoderB = new cv::VideoWriter();
  2861. if ( m_pEncoderA == NULL ) {
  2862. LOG_ERROR("Encoder B Create Failure!");
  2863. return false;
  2864. };
  2865. m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 10.0 );
  2866. m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, -1.0 );
  2867. #else
  2868. if( !initLibAV() ) return false;
  2869. m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL );
  2870. if ( m_pFormat == NULL ) {
  2871. LOG_ERROR("Out VideoFormat Not Found!");
  2872. return false;
  2873. #ifdef DEBUG_EXTRA
  2874. } else {
  2875. LOG("Output video Format");
  2876. LOG( VIDEO_OUTPUT_CONTAINER );
  2877. #endif
  2878. };
  2879. #ifdef SEPARATED_VIDEO_ENCODERS
  2880. /* Stream A */
  2881. m_pVideoACodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  2882. if( m_pVideoACodec == NULL ){
  2883. LOG_ERROR("Encoder Video Codec Not Found!");
  2884. return false;
  2885. #ifdef DEBUG_EXTRA
  2886. } else {
  2887. LOG("Video Encoder A Created");
  2888. #endif
  2889. };
  2890. m_pCodecACtx = avcodec_alloc_context3( m_pVideoACodec );
  2891. if ( m_pCodecACtx == NULL){
  2892. LOG_ERROR("Video Encoder A Context Memory Allocation Error!");
  2893. av_free( m_pVideoACodec );
  2894. avformat_free_context( m_pFormatCtxA );
  2895. return false;
  2896. #ifdef DEBUG_EXTRA
  2897. } else {
  2898. LOG("Video Encoder Context A Allocated");
  2899. #endif
  2900. };
  2901. /* Stream B */
  2902. m_pVideoBCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  2903. if( m_pVideoBCodec == NULL ){
  2904. LOG_ERROR("Out VideoCodec Not Found!");
  2905. av_free( m_pVideoACodec );
  2906. return false;
  2907. #ifdef DEBUG_EXTRA
  2908. } else {
  2909. LOG("Video Encoder B Created");
  2910. #endif
  2911. };
  2912. m_pCodecBCtx = avcodec_alloc_context3( m_pVideoBCodec );
  2913. if ( m_pCodecBCtx == NULL){
  2914. LOG_ERROR("Video Encoder B Context Memory Allocation Error!");
  2915. av_free( m_pVideoACodec );
  2916. av_free( m_pVideoBCodec );
  2917. avformat_free_context( m_pFormatCtxA );
  2918. avformat_free_context( m_pFormatCtxB );
  2919. return false;
  2920. #ifdef DEBUG_EXTRA
  2921. } else {
  2922. LOG("Video Encoder Context B Allocated");
  2923. #endif
  2924. };
  2925. m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC;
  2926. m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO;
  2927. m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2928. m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  2929. m_pCodecACtx->max_b_frames=1;
  2930. m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width;
  2931. m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height;
  2932. m_pCodecACtx->time_base.num = 1;
  2933. m_pCodecACtx->time_base.den = m_sStreamData.fps;
  2934. m_pCodecACtx->framerate.num = m_sStreamData.fps;
  2935. m_pCodecACtx->framerate.den = 1;
  2936. m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC;
  2937. m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  2938. m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  2939. m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  2940. m_pCodecBCtx->max_b_frames=1;
  2941. m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width;
  2942. m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height;
  2943. m_pCodecBCtx->time_base.num = 1;
  2944. m_pCodecBCtx->time_base.den = m_sStreamData.fps;
  2945. m_pCodecBCtx->framerate.num = m_sStreamData.fps;
  2946. m_pCodecBCtx->framerate.den = 1;
  2947. //https://pastebin.com/yG37YhWW
  2948. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  2949. //G@ avcodec encode NALU mp4
  2950. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2951. ////m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  2952. #endif
  2953. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  2954. ////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  2955. #endif
  2956. m_pFormatOpts = NULL;
  2957. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  2958. if( ( m_pCodecACtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecACtx->codec_id == AV_CODEC_ID_H265 ) ){
  2959. #ifdef DEBUG_EXTRA
  2960. LOG("Begin Options!");
  2961. #endif
  2962. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  2963. //Set format's privater options, to be passed to avformat_write_header()
  2964. /*
  2965. mp4 muxer AVOptions:
  2966. -movflags E..... MOV muxer flags (default 0)
  2967. rtphint E..... Add RTP hint tracks
  2968. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  2969. frag_keyframe E..... Fragment at video keyframes
  2970. separate_moof E..... Write separate moof/mdat atoms for each track
  2971. frag_custom E..... Flush fragments on caller requests
  2972. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  2973. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  2974. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  2975. delay_moov ??
  2976. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  2977. -rtpflags E..... RTP muxer flags (default 0)
  2978. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  2979. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  2980. skip_rtcp E..... Don't send RTCP sender reports
  2981. h264_mode0 E..... Use mode 0 for H264 in RTP
  2982. send_bye E..... Send RTCP BYE packets when finishing
  2983. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  2984. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  2985. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  2986. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  2987. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  2988. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  2989. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  2990. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  2991. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  2992. */
  2993. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  2994. LOG_ERROR( "av_dict_set movflags!");
  2995. #ifdef DEBUG_EXTRA
  2996. } else {
  2997. LOG("MOV FLAG SET!");
  2998. #endif
  2999. };
  3000. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  3001. // LOG_ERROR( "av_dict_set live!" );
  3002. //};
  3003. //default brand is "isom", which fails on some devices
  3004. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  3005. LOG_ERROR( "av_dict_set brand!" );
  3006. };
  3007. //m_pCodecCtx->max_b_frames = 1;
  3008. //m_pCodecCtx->level = 31;
  3009. m_pCodecACtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  3010. /// P-frames, generated by referencing data from prev and future frames.
  3011. /// [Compression up, CPU usage up]
  3012. /// [use 3/gop]
  3013. m_pCodecACtx->max_b_frames = 5;
  3014. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  3015. /// [use 3�5 ref per P]
  3016. m_pCodecACtx->refs = 3;
  3017. /// Compression efficiency (slower -> better quality + higher cpu%)
  3018. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  3019. /// Set this option to "ultrafast" is critical for realtime encoding
  3020. av_opt_set( m_pCodecACtx->priv_data, "preset", "ultrafast", 0);
  3021. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  3022. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  3023. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  3024. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  3025. av_opt_set( m_pCodecACtx->priv_data, "crf", "32", 0);
  3026. /// Change settings based upon the specifics of input
  3027. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  3028. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  3029. av_opt_set( m_pCodecACtx->priv_data, "tune", "zerolatency", 0);
  3030. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  3031. /// Because Quicktime (ie. iOS) doesn't support this option
  3032. av_opt_set( m_pCodecACtx->priv_data, "b-pyramid", "0", 0 );
  3033. #ifdef DEBUG_EXTRA
  3034. LOG("End Options!");
  3035. #endif
  3036. } else {
  3037. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3038. };
  3039. if( ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H265 ) ){
  3040. #ifdef DEBUG_EXTRA
  3041. LOG("Begin Options!");
  3042. #endif
  3043. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  3044. //Set format's privater options, to be passed to avformat_write_header()
  3045. /*
  3046. mp4 muxer AVOptions:
  3047. -movflags E..... MOV muxer flags (default 0)
  3048. rtphint E..... Add RTP hint tracks
  3049. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  3050. frag_keyframe E..... Fragment at video keyframes
  3051. separate_moof E..... Write separate moof/mdat atoms for each track
  3052. frag_custom E..... Flush fragments on caller requests
  3053. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  3054. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  3055. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  3056. delay_moov ??
  3057. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  3058. -rtpflags E..... RTP muxer flags (default 0)
  3059. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  3060. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  3061. skip_rtcp E..... Don't send RTCP sender reports
  3062. h264_mode0 E..... Use mode 0 for H264 in RTP
  3063. send_bye E..... Send RTCP BYE packets when finishing
  3064. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  3065. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  3066. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  3067. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  3068. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  3069. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  3070. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  3071. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  3072. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  3073. */
  3074. //m_pCodecCtx->max_b_frames = 1;
  3075. //m_pCodecCtx->level = 31;
  3076. m_pCodecBCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  3077. /// P-frames, generated by referencing data from prev and future frames.
  3078. /// [Compression up, CPU usage up]
  3079. /// [use 3/gop]
  3080. m_pCodecBCtx->max_b_frames = 5;
  3081. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  3082. /// [use 3�5 ref per P]
  3083. m_pCodecBCtx->refs = 3;
  3084. /// Compression efficiency (slower -> better quality + higher cpu%)
  3085. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  3086. /// Set this option to "ultrafast" is critical for realtime encoding
  3087. av_opt_set( m_pCodecBCtx->priv_data, "preset", "ultrafast", 0);
  3088. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  3089. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  3090. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  3091. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  3092. av_opt_set( m_pCodecBCtx->priv_data, "crf", "32", 0);
  3093. /// Change settings based upon the specifics of input
  3094. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  3095. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  3096. av_opt_set( m_pCodecBCtx->priv_data, "tune", "zerolatency", 0);
  3097. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  3098. /// Because Quicktime (ie. iOS) doesn't support this option
  3099. av_opt_set( m_pCodecBCtx->priv_data, "b-pyramid", "0", 0 );
  3100. #ifdef DEBUG_EXTRA
  3101. LOG("End Options!");
  3102. #endif
  3103. } else {
  3104. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3105. };
  3106. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  3107. #ifdef DEBUG_EXTRA
  3108. char TB[129];
  3109. sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den );
  3110. LOG(TB);
  3111. sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den );
  3112. LOG(TB);
  3113. #endif
  3114. ////m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  3115. ////m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  3116. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  3117. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3118. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3119. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3120. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3121. //// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate =
  3122. ////dst_fps;
  3123. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  3124. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3125. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3126. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3127. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3128. //// m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate =
  3129. ////dst_fps;
  3130. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3131. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3132. //// avcodec_parameters_from_context( m_pVideoStrA->codecpar,
  3133. ////m_pCodecACtx );
  3134. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3135. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  3136. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3137. //// avcodec_parameters_from_context( m_pVideoStrB->codecpar,
  3138. ////m_pCodecBCtx );
  3139. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3140. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  3141. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3142. if ( avcodec_is_open( m_pCodecACtx ) == 0 ) {
  3143. LOG("output codec context is closed, opening");
  3144. if ( avcodec_open2( m_pCodecACtx, m_pVideoACodec, NULL) < 0 ) {
  3145. LOG_ERROR("Error opening2 encoder");
  3146. return false;
  3147. #ifdef DEBUG_EXTRA
  3148. } else {
  3149. LOG("output codec context is opened");
  3150. #endif
  3151. };
  3152. #ifdef DEBUG_EXTRA
  3153. } else {
  3154. LOG("output codec context is already opened");
  3155. #endif
  3156. };
  3157. if ( avcodec_is_open( m_pCodecBCtx ) == 0 ) {
  3158. LOG("output codec context is closed, opening");
  3159. if ( avcodec_open2( m_pCodecBCtx, m_pVideoBCodec, NULL) < 0 ) {
  3160. LOG_ERROR("Error opening2 encoder");
  3161. return false;
  3162. #ifdef DEBUG_EXTRA
  3163. } else {
  3164. LOG("output codec context is opened");
  3165. #endif
  3166. };
  3167. #ifdef DEBUG_EXTRA
  3168. } else {
  3169. LOG("output codec context is already opened");
  3170. #endif
  3171. };
  3172. #else // SEPARATED_VIDEO_ENCODERS
  3173. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  3174. LOG_ERROR("Format CTX A alloc error!");
  3175. return false;
  3176. } else {
  3177. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  3178. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  3179. };
  3180. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  3181. LOG_ERROR("Format CTX B alloc error!");
  3182. avformat_free_context( m_pFormatCtxA );
  3183. return false;
  3184. } else {
  3185. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  3186. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  3187. };
  3188. m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  3189. if( m_pVideoCodec == NULL ){
  3190. LOG_ERROR("Output VideoCodec Not Found!");
  3191. avformat_free_context( m_pFormatCtxA );
  3192. avformat_free_context( m_pFormatCtxB );
  3193. return false;
  3194. #ifdef DEBUG_EXTRA
  3195. } else {
  3196. LOG("Output Video Codec Found");
  3197. #endif
  3198. };
  3199. m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec );
  3200. if ( m_pCodecCtx == NULL){
  3201. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  3202. av_free( m_pVideoCodec );
  3203. avformat_free_context( m_pFormatCtxA );
  3204. avformat_free_context( m_pFormatCtxB );
  3205. return false;
  3206. #ifdef DEBUG_EXTRA
  3207. } else {
  3208. LOG("Out Codec Context3 Allocated");
  3209. #endif
  3210. };
  3211. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec );
  3212. if ( m_pVideoStrA == NULL){
  3213. LOG_ERROR("VideoStream A Not Created!");
  3214. avcodec_free_context( &m_pCodecCtx );
  3215. av_free( m_pCodecCtx );
  3216. av_free( m_pVideoCodec );
  3217. //avformat_close_input ( &m_pFormatCtxA );
  3218. //avformat_close_input ( &m_pFormatCtxB );
  3219. avformat_free_context( m_pFormatCtxA );
  3220. avformat_free_context( m_pFormatCtxB );
  3221. return false;
  3222. #ifdef DEBUG_EXTRA
  3223. } else {
  3224. LOG("VideoStream A is Created");
  3225. #endif
  3226. };
  3227. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec );
  3228. if ( m_pVideoStrB == NULL){
  3229. LOG_ERROR("VideoStream B Not Created!");
  3230. avcodec_free_context( &m_pCodecCtx );
  3231. av_free( m_pCodecCtx );
  3232. av_free( m_pVideoCodec );
  3233. //avformat_close_input ( &m_pFormatCtxA );
  3234. //avformat_close_input ( &m_pFormatCtxB );
  3235. avformat_free_context( m_pFormatCtxA );
  3236. avformat_free_context( m_pFormatCtxB );
  3237. return false;
  3238. #ifdef DEBUG_EXTRA
  3239. } else {
  3240. LOG("VideoStream B is Created");
  3241. #endif
  3242. };
  3243. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  3244. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  3245. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3246. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  3247. //m_pCodecCtx->thread_count = 1;
  3248. //m_pCodecCtx->bit_rate_tolerance = 1;
  3249. //m_pCodecCtx->global_quality = 100;
  3250. //m_pCodecCtx->compression_level = 2;
  3251. m_pCodecCtx->max_b_frames=1;
  3252. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  3253. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  3254. m_pCodecCtx->time_base.num = 1;
  3255. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  3256. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  3257. m_pCodecCtx->framerate.den = 1;
  3258. //https://pastebin.com/yG37YhWW
  3259. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  3260. //G@ avcodec encode NALU mp4
  3261. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  3262. m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  3263. #endif
  3264. m_pFormatOpts = NULL;
  3265. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  3266. if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){
  3267. #ifdef DEBUG_EXTRA
  3268. LOG("Begin Options!");
  3269. #endif
  3270. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  3271. //Set format's privater options, to be passed to avformat_write_header()
  3272. /*
  3273. mp4 muxer AVOptions:
  3274. -movflags E..... MOV muxer flags (default 0)
  3275. rtphint E..... Add RTP hint tracks
  3276. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  3277. frag_keyframe E..... Fragment at video keyframes
  3278. separate_moof E..... Write separate moof/mdat atoms for each track
  3279. frag_custom E..... Flush fragments on caller requests
  3280. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  3281. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  3282. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  3283. delay_moov ??
  3284. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  3285. -rtpflags E..... RTP muxer flags (default 0)
  3286. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  3287. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  3288. skip_rtcp E..... Don't send RTCP sender reports
  3289. h264_mode0 E..... Use mode 0 for H264 in RTP
  3290. send_bye E..... Send RTCP BYE packets when finishing
  3291. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  3292. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  3293. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  3294. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  3295. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  3296. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  3297. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  3298. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  3299. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  3300. */
  3301. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  3302. LOG_ERROR( "av_dict_set movflags!");
  3303. #ifdef DEBUG_EXTRA
  3304. } else {
  3305. LOG("MOV FLAG SET!");
  3306. #endif
  3307. };
  3308. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  3309. // LOG_ERROR( "av_dict_set live!" );
  3310. //};
  3311. //default brand is "isom", which fails on some devices
  3312. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  3313. LOG_ERROR( "av_dict_set brand!" );
  3314. };
  3315. //m_pCodecCtx->max_b_frames = 1;
  3316. //m_pCodecCtx->level = 31;
  3317. m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  3318. /// P-frames, generated by referencing data from prev and future frames.
  3319. /// [Compression up, CPU usage up]
  3320. /// [use 3/gop]
  3321. m_pCodecCtx->max_b_frames = 5;
  3322. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  3323. /// [use 3�5 ref per P]
  3324. m_pCodecCtx->refs = 3;
  3325. /// Compression efficiency (slower -> better quality + higher cpu%)
  3326. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  3327. /// Set this option to "ultrafast" is critical for realtime encoding
  3328. av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  3329. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  3330. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  3331. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  3332. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  3333. av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0);
  3334. /// Change settings based upon the specifics of input
  3335. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  3336. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  3337. av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  3338. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  3339. /// Because Quicktime (ie. iOS) doesn't support this option
  3340. av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
  3341. #ifdef DEBUG_EXTRA
  3342. LOG("End Options!");
  3343. #endif
  3344. } else {
  3345. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3346. };
  3347. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  3348. #ifdef DEBUG_EXTRA
  3349. char TB[129];
  3350. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den );
  3351. LOG(TB);
  3352. #endif
  3353. m_pVideoStrA->time_base = m_pCodecCtx->time_base;
  3354. m_pVideoStrB->time_base = m_pCodecCtx->time_base;
  3355. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  3356. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3357. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3358. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3359. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3360. m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  3361. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  3362. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3363. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3364. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3365. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3366. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  3367. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3368. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3369. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx );
  3370. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3371. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  3372. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3373. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx );
  3374. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3375. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  3376. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3377. if ( avcodec_is_open( m_pCodecCtx ) == 0 ) {
  3378. LOG("output codec context is closed, opening");
  3379. if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) {
  3380. LOG_ERROR("Error opening2 encoder");
  3381. return false;
  3382. #ifdef DEBUG_EXTRA
  3383. } else {
  3384. LOG("output codec context is opened");
  3385. #endif
  3386. };
  3387. #ifdef DEBUG_EXTRA
  3388. } else {
  3389. LOG("output codec context is already opened");
  3390. #endif
  3391. };
  3392. #endif // SEPARATED_VIDEO_ENCODERS
  3393. m_pConvertCtx = sws_getContext(
  3394. m_pMaster->m_sEmbedVideoData.width,
  3395. m_pMaster->m_sEmbedVideoData.height,
  3396. AV_PIX_FMT_BGR24,
  3397. m_pMaster->m_sEmbedVideoData.width,
  3398. m_pMaster->m_sEmbedVideoData.height,
  3399. VIDEO_OUTPUT_PIX_FMT,
  3400. SWS_FAST_BILINEAR,
  3401. NULL,
  3402. NULL,
  3403. NULL
  3404. );
  3405. if ( m_pConvertCtx == NULL ) {
  3406. return false;
  3407. }
  3408. m_pAVFrame = av_frame_alloc();
  3409. if ( m_pAVFrame == NULL ) {
  3410. return false;
  3411. };
  3412. 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));
  3413. if( m_pOutBuffer == NULL ) {
  3414. return false;
  3415. };
  3416. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  3417. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  3418. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  3419. //av_frame_get_buffer( m_pAVFrame, 0 );
  3420. 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 );
  3421. //av_frame_make_writable( m_pAVFrame );
  3422. #endif // !OPENCV_VIDEO_OUTPUT
  3423. #endif // !DIRECT_MJPEG_COMPOSING
  3424. return init();
  3425. };
  3426. //encoding thread
  3427. void streamHandler::m_fThreadProc( void ){
  3428. char tB[128];
  3429. //#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3430. size_t nQueueSize;
  3431. //#endif
  3432. #ifndef DIRECT_MJPEG_COMPOSING
  3433. #ifndef OPENCV_VIDEO_OUTPUT
  3434. AVPacket mPacket;
  3435. int bGotPacket;
  3436. int rVal = 0;
  3437. av_init_packet( &mPacket );
  3438. #endif
  3439. #endif
  3440. while( m_bThreadStatus != TH_ENDED ){
  3441. //At the begining All streams are closed --> try to Open
  3442. if( m_bThreadStatus < TH_WORKING ){
  3443. if( !openSegmentA() ){
  3444. m_bThreadStatus = TH_ENDED;
  3445. LOG_ERROR("Can not Open Seg A for first time!");
  3446. continue;
  3447. };
  3448. //if( !openSegmentB() ){
  3449. // m_bThreadStatus = TH_ENDED;
  3450. // continue;
  3451. //};
  3452. m_bThreadStatus = TH_WORKING;
  3453. continue;
  3454. };
  3455. m_mEncodingQueueProtector.lock();
  3456. nQueueSize = m_qEncodingQueue.size();
  3457. m_mEncodingQueueProtector.unlock();
  3458. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3459. if ( nQueueSize > EVE_EASE_FPS_QUEUE_SIZE_MAXIMUM ) {
  3460. //Just in case allredy applied to a streams
  3461. if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider ){
  3462. m_bWebFrameSkeepDivider++;
  3463. if ( m_bWebFrameSkeepDivider > EVE_EASE_FPS_DIVIDER_MAXIMUM ) {
  3464. m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MAXIMUM;
  3465. } else {
  3466. #ifdef DEBUG_EXTRA
  3467. LOG("Video Quality Degraded!");
  3468. #endif
  3469. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_DEGRADED, NULL, NULL, NULL );
  3470. if ( bEVT ) {
  3471. basicEventHeap::getInstance()->broadcast( bEVT );
  3472. } else LOG_ERROR( "Event Creation failure!");
  3473. };
  3474. };
  3475. } else if( nQueueSize < EVE_EASE_FPS_QUEUE_SIZE_MINIMUM ){
  3476. //Just in case allredy applied to a streams
  3477. if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider ){
  3478. m_bWebFrameSkeepDivider--;
  3479. if ( m_bWebFrameSkeepDivider < EVE_EASE_FPS_DIVIDER_MINIMUM ) {
  3480. m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MINIMUM;
  3481. } else {
  3482. #ifdef DEBUG_EXTRA
  3483. LOG("Video Quality Upgraded!");
  3484. #endif
  3485. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_RAISED, NULL, NULL, NULL );
  3486. if ( bEVT ) {
  3487. basicEventHeap::getInstance()->broadcast( bEVT );
  3488. } else LOG_ERROR( "Event Creation failure!");
  3489. };
  3490. };
  3491. };
  3492. if ( nQueueSize ) {
  3493. #else
  3494. if ( nQueueSize ) {
  3495. #endif
  3496. m_mEncodingQueueProtector.lock();
  3497. ENCODING_BUFFER *tData = m_qEncodingQueue.front();
  3498. if( tData ){
  3499. m_qEncodingQueue.pop();
  3500. m_mEncodingQueueProtector.unlock();
  3501. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3502. bool bSkeepA = tData->flag_sa;
  3503. bool bSkeepB = tData->flag_sb;
  3504. #endif
  3505. #ifdef DIRECT_MJPEG_COMPOSING
  3506. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3507. if( !bSkeepA )
  3508. #endif
  3509. if( m_bSegAActive ) if( m_pOutputFD[0] ){
  3510. fwrite( tData->data, 1, tData->size, m_pOutputFD[0] );
  3511. m_mFrameCounterProtector.lock();
  3512. m_nSegAFrameCounter++;
  3513. m_mFrameCounterProtector.unlock();
  3514. };
  3515. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3516. if( !bSkeepB )
  3517. #endif
  3518. if( m_bSegBActive ) if( m_pOutputFD[1] ){
  3519. fwrite( tData->data, 1, tData->size, m_pOutputFD[1] );
  3520. m_mFrameCounterProtector.lock();
  3521. m_nSegBFrameCounter++;
  3522. m_mFrameCounterProtector.unlock();
  3523. };
  3524. // Don't free tData->data since is pointer on static data
  3525. free( tData->data );
  3526. free( tData );
  3527. #else // !DIRECT_MJPEG_COMPOSING
  3528. #ifdef OPENCV_VIDEO_OUTPUT
  3529. cv::Mat image( tData->rows, tData->cols, CV_8UC3 );
  3530. memcpy( image.data, tData->data, tData->size );
  3531. free( tData->data );
  3532. free( tData );
  3533. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3534. if( !bSkeepA ){
  3535. #endif
  3536. if (m_bSegAActive) {
  3537. if ( m_pEncoderA->isOpened() ) {
  3538. m_pEncoderA->write( image );
  3539. m_mFrameCounterProtector.lock();
  3540. m_nSegAFrameCounter++;
  3541. m_mFrameCounterProtector.unlock();
  3542. };
  3543. };
  3544. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3545. };
  3546. if( !bSkeepB ){
  3547. #endif
  3548. if ( m_bSegBActive ) {
  3549. if ( m_pEncoderB->isOpened() ) {
  3550. m_pEncoderB->write( image );
  3551. m_mFrameCounterProtector.lock();
  3552. m_nSegBFrameCounter++;
  3553. m_mFrameCounterProtector.unlock();
  3554. };
  3555. };
  3556. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3557. };
  3558. #endif
  3559. #else // !OPENCV_VIDEO_OUTPUT
  3560. //av_frame_make_writable( m_pAVFrame );
  3561. //m_qEncodingQueue.pop();
  3562. //m_mEncodingQueueProtector.unlock();
  3563. sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize );
  3564. free( tData->data[0] );
  3565. free( tData );
  3566. /*
  3567. AV_PICTURE_TYPE_NONE Undefined.
  3568. AV_PICTURE_TYPE_I Intra.
  3569. AV_PICTURE_TYPE_P Predicted.
  3570. AV_PICTURE_TYPE_B Bi-dir predicted.
  3571. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4.
  3572. AV_PICTURE_TYPE_SI Switching Intra.
  3573. AV_PICTURE_TYPE_SP Switching Predicted.
  3574. AV_PICTURE_TYPE_BI BI type.
  3575. */
  3576. if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) {
  3577. m_pAVFrame->key_frame = 1;
  3578. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I;
  3579. } else {
  3580. m_pAVFrame->key_frame = 0;
  3581. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
  3582. };
  3583. m_pAVFrame->pts = m_nGlobalFrameCounter + 1;
  3584. #ifdef SEPARATED_VIDEO_ENCODERS
  3585. //if( m_bSegAActive ) {
  3586. rVal = avcodec_send_frame(m_pCodecACtx, m_pAVFrame );
  3587. //};
  3588. //if( m_bSegBActive ) {
  3589. // rVal = avcodec_send_frame(m_pCodecBCtx, m_pAVFrame );
  3590. //};
  3591. #else // SEPARATED_VIDEO_ENCODERS
  3592. rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame );
  3593. #endif // SEPARATED_VIDEO_ENCODERS
  3594. #endif // !OPENCV_VIDEO_OUTPUT
  3595. #endif // !DIRECT_MJPEG_COMPOSING
  3596. m_mFrameCounterProtector.lock();
  3597. m_nGlobalFrameCounter++;
  3598. m_mFrameCounterProtector.unlock();
  3599. } else m_mEncodingQueueProtector.unlock();
  3600. };
  3601. // Test Commands!
  3602. m_mCurrentOperationProtector.lock();
  3603. switch ( m_bCOP ) {
  3604. case 0x01:{
  3605. #ifdef DEBUG_EXTRA
  3606. LOG("Actual Closing Video Stream A!");
  3607. LOG( m_sStreamSegmentInfo[0].scratchPath );
  3608. #endif
  3609. m_bSegAActive = false;
  3610. if ( !m_bSegADelete ) {
  3611. #ifdef DIRECT_MJPEG_COMPOSING
  3612. if ( m_pOutputFD[0] ) {
  3613. fclose( m_pOutputFD[0] );
  3614. m_pOutputFD[0] = NULL;
  3615. };
  3616. #else // !DIRECT_MJPEG_COMPOSING
  3617. #ifdef OPENCV_VIDEO_OUTPUT
  3618. if ( m_pEncoderA->isOpened() ) {
  3619. m_pEncoderA->release();
  3620. #ifdef DEBUG_EXTRA
  3621. } else {
  3622. LOG(" Encoder A is NOT Opened!");
  3623. #endif
  3624. };
  3625. #else
  3626. av_write_trailer( m_pFormatCtxA );
  3627. avio_close( m_pFormatCtxA->pb );
  3628. #endif //OPENCV_VIDEO_OUTPUT
  3629. #endif // !DIRECT_MJPEG_COMPOSING
  3630. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0] );
  3631. if ( bEVT ) {
  3632. basicEventHeap::getInstance()->broadcast( bEVT );
  3633. } else LOG_ERROR( "Event Creation failure!");
  3634. #ifdef DEBUG_EXTRA
  3635. LOG("Stream A is Saved");
  3636. #endif
  3637. } else {
  3638. #ifdef DIRECT_MJPEG_COMPOSING
  3639. if ( m_pOutputFD[0] ) {
  3640. fclose( m_pOutputFD[0] );
  3641. m_pOutputFD[0] = NULL;
  3642. };
  3643. #else // !DIRECT_MJPEG_COMPOSING
  3644. #ifdef OPENCV_VIDEO_OUTPUT
  3645. if ( m_pEncoderA->isOpened() ) {
  3646. m_pEncoderA->release();
  3647. #ifdef DEBUG_EXTRA
  3648. } else {
  3649. LOG(" Encoder A is NOT Opened!");
  3650. #endif
  3651. };
  3652. #else // !OPENCV
  3653. #ifdef EVE_DONT_DELETE_SEGMENTS
  3654. av_write_trailer( m_pFormatCtxA );
  3655. #endif
  3656. avio_close( m_pFormatCtxA->pb );
  3657. #endif // !OPENCV_VIDEO_OUTPUT
  3658. #endif // !DIRECT_MJPEG_COMPOSING
  3659. #ifndef EVE_DONT_DELETE_SEGMENTS
  3660. unlink( m_sStreamSegmentInfo[0].scratchPath );
  3661. #endif
  3662. #ifdef DEBUG_EXTRA
  3663. LOG("Stream A is Closed!");
  3664. #endif
  3665. };
  3666. #ifndef DIRECT_MJPEG_COMPOSING
  3667. #ifndef OPENCV_VIDEO_OUTPUT
  3668. #ifdef SEPARATED_VIDEO_ENCODERS
  3669. #ifdef DEBUG_EXTRA
  3670. LOG("Del FCTX");
  3671. #endif
  3672. avformat_free_context( m_pFormatCtxA );
  3673. m_pVideoStrA = NULL;
  3674. #ifdef DEBUG_EXTRA
  3675. LOG("Del FCTX DONE");
  3676. #endif
  3677. #endif // SEPARATED_VIDEO_ENCODERS
  3678. #endif // !OPENCV
  3679. #endif // !DIRECT_MJPEG_COMPOSING
  3680. break;
  3681. };
  3682. case 0x02:{
  3683. #ifdef DEBUG_EXTRA
  3684. LOG("Actual Closing Video Stream B!");
  3685. LOG( m_sStreamSegmentInfo[1].scratchPath );
  3686. #endif
  3687. m_bSegBActive = false;
  3688. if ( !m_bSegBDelete ) {
  3689. #ifdef DIRECT_MJPEG_COMPOSING
  3690. if ( m_pOutputFD[1] ) {
  3691. fclose( m_pOutputFD[1] );
  3692. m_pOutputFD[1] = NULL;
  3693. };
  3694. #else // !DIRECT_MJPEG_COMPOSING
  3695. #ifdef OPENCV_VIDEO_OUTPUT
  3696. if ( m_pEncoderB->isOpened() ) {
  3697. m_pEncoderB->release();
  3698. #ifdef DEBUG_EXTRA
  3699. } else {
  3700. LOG(" Encoder B is NOT Opened!");
  3701. #endif
  3702. };
  3703. #else // !OpenCV
  3704. av_write_trailer( m_pFormatCtxB );
  3705. avio_close( m_pFormatCtxB->pb );
  3706. #endif // !OPENCV_VIDEO_OUTPUT
  3707. #endif // !DIRECT_MJPEG_COMPOSING
  3708. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1] );
  3709. if ( bEVT ) {
  3710. basicEventHeap::getInstance()->broadcast( bEVT );
  3711. } else LOG_ERROR( "Event Creation failure!");
  3712. #ifdef DEBUG_EXTRA
  3713. LOG("Stream B is Saved");
  3714. #endif
  3715. } else {
  3716. #ifdef DIRECT_MJPEG_COMPOSING
  3717. if ( m_pOutputFD[1] ) {
  3718. fclose( m_pOutputFD[1] );
  3719. m_pOutputFD[1] = NULL;
  3720. };
  3721. #else
  3722. #ifdef OPENCV_VIDEO_OUTPUT
  3723. if ( m_pEncoderB->isOpened() ) {
  3724. m_pEncoderB->release();
  3725. #ifdef DEBUG_EXTRA
  3726. } else {
  3727. LOG(" Encoder B is NOT Opened!");
  3728. #endif
  3729. };
  3730. #else // !OPenCV
  3731. #ifdef EVE_DONT_DELETE_SEGMENTS
  3732. av_write_trailer( m_pFormatCtxB );
  3733. #endif
  3734. avio_close( m_pFormatCtxB->pb );
  3735. #endif // !OPENCV_VIDEO_OUTPUT
  3736. #endif // !DIRECT_MJPEG_COMPOSING
  3737. #ifndef EVE_DONT_DELETE_SEGMENTS
  3738. unlink( m_sStreamSegmentInfo[1].scratchPath );
  3739. #endif
  3740. #ifdef DEBUG_EXTRA
  3741. LOG("Stream B is Closed!");
  3742. #endif
  3743. };
  3744. #ifndef DIRECT_MJPEG_COMPOSING
  3745. #ifndef OPENCV_VIDEO_OUTPUT
  3746. #ifdef SEPARATED_VIDEO_ENCODERS
  3747. avformat_free_context( m_pFormatCtxB );
  3748. m_pVideoStrB = NULL;
  3749. #endif // SEPARATED_VIDEO_ENCODERS
  3750. #endif // !OPENCV
  3751. #endif // !DIRECT_MJPEG_COMPOSING
  3752. break;
  3753. };
  3754. };
  3755. m_bCOP = 0;
  3756. m_mCurrentOperationProtector.unlock();
  3757. //};
  3758. #ifndef DIRECT_MJPEG_COMPOSING
  3759. #ifndef OPENCV_VIDEO_OUTPUT
  3760. #ifdef SEPARATED_VIDEO_ENCODERS
  3761. do {
  3762. mPacket.data = NULL;
  3763. mPacket.size = 0;
  3764. rVal = avcodec_receive_packet( m_pCodecACtx, &mPacket );
  3765. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  3766. break;
  3767. } else if( rVal < 0 ){
  3768. LOG_ERROR( "Error during encoding " );
  3769. m_bThreadStatus = TH_ENDED;
  3770. break;
  3771. };
  3772. if( !rVal ){
  3773. if ( m_bSegAActive ) {
  3774. mPacket.stream_index = m_pVideoStrA->index;
  3775. mPacket.duration = 1;
  3776. m_mFrameCounterProtector.lock();
  3777. m_nSegAFrameCounter++;
  3778. m_mFrameCounterProtector.unlock();
  3779. mPacket.pts = av_rescale_q( m_nSegAFrameCounter, m_pCodecACtx->time_base, m_pVideoStrA->time_base );
  3780. //mPacket.pts = AV_NOPTS_VALUE;
  3781. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3782. mPacket.dts = mPacket.pts;
  3783. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  3784. if( rc < 0 ){
  3785. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  3786. m_bThreadStatus = TH_ENDED;
  3787. LOG_ERROR("Trouble with Video Output A!");
  3788. av_strerror( rc, tB, 128 );
  3789. LOG_ERROR( tB );
  3790. break; //continue (changed since embed into do-while)
  3791. };
  3792. };
  3793. if ( m_bSegBActive ) {
  3794. mPacket.stream_index = m_pVideoStrB->index;
  3795. mPacket.duration = 1;
  3796. m_mFrameCounterProtector.lock();
  3797. m_nSegBFrameCounter++;
  3798. m_mFrameCounterProtector.unlock();
  3799. mPacket.pts = av_rescale_q( m_nSegBFrameCounter, m_pCodecBCtx->time_base, m_pVideoStrB->time_base );
  3800. //mPacket.pts = AV_NOPTS_VALUE;
  3801. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  3802. mPacket.dts = mPacket.pts;
  3803. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  3804. if( rc < 0 ) {
  3805. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  3806. m_bThreadStatus = TH_ENDED;
  3807. LOG_ERROR( "Trouble with Video Output B!" );
  3808. av_strerror( rc, tB, 128 );
  3809. LOG_ERROR( tB );
  3810. break; //continue (changed since embed into do-while)
  3811. };
  3812. };
  3813. av_packet_unref( &mPacket );
  3814. };
  3815. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  3816. #else // ! SEPARATED_VIDEO_ENCODERS
  3817. do {
  3818. mPacket.data = NULL;
  3819. mPacket.size = 0;
  3820. rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket );
  3821. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  3822. break;
  3823. } else if( rVal < 0 ){
  3824. LOG_ERROR( "Error during encoding " );
  3825. m_bThreadStatus = TH_ENDED;
  3826. break;
  3827. };
  3828. if( !rVal ){
  3829. if ( m_bSegAActive ) {
  3830. mPacket.stream_index = m_pVideoStrA->index;
  3831. mPacket.duration = 1;
  3832. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3833. //mPacket.pts = AV_NOPTS_VALUE;
  3834. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3835. mPacket.dts = mPacket.pts;
  3836. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  3837. if( rc < 0 ){
  3838. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  3839. m_bThreadStatus = TH_ENDED;
  3840. LOG_ERROR("Trouble with Video Output A!");
  3841. av_strerror( rc, tB, 128 );
  3842. LOG_ERROR( tB );
  3843. break; //continue (changed since embed into do-while)
  3844. };
  3845. };
  3846. if ( m_bSegBActive ) {
  3847. mPacket.stream_index = m_pVideoStrB->index;
  3848. mPacket.duration = 1;
  3849. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3850. //mPacket.pts = AV_NOPTS_VALUE;
  3851. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  3852. mPacket.dts = mPacket.pts;
  3853. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  3854. if( rc < 0 ) {
  3855. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  3856. m_bThreadStatus = TH_ENDED;
  3857. LOG_ERROR( "Trouble with Video Output B!" );
  3858. av_strerror( rc, tB, 128 );
  3859. LOG_ERROR( tB );
  3860. break; //continue (changed since embed into do-while)
  3861. };
  3862. };
  3863. av_packet_unref( &mPacket );
  3864. };
  3865. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  3866. #endif // ! SEPARATED_VIDEO_ENCODERS
  3867. #endif // !OPENCV_VIDEO_OUTPUT
  3868. #endif // !DIRECT_MJPEG_COMPOSING
  3869. SLEEP( 10 );
  3870. };
  3871. #ifdef DEBUG_EXTRA
  3872. LOG("Encoder Loop Ended!");
  3873. #endif
  3874. };
  3875. void streamHandler::swapActiveStreams( void ){
  3876. //m_mFrameCounterProtector.lock();
  3877. m_bActiveEncoderStream = 1 - m_bActiveEncoderStream;
  3878. if ( m_bActiveEncoderStream ) {
  3879. if ( m_bSegADelete ) closeSegmentA();
  3880. } else {
  3881. if ( m_bSegBDelete ) closeSegmentB();
  3882. };
  3883. //m_mFrameCounterProtector.unlock();
  3884. };
  3885. #endif // EVE_ENABLE_VIDEO
  3886. bool streamHandler::triggerEvent( uint32_t eid, uint32_t &dbid, uint32_t &frame ){
  3887. #ifdef DEBUG_EXTRA
  3888. LOG("Trig Evt");
  3889. #endif
  3890. #ifdef EVE_ENABLE_VIDEO
  3891. m_mFrameCounterProtector.lock();
  3892. // To Mark Events Frames
  3893. m_bEvtMarkerCounter = 255;
  3894. PF_TIMESTAMP ts;
  3895. getPFTS( &ts );
  3896. /*
  3897. if ( m_nVideoRegisteredDBID == 0 ) {
  3898. LOG("New Event!");
  3899. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  3900. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  3901. m_sStreamData.id,
  3902. m_cSegMD5A,
  3903. VIDEO_OUTPUT_CONTAINER,
  3904. ts.seconds,
  3905. ts.milliseconds,
  3906. m_sStreamData.fps
  3907. );
  3908. m_bSegADelete = false;
  3909. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  3910. } else { // Stream B is Active
  3911. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  3912. m_sStreamData.id,
  3913. m_cSegMD5B,
  3914. VIDEO_OUTPUT_CONTAINER,
  3915. ts.seconds,
  3916. ts.milliseconds,
  3917. m_sStreamData.fps
  3918. );
  3919. m_bSegBDelete = false;
  3920. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  3921. };
  3922. };
  3923. */
  3924. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  3925. m_bSegADelete = false;
  3926. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  3927. } else { // Stream B is Active
  3928. m_bSegBDelete = false;
  3929. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  3930. };
  3931. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventIDS.push_back( eid );
  3932. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTSS.push_back( ts.seconds );
  3933. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTMS.push_back( ts.milliseconds );
  3934. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventFrames.push_back( frame );
  3935. //dbid = m_sStreamSegmentInfo[m_bActiveEncoderStream].db_id;// = m_nVideoRegisteredDBID;
  3936. m_mFrameCounterProtector.unlock();
  3937. //if ( dbid == 0 ) return false;
  3938. //dbid = m_nVideoRegisteredDBID;
  3939. #ifdef DEBUG_EXTRA
  3940. LOG("Event Registered!");
  3941. #endif
  3942. #endif // EVE_ENABLE_VIDEO
  3943. return true;
  3944. };
  3945. bool streamHandler::triggerCamMove( void ){
  3946. #ifdef DEBUG_EXTRA
  3947. LOG("Trig Cammove");
  3948. #endif
  3949. m_bCamMoveCounter = 255;
  3950. return true;
  3951. };
  3952. bool streamHandler::validate( void ){
  3953. if ( m_pSource ) {
  3954. if( m_pSource->getStatus() < MS_CLOSING ){
  3955. #ifdef EVE_ENABLE_VIDEO
  3956. if( m_nGlobalFrameCounter ) { //Frames Received from a source
  3957. if( m_nGlobalFrameCounter == m_nValidatorFrameCounter ) {
  3958. // Video Stalled!
  3959. LOG_ERROR("Video Stalled");
  3960. return false;// Try use System to recuperate
  3961. } else m_nValidatorFrameCounter = m_nGlobalFrameCounter;
  3962. };
  3963. if( m_bThreadStatus < TH_ENDED ) return true; else LOG_ERROR( "Thread Ended!");
  3964. #endif
  3965. } else LOG_ERROR("Video Ended");
  3966. };
  3967. return false;
  3968. };
  3969. //#undef DEBUG_EXTRA
  3970. //#undef DEBUG
  3971. #undef LOG
  3972. #undef LOG_ERROR
  3973. #undef TLOG
  3974. #undef TLOG_ERROR