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.

4145 lines
175 KiB

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