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.

4116 lines
178 KiB

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