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.

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