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.

4295 lines
180 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
​
​
​
​
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
​
​
​
​
​
​
​
​
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
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
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. free( 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. /// @todo Valgrind is reporting an important memory leak in this method.
  1902. bool SkeepW, SkeepA, SkeepB;
  1903. if( m_pMaster == NULL ) return false;
  1904. MEDIA_SOURCE_DESC * tMD = (MEDIA_SOURCE_DESC *) src;
  1905. char tBuffer[128];
  1906. if( tMD ) {
  1907. float mK, oK;
  1908. cv::Rect ROI;
  1909. m_pMaster->m_mPictureProtector.lock();
  1910. if( m_pMaster->m_mapMATS[tMD->mediaStreamId].cols == 0 ) {
  1911. LOG("First Frame Enqueued");
  1912. sprintf( tBuffer, "INP: [%dx%d] SrcID:%d StreamID:%d", Frame.cols, Frame.rows, tMD->mediaSourceId, tMD->mediaStreamId );
  1913. LOG( tBuffer );
  1914. m_pMaster->m_mapMATS[tMD->mediaStreamId].create(
  1915. m_pMaster->m_sEmbedVideoData.height,
  1916. m_pMaster->m_sEmbedVideoData.width,
  1917. CV_8UC3
  1918. );
  1919. cv::rectangle(
  1920. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  1921. cv::Point( 0, 0 ),
  1922. cv::Point(
  1923. m_pMaster->m_sEmbedVideoData.height,
  1924. m_pMaster->m_sEmbedVideoData.width
  1925. ),
  1926. cv::Scalar( 0, 0, 0 ),
  1927. cv::FILLED
  1928. );
  1929. };
  1930. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  1931. SkeepW = !((m_bWebFrameSkeepDividerCounter % m_bWebFrameSkeepDivider) == 0 );
  1932. m_bWebFrameSkeepDividerCounter = ( ++m_bWebFrameSkeepDividerCounter ) % m_bWebFrameSkeepDivider;
  1933. #ifdef EVE_ENABLE_VIDEO
  1934. SkeepA = !((m_bAFrameSkeepDividerCounter % m_bAFrameSkeepDivider) == 0 );
  1935. //m_bAFrameSkeepDividerCounter++;
  1936. m_bAFrameSkeepDividerCounter = ( ++m_bAFrameSkeepDividerCounter ) % m_bAFrameSkeepDivider;
  1937. SkeepB = !((m_bBFrameSkeepDividerCounter % m_bBFrameSkeepDivider) == 0 );
  1938. //m_bBFrameSkeepDividerCounter++;
  1939. m_bBFrameSkeepDividerCounter = ( ++m_bBFrameSkeepDividerCounter ) % m_bBFrameSkeepDivider;
  1940. #ifdef DEBUG_ALL
  1941. if( SkeepW || SkeepA || SkeepB ){
  1942. char tzB[256];
  1943. sprintf( tzB,"SkipF: %d:%d %d:%d %d:%d", m_bWebFrameSkeepDividerCounter, m_bWebFrameSkeepDivider, m_bAFrameSkeepDividerCounter, m_bAFrameSkeepDivider, m_bBFrameSkeepDividerCounter, m_bBFrameSkeepDivider );
  1944. LOG( tzB );
  1945. } else {
  1946. LOG( "PushF" );
  1947. };
  1948. #endif
  1949. //if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDividerCounter ) = 1;
  1950. //if( SkeepB ) m_bBFrameSkeepDividerCounter = 1;
  1951. //if( SkeepW ) m_bWebFrameSkeepDividerCounter = 1;
  1952. #else
  1953. #ifdef DEBUG_ALL
  1954. if( SkeepW ){
  1955. char tB[256];
  1956. sprintf( tB,"Skip: %d:%d", m_bWebFrameSkeepDividerCounter, m_bWebFrameSkeepDivider );
  1957. LOG( tB );
  1958. };
  1959. #endif
  1960. if( SkeepW ) m_bWebFrameSkeepDividerCounter = 1;
  1961. #endif
  1962. #endif
  1963. #ifdef USE_SCALING_IN
  1964. oK = ((float)m_pMaster->m_sEmbedVideoData.height )/ ((float)m_pMaster->m_sEmbedVideoData.width);
  1965. mK = ((float)Frame.rows )/ ((float)Frame.cols);
  1966. //sprintf( tBuffer, "INP: [%dx%d] IK:%0.3f OK:%0.3f", Frame.cols, Frame.rows, mK, oK );
  1967. if( ( fabsf( mK - oK ) < 0.1f ) || ( fabsf( oK - mK ) < 0.1f ) ) {
  1968. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1969. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1970. ROI.x = (int) 0;
  1971. ROI.y = (int) 0;
  1972. } else {
  1973. if( mK < oK ) {
  1974. ROI.width = (int) m_pMaster->m_sEmbedVideoData.width;
  1975. ROI.height = (int) (((float)m_pMaster->m_sEmbedVideoData.width) * mK );
  1976. ROI.x = (int) 0;
  1977. ROI.y = (int)( m_pMaster->m_sEmbedVideoData.height - ROI.height ) >> 1;
  1978. } else {
  1979. ROI.height = (int) m_pMaster->m_sEmbedVideoData.height;
  1980. ROI.width = (int) (((float)m_pMaster->m_sEmbedVideoData.height) / mK );
  1981. ROI.y = (int) 0;
  1982. ROI.x = (int) ( m_pMaster->m_sEmbedVideoData.width - ROI.width ) >> 1;
  1983. };
  1984. };
  1985. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  1986. #ifndef USE_CV_DENOISE
  1987. cv::resize( Frame, mROI , mROI.size(), 0, 0, cv::INTER_LINEAR );
  1988. #else
  1989. cv::Mat mDenoiser;
  1990. cv::resize( Frame, mDenoiser, mROI.size(), 0, 0, cv::INTER_LINEAR );
  1991. cv::fastNlMeansDenoisingColored ( mDenoiser, mROI, 10, 10, 7, 17 );
  1992. #endif
  1993. #ifdef USE_CV_TONEMAP
  1994. cv::Mat ldrReinhard;
  1995. cv::Ptr< cv::TonemapReinhard > tonemapReinhard = cv::createTonemapReinhard( 1.5, 0, 0 ,0 );
  1996. tonemapReinhard->process( mROI, ldrReinhard );
  1997. ldrReinhard = ldrReinhard * 255;
  1998. ldrReinhard.copyTo(mROI);
  1999. #endif
  2000. #else
  2001. if(( m_pMaster->m_sEmbedVideoData.height==Frame.rows )&&( m_pMaster->m_sEmbedVideoData.width==Frame.cols )){
  2002. Frame.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] );
  2003. } else {
  2004. //Mat dst_roi = dst(Rect(left, top, src.cols, src.rows));
  2005. //src.copyTo(dst_roi);
  2006. if (m_pMaster->m_sEmbedVideoData.width == Frame.cols ) {
  2007. ROI.width = Frame.cols;
  2008. ROI.height = Frame.rows;
  2009. ROI.x = 0;
  2010. ROI.y = ( m_pMaster->m_sEmbedVideoData.height - Frame.rows ) >> 1;
  2011. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  2012. #ifdef USE_CV_DENOISE
  2013. cv::fastNlMeansDenoisingColored ( Frame, mROI, 10, 10, 7, 17 );
  2014. #else
  2015. Frame.copyTo(mROI);
  2016. #endif
  2017. #ifdef USE_CV_TONEMAP
  2018. cv::Mat ldrReinhard;
  2019. cv::Ptr< cv::TonemapReinhard > tonemapReinhard = cv::createTonemapReinhard( 1.5, 0, 0 ,0 );
  2020. tonemapReinhard->process( mROI, ldrReinhard );
  2021. ldrReinhard = ldrReinhard * 255;
  2022. ldrReinhard.copyTo(mROI);
  2023. #endif
  2024. } else {
  2025. ROI.width = Frame.cols;
  2026. ROI.height = Frame.rows;
  2027. ROI.x = ( m_pMaster->m_sEmbedVideoData.width - Frame.cols ) >> 1;
  2028. ROI.y = 0;
  2029. cv::Mat mROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( ROI );
  2030. #ifdef USE_CV_DENOISE
  2031. cv::fastNlMeansDenoisingColored ( Frame, mROI, 10, 10, 7, 17 );
  2032. #else
  2033. Frame.copyTo(mROI);
  2034. #endif
  2035. #ifdef USE_CV_TONEMAP
  2036. cv::Mat ldrReinhard;
  2037. cv::Ptr< cv::TonemapReinhard > tonemapReinhard = cv::createTonemapReinhard( 1.5, 0, 0 ,0 );
  2038. tonemapReinhard->process( mROI, ldrReinhard );
  2039. ldrReinhard = ldrReinhard * 255;
  2040. ldrReinhard.copyTo(mROI);
  2041. #endif
  2042. };
  2043. };
  2044. #endif
  2045. // 0 - dis .. 1 - Hor ... 2 - vert 3 - both
  2046. if ( m_bFlipMode ) {
  2047. //Flip Horizontally = 1 vertically = 0 both = -1
  2048. cv::Mat mirroredImage;
  2049. cv::flip( m_pMaster->m_mapMATS[tMD->mediaStreamId], mirroredImage, ( 2 - m_bFlipMode ) );
  2050. mirroredImage.copyTo( m_pMaster->m_mapMATS[tMD->mediaStreamId] );
  2051. };
  2052. #ifdef EVE_ENABLE_DROP_OUTPUT_FPS
  2053. //LOG("T");
  2054. m_mEncodingQueueProtector.lock();
  2055. if( m_qEncodingQueue.size() > 10 ){
  2056. m_mEncodingQueueProtector.unlock();
  2057. m_pMaster->m_mPictureProtector.unlock();
  2058. //LOG("D");
  2059. return true;
  2060. };
  2061. m_mEncodingQueueProtector.unlock();
  2062. //LOG("Q");
  2063. #endif
  2064. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2065. #ifdef EVE_ENABLE_VIDEO
  2066. if( SkeepW && SkeepA && SkeepB ) {
  2067. m_pMaster->m_mPictureProtector.unlock();
  2068. return true;
  2069. };
  2070. #else
  2071. if( SkeepW ){
  2072. m_pMaster->m_mPictureProtector.unlock();
  2073. return true;
  2074. };
  2075. #endif
  2076. #endif
  2077. if ( m_bCamMoveCounter > m_bEvtMarkerCounter ) {
  2078. cv::rectangle(
  2079. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2080. cv::Rect( 10, 10, 20, 20 ),
  2081. cv::Scalar( m_bCamMoveCounter, 0, 0 ),
  2082. cv::FILLED
  2083. );
  2084. m_bCamMoveCounter -=4;
  2085. if ( m_bCamMoveCounter < 4 ) m_bCamMoveCounter = 0;
  2086. } else {
  2087. if ( m_bEvtMarkerCounter ) {
  2088. m_bCamMoveCounter = 0;
  2089. cv::rectangle(
  2090. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2091. cv::Rect( 10, 10, 20, 20 ),
  2092. cv::Scalar( 0, 0, m_bEvtMarkerCounter ),
  2093. cv::FILLED
  2094. );
  2095. m_bEvtMarkerCounter -=4;
  2096. if ( m_bEvtMarkerCounter < 4 ) m_bEvtMarkerCounter = 0;
  2097. };
  2098. };
  2099. if (m_pMaster->m_sEmbedVideoData.show_label) {
  2100. time_t t = time( NULL );
  2101. //struct tm * tmp = gmtime( &t );
  2102. struct tm * tmp = localtime( &t );
  2103. if( tmp ){
  2104. char tsb[64];
  2105. //if( strftime( tsb, sizeof(tsb), "%F %T GMT", tmp )!=0 ){
  2106. if( strftime( tsb, sizeof(tsb), "%F %T", tmp )!=0 ){
  2107. //sprintf( tBuffer, ">>%d>%d>%s>%s>", tMD->mediaSourceId, tMD->mediaStreamId, tMD->mediaName, tsb );
  2108. sprintf( tBuffer, ">>>%s>%s>", tMD->mediaName, tsb );
  2109. int baseline=0;
  2110. cv::Size textSize = cv::getTextSize( tBuffer,
  2111. m_pMaster->m_sEmbedVideoData.label_font_face,
  2112. m_pMaster->m_sEmbedVideoData.label_font_scale,
  2113. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  2114. &baseline
  2115. );
  2116. int x = m_pMaster->m_sEmbedVideoData.label_x;
  2117. int y = m_pMaster->m_sEmbedVideoData.label_y;
  2118. if( x < 0 ) {
  2119. x = m_pMaster->m_sEmbedVideoData.width+x-textSize.width;
  2120. };
  2121. if( y < 0 ) {
  2122. y = m_pMaster->m_sEmbedVideoData.height+y-baseline;//
  2123. };
  2124. if( !m_pMaster->m_sEmbedVideoData.label_transperant ) {
  2125. cv::rectangle(
  2126. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2127. cv::Rect( x, y-textSize.height-4, textSize.width, textSize.height+baseline+4 ),
  2128. cv::Scalar( 0, 0, 0 ),
  2129. cv::FILLED
  2130. );
  2131. };
  2132. cv::putText(
  2133. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2134. tBuffer,
  2135. cv::Point( x, y ),
  2136. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.label_font_face,
  2137. m_pMaster->m_sEmbedVideoData.label_font_scale,
  2138. cv::Scalar( 0, 255, 0 ),
  2139. m_pMaster->m_sEmbedVideoData.label_font_thickness,
  2140. m_pMaster->m_sEmbedVideoData.label_line_type
  2141. );
  2142. };
  2143. };
  2144. } else {
  2145. if( m_pMaster->m_sEmbedVideoData.show_ts ){
  2146. time_t t = time( NULL );
  2147. //struct tm * tmp = gmtime( &t );
  2148. struct tm * tmp = localtime( &t );
  2149. if( tmp ){
  2150. if( strftime( tBuffer, sizeof(tBuffer), "%F %T GMT", tmp )!=0 ){
  2151. uint8_t shift_x = 0;
  2152. uint8_t shift_y = 15;
  2153. if( !m_pMaster->m_sEmbedVideoData.ts_transperant ) {
  2154. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  2155. shift_y = 15;
  2156. cv::rectangle(
  2157. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2158. cv::Point(
  2159. m_pMaster->m_sEmbedVideoData.ts_x,
  2160. m_pMaster->m_sEmbedVideoData.ts_y
  2161. ),
  2162. cv::Point( 490, 60 ),
  2163. cv::Scalar( 0, 0, 0 ),
  2164. cv::FILLED
  2165. );
  2166. } else {
  2167. shift_y = 23;
  2168. cv::rectangle(
  2169. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2170. cv::Point(
  2171. m_pMaster->m_sEmbedVideoData.ts_x,
  2172. m_pMaster->m_sEmbedVideoData.ts_y
  2173. ),
  2174. cv::Point( 490, 60 ),
  2175. cv::Scalar( 0, 0, 0 ),
  2176. cv::FILLED
  2177. );
  2178. };
  2179. cv::putText(
  2180. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2181. tBuffer,
  2182. cv::Point(
  2183. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  2184. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  2185. ),
  2186. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  2187. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  2188. cv::Scalar( 0, 255, 255 ),
  2189. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  2190. m_pMaster->m_sEmbedVideoData.ts_line_type
  2191. );
  2192. } else {
  2193. if( m_pMaster->m_sEmbedVideoData.ts_font_face ) {
  2194. shift_y = 15;
  2195. } else {
  2196. shift_y = 23;
  2197. };
  2198. cv::putText(
  2199. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2200. tBuffer,
  2201. cv::Point(
  2202. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  2203. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  2204. ),
  2205. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  2206. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  2207. cv::Scalar( 0, 0, 0 ),
  2208. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  2209. m_pMaster->m_sEmbedVideoData.ts_line_type
  2210. );
  2211. cv::putText(
  2212. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2213. tBuffer,
  2214. cv::Point(
  2215. m_pMaster->m_sEmbedVideoData.ts_x + shift_x + 1,
  2216. m_pMaster->m_sEmbedVideoData.ts_y + shift_y - 1
  2217. ),
  2218. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  2219. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  2220. cv::Scalar( 0, 0, 0 ),
  2221. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  2222. m_pMaster->m_sEmbedVideoData.ts_line_type
  2223. );
  2224. cv::putText(
  2225. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2226. tBuffer,
  2227. cv::Point(
  2228. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  2229. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 1
  2230. ),
  2231. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  2232. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  2233. cv::Scalar( 0, 0, 0 ),
  2234. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  2235. m_pMaster->m_sEmbedVideoData.ts_line_type
  2236. );
  2237. cv::putText(
  2238. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2239. tBuffer,
  2240. cv::Point(
  2241. m_pMaster->m_sEmbedVideoData.ts_x + shift_x - 1,
  2242. m_pMaster->m_sEmbedVideoData.ts_y + shift_y + 2
  2243. ),
  2244. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  2245. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  2246. cv::Scalar( 0, 0, 0 ),
  2247. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  2248. m_pMaster->m_sEmbedVideoData.ts_line_type
  2249. );
  2250. cv::putText(
  2251. m_pMaster->m_mapMATS[tMD->mediaStreamId],
  2252. tBuffer,
  2253. cv::Point(
  2254. m_pMaster->m_sEmbedVideoData.ts_x + shift_x,
  2255. m_pMaster->m_sEmbedVideoData.ts_y + shift_y
  2256. ),
  2257. (cv::HersheyFonts) m_pMaster->m_sEmbedVideoData.ts_font_face,
  2258. m_pMaster->m_sEmbedVideoData.ts_font_scale,
  2259. cv::Scalar( 0, 255, 255 ),
  2260. m_pMaster->m_sEmbedVideoData.ts_font_thickness,
  2261. m_pMaster->m_sEmbedVideoData.ts_line_type
  2262. );
  2263. }
  2264. };
  2265. };
  2266. };
  2267. };
  2268. if( m_pMaster->m_sEmbedVideoData.show_logo ){
  2269. cv::Rect roi(
  2270. cv::Point(
  2271. m_pMaster->m_sEmbedVideoData.logo_x,
  2272. m_pMaster->m_sEmbedVideoData.logo_y
  2273. ),
  2274. cv::Size(
  2275. m_pMaster->m_sEmbedVideoData.logo_w,
  2276. m_pMaster->m_sEmbedVideoData.logo_h
  2277. )
  2278. );
  2279. cv::Mat destinationROI = m_pMaster->m_mapMATS[tMD->mediaStreamId]( roi );
  2280. m_pMaster->m_mLogoPic.copyTo( destinationROI, m_pMaster->m_mLogoMask );
  2281. };
  2282. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2283. if ( !SkeepW ) {
  2284. #endif
  2285. vector<int> compression_params;
  2286. //compression_params.push_back(CV_IMWRITE_PNG_COMPRESSION);
  2287. //compression_params.push_back(9);
  2288. compression_params.push_back( cv::IMWRITE_JPEG_QUALITY );
  2289. compression_params.push_back( 50 ); //m_pMaster->m_sEmbedVideoData.compression_quality );
  2290. m_pMaster->m_mEncodedProtector.lock();
  2291. m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].clear();
  2292. cv::imencode( ".jpg", m_pMaster->m_mapMATS[tMD->mediaStreamId], m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  2293. //cv::Mat bw_dst;
  2294. //cv::cvtColor( m_pMaster->m_mapMATS[tMD->mediaStreamId], bw_dst, cv::COLOR_BGR2GRAY );
  2295. //cv::imencode( ".jpg", bw_dst, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId], compression_params );
  2296. #ifdef HAVE_SMAL_PREVIEW_STREAMS
  2297. // Make Small Preview Thumb
  2298. cv::Mat dst;
  2299. cv::resize( m_pMaster->m_mapMATS[tMD->mediaStreamId], dst, cv::Size( PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT ));
  2300. //cv::resize( bw_dst, dst, cv::Size( PREVIEW_SIZE_WIDTH, PREVIEW_SIZE_HEIGHT ));
  2301. m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId].clear();
  2302. cv::imencode( ".jpg", dst, m_pMaster->m_mapPREVIEWS[tMD->mediaStreamId], compression_params );
  2303. #endif
  2304. m_pMaster->m_mEncodedProtector.unlock();
  2305. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2306. };
  2307. #endif
  2308. #ifdef EVE_ENABLE_VIDEO
  2309. // if only decode Video Stream -> Exit
  2310. if( m_eWM == MS_MODE_DECODE_FRAMES ){
  2311. m_pMaster->m_mPictureProtector.unlock();
  2312. return true;
  2313. };
  2314. // encode Video Stream
  2315. //m_nPreAlarmFrames
  2316. //m_nPostAlarmFrames
  2317. //m_nNoAlarmSegmentFrames
  2318. //m_nSegmentLimitFrames
  2319. //m_nHardLimitFrames
  2320. if ( m_bSegAActive || m_bSegBActive ) {
  2321. m_mFrameCounterProtector.lock();
  2322. if( m_bSegAActive ){
  2323. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2324. //do {
  2325. //In Any Case Close Stream if it Long enough
  2326. if( m_nSegAFrameCounter > m_nAHardLimitFrames ){
  2327. #ifdef DEBUG_EXTRA
  2328. LOG("HardLimit Reached!(A)");
  2329. #endif
  2330. closeSegmentA();
  2331. //break;
  2332. };
  2333. if( m_nSegAFrameCounter > ( m_nASegmentLimitFrames - ( m_nAPostAlarmFrames + m_nBPreAlarmFrames ))){
  2334. if ( !m_bSegBActive ){
  2335. #ifdef DEBUG_EXTRA
  2336. LOG("Start Alt!(A)");
  2337. #endif
  2338. openSegmentB();
  2339. };
  2340. };
  2341. if( m_nSegAFrameCounter > ( m_nASegmentLimitFrames - m_nAPostAlarmFrames ) && !m_bActiveEncoderStream ){
  2342. #ifdef DEBUG_EXTRA
  2343. LOG("Swap Active!(A)");
  2344. #endif
  2345. swapActiveStreams();
  2346. //break;
  2347. };
  2348. // } while ( 0 );
  2349. #else
  2350. //do {
  2351. //In Any Case Close Stream if it Long enough
  2352. if( m_nSegAFrameCounter > m_nHardLimitFrames ){
  2353. #ifdef DEBUG_EXTRA
  2354. LOG("HardLimit Reached!(A)");
  2355. #endif
  2356. closeSegmentA();
  2357. //break;
  2358. };
  2359. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  2360. if ( !m_bSegBActive ){
  2361. #ifdef DEBUG_EXTRA
  2362. LOG("Start Alt!(A)");
  2363. #endif
  2364. openSegmentB();
  2365. };
  2366. };
  2367. if( m_nSegAFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && !m_bActiveEncoderStream ){
  2368. #ifdef DEBUG_EXTRA
  2369. LOG("Swap Active!(A)");
  2370. #endif
  2371. swapActiveStreams();
  2372. //break;
  2373. };
  2374. // } while ( 0 );
  2375. #endif// !EVE_ENABLE_EASE_OUTPUT_FPS
  2376. };
  2377. if( m_bSegBActive ) {
  2378. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2379. // do {
  2380. //In Any Case Close Stream if it Long enough
  2381. if( m_nSegBFrameCounter > m_nBHardLimitFrames ){
  2382. #ifdef DEBUG_EXTRA
  2383. LOG("HardLimit Reached!(B)");
  2384. #endif
  2385. closeSegmentB();
  2386. //break;
  2387. };
  2388. if( m_nSegBFrameCounter > ( m_nBSegmentLimitFrames - ( m_nBPostAlarmFrames + m_nAPreAlarmFrames ))){
  2389. if ( !m_bSegAActive ){
  2390. #ifdef DEBUG_EXTRA
  2391. LOG("Start Alt!(B)");
  2392. #endif
  2393. openSegmentA();
  2394. };
  2395. };
  2396. if( m_nSegBFrameCounter > ( m_nBSegmentLimitFrames - m_nBPostAlarmFrames ) && m_bActiveEncoderStream ){
  2397. #ifdef DEBUG_EXTRA
  2398. LOG("Swap Active!(B)");
  2399. #endif
  2400. swapActiveStreams();
  2401. // break;
  2402. };
  2403. //} while ( 0 );
  2404. #else // !EVE_ENABLE_EASE_OUTPUT_FPS
  2405. // do {
  2406. //In Any Case Close Stream if it Long enough
  2407. if( m_nSegBFrameCounter > m_nHardLimitFrames ){
  2408. #ifdef DEBUG_EXTRA
  2409. LOG("HardLimit Reached!(B)");
  2410. #endif
  2411. closeSegmentB();
  2412. //break;
  2413. };
  2414. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - ( m_nPostAlarmFrames + m_nPreAlarmFrames ))){
  2415. if ( !m_bSegAActive ){
  2416. #ifdef DEBUG_EXTRA
  2417. LOG("Start Alt!(B)");
  2418. #endif
  2419. openSegmentA();
  2420. };
  2421. };
  2422. if( m_nSegBFrameCounter > ( m_nSegmentLimitFrames - m_nPostAlarmFrames ) && m_bActiveEncoderStream ){
  2423. #ifdef DEBUG_EXTRA
  2424. LOG("Swap Active!(B)");
  2425. #endif
  2426. swapActiveStreams();
  2427. // break;
  2428. };
  2429. //} while ( 0 );
  2430. #endif // !EVE_ENABLE_EASE_OUTPUT_FPS
  2431. };
  2432. m_mFrameCounterProtector.unlock();
  2433. ENCODING_BUFFER *tData = (ENCODING_BUFFER *) malloc( sizeof(ENCODING_BUFFER));
  2434. if ( tData ) {
  2435. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2436. tData->flag_sa = SkeepA;
  2437. tData->flag_sb = SkeepB;
  2438. #endif
  2439. #ifdef DIRECT_MJPEG_COMPOSING
  2440. tData->size = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].size();
  2441. tData->data = (uint8_t *)malloc( tData->size );
  2442. if ( tData->data ) {
  2443. memcpy( tData->data, m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data(), tData->size );
  2444. //tData->data = m_pMaster->m_mapCAPTURES[tMD->mediaStreamId].data();
  2445. //if ( tData->data ) {
  2446. #else
  2447. #ifdef OPENCV_VIDEO_OUTPUT
  2448. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  2449. tData->cols = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols;
  2450. tData->size = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize()*tData->rows;
  2451. tData->data = (uint8_t *)malloc( tData->size );
  2452. if ( tData->data ) {
  2453. memcpy( tData->data, m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size );
  2454. #else //OPENCV_VIDEO_OUTPUT
  2455. tData->linesize[0] = m_pMaster->m_mapMATS[tMD->mediaStreamId].cols*m_pMaster->m_mapMATS[tMD->mediaStreamId].elemSize();
  2456. tData->linesize[1] = 0;
  2457. tData->rows = m_pMaster->m_mapMATS[tMD->mediaStreamId].rows;
  2458. tData->size = tData->linesize[0]*tData->rows;
  2459. tData->data[1] = NULL;
  2460. tData->data[0] = (uint8_t *)malloc( tData->size );
  2461. if ( tData->data[0] ) {
  2462. memcpy( tData->data[0], m_pMaster->m_mapMATS[tMD->mediaStreamId].data, tData->size );
  2463. #endif //OPENCV_VIDEO_OUTPUT
  2464. #endif //!DIRECT_MJPEG_COMPOSING
  2465. m_mEncodingQueueProtector.lock();
  2466. m_qEncodingQueue.push( tData );
  2467. m_mEncodingQueueProtector.unlock();
  2468. } else {
  2469. LOG_ERROR("MAT_CPY malloc Error!");
  2470. free( tData );
  2471. };
  2472. } else LOG_ERROR("ENC_BUF malloc Error!");
  2473. };
  2474. #endif // EVE_ENABLE_VIDEO
  2475. m_pMaster->m_mPictureProtector.unlock();
  2476. } else {
  2477. LOG_ERROR("No PayLoad!");
  2478. };
  2479. return true;
  2480. };
  2481. #ifdef EVE_ENABLE_VIDEO
  2482. void streamHandler::closeSegmentA( void ){
  2483. m_mCurrentOperationProtector.lock();
  2484. if ( m_bCOP == 0 ) m_bCOP = 0x01;
  2485. m_mCurrentOperationProtector.unlock();
  2486. #ifdef DEBUG_EXTRA
  2487. LOG("Closing Stream A");
  2488. #endif
  2489. };
  2490. void streamHandler::closeSegmentB( void ){
  2491. m_mCurrentOperationProtector.lock();
  2492. if ( m_bCOP == 0 ) m_bCOP = 0x02;
  2493. m_mCurrentOperationProtector.unlock();
  2494. #ifdef DEBUG_EXTRA
  2495. LOG("Closing Stream B");
  2496. #endif
  2497. };
  2498. void streamHandler::closeAll(){
  2499. waitThreadEnd( true );
  2500. #ifdef OPENCV_VIDEO_OUTPUT
  2501. if( m_pEncoderA ){
  2502. if ( m_pEncoderA->isOpened() ) {
  2503. m_pEncoderA->release();
  2504. };
  2505. delete(m_pEncoderA);
  2506. };
  2507. if( m_pEncoderB ){
  2508. if ( m_pEncoderB->isOpened() ) {
  2509. m_pEncoderB->release();
  2510. };
  2511. delete( m_pEncoderB );
  2512. };
  2513. #else //OPENCV_VIDEO_OUTPUT
  2514. #ifdef DIRECT_MJPEG_COMPOSING
  2515. if( m_pOutputFD[0] ){
  2516. fclose( m_pOutputFD[0] );
  2517. m_pOutputFD[0] = NULL;
  2518. };
  2519. if( m_pOutputFD[1] ){
  2520. fclose( m_pOutputFD[1] );
  2521. m_pOutputFD[1] = NULL;
  2522. };
  2523. #else // ! DIRECT_MJPEG_COMPOSING
  2524. #ifdef SEPARATED_VIDEO_ENCODERS
  2525. if( ( m_pCodecACtx != NULL || m_pCodecBCtx != NULL ) && (m_bSegAActive || m_bSegBActive )) {
  2526. if( m_pCodecACtx != NULL ) {
  2527. avcodec_send_frame(m_pCodecACtx, NULL);
  2528. int ret = 0;
  2529. AVPacket *avp = av_packet_alloc();
  2530. if ( avp ) {
  2531. do {
  2532. av_packet_unref( avp );
  2533. ret = avcodec_receive_packet( m_pCodecACtx, avp );
  2534. if ( !ret ) {
  2535. if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp );
  2536. };
  2537. } while ( !ret );
  2538. av_packet_unref( avp );
  2539. av_packet_free( &avp );
  2540. };
  2541. };
  2542. if( m_pCodecBCtx != NULL ) {
  2543. avcodec_send_frame(m_pCodecBCtx, NULL);
  2544. int ret = 0;
  2545. AVPacket *avp = av_packet_alloc();
  2546. if ( avp ) {
  2547. do {
  2548. av_packet_unref( avp );
  2549. ret = avcodec_receive_packet( m_pCodecBCtx, avp );
  2550. if ( !ret ) {
  2551. if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp );
  2552. };
  2553. } while ( !ret );
  2554. av_packet_unref( avp );
  2555. av_packet_free( &avp );
  2556. };
  2557. };
  2558. if ( m_bSegAActive ) {
  2559. av_write_trailer(m_pFormatCtxA);
  2560. avformat_close_input( &m_pFormatCtxA );
  2561. m_bSegAActive = false;
  2562. };
  2563. if ( m_bSegBActive ) {
  2564. av_write_trailer(m_pFormatCtxB);
  2565. avformat_close_input( &m_pFormatCtxB );
  2566. m_bSegBActive = false;
  2567. };
  2568. };
  2569. #else // !SEPARATED_VIDEO_ENCODERS
  2570. if( m_pCodecCtx != NULL && (m_bSegAActive || m_bSegBActive )) {
  2571. avcodec_send_frame( m_pCodecCtx, NULL );
  2572. int ret = 0;
  2573. AVPacket *avp = av_packet_alloc();
  2574. if ( avp ) {
  2575. do {
  2576. av_packet_unref( avp );
  2577. ret = avcodec_receive_packet( m_pCodecCtx, avp );
  2578. if ( !ret ) {
  2579. if ( m_bSegAActive ) av_write_frame( m_pFormatCtxA, avp );
  2580. if ( m_bSegBActive ) av_write_frame( m_pFormatCtxB, avp );
  2581. };
  2582. } while ( !ret );
  2583. av_packet_unref( avp );
  2584. av_packet_free( &avp );
  2585. };
  2586. if ( m_bSegAActive ) {
  2587. av_write_trailer(m_pFormatCtxA);
  2588. avformat_close_input( &m_pFormatCtxA );
  2589. m_bSegAActive = false;
  2590. };
  2591. if ( m_bSegBActive ) {
  2592. av_write_trailer(m_pFormatCtxB);
  2593. avformat_close_input( &m_pFormatCtxB );
  2594. m_bSegBActive = false;
  2595. };
  2596. };
  2597. #endif // !SEPARATED_VIDEO_ENCODERS
  2598. #endif // !DIRECT_MJPEG_COMPOSING
  2599. //if( m_pFormat != NULL ) {
  2600. //av_free( m_pFormat );
  2601. //};
  2602. #endif // OPENCV_VIDEO_OUTPUT
  2603. };
  2604. bool streamHandler::openSegmentA( void ){
  2605. if( !m_bSegAActive ){
  2606. CSTR tAM = getUniqID_MD5();
  2607. if ( tAM ) {
  2608. sprintf( m_sStreamSegmentInfo[0].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER );
  2609. strncpy( m_sStreamSegmentInfo[0].recordMD5, tAM, 32 );
  2610. m_sStreamSegmentInfo[0].recordMD5[32] = (char)0;
  2611. free( tAM );
  2612. m_sStreamSegmentInfo[0].stream_id = m_sStreamData.id;
  2613. PF_TIMESTAMP ts;
  2614. getPFTS( &ts );
  2615. m_sStreamSegmentInfo[0].streamTSS = ts.seconds;
  2616. m_sStreamSegmentInfo[0].streamTMS = ts.milliseconds;
  2617. #ifdef DEBUG_EXTRA
  2618. char tB[128];
  2619. sprintf( tB, "A opened %d.%d", m_sStreamSegmentInfo[0].streamTSS, m_sStreamSegmentInfo[0].streamTMS );
  2620. LOG( tB );
  2621. #endif
  2622. strncpy( m_sStreamSegmentInfo[0].recordEXT, VIDEO_OUTPUT_CONTAINER, 6 );
  2623. m_sStreamSegmentInfo[0].streamFPS = m_sStreamData.fps;
  2624. m_sStreamSegmentInfo[0].streamWidth = m_pMaster->getWidh();
  2625. m_sStreamSegmentInfo[0].streamHeight = m_pMaster->getHeight();
  2626. m_sStreamSegmentInfo[0].eventIDS.clear();
  2627. m_sStreamSegmentInfo[0].eventTSS.clear();
  2628. m_sStreamSegmentInfo[0].eventTMS.clear();
  2629. m_sStreamSegmentInfo[0].eventFrames.clear();
  2630. m_sStreamSegmentInfo[0].dataSize = 0;
  2631. m_sStreamSegmentInfo[0].db_id = 0;
  2632. #ifdef DIRECT_MJPEG_COMPOSING
  2633. m_pOutputFD[0] = fopen( m_sStreamSegmentInfo[0].scratchPath, "wb+" );
  2634. m_nSegAFrameCounter = 0;
  2635. m_nSegAShiftFrames = 0;
  2636. m_bSegAActive = true;
  2637. m_bSegADelete = true;
  2638. #else // !DIRECT_MJPEG_COMPOSING
  2639. #ifdef OPENCV_VIDEO_OUTPUT
  2640. if ( m_pEncoderA ) {
  2641. //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  2642. int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  2643. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2644. m_bAFrameSkeepDivider = m_bWebFrameSkeepDivider;
  2645. m_bAOutputFPS = m_bInitialOutputFPS / m_bAFrameSkeepDivider;
  2646. double fps = m_bAOutputFPS;
  2647. #else
  2648. double fps = m_sStreamData.fps;
  2649. #endif
  2650. cv::String mn( m_sStreamSegmentInfo[0].scratchPath );
  2651. cv::Size fz( m_sStreamData.width, m_sStreamData.height );
  2652. //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  2653. if( !m_pEncoderA->open( mn, fourcc, fps, fz ) ){
  2654. LOG_ERROR("Cannot Open Output Segment A!");
  2655. return false;
  2656. #ifdef DEBUG_EXTRA
  2657. } else {
  2658. char tB[256];
  2659. sprintf( tB,"VideoStream A is Created [%s] %.2f fps", m_sStreamSegmentInfo[0].scratchPath, fps );
  2660. LOG( tB );
  2661. #endif
  2662. };
  2663. m_bSegAActive = true;
  2664. m_bSegADelete = true;
  2665. m_nSegAFrameCounter = 0;
  2666. m_nSegAShiftFrames = 0;
  2667. } else {
  2668. LOG_ERROR("No Encoder(A) Object!");
  2669. return false;
  2670. };
  2671. #else// !OPENCV_VIDEO_OUTPUT
  2672. //Check if Encoder is Ready
  2673. if ( m_pFormat == NULL ) return false;
  2674. #ifdef SEPARATED_VIDEO_ENCODERS
  2675. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  2676. LOG_ERROR("Format CTX A alloc error!");
  2677. return false;
  2678. } else {
  2679. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  2680. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2681. };
  2682. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoACodec );
  2683. if ( m_pVideoStrA == NULL){
  2684. avformat_free_context( m_pFormatCtxA );
  2685. return false;
  2686. #ifdef DEBUG_EXTRA
  2687. } else {
  2688. LOG("VideoStream A is Created");
  2689. #endif
  2690. };
  2691. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  2692. m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate = dst_fps;
  2693. m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  2694. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecACtx );
  2695. #ifdef DEBUG_EXTRA
  2696. LOG("Opening Stream A");
  2697. LOG(m_cSegNameA);
  2698. char tB[128];
  2699. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  2700. LOG( tB );
  2701. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  2702. LOG( tB );
  2703. #endif
  2704. //if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  2705. if (avio_open(&m_pFormatCtxA->pb, m_sStreamSegmentInfo[0].scratchPath, AVIO_FLAG_WRITE) < 0) {
  2706. LOG_ERROR("Could not open output file.");
  2707. return m_bSegAActive;
  2708. };
  2709. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  2710. LOG_ERROR("Error occurred when writing header to output file.");
  2711. return m_bSegAActive;
  2712. };
  2713. //m_mFrameCounterProtector.lock();
  2714. m_nSegAFrameCounter = 0;
  2715. m_nSegAShiftFrames = 0;
  2716. m_bSegAActive = true;
  2717. m_bSegADelete = true;
  2718. //m_mFrameCounterProtector.unlock();
  2719. #else // SEPARATED_VIDEO_ENCODERS
  2720. m_nSegASkippedFrames = m_pVideoStrA->nb_frames + 1;
  2721. if (m_pVideoStrA->nb_frames) {
  2722. m_pVideoStrA->nb_frames = 0;
  2723. m_pVideoStrA->start_time = 0;
  2724. m_pVideoStrA->first_dts = 0;
  2725. m_pFormatCtxA->start_time = 0;
  2726. };
  2727. #ifdef DEBUG_EXTRA
  2728. LOG("Opening Stream A");
  2729. LOG(m_cSegNameA);
  2730. char tB[128];
  2731. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrA->start_time, m_pVideoStrA->nb_frames, m_pVideoStrA->first_dts );
  2732. LOG( tB );
  2733. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxA->start_time, m_pFormatCtxA->duration );
  2734. LOG( tB );
  2735. #endif
  2736. if (avio_open(&m_pFormatCtxA->pb, m_cSegNameA, AVIO_FLAG_WRITE) < 0) {
  2737. LOG_ERROR("Could not open output file.");
  2738. return m_bSegAActive;
  2739. };
  2740. if ( avformat_write_header( m_pFormatCtxA, &m_pFormatOpts ) < 0 ){
  2741. LOG_ERROR("Error occurred when writing header to output file.");
  2742. return m_bSegAActive;
  2743. };
  2744. //m_mFrameCounterProtector.lock();
  2745. m_nSegAFrameCounter = 0;
  2746. m_nSegAShiftFrames = 0;
  2747. m_bSegAActive = true;
  2748. m_bSegADelete = true;
  2749. //m_mFrameCounterProtector.unlock();
  2750. #endif // SEPARATED_VIDEO_ENCODERS
  2751. #ifdef DEBUG_EXTRA
  2752. LOG("Stream A Opened");
  2753. #endif
  2754. #endif // !OPENCV_VIDEO_OUTPUT
  2755. #endif // !DIRECT_MJPEG_COMPOSING
  2756. };
  2757. };
  2758. return m_bSegAActive;
  2759. };
  2760. bool streamHandler::openSegmentB( void ){
  2761. if( !m_bSegBActive ){
  2762. CSTR tAM = getUniqID_MD5();
  2763. if ( tAM ) {
  2764. sprintf( m_sStreamSegmentInfo[1].scratchPath, "%s/%s.%s", m_pVideoScratchPath, tAM, VIDEO_OUTPUT_CONTAINER );
  2765. strncpy( m_sStreamSegmentInfo[1].recordMD5, tAM, 32 );
  2766. m_sStreamSegmentInfo[1].recordMD5[32] = (char)0;
  2767. free( tAM );
  2768. m_sStreamSegmentInfo[1].stream_id = m_sStreamData.id;
  2769. PF_TIMESTAMP ts;
  2770. getPFTS( &ts );
  2771. m_sStreamSegmentInfo[1].streamTSS = ts.seconds;
  2772. m_sStreamSegmentInfo[1].streamTMS = ts.milliseconds;
  2773. #ifdef DEBUG_EXTRA
  2774. char tB[128];
  2775. sprintf( tB, "B opened %d.%d", m_sStreamSegmentInfo[1].streamTSS, m_sStreamSegmentInfo[1].streamTMS );
  2776. LOG( tB );
  2777. #endif
  2778. strncpy( m_sStreamSegmentInfo[1].recordEXT, VIDEO_OUTPUT_CONTAINER, 6 );
  2779. m_sStreamSegmentInfo[1].streamFPS = m_sStreamData.fps;
  2780. m_sStreamSegmentInfo[1].streamWidth = m_pMaster->getWidh();
  2781. m_sStreamSegmentInfo[1].streamHeight = m_pMaster->getHeight();
  2782. m_sStreamSegmentInfo[1].eventIDS.clear();
  2783. m_sStreamSegmentInfo[1].eventTSS.clear();
  2784. m_sStreamSegmentInfo[1].eventTMS.clear();
  2785. m_sStreamSegmentInfo[1].eventFrames.clear();
  2786. m_sStreamSegmentInfo[1].dataSize = 0;
  2787. m_sStreamSegmentInfo[1].db_id = 0;
  2788. #ifdef DIRECT_MJPEG_COMPOSING
  2789. m_pOutputFD[1] = fopen( m_sStreamSegmentInfo[1].scratchPath, "wb+" );
  2790. m_nSegBFrameCounter = 0;
  2791. m_nSegBShiftFrames = 0;
  2792. m_bSegBActive = true;
  2793. m_bSegBDelete = true;
  2794. #else // !DIRECT_MJPEG_COMPOSING
  2795. #ifdef OPENCV_VIDEO_OUTPUT
  2796. if ( m_pEncoderB ) {
  2797. //int fourcc = cv::VideoWriter::fourcc('H', '2', '6', '4');
  2798. int fourcc = cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
  2799. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2800. m_bBFrameSkeepDivider = m_bWebFrameSkeepDivider;
  2801. m_bBOutputFPS = m_bInitialOutputFPS / m_bBFrameSkeepDivider;
  2802. double fps = m_bBOutputFPS;
  2803. #else
  2804. double fps = m_sStreamData.fps;
  2805. #endif
  2806. cv::String mn( m_sStreamSegmentInfo[1].scratchPath );
  2807. cv::Size fz( m_sStreamData.width, m_sStreamData.height );
  2808. //open (const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
  2809. if( !m_pEncoderB->open( mn, fourcc, fps, fz ) ){
  2810. LOG_ERROR("Cannot Open Output Segment B!");
  2811. return false;
  2812. #ifdef DEBUG_EXTRA
  2813. } else {
  2814. char tB[256];
  2815. sprintf( tB,"VideoStream B is Created [%s] %.2f fps", m_sStreamSegmentInfo[1].scratchPath, fps );
  2816. LOG( tB );
  2817. #endif
  2818. };
  2819. m_bSegBActive = true;
  2820. m_bSegBDelete = true;
  2821. m_nSegBFrameCounter = 0;
  2822. m_nSegBShiftFrames = 0;
  2823. } else {
  2824. LOG_ERROR("No Encoder(B) Object!");
  2825. return false;
  2826. };
  2827. #else // !OPENCV
  2828. //Check if Encoder is Ready
  2829. if ( m_pFormat == NULL ) return false;
  2830. #ifdef SEPARATED_VIDEO_ENCODERS
  2831. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  2832. LOG_ERROR("Format CTX B alloc error!");
  2833. return false;
  2834. } else {
  2835. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  2836. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  2837. };
  2838. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoBCodec );
  2839. if ( m_pVideoStrB == NULL){
  2840. avformat_free_context( m_pFormatCtxB );
  2841. return false;
  2842. #ifdef DEBUG_EXTRA
  2843. } else {
  2844. LOG("VideoStream B is Created");
  2845. #endif
  2846. };
  2847. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  2848. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  2849. m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  2850. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecBCtx );
  2851. #ifdef DEBUG_EXTRA
  2852. LOG("Opening Stream B");
  2853. LOG( m_cSegNameB );
  2854. char tB[128];
  2855. sprintf( tB, "FFPTS:%llu FNUM:%llu S2KF:%llu", m_pVideoStrB->start_time, m_pVideoStrB->nb_frames, m_pVideoStrB->first_dts );
  2856. LOG( tB );
  2857. sprintf( tB, "CON ST:%llu DUR:%llu", m_pFormatCtxB->start_time, m_pFormatCtxB->duration );
  2858. LOG( tB );
  2859. #endif
  2860. //if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  2861. if ( avio_open( &m_pFormatCtxB->pb, m_sStreamSegmentInfo[1].scratchPath, AVIO_FLAG_WRITE ) < 0 ){
  2862. LOG_ERROR("Could not open output file.");
  2863. avformat_free_context( m_pFormatCtxB );
  2864. return false;
  2865. };
  2866. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  2867. LOG_ERROR("Error occurred when writing header to output file.");
  2868. avio_close( m_pFormatCtxB->pb );
  2869. avformat_free_context( m_pFormatCtxB );
  2870. return false;
  2871. };
  2872. //m_mFrameCounterProtector.lock();
  2873. m_nSegBFrameCounter = 0;
  2874. m_nSegBShiftFrames = 0;
  2875. m_bSegBActive = true;
  2876. m_bSegBDelete = true;
  2877. //m_mFrameCounterProtector.unlock();
  2878. #else // SEPARATED_VIDEO_ENCODERS
  2879. m_nSegBSkippedFrames = m_pVideoStrB->nb_frames + 1;
  2880. if (m_pVideoStrB->nb_frames) {
  2881. m_pVideoStrB->nb_frames = 0;
  2882. m_pVideoStrB->start_time = 0;
  2883. m_pVideoStrB->first_dts = 0;
  2884. m_pFormatCtxB->start_time = 0;
  2885. };
  2886. if ( avio_open( &m_pFormatCtxB->pb, m_cSegNameB, AVIO_FLAG_WRITE ) < 0 ){
  2887. LOG_ERROR("Could not open output file.");
  2888. return m_bSegBActive;
  2889. };
  2890. if ( avformat_write_header( m_pFormatCtxB, &m_pFormatOpts ) < 0 ){
  2891. LOG_ERROR("Error occurred when writing header to output file.");
  2892. return m_bSegBActive;
  2893. };
  2894. //m_mFrameCounterProtector.lock();
  2895. m_nSegBFrameCounter = 0;
  2896. m_nSegBShiftFrames = 0;
  2897. m_bSegBActive = true;
  2898. m_bSegBDelete = true;
  2899. //m_mFrameCounterProtector.unlock();
  2900. #endif // SEPARATED_VIDEO_ENCODERS
  2901. #ifdef DEBUG_EXTRA
  2902. LOG("Stream B Opened");
  2903. #endif
  2904. #endif // !OPENCV_VIDEO_OUTPUT
  2905. #endif // !DIRECT_MJPEG_COMPOSING
  2906. };
  2907. };
  2908. return m_bSegBActive;
  2909. };
  2910. bool streamHandler::initVideoOutput(){
  2911. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  2912. m_bAFrameSkeepDivider = m_bBFrameSkeepDivider = 1;
  2913. m_bAFrameSkeepDividerCounter = m_bBFrameSkeepDividerCounter = 0;
  2914. m_bCurrentOutputFPS = m_bInitialOutputFPS = m_sStreamData.fps;
  2915. m_nAPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_bAOutputFPS ) / 1000;
  2916. m_nAPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_bAOutputFPS ) / 1000;
  2917. m_nASegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_bAOutputFPS ) / 1000;
  2918. m_nAHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bAOutputFPS ) / 1000;
  2919. m_nBPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_bBOutputFPS ) / 1000;
  2920. m_nBPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_bBOutputFPS ) / 1000;
  2921. m_nBSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_bBOutputFPS ) / 1000;
  2922. m_nBHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_bBOutputFPS ) / 1000;
  2923. #else
  2924. m_nPreAlarmFrames = ( PRE_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  2925. m_nPostAlarmFrames = ( POST_ALARM_TIME_MILSECONDS * m_sStreamData.fps ) / 1000;
  2926. m_nSegmentLimitFrames = ( ENCODING_SEGMENT_MILSECONDS * m_sStreamData.fps ) / 1000;
  2927. m_nHardLimitFrames = ( ENCODING_SEGMENT_LIMIT_MILSECONDS * m_sStreamData.fps ) / 1000;
  2928. #endif
  2929. #ifndef DIRECT_MJPEG_COMPOSING
  2930. #ifdef OPENCV_VIDEO_OUTPUT
  2931. m_pEncoderA = new cv::VideoWriter();
  2932. if ( m_pEncoderA == NULL ) {
  2933. LOG_ERROR("Encoder A Create Failure!");
  2934. return false;
  2935. };
  2936. m_pEncoderA->set( cv::VIDEOWRITER_PROP_QUALITY, 10.0 );
  2937. m_pEncoderA->set( cv::VIDEOWRITER_PROP_NSTRIPES, -1.0 );
  2938. m_pEncoderB = new cv::VideoWriter();
  2939. if ( m_pEncoderA == NULL ) {
  2940. LOG_ERROR("Encoder B Create Failure!");
  2941. return false;
  2942. };
  2943. m_pEncoderB->set( cv::VIDEOWRITER_PROP_QUALITY, 10.0 );
  2944. m_pEncoderB->set( cv::VIDEOWRITER_PROP_NSTRIPES, -1.0 );
  2945. #else
  2946. if( !initLibAV() ) return false;
  2947. m_pFormat = av_guess_format( VIDEO_OUTPUT_CONTAINER, "test." VIDEO_OUTPUT_CONTAINER, NULL );
  2948. if ( m_pFormat == NULL ) {
  2949. LOG_ERROR("Out VideoFormat Not Found!");
  2950. return false;
  2951. #ifdef DEBUG_EXTRA
  2952. } else {
  2953. LOG("Output video Format");
  2954. LOG( VIDEO_OUTPUT_CONTAINER );
  2955. #endif
  2956. };
  2957. #ifdef SEPARATED_VIDEO_ENCODERS
  2958. /* Stream A */
  2959. m_pVideoACodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  2960. if( m_pVideoACodec == NULL ){
  2961. LOG_ERROR("Encoder Video Codec Not Found!");
  2962. return false;
  2963. #ifdef DEBUG_EXTRA
  2964. } else {
  2965. LOG("Video Encoder A Created");
  2966. #endif
  2967. };
  2968. m_pCodecACtx = avcodec_alloc_context3( m_pVideoACodec );
  2969. if ( m_pCodecACtx == NULL){
  2970. LOG_ERROR("Video Encoder A Context Memory Allocation Error!");
  2971. av_free( m_pVideoACodec );
  2972. avformat_free_context( m_pFormatCtxA );
  2973. return false;
  2974. #ifdef DEBUG_EXTRA
  2975. } else {
  2976. LOG("Video Encoder Context A Allocated");
  2977. #endif
  2978. };
  2979. /* Stream B */
  2980. m_pVideoBCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  2981. if( m_pVideoBCodec == NULL ){
  2982. LOG_ERROR("Out VideoCodec Not Found!");
  2983. av_free( m_pVideoACodec );
  2984. return false;
  2985. #ifdef DEBUG_EXTRA
  2986. } else {
  2987. LOG("Video Encoder B Created");
  2988. #endif
  2989. };
  2990. m_pCodecBCtx = avcodec_alloc_context3( m_pVideoBCodec );
  2991. if ( m_pCodecBCtx == NULL){
  2992. LOG_ERROR("Video Encoder B Context Memory Allocation Error!");
  2993. av_free( m_pVideoACodec );
  2994. av_free( m_pVideoBCodec );
  2995. avformat_free_context( m_pFormatCtxA );
  2996. avformat_free_context( m_pFormatCtxB );
  2997. return false;
  2998. #ifdef DEBUG_EXTRA
  2999. } else {
  3000. LOG("Video Encoder Context B Allocated");
  3001. #endif
  3002. };
  3003. m_pCodecACtx->codec_id = VIDEO_OUTPUT_CODEC;
  3004. m_pCodecACtx->codec_type = AVMEDIA_TYPE_VIDEO;
  3005. m_pCodecACtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3006. m_pCodecACtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  3007. m_pCodecACtx->max_b_frames=1;
  3008. m_pCodecACtx->width = m_pMaster->m_sEmbedVideoData.width;
  3009. m_pCodecACtx->height = m_pMaster->m_sEmbedVideoData.height;
  3010. m_pCodecACtx->time_base.num = 1;
  3011. m_pCodecACtx->time_base.den = m_sStreamData.fps;
  3012. m_pCodecACtx->framerate.num = m_sStreamData.fps;
  3013. m_pCodecACtx->framerate.den = 1;
  3014. m_pCodecBCtx->codec_id = VIDEO_OUTPUT_CODEC;
  3015. m_pCodecBCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  3016. m_pCodecBCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3017. m_pCodecBCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  3018. m_pCodecBCtx->max_b_frames=1;
  3019. m_pCodecBCtx->width = m_pMaster->m_sEmbedVideoData.width;
  3020. m_pCodecBCtx->height = m_pMaster->m_sEmbedVideoData.height;
  3021. m_pCodecBCtx->time_base.num = 1;
  3022. m_pCodecBCtx->time_base.den = m_sStreamData.fps;
  3023. m_pCodecBCtx->framerate.num = m_sStreamData.fps;
  3024. m_pCodecBCtx->framerate.den = 1;
  3025. //https://pastebin.com/yG37YhWW
  3026. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  3027. //G@ avcodec encode NALU mp4
  3028. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  3029. ////m_pCodecACtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  3030. #endif
  3031. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  3032. ////m_pCodecBCtx->codec_tag = av_codec_get_tag( m_pFormatCtxB->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  3033. #endif
  3034. m_pFormatOpts = NULL;
  3035. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  3036. if( ( m_pCodecACtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecACtx->codec_id == AV_CODEC_ID_H265 ) ){
  3037. #ifdef DEBUG_EXTRA
  3038. LOG("Begin Options!");
  3039. #endif
  3040. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  3041. //Set format's privater options, to be passed to avformat_write_header()
  3042. /*
  3043. mp4 muxer AVOptions:
  3044. -movflags E..... MOV muxer flags (default 0)
  3045. rtphint E..... Add RTP hint tracks
  3046. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  3047. frag_keyframe E..... Fragment at video keyframes
  3048. separate_moof E..... Write separate moof/mdat atoms for each track
  3049. frag_custom E..... Flush fragments on caller requests
  3050. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  3051. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  3052. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  3053. delay_moov ??
  3054. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  3055. -rtpflags E..... RTP muxer flags (default 0)
  3056. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  3057. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  3058. skip_rtcp E..... Don't send RTCP sender reports
  3059. h264_mode0 E..... Use mode 0 for H264 in RTP
  3060. send_bye E..... Send RTCP BYE packets when finishing
  3061. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  3062. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  3063. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  3064. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  3065. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  3066. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  3067. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  3068. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  3069. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  3070. */
  3071. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  3072. LOG_ERROR( "av_dict_set movflags!");
  3073. #ifdef DEBUG_EXTRA
  3074. } else {
  3075. LOG("MOV FLAG SET!");
  3076. #endif
  3077. };
  3078. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  3079. // LOG_ERROR( "av_dict_set live!" );
  3080. //};
  3081. //default brand is "isom", which fails on some devices
  3082. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  3083. LOG_ERROR( "av_dict_set brand!" );
  3084. };
  3085. //m_pCodecCtx->max_b_frames = 1;
  3086. //m_pCodecCtx->level = 31;
  3087. m_pCodecACtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  3088. /// P-frames, generated by referencing data from prev and future frames.
  3089. /// [Compression up, CPU usage up]
  3090. /// [use 3/gop]
  3091. m_pCodecACtx->max_b_frames = 5;
  3092. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  3093. /// [use 3�1�75 ref per P]
  3094. m_pCodecACtx->refs = 3;
  3095. /// Compression efficiency (slower -> better quality + higher cpu%)
  3096. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  3097. /// Set this option to "ultrafast" is critical for realtime encoding
  3098. av_opt_set( m_pCodecACtx->priv_data, "preset", "ultrafast", 0);
  3099. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  3100. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  3101. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  3102. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  3103. av_opt_set( m_pCodecACtx->priv_data, "crf", "32", 0);
  3104. /// Change settings based upon the specifics of input
  3105. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  3106. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  3107. av_opt_set( m_pCodecACtx->priv_data, "tune", "zerolatency", 0);
  3108. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  3109. /// Because Quicktime (ie. iOS) doesn't support this option
  3110. av_opt_set( m_pCodecACtx->priv_data, "b-pyramid", "0", 0 );
  3111. #ifdef DEBUG_EXTRA
  3112. LOG("End Options!");
  3113. #endif
  3114. } else {
  3115. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecACtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3116. };
  3117. if( ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecBCtx->codec_id == AV_CODEC_ID_H265 ) ){
  3118. #ifdef DEBUG_EXTRA
  3119. LOG("Begin Options!");
  3120. #endif
  3121. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  3122. //Set format's privater options, to be passed to avformat_write_header()
  3123. /*
  3124. mp4 muxer AVOptions:
  3125. -movflags E..... MOV muxer flags (default 0)
  3126. rtphint E..... Add RTP hint tracks
  3127. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  3128. frag_keyframe E..... Fragment at video keyframes
  3129. separate_moof E..... Write separate moof/mdat atoms for each track
  3130. frag_custom E..... Flush fragments on caller requests
  3131. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  3132. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  3133. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  3134. delay_moov ??
  3135. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  3136. -rtpflags E..... RTP muxer flags (default 0)
  3137. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  3138. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  3139. skip_rtcp E..... Don't send RTCP sender reports
  3140. h264_mode0 E..... Use mode 0 for H264 in RTP
  3141. send_bye E..... Send RTCP BYE packets when finishing
  3142. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  3143. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  3144. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  3145. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  3146. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  3147. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  3148. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  3149. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  3150. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  3151. */
  3152. //m_pCodecCtx->max_b_frames = 1;
  3153. //m_pCodecCtx->level = 31;
  3154. m_pCodecBCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  3155. /// P-frames, generated by referencing data from prev and future frames.
  3156. /// [Compression up, CPU usage up]
  3157. /// [use 3/gop]
  3158. m_pCodecBCtx->max_b_frames = 5;
  3159. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  3160. /// [use 3�1�75 ref per P]
  3161. m_pCodecBCtx->refs = 3;
  3162. /// Compression efficiency (slower -> better quality + higher cpu%)
  3163. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  3164. /// Set this option to "ultrafast" is critical for realtime encoding
  3165. av_opt_set( m_pCodecBCtx->priv_data, "preset", "ultrafast", 0);
  3166. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  3167. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  3168. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  3169. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  3170. av_opt_set( m_pCodecBCtx->priv_data, "crf", "32", 0);
  3171. /// Change settings based upon the specifics of input
  3172. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  3173. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  3174. av_opt_set( m_pCodecBCtx->priv_data, "tune", "zerolatency", 0);
  3175. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  3176. /// Because Quicktime (ie. iOS) doesn't support this option
  3177. av_opt_set( m_pCodecBCtx->priv_data, "b-pyramid", "0", 0 );
  3178. #ifdef DEBUG_EXTRA
  3179. LOG("End Options!");
  3180. #endif
  3181. } else {
  3182. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecBCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3183. };
  3184. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  3185. #ifdef DEBUG_EXTRA
  3186. char TB[129];
  3187. sprintf(TB, "TimeBaseA: num[%d]/den[%d]", m_pCodecACtx->time_base.num, m_pCodecACtx->time_base.den );
  3188. LOG(TB);
  3189. sprintf(TB, "TimeBaseB: num[%d]/den[%d]", m_pCodecBCtx->time_base.num, m_pCodecBCtx->time_base.den );
  3190. LOG(TB);
  3191. #endif
  3192. ////m_pVideoStrA->time_base = m_pCodecACtx->time_base;
  3193. ////m_pVideoStrB->time_base = m_pCodecBCtx->time_base;
  3194. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  3195. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3196. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3197. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3198. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3199. //// m_pVideoStrA->r_frame_rate = m_pVideoStrA->avg_frame_rate =
  3200. ////dst_fps;
  3201. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  3202. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3203. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3204. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3205. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3206. //// m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate =
  3207. ////dst_fps;
  3208. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3209. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3210. //// avcodec_parameters_from_context( m_pVideoStrA->codecpar,
  3211. ////m_pCodecACtx );
  3212. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3213. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  3214. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3215. //// avcodec_parameters_from_context( m_pVideoStrB->codecpar,
  3216. ////m_pCodecBCtx );
  3217. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3218. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  3219. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3220. if ( avcodec_is_open( m_pCodecACtx ) == 0 ) {
  3221. LOG("output codec context is closed, opening");
  3222. if ( avcodec_open2( m_pCodecACtx, m_pVideoACodec, NULL) < 0 ) {
  3223. LOG_ERROR("Error opening2 encoder");
  3224. return false;
  3225. #ifdef DEBUG_EXTRA
  3226. } else {
  3227. LOG("output codec context is opened");
  3228. #endif
  3229. };
  3230. #ifdef DEBUG_EXTRA
  3231. } else {
  3232. LOG("output codec context is already opened");
  3233. #endif
  3234. };
  3235. if ( avcodec_is_open( m_pCodecBCtx ) == 0 ) {
  3236. LOG("output codec context is closed, opening");
  3237. if ( avcodec_open2( m_pCodecBCtx, m_pVideoBCodec, NULL) < 0 ) {
  3238. LOG_ERROR("Error opening2 encoder");
  3239. return false;
  3240. #ifdef DEBUG_EXTRA
  3241. } else {
  3242. LOG("output codec context is opened");
  3243. #endif
  3244. };
  3245. #ifdef DEBUG_EXTRA
  3246. } else {
  3247. LOG("output codec context is already opened");
  3248. #endif
  3249. };
  3250. #else // SEPARATED_VIDEO_ENCODERS
  3251. if ( avformat_alloc_output_context2( &m_pFormatCtxA, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  3252. LOG_ERROR("Format CTX A alloc error!");
  3253. return false;
  3254. } else {
  3255. av_dict_set( &m_pFormatCtxA->metadata, "Author", "Argus Sec. System", 0 );
  3256. m_pFormatCtxA->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  3257. };
  3258. if ( avformat_alloc_output_context2( &m_pFormatCtxB, m_pFormat, NULL, "test." VIDEO_OUTPUT_CONTAINER ) < 0 ) {
  3259. LOG_ERROR("Format CTX B alloc error!");
  3260. avformat_free_context( m_pFormatCtxA );
  3261. return false;
  3262. } else {
  3263. av_dict_set( &m_pFormatCtxB->metadata, "Author", "Argus Sec. System", 0 );
  3264. m_pFormatCtxB->flags |= AVFMT_NOTIMESTAMPS | AVFMT_TS_NONSTRICT;
  3265. };
  3266. m_pVideoCodec = avcodec_find_encoder( VIDEO_OUTPUT_CODEC );
  3267. if( m_pVideoCodec == NULL ){
  3268. LOG_ERROR("Output VideoCodec Not Found!");
  3269. avformat_free_context( m_pFormatCtxA );
  3270. avformat_free_context( m_pFormatCtxB );
  3271. return false;
  3272. #ifdef DEBUG_EXTRA
  3273. } else {
  3274. LOG("Output Video Codec Found");
  3275. #endif
  3276. };
  3277. m_pCodecCtx = avcodec_alloc_context3( m_pVideoCodec );
  3278. if ( m_pCodecCtx == NULL){
  3279. LOG_ERROR("Out VideoCodec Context Memory Allocation Error");
  3280. av_free( m_pVideoCodec );
  3281. avformat_free_context( m_pFormatCtxA );
  3282. avformat_free_context( m_pFormatCtxB );
  3283. return false;
  3284. #ifdef DEBUG_EXTRA
  3285. } else {
  3286. LOG("Out Codec Context3 Allocated");
  3287. #endif
  3288. };
  3289. m_pVideoStrA = avformat_new_stream( m_pFormatCtxA, m_pVideoCodec );
  3290. if ( m_pVideoStrA == NULL){
  3291. LOG_ERROR("VideoStream A Not Created!");
  3292. avcodec_free_context( &m_pCodecCtx );
  3293. av_free( m_pCodecCtx );
  3294. av_free( m_pVideoCodec );
  3295. //avformat_close_input ( &m_pFormatCtxA );
  3296. //avformat_close_input ( &m_pFormatCtxB );
  3297. avformat_free_context( m_pFormatCtxA );
  3298. avformat_free_context( m_pFormatCtxB );
  3299. return false;
  3300. #ifdef DEBUG_EXTRA
  3301. } else {
  3302. LOG("VideoStream A is Created");
  3303. #endif
  3304. };
  3305. m_pVideoStrB = avformat_new_stream( m_pFormatCtxB, m_pVideoCodec );
  3306. if ( m_pVideoStrB == NULL){
  3307. LOG_ERROR("VideoStream B Not Created!");
  3308. avcodec_free_context( &m_pCodecCtx );
  3309. av_free( m_pCodecCtx );
  3310. av_free( m_pVideoCodec );
  3311. //avformat_close_input ( &m_pFormatCtxA );
  3312. //avformat_close_input ( &m_pFormatCtxB );
  3313. avformat_free_context( m_pFormatCtxA );
  3314. avformat_free_context( m_pFormatCtxB );
  3315. return false;
  3316. #ifdef DEBUG_EXTRA
  3317. } else {
  3318. LOG("VideoStream B is Created");
  3319. #endif
  3320. };
  3321. m_pCodecCtx->codec_id = VIDEO_OUTPUT_CODEC;
  3322. m_pCodecCtx->codec_type = AVMEDIA_TYPE_VIDEO;
  3323. m_pCodecCtx->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3324. m_pCodecCtx->bit_rate = VIDEO_OUTPUT_BITRATE;
  3325. //m_pCodecCtx->thread_count = 1;
  3326. //m_pCodecCtx->bit_rate_tolerance = 1;
  3327. //m_pCodecCtx->global_quality = 100;
  3328. //m_pCodecCtx->compression_level = 2;
  3329. m_pCodecCtx->max_b_frames=1;
  3330. m_pCodecCtx->width = m_pMaster->m_sEmbedVideoData.width;
  3331. m_pCodecCtx->height = m_pMaster->m_sEmbedVideoData.height;
  3332. m_pCodecCtx->time_base.num = 1;
  3333. m_pCodecCtx->time_base.den = m_sStreamData.fps;
  3334. m_pCodecCtx->framerate.num = m_sStreamData.fps;
  3335. m_pCodecCtx->framerate.den = 1;
  3336. //https://pastebin.com/yG37YhWW
  3337. //https://stackoverflow.com/questions/49276997/raw-h264-frames-in-mp4-container-using-libavcodec
  3338. //G@ avcodec encode NALU mp4
  3339. #if (LIBAVCODEC_VERSION_MAJOR > 54)
  3340. m_pCodecCtx->codec_tag = av_codec_get_tag( m_pFormatCtxA->oformat->codec_tag, VIDEO_OUTPUT_CODEC );
  3341. #endif
  3342. m_pFormatOpts = NULL;
  3343. // https://stackoverflow.com/questions/70060148/libav-producing-mp4-file-with-extremely-high-frame-rate
  3344. if( ( m_pCodecCtx->codec_id == AV_CODEC_ID_H264 ) || ( m_pCodecCtx->codec_id == AV_CODEC_ID_H265 ) ){
  3345. #ifdef DEBUG_EXTRA
  3346. LOG("Begin Options!");
  3347. #endif
  3348. //Reference for AvFormatContext options : https://ffmpeg.org/doxygen/2.8/movenc_8c_source.html
  3349. //Set format's privater options, to be passed to avformat_write_header()
  3350. /*
  3351. mp4 muxer AVOptions:
  3352. -movflags E..... MOV muxer flags (default 0)
  3353. rtphint E..... Add RTP hint tracks
  3354. empty_moov E..... Make the initial moov atom empty (not supported by QuickTime)
  3355. frag_keyframe E..... Fragment at video keyframes
  3356. separate_moof E..... Write separate moof/mdat atoms for each track
  3357. frag_custom E..... Flush fragments on caller requests
  3358. isml E..... Create a live smooth streaming feed (for pushing to a publishing point)
  3359. faststart E..... Run a second pass to put the index (moov atom) at the beginning of the file
  3360. omit_tfhd_offset E..... Omit the base data offset in tfhd atoms
  3361. delay_moov ??
  3362. -moov_size E..... maximum moov size so it can be placed at the begin (from 0 to INT_MAX) (default 0)
  3363. -rtpflags E..... RTP muxer flags (default 0)
  3364. latm E..... Use MP4A-LATM packetization instead of MPEG4-GENERIC for AAC
  3365. rfc2190 E..... Use RFC 2190 packetization instead of RFC 4629 for H.263
  3366. skip_rtcp E..... Don't send RTCP sender reports
  3367. h264_mode0 E..... Use mode 0 for H264 in RTP
  3368. send_bye E..... Send RTCP BYE packets when finishing
  3369. -skip_iods E..... Skip writing iods atom. (from 0 to 1) (default 1)
  3370. -iods_audio_profile E..... iods audio profile atom. (from -1 to 255) (default -1)
  3371. -iods_video_profile E..... iods video profile atom. (from -1 to 255) (default -1)
  3372. -frag_duration E..... Maximum fragment duration (from 0 to INT_MAX) (default 0)
  3373. -min_frag_duration E..... Minimum fragment duration (from 0 to INT_MAX) (default 0)
  3374. -frag_size E..... Maximum fragment size (from 0 to INT_MAX) (default 0)
  3375. -ism_lookahead E..... Number of lookahead entries for ISM files (from 0 to INT_MAX) (default 0)
  3376. -use_editlist E..... use edit list (from -1 to 1) (default -1)
  3377. -video_track_timescale E..... set timescale of all video tracks (from 0 to INT_MAX) (default 0)
  3378. */
  3379. if( av_dict_set( &m_pFormatOpts, "movflags", "isml+faststart+frag_keyframe+empty_moov+omit_tfhd_offset", 0 ) < 0 ){
  3380. LOG_ERROR( "av_dict_set movflags!");
  3381. #ifdef DEBUG_EXTRA
  3382. } else {
  3383. LOG("MOV FLAG SET!");
  3384. #endif
  3385. };
  3386. //if( av_dict_set( &m_pFormatOpts, "live", "1", 0 ) < 0 ){
  3387. // LOG_ERROR( "av_dict_set live!" );
  3388. //};
  3389. //default brand is "isom", which fails on some devices
  3390. if( av_dict_set( &m_pFormatOpts, "brand", "mp42", 0) < 0 ){
  3391. LOG_ERROR( "av_dict_set brand!" );
  3392. };
  3393. //m_pCodecCtx->max_b_frames = 1;
  3394. //m_pCodecCtx->level = 31;
  3395. m_pCodecCtx->gop_size = m_sStreamData.fps << 1;//VIDEO_OUTPUT_GOP; // emit one intra frame every X frames
  3396. /// P-frames, generated by referencing data from prev and future frames.
  3397. /// [Compression up, CPU usage up]
  3398. /// [use 3/gop]
  3399. m_pCodecCtx->max_b_frames = 5;
  3400. /// Can be used by a P-frame(predictive, partial frame) to help define a future frame in a compressed video.
  3401. /// [use 3�1�75 ref per P]
  3402. m_pCodecCtx->refs = 3;
  3403. /// Compression efficiency (slower -> better quality + higher cpu%)
  3404. /// [ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow]
  3405. /// Set this option to "ultrafast" is critical for realtime encoding
  3406. av_opt_set( m_pCodecCtx->priv_data, "preset", "ultrafast", 0);
  3407. //av_opt_set( m_pCodecCtx->priv_data, "preset", "fast", 0 );
  3408. //av_opt_set( m_pCodecCtx->priv_data, "preset", "slow", 0 );
  3409. /// Compression rate (lower -> higher compression) compress to lower size, makes decoded image more noisy
  3410. /// Range: [0; 51], sane range: [18; 26]. I used 35 as good compression/quality compromise. This option also critical for realtime encoding
  3411. av_opt_set( m_pCodecCtx->priv_data, "crf", "32", 0);
  3412. /// Change settings based upon the specifics of input
  3413. /// [psnr, ssim, grain, zerolatency, fastdecode, animation]
  3414. /// This option is most critical for realtime encoding, because it removes delay between 1th input frame and 1th output packet.
  3415. av_opt_set( m_pCodecCtx->priv_data, "tune", "zerolatency", 0);
  3416. /// Disable b-pyramid. CLI options for this is "-b-pyramid 0"
  3417. /// Because Quicktime (ie. iOS) doesn't support this option
  3418. av_opt_set( m_pCodecCtx->priv_data, "b-pyramid", "0", 0 );
  3419. #ifdef DEBUG_EXTRA
  3420. LOG("End Options!");
  3421. #endif
  3422. } else {
  3423. if( m_pFormat->flags & AVFMT_GLOBALHEADER ) m_pCodecCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3424. };
  3425. const AVRational dst_fps = { m_sStreamData.fps, 1 };
  3426. #ifdef DEBUG_EXTRA
  3427. char TB[129];
  3428. sprintf(TB, "TimeBase: num[%d]/den[%d]", m_pCodecCtx->time_base.num, m_pCodecCtx->time_base.den );
  3429. LOG(TB);
  3430. #endif
  3431. m_pVideoStrA->time_base = m_pCodecCtx->time_base;
  3432. m_pVideoStrB->time_base = m_pCodecCtx->time_base;
  3433. //avcodec_get_context_defaults3( m_pVideoStrA->codec, m_pVideoCodec );
  3434. //m_pVideoStrA->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3435. //m_pVideoStrA->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3436. //m_pVideoStrA->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3437. //m_pVideoStrA->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3438. m_pVideoStrA->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  3439. //avcodec_get_context_defaults3( m_pVideoStrB->codec, m_pVideoCodec );
  3440. //m_pVideoStrB->codec->width = m_pMaster->m_sEmbedVideoData.width;
  3441. //m_pVideoStrB->codec->height = m_pMaster->m_sEmbedVideoData.height;
  3442. //m_pVideoStrB->codec->pix_fmt = VIDEO_OUTPUT_PIX_FMT;
  3443. //m_pVideoStrB->codec->time_base = m_pVideoStrB->time_base = av_inv_q(dst_fps);
  3444. m_pVideoStrB->r_frame_rate = m_pVideoStrB->avg_frame_rate = dst_fps;
  3445. //if ( m_pFormatCtxA->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrA->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3446. //if ( m_pFormatCtxB->oformat->flags & AVFMT_GLOBALHEADER ) m_pVideoStrB->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  3447. avcodec_parameters_from_context( m_pVideoStrA->codecpar, m_pCodecCtx );
  3448. //m_pVideoStrA->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3449. //m_pVideoStrA->codecpar->extradata = m_pCodecCtx->extradata;
  3450. //m_pVideoStrA->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3451. avcodec_parameters_from_context( m_pVideoStrB->codecpar, m_pCodecCtx );
  3452. //m_pVideoStrB->codecpar->format = VIDEO_OUTPUT_PIX_FMT;
  3453. //m_pVideoStrB->codecpar->extradata = m_pCodecCtx->extradata;
  3454. //m_pVideoStrB->codecpar->extradata_size = m_pCodecCtx->extradata_size;
  3455. if ( avcodec_is_open( m_pCodecCtx ) == 0 ) {
  3456. LOG("output codec context is closed, opening");
  3457. if ( avcodec_open2( m_pCodecCtx, m_pVideoCodec, NULL) < 0 ) {
  3458. LOG_ERROR("Error opening2 encoder");
  3459. return false;
  3460. #ifdef DEBUG_EXTRA
  3461. } else {
  3462. LOG("output codec context is opened");
  3463. #endif
  3464. };
  3465. #ifdef DEBUG_EXTRA
  3466. } else {
  3467. LOG("output codec context is already opened");
  3468. #endif
  3469. };
  3470. #endif // SEPARATED_VIDEO_ENCODERS
  3471. m_pConvertCtx = sws_getContext(
  3472. m_pMaster->m_sEmbedVideoData.width,
  3473. m_pMaster->m_sEmbedVideoData.height,
  3474. AV_PIX_FMT_BGR24,
  3475. m_pMaster->m_sEmbedVideoData.width,
  3476. m_pMaster->m_sEmbedVideoData.height,
  3477. VIDEO_OUTPUT_PIX_FMT,
  3478. SWS_FAST_BILINEAR,
  3479. NULL,
  3480. NULL,
  3481. NULL
  3482. );
  3483. if ( m_pConvertCtx == NULL ) {
  3484. return false;
  3485. }
  3486. m_pAVFrame = av_frame_alloc();
  3487. if ( m_pAVFrame == NULL ) {
  3488. return false;
  3489. };
  3490. 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));
  3491. if( m_pOutBuffer == NULL ) {
  3492. return false;
  3493. };
  3494. m_pAVFrame->width = m_pMaster->m_sEmbedVideoData.width;
  3495. m_pAVFrame->height = m_pMaster->m_sEmbedVideoData.height;
  3496. m_pAVFrame->format = VIDEO_OUTPUT_PIX_FMT;
  3497. //av_frame_get_buffer( m_pAVFrame, 0 );
  3498. 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 );
  3499. //av_frame_make_writable( m_pAVFrame );
  3500. #endif // !OPENCV_VIDEO_OUTPUT
  3501. #endif // !DIRECT_MJPEG_COMPOSING
  3502. return init();
  3503. };
  3504. //encoding thread
  3505. void streamHandler::m_fThreadProc( void ){
  3506. char tB[128];
  3507. //#ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3508. size_t nQueueSize;
  3509. //#endif
  3510. #ifndef DIRECT_MJPEG_COMPOSING
  3511. #ifndef OPENCV_VIDEO_OUTPUT
  3512. AVPacket mPacket;
  3513. int bGotPacket;
  3514. int rVal = 0;
  3515. av_init_packet( &mPacket );
  3516. #endif
  3517. #endif
  3518. while( m_bThreadStatus != TH_ENDED ){
  3519. //At the begining All streams are closed --> try to Open
  3520. if( m_bThreadStatus < TH_WORKING ){
  3521. if( !openSegmentA() ){
  3522. m_bThreadStatus = TH_ENDED;
  3523. LOG_ERROR("Can not Open Seg A for first time!");
  3524. continue;
  3525. };
  3526. //if( !openSegmentB() ){
  3527. // m_bThreadStatus = TH_ENDED;
  3528. // continue;
  3529. //};
  3530. m_bThreadStatus = TH_WORKING;
  3531. continue;
  3532. };
  3533. m_mEncodingQueueProtector.lock();
  3534. nQueueSize = m_qEncodingQueue.size();
  3535. m_mEncodingQueueProtector.unlock();
  3536. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3537. if ( nQueueSize > EVE_EASE_FPS_QUEUE_SIZE_MAXIMUM ) {
  3538. //Just in case allredy applied to a streams
  3539. if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider ){
  3540. m_bWebFrameSkeepDivider++;
  3541. if ( m_bWebFrameSkeepDivider > EVE_EASE_FPS_DIVIDER_MAXIMUM ) {
  3542. m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MAXIMUM;
  3543. } else {
  3544. #ifdef DEBUG_EXTRA
  3545. LOG("Video Quality Degraded!");
  3546. #endif
  3547. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_DEGRADED, NULL, NULL, NULL );
  3548. if ( bEVT ) {
  3549. basicEventHeap::getInstance()->broadcast( bEVT );
  3550. } else LOG_ERROR( "Event Creation failure!");
  3551. };
  3552. };
  3553. } else if( nQueueSize < EVE_EASE_FPS_QUEUE_SIZE_MINIMUM ){
  3554. //Just in case allredy applied to a streams
  3555. if( m_bWebFrameSkeepDivider == m_bAFrameSkeepDivider && m_bWebFrameSkeepDivider == m_bBFrameSkeepDivider ){
  3556. m_bWebFrameSkeepDivider--;
  3557. if ( m_bWebFrameSkeepDivider < EVE_EASE_FPS_DIVIDER_MINIMUM ) {
  3558. m_bWebFrameSkeepDivider = EVE_EASE_FPS_DIVIDER_MINIMUM;
  3559. } else {
  3560. #ifdef DEBUG_EXTRA
  3561. LOG("Video Quality Upgraded!");
  3562. #endif
  3563. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_VIDEO_FPS_RAISED, NULL, NULL, NULL );
  3564. if ( bEVT ) {
  3565. basicEventHeap::getInstance()->broadcast( bEVT );
  3566. } else LOG_ERROR( "Event Creation failure!");
  3567. };
  3568. };
  3569. };
  3570. #endif //EVE_ENABLE_EASE_OUTPUT_FPS
  3571. if ( nQueueSize ) {
  3572. m_mEncodingQueueProtector.lock();
  3573. ENCODING_BUFFER *tData = m_qEncodingQueue.front();
  3574. if( tData ){
  3575. m_qEncodingQueue.pop();
  3576. m_mEncodingQueueProtector.unlock();
  3577. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3578. bool bSkeepA = tData->flag_sa;
  3579. bool bSkeepB = tData->flag_sb;
  3580. #endif
  3581. #ifdef DIRECT_MJPEG_COMPOSING
  3582. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3583. if( !bSkeepA )
  3584. #endif
  3585. if( m_bSegAActive ) if( m_pOutputFD[0] ){
  3586. fwrite( tData->data, 1, tData->size, m_pOutputFD[0] );
  3587. m_mFrameCounterProtector.lock();
  3588. m_nSegAFrameCounter++;
  3589. m_mFrameCounterProtector.unlock();
  3590. };
  3591. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3592. if( !bSkeepB )
  3593. #endif
  3594. if( m_bSegBActive ) if( m_pOutputFD[1] ){
  3595. fwrite( tData->data, 1, tData->size, m_pOutputFD[1] );
  3596. m_mFrameCounterProtector.lock();
  3597. m_nSegBFrameCounter++;
  3598. m_mFrameCounterProtector.unlock();
  3599. };
  3600. // Don't free tData->data since is pointer on static data
  3601. free( tData->data );
  3602. #else // !DIRECT_MJPEG_COMPOSING
  3603. #ifdef OPENCV_VIDEO_OUTPUT
  3604. cv::Mat image( tData->rows, tData->cols, CV_8UC3 );
  3605. memcpy( image.data, tData->data, tData->size );
  3606. free( tData->data );
  3607. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3608. if( !bSkeepA )
  3609. #endif
  3610. if (m_bSegAActive) if ( m_pEncoderA->isOpened() ) {
  3611. m_pEncoderA->write( image );
  3612. m_mFrameCounterProtector.lock();
  3613. m_nSegAFrameCounter++;
  3614. m_mFrameCounterProtector.unlock();
  3615. };
  3616. #ifdef EVE_ENABLE_EASE_OUTPUT_FPS
  3617. if( !bSkeepB )
  3618. #endif
  3619. if ( m_bSegBActive ) if ( m_pEncoderB->isOpened() ) {
  3620. m_pEncoderB->write( image );
  3621. m_mFrameCounterProtector.lock();
  3622. m_nSegBFrameCounter++;
  3623. m_mFrameCounterProtector.unlock();
  3624. };
  3625. #else //!OPENCV_VIDEO_OUTPUT
  3626. //av_frame_make_writable( m_pAVFrame );
  3627. //m_qEncodingQueue.pop();
  3628. //m_mEncodingQueueProtector.unlock();
  3629. sws_scale( m_pConvertCtx, tData->data, tData->linesize, 0, tData->rows, m_pAVFrame->data, m_pAVFrame->linesize );
  3630. free( tData->data[0] );
  3631. /*
  3632. AV_PICTURE_TYPE_NONE Undefined.
  3633. AV_PICTURE_TYPE_I Intra.
  3634. AV_PICTURE_TYPE_P Predicted.
  3635. AV_PICTURE_TYPE_B Bi-dir predicted.
  3636. AV_PICTURE_TYPE_S S(GMC)-VOP MPEG4.
  3637. AV_PICTURE_TYPE_SI Switching Intra.
  3638. AV_PICTURE_TYPE_SP Switching Predicted.
  3639. AV_PICTURE_TYPE_BI BI type.
  3640. */
  3641. if ( ( m_nGlobalFrameCounter % m_sStreamData.fps ) == 0 ) {
  3642. m_pAVFrame->key_frame = 1;
  3643. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_I;
  3644. } else {
  3645. m_pAVFrame->key_frame = 0;
  3646. m_pAVFrame->pict_type = AVPictureType::AV_PICTURE_TYPE_NONE;
  3647. };
  3648. m_pAVFrame->pts = m_nGlobalFrameCounter + 1;
  3649. #ifdef SEPARATED_VIDEO_ENCODERS
  3650. if( m_bSegAActive ) rVal = avcodec_send_frame( m_pCodecACtx, m_pAVFrame );
  3651. if( m_bSegBActive ) rVal = avcodec_send_frame( m_pCodecBCtx, m_pAVFrame );
  3652. #else //!SEPARATED_VIDEO_ENCODERS
  3653. rVal = avcodec_send_frame( m_pCodecCtx, m_pAVFrame );
  3654. #endif //!SEPARATED_VIDEO_ENCODERS
  3655. #endif //!OPENCV_VIDEO_OUTPUT
  3656. #endif //!DIRECT_MJPEG_COMPOSING
  3657. free( tData );
  3658. m_mFrameCounterProtector.lock();
  3659. m_nGlobalFrameCounter++;
  3660. m_mFrameCounterProtector.unlock();
  3661. } else m_mEncodingQueueProtector.unlock();
  3662. };
  3663. // Test Commands!
  3664. m_mCurrentOperationProtector.lock();
  3665. switch ( m_bCOP ) {
  3666. case 0x01:{
  3667. #ifdef DEBUG_EXTRA
  3668. LOG("Actual Closing Video Stream A!");
  3669. LOG( m_sStreamSegmentInfo[0].scratchPath );
  3670. #endif
  3671. m_bSegAActive = false;
  3672. if ( !m_bSegADelete ) {
  3673. #ifdef DIRECT_MJPEG_COMPOSING
  3674. if ( m_pOutputFD[0] ) {
  3675. fclose( m_pOutputFD[0] );
  3676. m_pOutputFD[0] = NULL;
  3677. };
  3678. #else //!DIRECT_MJPEG_COMPOSING
  3679. #ifdef OPENCV_VIDEO_OUTPUT
  3680. if ( m_pEncoderA->isOpened() ) {
  3681. m_pEncoderA->release();
  3682. #ifdef DEBUG_EXTRA
  3683. } else {
  3684. LOG(" Encoder A is NOT Opened!");
  3685. #endif
  3686. };
  3687. #else //!OPENCV_VIDEO_OUTPUT
  3688. av_write_trailer( m_pFormatCtxA );
  3689. avio_close( m_pFormatCtxA->pb );
  3690. #endif //!OPENCV_VIDEO_OUTPUT
  3691. #endif //!DIRECT_MJPEG_COMPOSING
  3692. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[0] );
  3693. if ( bEVT ) {
  3694. basicEventHeap::getInstance()->broadcast( bEVT );
  3695. } else LOG_ERROR( "Event Creation failure!");
  3696. #ifdef DEBUG_EXTRA
  3697. LOG("Stream A is Saved");
  3698. #endif
  3699. } else {
  3700. #ifdef DIRECT_MJPEG_COMPOSING
  3701. if ( m_pOutputFD[0] ) {
  3702. fclose( m_pOutputFD[0] );
  3703. m_pOutputFD[0] = NULL;
  3704. };
  3705. #else // !DIRECT_MJPEG_COMPOSING
  3706. #ifdef OPENCV_VIDEO_OUTPUT
  3707. if ( m_pEncoderA->isOpened() ) {
  3708. m_pEncoderA->release();
  3709. #ifdef DEBUG_EXTRA
  3710. } else {
  3711. LOG(" Encoder A is NOT Opened!");
  3712. #endif
  3713. };
  3714. #else // !OPENCV
  3715. #ifdef EVE_DONT_DELETE_SEGMENTS
  3716. av_write_trailer( m_pFormatCtxA );
  3717. #endif
  3718. avio_close( m_pFormatCtxA->pb );
  3719. #endif // !OPENCV_VIDEO_OUTPUT
  3720. #endif // !DIRECT_MJPEG_COMPOSING
  3721. #ifndef EVE_DONT_DELETE_SEGMENTS
  3722. unlink( m_sStreamSegmentInfo[0].scratchPath );
  3723. #endif
  3724. #ifdef DEBUG_EXTRA
  3725. LOG("Stream A is Closed!");
  3726. #endif
  3727. };
  3728. #ifndef DIRECT_MJPEG_COMPOSING
  3729. #ifndef OPENCV_VIDEO_OUTPUT
  3730. #ifdef SEPARATED_VIDEO_ENCODERS
  3731. #ifdef DEBUG_EXTRA
  3732. LOG("Del FCTX");
  3733. #endif
  3734. avformat_free_context( m_pFormatCtxA );
  3735. m_pVideoStrA = NULL;
  3736. #ifdef DEBUG_EXTRA
  3737. LOG("Del FCTX DONE");
  3738. #endif
  3739. #endif // SEPARATED_VIDEO_ENCODERS
  3740. #endif // !OPENCV
  3741. #endif // !DIRECT_MJPEG_COMPOSING
  3742. break;
  3743. };
  3744. case 0x02:{
  3745. #ifdef DEBUG_EXTRA
  3746. LOG("Actual Closing Video Stream B!");
  3747. LOG( m_sStreamSegmentInfo[1].scratchPath );
  3748. #endif
  3749. m_bSegBActive = false;
  3750. if ( !m_bSegBDelete ) {
  3751. #ifdef DIRECT_MJPEG_COMPOSING
  3752. if ( m_pOutputFD[1] ) {
  3753. fclose( m_pOutputFD[1] );
  3754. m_pOutputFD[1] = NULL;
  3755. };
  3756. #else // !DIRECT_MJPEG_COMPOSING
  3757. #ifdef OPENCV_VIDEO_OUTPUT
  3758. if ( m_pEncoderB->isOpened() ) {
  3759. m_pEncoderB->release();
  3760. #ifdef DEBUG_EXTRA
  3761. } else {
  3762. LOG(" Encoder B is NOT Opened!");
  3763. #endif
  3764. };
  3765. #else // !OpenCV
  3766. av_write_trailer( m_pFormatCtxB );
  3767. avio_close( m_pFormatCtxB->pb );
  3768. #endif // !OPENCV_VIDEO_OUTPUT
  3769. #endif // !DIRECT_MJPEG_COMPOSING
  3770. EVENT_CONTAINER *bEVT = createBasicEvent( m_sStreamData.source_id, EVT_CLASS_VIDEO, EVT_CAPTURE_DONE, NULL, NULL, &m_sStreamSegmentInfo[1] );
  3771. if ( bEVT ) {
  3772. basicEventHeap::getInstance()->broadcast( bEVT );
  3773. } else LOG_ERROR( "Event Creation failure!");
  3774. #ifdef DEBUG_EXTRA
  3775. LOG("Stream B is Saved");
  3776. #endif
  3777. } else {
  3778. #ifdef DIRECT_MJPEG_COMPOSING
  3779. if ( m_pOutputFD[1] ) {
  3780. fclose( m_pOutputFD[1] );
  3781. m_pOutputFD[1] = NULL;
  3782. };
  3783. #else
  3784. #ifdef OPENCV_VIDEO_OUTPUT
  3785. if ( m_pEncoderB->isOpened() ) {
  3786. m_pEncoderB->release();
  3787. #ifdef DEBUG_EXTRA
  3788. } else {
  3789. LOG(" Encoder B is NOT Opened!");
  3790. #endif
  3791. };
  3792. #else // !OPenCV
  3793. #ifdef EVE_DONT_DELETE_SEGMENTS
  3794. av_write_trailer( m_pFormatCtxB );
  3795. #endif
  3796. avio_close( m_pFormatCtxB->pb );
  3797. #endif // !OPENCV_VIDEO_OUTPUT
  3798. #endif // !DIRECT_MJPEG_COMPOSING
  3799. #ifndef EVE_DONT_DELETE_SEGMENTS
  3800. unlink( m_sStreamSegmentInfo[1].scratchPath );
  3801. #endif
  3802. #ifdef DEBUG_EXTRA
  3803. LOG("Stream B is Closed!");
  3804. #endif
  3805. };
  3806. #ifndef DIRECT_MJPEG_COMPOSING
  3807. #ifndef OPENCV_VIDEO_OUTPUT
  3808. #ifdef SEPARATED_VIDEO_ENCODERS
  3809. avformat_free_context( m_pFormatCtxB );
  3810. m_pVideoStrB = NULL;
  3811. #endif // SEPARATED_VIDEO_ENCODERS
  3812. #endif // !OPENCV
  3813. #endif // !DIRECT_MJPEG_COMPOSING
  3814. break;
  3815. };
  3816. };
  3817. m_bCOP = 0;
  3818. m_mCurrentOperationProtector.unlock();
  3819. //};
  3820. #ifndef DIRECT_MJPEG_COMPOSING
  3821. #ifndef OPENCV_VIDEO_OUTPUT
  3822. #ifdef SEPARATED_VIDEO_ENCODERS
  3823. do {
  3824. mPacket.data = NULL;
  3825. mPacket.size = 0;
  3826. rVal = avcodec_receive_packet( m_pCodecACtx, &mPacket );
  3827. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  3828. break;
  3829. } else if( rVal < 0 ){
  3830. LOG_ERROR( "Error during encoding " );
  3831. m_bThreadStatus = TH_ENDED;
  3832. break;
  3833. };
  3834. if( !rVal ){
  3835. if ( m_bSegAActive ) {
  3836. mPacket.stream_index = m_pVideoStrA->index;
  3837. mPacket.duration = 1;
  3838. m_mFrameCounterProtector.lock();
  3839. m_nSegAFrameCounter++;
  3840. m_mFrameCounterProtector.unlock();
  3841. mPacket.pts = av_rescale_q( m_nSegAFrameCounter, m_pCodecACtx->time_base, m_pVideoStrA->time_base );
  3842. //mPacket.pts = AV_NOPTS_VALUE;
  3843. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3844. mPacket.dts = mPacket.pts;
  3845. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  3846. if( rc < 0 ){
  3847. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  3848. m_bThreadStatus = TH_ENDED;
  3849. LOG_ERROR("Trouble with Video Output A!");
  3850. av_strerror( rc, tB, 128 );
  3851. LOG_ERROR( tB );
  3852. break; //continue (changed since embed into do-while)
  3853. };
  3854. };
  3855. if ( m_bSegBActive ) {
  3856. mPacket.stream_index = m_pVideoStrB->index;
  3857. mPacket.duration = 1;
  3858. m_mFrameCounterProtector.lock();
  3859. m_nSegBFrameCounter++;
  3860. m_mFrameCounterProtector.unlock();
  3861. mPacket.pts = av_rescale_q( m_nSegBFrameCounter, m_pCodecBCtx->time_base, m_pVideoStrB->time_base );
  3862. //mPacket.pts = AV_NOPTS_VALUE;
  3863. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  3864. mPacket.dts = mPacket.pts;
  3865. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  3866. if( rc < 0 ) {
  3867. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  3868. m_bThreadStatus = TH_ENDED;
  3869. LOG_ERROR( "Trouble with Video Output B!" );
  3870. av_strerror( rc, tB, 128 );
  3871. LOG_ERROR( tB );
  3872. break; //continue (changed since embed into do-while)
  3873. };
  3874. };
  3875. av_packet_unref( &mPacket );
  3876. };
  3877. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  3878. #else // ! SEPARATED_VIDEO_ENCODERS
  3879. do {
  3880. mPacket.data = NULL;
  3881. mPacket.size = 0;
  3882. rVal = avcodec_receive_packet( m_pCodecCtx, &mPacket );
  3883. if( rVal == AVERROR(EAGAIN) || rVal == AVERROR_EOF ){
  3884. break;
  3885. } else if( rVal < 0 ){
  3886. LOG_ERROR( "Error during encoding " );
  3887. m_bThreadStatus = TH_ENDED;
  3888. break;
  3889. };
  3890. if( !rVal ){
  3891. if ( m_bSegAActive ) {
  3892. mPacket.stream_index = m_pVideoStrA->index;
  3893. mPacket.duration = 1;
  3894. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3895. //mPacket.pts = AV_NOPTS_VALUE;
  3896. //mPacket.pts = av_rescale_q( m_nSegASkippedFrames + m_nSegAFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3897. mPacket.dts = mPacket.pts;
  3898. int rc = av_write_frame( m_pFormatCtxA, &mPacket );
  3899. if( rc < 0 ){
  3900. //if( av_interleaved_write_frame( m_pFormatCtxA, &mPacket) < 0 ) {
  3901. m_bThreadStatus = TH_ENDED;
  3902. LOG_ERROR("Trouble with Video Output A!");
  3903. av_strerror( rc, tB, 128 );
  3904. LOG_ERROR( tB );
  3905. break; //continue (changed since embed into do-while)
  3906. };
  3907. };
  3908. if ( m_bSegBActive ) {
  3909. mPacket.stream_index = m_pVideoStrB->index;
  3910. mPacket.duration = 1;
  3911. mPacket.pts = av_rescale_q( m_nGlobalFrameCounter, m_pCodecCtx->time_base, m_pVideoStrA->time_base );
  3912. //mPacket.pts = AV_NOPTS_VALUE;
  3913. //mPacket.pts = av_rescale_q( m_nSegBSkippedFrames + m_nSegBFrameCounter, m_pCodecCtx->time_base, m_pVideoStrB->time_base );
  3914. mPacket.dts = mPacket.pts;
  3915. int rc = av_write_frame( m_pFormatCtxB, &mPacket);
  3916. if( rc < 0 ) {
  3917. //if( av_interleaved_write_frame( m_pFormatCtxB, &mPacket) < 0 ) {
  3918. m_bThreadStatus = TH_ENDED;
  3919. LOG_ERROR( "Trouble with Video Output B!" );
  3920. av_strerror( rc, tB, 128 );
  3921. LOG_ERROR( tB );
  3922. break; //continue (changed since embed into do-while)
  3923. };
  3924. };
  3925. av_packet_unref( &mPacket );
  3926. };
  3927. } while ( rVal >= 0 && m_bThreadStatus != TH_ENDED );
  3928. #endif // ! SEPARATED_VIDEO_ENCODERS
  3929. #endif // !OPENCV_VIDEO_OUTPUT
  3930. #endif // !DIRECT_MJPEG_COMPOSING
  3931. SLEEP( 10 );
  3932. };
  3933. #ifdef DEBUG_EXTRA
  3934. LOG("Encoder Loop Ended!");
  3935. #endif
  3936. };
  3937. void streamHandler::swapActiveStreams( void ){
  3938. //m_mFrameCounterProtector.lock();
  3939. m_bActiveEncoderStream = 1 - m_bActiveEncoderStream;
  3940. if ( m_bActiveEncoderStream ) {
  3941. if ( m_bSegADelete ) closeSegmentA();
  3942. } else {
  3943. if ( m_bSegBDelete ) closeSegmentB();
  3944. };
  3945. //m_mFrameCounterProtector.unlock();
  3946. };
  3947. #endif // EVE_ENABLE_VIDEO
  3948. bool streamHandler::triggerEvent( uint32_t eid, uint32_t &dbid, uint32_t &frame ){
  3949. #ifdef DEBUG_EXTRA
  3950. LOG("Trig Evt");
  3951. #endif
  3952. #ifdef EVE_ENABLE_VIDEO
  3953. m_mFrameCounterProtector.lock();
  3954. // To Mark Events Frames
  3955. m_bEvtMarkerCounter = 255;
  3956. PF_TIMESTAMP ts;
  3957. getPFTS( &ts );
  3958. /*
  3959. if ( m_nVideoRegisteredDBID == 0 ) {
  3960. LOG("New Event!");
  3961. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  3962. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  3963. m_sStreamData.id,
  3964. m_cSegMD5A,
  3965. VIDEO_OUTPUT_CONTAINER,
  3966. ts.seconds,
  3967. ts.milliseconds,
  3968. m_sStreamData.fps
  3969. );
  3970. m_bSegADelete = false;
  3971. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  3972. } else { // Stream B is Active
  3973. m_nVideoRegisteredDBID = m_pDBC->addVideoRecord(
  3974. m_sStreamData.id,
  3975. m_cSegMD5B,
  3976. VIDEO_OUTPUT_CONTAINER,
  3977. ts.seconds,
  3978. ts.milliseconds,
  3979. m_sStreamData.fps
  3980. );
  3981. m_bSegBDelete = false;
  3982. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  3983. };
  3984. };
  3985. */
  3986. if ( !m_bActiveEncoderStream ) { // Stream A is Active
  3987. m_bSegADelete = false;
  3988. m_nSegAShiftFrames = frame = m_nSegAFrameCounter;
  3989. } else { // Stream B is Active
  3990. m_bSegBDelete = false;
  3991. m_nSegBShiftFrames = frame = m_nSegBFrameCounter;
  3992. };
  3993. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventIDS.push_back( eid );
  3994. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTSS.push_back( ts.seconds );
  3995. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventTMS.push_back( ts.milliseconds );
  3996. m_sStreamSegmentInfo[m_bActiveEncoderStream].eventFrames.push_back( frame );
  3997. //dbid = m_sStreamSegmentInfo[m_bActiveEncoderStream].db_id;// = m_nVideoRegisteredDBID;
  3998. m_mFrameCounterProtector.unlock();
  3999. //if ( dbid == 0 ) return false;
  4000. //dbid = m_nVideoRegisteredDBID;
  4001. #ifdef DEBUG_EXTRA
  4002. LOG("Event Registered!");
  4003. #endif
  4004. #endif // EVE_ENABLE_VIDEO
  4005. return true;
  4006. };
  4007. bool streamHandler::triggerCamMove( void ){
  4008. #ifdef DEBUG_EXTRA
  4009. LOG("Trig Cammove");
  4010. #endif
  4011. m_bCamMoveCounter = 255;
  4012. return true;
  4013. };
  4014. bool streamHandler::validate( void ){
  4015. if ( m_pSource ) {
  4016. if( m_pSource->getStatus() < MS_CLOSING ){
  4017. #ifdef EVE_ENABLE_VIDEO
  4018. if( m_nGlobalFrameCounter ) { //Frames Received from a source
  4019. if( m_nGlobalFrameCounter == m_nValidatorFrameCounter ) {
  4020. // Video Stalled!
  4021. LOG_ERROR("Video Stalled");
  4022. return false;// Try use System to recuperate
  4023. } else m_nValidatorFrameCounter = m_nGlobalFrameCounter;
  4024. };
  4025. if( m_bThreadStatus < TH_ENDED ) return true; else LOG_ERROR( "Thread Ended!");
  4026. #endif
  4027. } else LOG_ERROR("Video Ended");
  4028. };
  4029. return false;
  4030. };
  4031. //#undef DEBUG_EXTRA
  4032. //#undef DEBUG
  4033. #undef LOG
  4034. #undef LOG_ERROR
  4035. #undef TLOG
  4036. #undef TLOG_ERROR