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.

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