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.

4115 lines
178 KiB

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