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.

4296 lines
181 KiB

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