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.

4132 lines
178 KiB

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