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.

4111 lines
178 KiB

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