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.

5137 lines
206 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "video/video_stream_encoder.h"
  11. #include <algorithm>
  12. #include <limits>
  13. #include <memory>
  14. #include <utility>
  15. #include "absl/memory/memory.h"
  16. #include "api/task_queue/default_task_queue_factory.h"
  17. #include "api/test/mock_fec_controller_override.h"
  18. #include "api/video/builtin_video_bitrate_allocator_factory.h"
  19. #include "api/video/i420_buffer.h"
  20. #include "api/video/video_bitrate_allocation.h"
  21. #include "api/video_codecs/video_encoder.h"
  22. #include "api/video_codecs/vp8_temporal_layers.h"
  23. #include "api/video_codecs/vp8_temporal_layers_factory.h"
  24. #include "common_video/h264/h264_common.h"
  25. #include "common_video/include/video_frame_buffer.h"
  26. #include "media/base/video_adapter.h"
  27. #include "modules/video_coding/codecs/vp9/include/vp9_globals.h"
  28. #include "modules/video_coding/utility/default_video_bitrate_allocator.h"
  29. #include "modules/video_coding/utility/simulcast_rate_allocator.h"
  30. #include "rtc_base/fake_clock.h"
  31. #include "rtc_base/logging.h"
  32. #include "rtc_base/ref_counted_object.h"
  33. #include "system_wrappers/include/field_trial.h"
  34. #include "system_wrappers/include/metrics.h"
  35. #include "system_wrappers/include/sleep.h"
  36. #include "test/encoder_settings.h"
  37. #include "test/fake_encoder.h"
  38. #include "test/field_trial.h"
  39. #include "test/frame_generator.h"
  40. #include "test/gmock.h"
  41. #include "test/gtest.h"
  42. #include "test/video_encoder_proxy_factory.h"
  43. #include "video/send_statistics_proxy.h"
  44. namespace webrtc {
  45. using ScaleReason = AdaptationObserverInterface::AdaptReason;
  46. using ::testing::_;
  47. using ::testing::AllOf;
  48. using ::testing::Field;
  49. using ::testing::StrictMock;
  50. namespace {
  51. const int kMinPixelsPerFrame = 320 * 180;
  52. const int kMinFramerateFps = 2;
  53. const int kMinBalancedFramerateFps = 7;
  54. const int64_t kFrameTimeoutMs = 100;
  55. const size_t kMaxPayloadLength = 1440;
  56. const uint32_t kTargetBitrateBps = 1000000;
  57. const uint32_t kStartBitrateBps = 600000;
  58. const uint32_t kSimulcastTargetBitrateBps = 3150000;
  59. const uint32_t kLowTargetBitrateBps = kTargetBitrateBps / 10;
  60. const int kMaxInitialFramedrop = 4;
  61. const int kDefaultFramerate = 30;
  62. const int64_t kFrameIntervalMs = rtc::kNumMillisecsPerSec / kDefaultFramerate;
  63. const int64_t kProcessIntervalMs = 1000;
  64. const VideoEncoder::ResolutionBitrateLimits
  65. kEncoderBitrateLimits540p(960 * 540, 100 * 1000, 100 * 1000, 2000 * 1000);
  66. const VideoEncoder::ResolutionBitrateLimits
  67. kEncoderBitrateLimits720p(1280 * 720, 200 * 1000, 200 * 1000, 4000 * 1000);
  68. uint8_t optimal_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
  69. 0x00, 0x00, 0x03, 0x03, 0xF4,
  70. 0x05, 0x03, 0xC7, 0xE0, 0x1B,
  71. 0x41, 0x10, 0x8D, 0x00};
  72. class TestBuffer : public webrtc::I420Buffer {
  73. public:
  74. TestBuffer(rtc::Event* event, int width, int height)
  75. : I420Buffer(width, height), event_(event) {}
  76. private:
  77. friend class rtc::RefCountedObject<TestBuffer>;
  78. ~TestBuffer() override {
  79. if (event_)
  80. event_->Set();
  81. }
  82. rtc::Event* const event_;
  83. };
  84. // A fake native buffer that can't be converted to I420.
  85. class FakeNativeBuffer : public webrtc::VideoFrameBuffer {
  86. public:
  87. FakeNativeBuffer(rtc::Event* event, int width, int height)
  88. : event_(event), width_(width), height_(height) {}
  89. webrtc::VideoFrameBuffer::Type type() const override { return Type::kNative; }
  90. int width() const override { return width_; }
  91. int height() const override { return height_; }
  92. rtc::scoped_refptr<webrtc::I420BufferInterface> ToI420() override {
  93. return nullptr;
  94. }
  95. private:
  96. friend class rtc::RefCountedObject<FakeNativeBuffer>;
  97. ~FakeNativeBuffer() override {
  98. if (event_)
  99. event_->Set();
  100. }
  101. rtc::Event* const event_;
  102. const int width_;
  103. const int height_;
  104. };
  105. class CpuOveruseDetectorProxy : public OveruseFrameDetector {
  106. public:
  107. explicit CpuOveruseDetectorProxy(CpuOveruseMetricsObserver* metrics_observer)
  108. : OveruseFrameDetector(metrics_observer),
  109. last_target_framerate_fps_(-1) {}
  110. virtual ~CpuOveruseDetectorProxy() {}
  111. void OnTargetFramerateUpdated(int framerate_fps) override {
  112. rtc::CritScope cs(&lock_);
  113. last_target_framerate_fps_ = framerate_fps;
  114. OveruseFrameDetector::OnTargetFramerateUpdated(framerate_fps);
  115. }
  116. int GetLastTargetFramerate() {
  117. rtc::CritScope cs(&lock_);
  118. return last_target_framerate_fps_;
  119. }
  120. CpuOveruseOptions GetOptions() { return options_; }
  121. private:
  122. rtc::CriticalSection lock_;
  123. int last_target_framerate_fps_ RTC_GUARDED_BY(lock_);
  124. };
  125. class VideoStreamEncoderUnderTest : public VideoStreamEncoder {
  126. public:
  127. VideoStreamEncoderUnderTest(SendStatisticsProxy* stats_proxy,
  128. const VideoStreamEncoderSettings& settings,
  129. TaskQueueFactory* task_queue_factory)
  130. : VideoStreamEncoder(Clock::GetRealTimeClock(),
  131. 1 /* number_of_cores */,
  132. stats_proxy,
  133. settings,
  134. std::unique_ptr<OveruseFrameDetector>(
  135. overuse_detector_proxy_ =
  136. new CpuOveruseDetectorProxy(stats_proxy)),
  137. task_queue_factory) {}
  138. void PostTaskAndWait(bool down, AdaptReason reason) {
  139. PostTaskAndWait(down, reason, /*expected_results=*/true);
  140. }
  141. void PostTaskAndWait(bool down, AdaptReason reason, bool expected_results) {
  142. rtc::Event event;
  143. encoder_queue()->PostTask([this, &event, reason, down, expected_results] {
  144. if (down)
  145. EXPECT_EQ(expected_results, AdaptDown(reason));
  146. else
  147. AdaptUp(reason);
  148. event.Set();
  149. });
  150. ASSERT_TRUE(event.Wait(5000));
  151. }
  152. // This is used as a synchronisation mechanism, to make sure that the
  153. // encoder queue is not blocked before we start sending it frames.
  154. void WaitUntilTaskQueueIsIdle() {
  155. rtc::Event event;
  156. encoder_queue()->PostTask([&event] { event.Set(); });
  157. ASSERT_TRUE(event.Wait(5000));
  158. }
  159. void TriggerCpuOveruse() {
  160. PostTaskAndWait(/*down=*/true, AdaptReason::kCpu);
  161. }
  162. void TriggerCpuNormalUsage() {
  163. PostTaskAndWait(/*down=*/false, AdaptReason::kCpu);
  164. }
  165. void TriggerQualityLow() {
  166. PostTaskAndWait(/*down=*/true, AdaptReason::kQuality);
  167. }
  168. void TriggerQualityLowExpectFalse() {
  169. PostTaskAndWait(/*down=*/true, AdaptReason::kQuality,
  170. /*expected_results=*/false);
  171. }
  172. void TriggerQualityHigh() {
  173. PostTaskAndWait(/*down=*/false, AdaptReason::kQuality);
  174. }
  175. CpuOveruseDetectorProxy* overuse_detector_proxy_;
  176. };
  177. class VideoStreamFactory
  178. : public VideoEncoderConfig::VideoStreamFactoryInterface {
  179. public:
  180. explicit VideoStreamFactory(size_t num_temporal_layers, int framerate)
  181. : num_temporal_layers_(num_temporal_layers), framerate_(framerate) {
  182. EXPECT_GT(num_temporal_layers, 0u);
  183. EXPECT_GT(framerate, 0);
  184. }
  185. private:
  186. std::vector<VideoStream> CreateEncoderStreams(
  187. int width,
  188. int height,
  189. const VideoEncoderConfig& encoder_config) override {
  190. std::vector<VideoStream> streams =
  191. test::CreateVideoStreams(width, height, encoder_config);
  192. for (VideoStream& stream : streams) {
  193. stream.num_temporal_layers = num_temporal_layers_;
  194. stream.max_framerate = framerate_;
  195. }
  196. return streams;
  197. }
  198. const size_t num_temporal_layers_;
  199. const int framerate_;
  200. };
  201. // Simulates simulcast behavior and makes highest stream resolutions divisible
  202. // by 4.
  203. class CroppingVideoStreamFactory
  204. : public VideoEncoderConfig::VideoStreamFactoryInterface {
  205. public:
  206. explicit CroppingVideoStreamFactory(size_t num_temporal_layers, int framerate)
  207. : num_temporal_layers_(num_temporal_layers), framerate_(framerate) {
  208. EXPECT_GT(num_temporal_layers, 0u);
  209. EXPECT_GT(framerate, 0);
  210. }
  211. private:
  212. std::vector<VideoStream> CreateEncoderStreams(
  213. int width,
  214. int height,
  215. const VideoEncoderConfig& encoder_config) override {
  216. std::vector<VideoStream> streams = test::CreateVideoStreams(
  217. width - width % 4, height - height % 4, encoder_config);
  218. for (VideoStream& stream : streams) {
  219. stream.num_temporal_layers = num_temporal_layers_;
  220. stream.max_framerate = framerate_;
  221. }
  222. return streams;
  223. }
  224. const size_t num_temporal_layers_;
  225. const int framerate_;
  226. };
  227. class AdaptingFrameForwarder : public test::FrameForwarder {
  228. public:
  229. AdaptingFrameForwarder() : adaptation_enabled_(false) {}
  230. ~AdaptingFrameForwarder() override {}
  231. void set_adaptation_enabled(bool enabled) {
  232. rtc::CritScope cs(&crit_);
  233. adaptation_enabled_ = enabled;
  234. }
  235. bool adaption_enabled() const {
  236. rtc::CritScope cs(&crit_);
  237. return adaptation_enabled_;
  238. }
  239. rtc::VideoSinkWants last_wants() const {
  240. rtc::CritScope cs(&crit_);
  241. return last_wants_;
  242. }
  243. absl::optional<int> last_sent_width() const { return last_width_; }
  244. absl::optional<int> last_sent_height() const { return last_height_; }
  245. void IncomingCapturedFrame(const VideoFrame& video_frame) override {
  246. int cropped_width = 0;
  247. int cropped_height = 0;
  248. int out_width = 0;
  249. int out_height = 0;
  250. if (adaption_enabled()) {
  251. if (adapter_.AdaptFrameResolution(
  252. video_frame.width(), video_frame.height(),
  253. video_frame.timestamp_us() * 1000, &cropped_width,
  254. &cropped_height, &out_width, &out_height)) {
  255. VideoFrame adapted_frame =
  256. VideoFrame::Builder()
  257. .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
  258. nullptr, out_width, out_height))
  259. .set_timestamp_rtp(99)
  260. .set_timestamp_ms(99)
  261. .set_rotation(kVideoRotation_0)
  262. .build();
  263. adapted_frame.set_ntp_time_ms(video_frame.ntp_time_ms());
  264. test::FrameForwarder::IncomingCapturedFrame(adapted_frame);
  265. last_width_.emplace(adapted_frame.width());
  266. last_height_.emplace(adapted_frame.height());
  267. } else {
  268. last_width_ = absl::nullopt;
  269. last_height_ = absl::nullopt;
  270. }
  271. } else {
  272. test::FrameForwarder::IncomingCapturedFrame(video_frame);
  273. last_width_.emplace(video_frame.width());
  274. last_height_.emplace(video_frame.height());
  275. }
  276. }
  277. void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
  278. const rtc::VideoSinkWants& wants) override {
  279. rtc::CritScope cs(&crit_);
  280. last_wants_ = sink_wants();
  281. adapter_.OnResolutionFramerateRequest(wants.target_pixel_count,
  282. wants.max_pixel_count,
  283. wants.max_framerate_fps);
  284. test::FrameForwarder::AddOrUpdateSink(sink, wants);
  285. }
  286. cricket::VideoAdapter adapter_;
  287. bool adaptation_enabled_ RTC_GUARDED_BY(crit_);
  288. rtc::VideoSinkWants last_wants_ RTC_GUARDED_BY(crit_);
  289. absl::optional<int> last_width_;
  290. absl::optional<int> last_height_;
  291. };
  292. // TODO(nisse): Mock only VideoStreamEncoderObserver.
  293. class MockableSendStatisticsProxy : public SendStatisticsProxy {
  294. public:
  295. MockableSendStatisticsProxy(Clock* clock,
  296. const VideoSendStream::Config& config,
  297. VideoEncoderConfig::ContentType content_type)
  298. : SendStatisticsProxy(clock, config, content_type) {}
  299. VideoSendStream::Stats GetStats() override {
  300. rtc::CritScope cs(&lock_);
  301. if (mock_stats_)
  302. return *mock_stats_;
  303. return SendStatisticsProxy::GetStats();
  304. }
  305. int GetInputFrameRate() const override {
  306. rtc::CritScope cs(&lock_);
  307. if (mock_stats_)
  308. return mock_stats_->input_frame_rate;
  309. return SendStatisticsProxy::GetInputFrameRate();
  310. }
  311. void SetMockStats(const VideoSendStream::Stats& stats) {
  312. rtc::CritScope cs(&lock_);
  313. mock_stats_.emplace(stats);
  314. }
  315. void ResetMockStats() {
  316. rtc::CritScope cs(&lock_);
  317. mock_stats_.reset();
  318. }
  319. private:
  320. rtc::CriticalSection lock_;
  321. absl::optional<VideoSendStream::Stats> mock_stats_ RTC_GUARDED_BY(lock_);
  322. };
  323. class MockBitrateObserver : public VideoBitrateAllocationObserver {
  324. public:
  325. MOCK_METHOD1(OnBitrateAllocationUpdated, void(const VideoBitrateAllocation&));
  326. };
  327. } // namespace
  328. class VideoStreamEncoderTest : public ::testing::Test {
  329. public:
  330. static const int kDefaultTimeoutMs = 30 * 1000;
  331. VideoStreamEncoderTest()
  332. : video_send_config_(VideoSendStream::Config(nullptr)),
  333. codec_width_(320),
  334. codec_height_(240),
  335. max_framerate_(kDefaultFramerate),
  336. task_queue_factory_(CreateDefaultTaskQueueFactory()),
  337. fake_encoder_(),
  338. encoder_factory_(&fake_encoder_),
  339. stats_proxy_(new MockableSendStatisticsProxy(
  340. Clock::GetRealTimeClock(),
  341. video_send_config_,
  342. webrtc::VideoEncoderConfig::ContentType::kRealtimeVideo)),
  343. sink_(&fake_encoder_) {}
  344. void SetUp() override {
  345. metrics::Reset();
  346. video_send_config_ = VideoSendStream::Config(nullptr);
  347. video_send_config_.encoder_settings.encoder_factory = &encoder_factory_;
  348. video_send_config_.encoder_settings.bitrate_allocator_factory =
  349. &bitrate_allocator_factory_;
  350. video_send_config_.rtp.payload_name = "FAKE";
  351. video_send_config_.rtp.payload_type = 125;
  352. VideoEncoderConfig video_encoder_config;
  353. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  354. video_encoder_config.video_stream_factory =
  355. new rtc::RefCountedObject<VideoStreamFactory>(1, max_framerate_);
  356. video_encoder_config_ = video_encoder_config.Copy();
  357. // Framerate limit is specified by the VideoStreamFactory.
  358. std::vector<VideoStream> streams =
  359. video_encoder_config.video_stream_factory->CreateEncoderStreams(
  360. codec_width_, codec_height_, video_encoder_config);
  361. max_framerate_ = streams[0].max_framerate;
  362. fake_clock_.SetTime(Timestamp::us(1234));
  363. ConfigureEncoder(std::move(video_encoder_config));
  364. }
  365. void ConfigureEncoder(VideoEncoderConfig video_encoder_config) {
  366. if (video_stream_encoder_)
  367. video_stream_encoder_->Stop();
  368. video_stream_encoder_.reset(new VideoStreamEncoderUnderTest(
  369. stats_proxy_.get(), video_send_config_.encoder_settings,
  370. task_queue_factory_.get()));
  371. video_stream_encoder_->SetSink(&sink_, false /* rotation_applied */);
  372. video_stream_encoder_->SetSource(
  373. &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  374. video_stream_encoder_->SetStartBitrate(kTargetBitrateBps);
  375. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  376. kMaxPayloadLength);
  377. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  378. }
  379. void ResetEncoder(const std::string& payload_name,
  380. size_t num_streams,
  381. size_t num_temporal_layers,
  382. unsigned char num_spatial_layers,
  383. bool screenshare) {
  384. video_send_config_.rtp.payload_name = payload_name;
  385. VideoEncoderConfig video_encoder_config;
  386. video_encoder_config.codec_type = PayloadStringToCodecType(payload_name);
  387. video_encoder_config.number_of_streams = num_streams;
  388. video_encoder_config.max_bitrate_bps =
  389. num_streams == 1 ? kTargetBitrateBps : kSimulcastTargetBitrateBps;
  390. video_encoder_config.video_stream_factory =
  391. new rtc::RefCountedObject<VideoStreamFactory>(num_temporal_layers,
  392. kDefaultFramerate);
  393. video_encoder_config.content_type =
  394. screenshare ? VideoEncoderConfig::ContentType::kScreen
  395. : VideoEncoderConfig::ContentType::kRealtimeVideo;
  396. if (payload_name == "VP9") {
  397. VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
  398. vp9_settings.numberOfSpatialLayers = num_spatial_layers;
  399. video_encoder_config.encoder_specific_settings =
  400. new rtc::RefCountedObject<
  401. VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
  402. }
  403. ConfigureEncoder(std::move(video_encoder_config));
  404. }
  405. VideoFrame CreateFrame(int64_t ntp_time_ms,
  406. rtc::Event* destruction_event) const {
  407. VideoFrame frame =
  408. VideoFrame::Builder()
  409. .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
  410. destruction_event, codec_width_, codec_height_))
  411. .set_timestamp_rtp(99)
  412. .set_timestamp_ms(99)
  413. .set_rotation(kVideoRotation_0)
  414. .build();
  415. frame.set_ntp_time_ms(ntp_time_ms);
  416. return frame;
  417. }
  418. VideoFrame CreateFrameWithUpdatedPixel(int64_t ntp_time_ms,
  419. rtc::Event* destruction_event,
  420. int offset_x) const {
  421. VideoFrame frame =
  422. VideoFrame::Builder()
  423. .set_video_frame_buffer(new rtc::RefCountedObject<TestBuffer>(
  424. destruction_event, codec_width_, codec_height_))
  425. .set_timestamp_rtp(99)
  426. .set_timestamp_ms(99)
  427. .set_rotation(kVideoRotation_0)
  428. .set_update_rect({offset_x, 0, 1, 1})
  429. .build();
  430. frame.set_ntp_time_ms(ntp_time_ms);
  431. return frame;
  432. }
  433. VideoFrame CreateFrame(int64_t ntp_time_ms, int width, int height) const {
  434. VideoFrame frame =
  435. VideoFrame::Builder()
  436. .set_video_frame_buffer(
  437. new rtc::RefCountedObject<TestBuffer>(nullptr, width, height))
  438. .set_timestamp_rtp(99)
  439. .set_timestamp_ms(99)
  440. .set_rotation(kVideoRotation_0)
  441. .build();
  442. frame.set_ntp_time_ms(ntp_time_ms);
  443. frame.set_timestamp_us(ntp_time_ms * 1000);
  444. return frame;
  445. }
  446. VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
  447. rtc::Event* destruction_event,
  448. int width,
  449. int height) const {
  450. VideoFrame frame =
  451. VideoFrame::Builder()
  452. .set_video_frame_buffer(new rtc::RefCountedObject<FakeNativeBuffer>(
  453. destruction_event, width, height))
  454. .set_timestamp_rtp(99)
  455. .set_timestamp_ms(99)
  456. .set_rotation(kVideoRotation_0)
  457. .build();
  458. frame.set_ntp_time_ms(ntp_time_ms);
  459. return frame;
  460. }
  461. VideoFrame CreateFakeNativeFrame(int64_t ntp_time_ms,
  462. rtc::Event* destruction_event) const {
  463. return CreateFakeNativeFrame(ntp_time_ms, destruction_event, codec_width_,
  464. codec_height_);
  465. }
  466. void VerifyAllocatedBitrate(const VideoBitrateAllocation& expected_bitrate) {
  467. MockBitrateObserver bitrate_observer;
  468. video_stream_encoder_->SetBitrateAllocationObserver(&bitrate_observer);
  469. EXPECT_CALL(bitrate_observer, OnBitrateAllocationUpdated(expected_bitrate))
  470. .Times(1);
  471. video_stream_encoder_->OnBitrateUpdated(
  472. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  473. DataRate::bps(kTargetBitrateBps), 0, 0);
  474. video_source_.IncomingCapturedFrame(
  475. CreateFrame(1, codec_width_, codec_height_));
  476. WaitForEncodedFrame(1);
  477. }
  478. void VerifyNoLimitation(const rtc::VideoSinkWants& wants) {
  479. EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_framerate_fps);
  480. EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_pixel_count);
  481. EXPECT_FALSE(wants.target_pixel_count);
  482. }
  483. void VerifyFpsEqResolutionEq(const rtc::VideoSinkWants& wants1,
  484. const rtc::VideoSinkWants& wants2) {
  485. EXPECT_EQ(wants1.max_framerate_fps, wants2.max_framerate_fps);
  486. EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
  487. }
  488. void VerifyFpsMaxResolutionMax(const rtc::VideoSinkWants& wants) {
  489. EXPECT_EQ(kDefaultFramerate, wants.max_framerate_fps);
  490. EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_pixel_count);
  491. EXPECT_FALSE(wants.target_pixel_count);
  492. }
  493. void VerifyFpsMaxResolutionLt(const rtc::VideoSinkWants& wants1,
  494. const rtc::VideoSinkWants& wants2) {
  495. EXPECT_EQ(kDefaultFramerate, wants1.max_framerate_fps);
  496. EXPECT_LT(wants1.max_pixel_count, wants2.max_pixel_count);
  497. EXPECT_GT(wants1.max_pixel_count, 0);
  498. }
  499. void VerifyFpsMaxResolutionGt(const rtc::VideoSinkWants& wants1,
  500. const rtc::VideoSinkWants& wants2) {
  501. EXPECT_EQ(kDefaultFramerate, wants1.max_framerate_fps);
  502. EXPECT_GT(wants1.max_pixel_count, wants2.max_pixel_count);
  503. }
  504. void VerifyFpsMaxResolutionEq(const rtc::VideoSinkWants& wants1,
  505. const rtc::VideoSinkWants& wants2) {
  506. EXPECT_EQ(kDefaultFramerate, wants1.max_framerate_fps);
  507. EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
  508. }
  509. void VerifyFpsLtResolutionEq(const rtc::VideoSinkWants& wants1,
  510. const rtc::VideoSinkWants& wants2) {
  511. EXPECT_LT(wants1.max_framerate_fps, wants2.max_framerate_fps);
  512. EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
  513. }
  514. void VerifyFpsGtResolutionEq(const rtc::VideoSinkWants& wants1,
  515. const rtc::VideoSinkWants& wants2) {
  516. EXPECT_GT(wants1.max_framerate_fps, wants2.max_framerate_fps);
  517. EXPECT_EQ(wants1.max_pixel_count, wants2.max_pixel_count);
  518. }
  519. void VerifyFpsEqResolutionLt(const rtc::VideoSinkWants& wants1,
  520. const rtc::VideoSinkWants& wants2) {
  521. EXPECT_EQ(wants1.max_framerate_fps, wants2.max_framerate_fps);
  522. EXPECT_LT(wants1.max_pixel_count, wants2.max_pixel_count);
  523. EXPECT_GT(wants1.max_pixel_count, 0);
  524. }
  525. void VerifyFpsEqResolutionGt(const rtc::VideoSinkWants& wants1,
  526. const rtc::VideoSinkWants& wants2) {
  527. EXPECT_EQ(wants1.max_framerate_fps, wants2.max_framerate_fps);
  528. EXPECT_GT(wants1.max_pixel_count, wants2.max_pixel_count);
  529. }
  530. void VerifyFpsMaxResolutionLt(const rtc::VideoSinkWants& wants,
  531. int pixel_count) {
  532. EXPECT_EQ(kDefaultFramerate, wants.max_framerate_fps);
  533. EXPECT_LT(wants.max_pixel_count, pixel_count);
  534. EXPECT_GT(wants.max_pixel_count, 0);
  535. }
  536. void VerifyFpsLtResolutionMax(const rtc::VideoSinkWants& wants, int fps) {
  537. EXPECT_LT(wants.max_framerate_fps, fps);
  538. EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_pixel_count);
  539. EXPECT_FALSE(wants.target_pixel_count);
  540. }
  541. void VerifyFpsEqResolutionMax(const rtc::VideoSinkWants& wants,
  542. int expected_fps) {
  543. EXPECT_EQ(expected_fps, wants.max_framerate_fps);
  544. EXPECT_EQ(std::numeric_limits<int>::max(), wants.max_pixel_count);
  545. EXPECT_FALSE(wants.target_pixel_count);
  546. }
  547. void VerifyBalancedModeFpsRange(const rtc::VideoSinkWants& wants,
  548. int last_frame_pixels) {
  549. // Balanced mode should always scale FPS to the desired range before
  550. // attempting to scale resolution.
  551. int fps_limit = wants.max_framerate_fps;
  552. if (last_frame_pixels <= 320 * 240) {
  553. EXPECT_TRUE(7 <= fps_limit && fps_limit <= 10);
  554. } else if (last_frame_pixels <= 480 * 270) {
  555. EXPECT_TRUE(10 <= fps_limit && fps_limit <= 15);
  556. } else if (last_frame_pixels <= 640 * 480) {
  557. EXPECT_LE(15, fps_limit);
  558. } else {
  559. EXPECT_EQ(kDefaultFramerate, fps_limit);
  560. }
  561. }
  562. void WaitForEncodedFrame(int64_t expected_ntp_time) {
  563. sink_.WaitForEncodedFrame(expected_ntp_time);
  564. fake_clock_.AdvanceTime(TimeDelta::seconds(1) / max_framerate_);
  565. }
  566. bool TimedWaitForEncodedFrame(int64_t expected_ntp_time, int64_t timeout_ms) {
  567. bool ok = sink_.TimedWaitForEncodedFrame(expected_ntp_time, timeout_ms);
  568. fake_clock_.AdvanceTime(TimeDelta::seconds(1) / max_framerate_);
  569. return ok;
  570. }
  571. void WaitForEncodedFrame(uint32_t expected_width, uint32_t expected_height) {
  572. sink_.WaitForEncodedFrame(expected_width, expected_height);
  573. fake_clock_.AdvanceTime(TimeDelta::seconds(1) / max_framerate_);
  574. }
  575. void ExpectDroppedFrame() {
  576. sink_.ExpectDroppedFrame();
  577. fake_clock_.AdvanceTime(TimeDelta::seconds(1) / max_framerate_);
  578. }
  579. bool WaitForFrame(int64_t timeout_ms) {
  580. bool ok = sink_.WaitForFrame(timeout_ms);
  581. fake_clock_.AdvanceTime(TimeDelta::seconds(1) / max_framerate_);
  582. return ok;
  583. }
  584. class TestEncoder : public test::FakeEncoder {
  585. public:
  586. TestEncoder() : FakeEncoder(Clock::GetRealTimeClock()) {}
  587. VideoCodec codec_config() const {
  588. rtc::CritScope lock(&crit_sect_);
  589. return config_;
  590. }
  591. void BlockNextEncode() {
  592. rtc::CritScope lock(&local_crit_sect_);
  593. block_next_encode_ = true;
  594. }
  595. VideoEncoder::EncoderInfo GetEncoderInfo() const override {
  596. rtc::CritScope lock(&local_crit_sect_);
  597. EncoderInfo info;
  598. if (initialized_ == EncoderState::kInitialized) {
  599. if (quality_scaling_) {
  600. info.scaling_settings =
  601. VideoEncoder::ScalingSettings(1, 2, kMinPixelsPerFrame);
  602. }
  603. info.is_hardware_accelerated = is_hardware_accelerated_;
  604. for (int i = 0; i < kMaxSpatialLayers; ++i) {
  605. if (temporal_layers_supported_[i]) {
  606. int num_layers = temporal_layers_supported_[i].value() ? 2 : 1;
  607. info.fps_allocation[i].resize(num_layers);
  608. }
  609. }
  610. }
  611. info.resolution_bitrate_limits = resolution_bitrate_limits_;
  612. return info;
  613. }
  614. int32_t RegisterEncodeCompleteCallback(
  615. EncodedImageCallback* callback) override {
  616. rtc::CritScope lock(&local_crit_sect_);
  617. encoded_image_callback_ = callback;
  618. return FakeEncoder::RegisterEncodeCompleteCallback(callback);
  619. }
  620. void ContinueEncode() { continue_encode_event_.Set(); }
  621. void CheckLastTimeStampsMatch(int64_t ntp_time_ms,
  622. uint32_t timestamp) const {
  623. rtc::CritScope lock(&local_crit_sect_);
  624. EXPECT_EQ(timestamp_, timestamp);
  625. EXPECT_EQ(ntp_time_ms_, ntp_time_ms);
  626. }
  627. void SetQualityScaling(bool b) {
  628. rtc::CritScope lock(&local_crit_sect_);
  629. quality_scaling_ = b;
  630. }
  631. void SetIsHardwareAccelerated(bool is_hardware_accelerated) {
  632. rtc::CritScope lock(&local_crit_sect_);
  633. is_hardware_accelerated_ = is_hardware_accelerated;
  634. }
  635. void SetTemporalLayersSupported(size_t spatial_idx, bool supported) {
  636. RTC_DCHECK_LT(spatial_idx, kMaxSpatialLayers);
  637. rtc::CritScope lock(&local_crit_sect_);
  638. temporal_layers_supported_[spatial_idx] = supported;
  639. }
  640. void SetResolutionBitrateLimits(
  641. std::vector<ResolutionBitrateLimits> thresholds) {
  642. rtc::CritScope cs(&local_crit_sect_);
  643. resolution_bitrate_limits_ = thresholds;
  644. }
  645. void ForceInitEncodeFailure(bool force_failure) {
  646. rtc::CritScope lock(&local_crit_sect_);
  647. force_init_encode_failed_ = force_failure;
  648. }
  649. void SimulateOvershoot(double rate_factor) {
  650. rtc::CritScope lock(&local_crit_sect_);
  651. rate_factor_ = rate_factor;
  652. }
  653. uint32_t GetLastFramerate() const {
  654. rtc::CritScope lock(&local_crit_sect_);
  655. return last_framerate_;
  656. }
  657. VideoFrame::UpdateRect GetLastUpdateRect() const {
  658. rtc::CritScope lock(&local_crit_sect_);
  659. return last_update_rect_;
  660. }
  661. const std::vector<VideoFrameType>& LastFrameTypes() const {
  662. rtc::CritScope lock(&local_crit_sect_);
  663. return last_frame_types_;
  664. }
  665. void InjectFrame(const VideoFrame& input_image, bool keyframe) {
  666. const std::vector<VideoFrameType> frame_type = {
  667. keyframe ? VideoFrameType::kVideoFrameKey
  668. : VideoFrameType::kVideoFrameDelta};
  669. {
  670. rtc::CritScope lock(&local_crit_sect_);
  671. last_frame_types_ = frame_type;
  672. }
  673. FakeEncoder::Encode(input_image, &frame_type);
  674. }
  675. void InjectEncodedImage(const EncodedImage& image) {
  676. rtc::CritScope lock(&local_crit_sect_);
  677. encoded_image_callback_->OnEncodedImage(image, nullptr, nullptr);
  678. }
  679. void InjectEncodedImage(const EncodedImage& image,
  680. const CodecSpecificInfo* codec_specific_info,
  681. const RTPFragmentationHeader* fragmentation) {
  682. rtc::CritScope lock(&local_crit_sect_);
  683. encoded_image_callback_->OnEncodedImage(image, codec_specific_info,
  684. fragmentation);
  685. }
  686. void ExpectNullFrame() {
  687. rtc::CritScope lock(&local_crit_sect_);
  688. expect_null_frame_ = true;
  689. }
  690. absl::optional<VideoEncoder::RateControlParameters>
  691. GetAndResetLastRateControlSettings() {
  692. auto settings = last_rate_control_settings_;
  693. last_rate_control_settings_.reset();
  694. return settings;
  695. }
  696. int GetNumEncoderInitializations() const {
  697. rtc::CritScope lock(&local_crit_sect_);
  698. return num_encoder_initializations_;
  699. }
  700. int GetNumSetRates() const {
  701. rtc::CritScope lock(&local_crit_sect_);
  702. return num_set_rates_;
  703. }
  704. private:
  705. int32_t Encode(const VideoFrame& input_image,
  706. const std::vector<VideoFrameType>* frame_types) override {
  707. bool block_encode;
  708. {
  709. rtc::CritScope lock(&local_crit_sect_);
  710. if (expect_null_frame_) {
  711. EXPECT_EQ(input_image.timestamp(), 0u);
  712. EXPECT_EQ(input_image.width(), 1);
  713. last_frame_types_ = *frame_types;
  714. expect_null_frame_ = false;
  715. } else {
  716. EXPECT_GT(input_image.timestamp(), timestamp_);
  717. EXPECT_GT(input_image.ntp_time_ms(), ntp_time_ms_);
  718. EXPECT_EQ(input_image.timestamp(), input_image.ntp_time_ms() * 90);
  719. }
  720. timestamp_ = input_image.timestamp();
  721. ntp_time_ms_ = input_image.ntp_time_ms();
  722. last_input_width_ = input_image.width();
  723. last_input_height_ = input_image.height();
  724. block_encode = block_next_encode_;
  725. block_next_encode_ = false;
  726. last_update_rect_ = input_image.update_rect();
  727. last_frame_types_ = *frame_types;
  728. }
  729. int32_t result = FakeEncoder::Encode(input_image, frame_types);
  730. if (block_encode)
  731. EXPECT_TRUE(continue_encode_event_.Wait(kDefaultTimeoutMs));
  732. return result;
  733. }
  734. int32_t InitEncode(const VideoCodec* config,
  735. const Settings& settings) override {
  736. int res = FakeEncoder::InitEncode(config, settings);
  737. rtc::CritScope lock(&local_crit_sect_);
  738. EXPECT_EQ(initialized_, EncoderState::kUninitialized);
  739. ++num_encoder_initializations_;
  740. if (config->codecType == kVideoCodecVP8) {
  741. // Simulate setting up temporal layers, in order to validate the life
  742. // cycle of these objects.
  743. Vp8TemporalLayersFactory factory;
  744. frame_buffer_controller_ =
  745. factory.Create(*config, settings, &fec_controller_override_);
  746. }
  747. if (force_init_encode_failed_) {
  748. initialized_ = EncoderState::kInitializationFailed;
  749. return -1;
  750. }
  751. initialized_ = EncoderState::kInitialized;
  752. return res;
  753. }
  754. int32_t Release() override {
  755. rtc::CritScope lock(&local_crit_sect_);
  756. EXPECT_NE(initialized_, EncoderState::kUninitialized);
  757. initialized_ = EncoderState::kUninitialized;
  758. return FakeEncoder::Release();
  759. }
  760. void SetRates(const RateControlParameters& parameters) {
  761. rtc::CritScope lock(&local_crit_sect_);
  762. num_set_rates_++;
  763. VideoBitrateAllocation adjusted_rate_allocation;
  764. for (size_t si = 0; si < kMaxSpatialLayers; ++si) {
  765. for (size_t ti = 0; ti < kMaxTemporalStreams; ++ti) {
  766. if (parameters.bitrate.HasBitrate(si, ti)) {
  767. adjusted_rate_allocation.SetBitrate(
  768. si, ti,
  769. static_cast<uint32_t>(parameters.bitrate.GetBitrate(si, ti) *
  770. rate_factor_));
  771. }
  772. }
  773. }
  774. last_framerate_ = static_cast<uint32_t>(parameters.framerate_fps + 0.5);
  775. last_rate_control_settings_ = parameters;
  776. RateControlParameters adjusted_paramters = parameters;
  777. adjusted_paramters.bitrate = adjusted_rate_allocation;
  778. FakeEncoder::SetRates(adjusted_paramters);
  779. }
  780. rtc::CriticalSection local_crit_sect_;
  781. enum class EncoderState {
  782. kUninitialized,
  783. kInitializationFailed,
  784. kInitialized
  785. } initialized_ RTC_GUARDED_BY(local_crit_sect_) =
  786. EncoderState::kUninitialized;
  787. bool block_next_encode_ RTC_GUARDED_BY(local_crit_sect_) = false;
  788. rtc::Event continue_encode_event_;
  789. uint32_t timestamp_ RTC_GUARDED_BY(local_crit_sect_) = 0;
  790. int64_t ntp_time_ms_ RTC_GUARDED_BY(local_crit_sect_) = 0;
  791. int last_input_width_ RTC_GUARDED_BY(local_crit_sect_) = 0;
  792. int last_input_height_ RTC_GUARDED_BY(local_crit_sect_) = 0;
  793. bool quality_scaling_ RTC_GUARDED_BY(local_crit_sect_) = true;
  794. bool is_hardware_accelerated_ RTC_GUARDED_BY(local_crit_sect_) = false;
  795. std::unique_ptr<Vp8FrameBufferController> frame_buffer_controller_
  796. RTC_GUARDED_BY(local_crit_sect_);
  797. absl::optional<bool>
  798. temporal_layers_supported_[kMaxSpatialLayers] RTC_GUARDED_BY(
  799. local_crit_sect_);
  800. bool force_init_encode_failed_ RTC_GUARDED_BY(local_crit_sect_) = false;
  801. double rate_factor_ RTC_GUARDED_BY(local_crit_sect_) = 1.0;
  802. uint32_t last_framerate_ RTC_GUARDED_BY(local_crit_sect_) = 0;
  803. absl::optional<VideoEncoder::RateControlParameters>
  804. last_rate_control_settings_;
  805. VideoFrame::UpdateRect last_update_rect_
  806. RTC_GUARDED_BY(local_crit_sect_) = {0, 0, 0, 0};
  807. std::vector<VideoFrameType> last_frame_types_;
  808. bool expect_null_frame_ = false;
  809. EncodedImageCallback* encoded_image_callback_
  810. RTC_GUARDED_BY(local_crit_sect_) = nullptr;
  811. MockFecControllerOverride fec_controller_override_;
  812. int num_encoder_initializations_ RTC_GUARDED_BY(local_crit_sect_) = 0;
  813. std::vector<ResolutionBitrateLimits> resolution_bitrate_limits_
  814. RTC_GUARDED_BY(local_crit_sect_);
  815. int num_set_rates_ RTC_GUARDED_BY(local_crit_sect_) = 0;
  816. };
  817. class TestSink : public VideoStreamEncoder::EncoderSink {
  818. public:
  819. explicit TestSink(TestEncoder* test_encoder)
  820. : test_encoder_(test_encoder) {}
  821. void WaitForEncodedFrame(int64_t expected_ntp_time) {
  822. EXPECT_TRUE(
  823. TimedWaitForEncodedFrame(expected_ntp_time, kDefaultTimeoutMs));
  824. }
  825. bool TimedWaitForEncodedFrame(int64_t expected_ntp_time,
  826. int64_t timeout_ms) {
  827. uint32_t timestamp = 0;
  828. if (!encoded_frame_event_.Wait(timeout_ms))
  829. return false;
  830. {
  831. rtc::CritScope lock(&crit_);
  832. timestamp = last_timestamp_;
  833. }
  834. test_encoder_->CheckLastTimeStampsMatch(expected_ntp_time, timestamp);
  835. return true;
  836. }
  837. void WaitForEncodedFrame(uint32_t expected_width,
  838. uint32_t expected_height) {
  839. EXPECT_TRUE(encoded_frame_event_.Wait(kDefaultTimeoutMs));
  840. CheckLastFrameSizeMatches(expected_width, expected_height);
  841. }
  842. void CheckLastFrameSizeMatches(uint32_t expected_width,
  843. uint32_t expected_height) {
  844. uint32_t width = 0;
  845. uint32_t height = 0;
  846. {
  847. rtc::CritScope lock(&crit_);
  848. width = last_width_;
  849. height = last_height_;
  850. }
  851. EXPECT_EQ(expected_height, height);
  852. EXPECT_EQ(expected_width, width);
  853. }
  854. void CheckLastFrameRotationMatches(VideoRotation expected_rotation) {
  855. VideoRotation rotation;
  856. {
  857. rtc::CritScope lock(&crit_);
  858. rotation = last_rotation_;
  859. }
  860. EXPECT_EQ(expected_rotation, rotation);
  861. }
  862. void ExpectDroppedFrame() { EXPECT_FALSE(encoded_frame_event_.Wait(100)); }
  863. bool WaitForFrame(int64_t timeout_ms) {
  864. return encoded_frame_event_.Wait(timeout_ms);
  865. }
  866. void SetExpectNoFrames() {
  867. rtc::CritScope lock(&crit_);
  868. expect_frames_ = false;
  869. }
  870. int number_of_reconfigurations() const {
  871. rtc::CritScope lock(&crit_);
  872. return number_of_reconfigurations_;
  873. }
  874. int last_min_transmit_bitrate() const {
  875. rtc::CritScope lock(&crit_);
  876. return min_transmit_bitrate_bps_;
  877. }
  878. void SetNumExpectedLayers(size_t num_layers) {
  879. rtc::CritScope lock(&crit_);
  880. num_expected_layers_ = num_layers;
  881. }
  882. int64_t GetLastCaptureTimeMs() const {
  883. rtc::CritScope lock(&crit_);
  884. return last_capture_time_ms_;
  885. }
  886. std::vector<uint8_t> GetLastEncodedImageData() {
  887. rtc::CritScope lock(&crit_);
  888. return std::move(last_encoded_image_data_);
  889. }
  890. RTPFragmentationHeader GetLastFragmentation() {
  891. rtc::CritScope lock(&crit_);
  892. return std::move(last_fragmentation_);
  893. }
  894. private:
  895. Result OnEncodedImage(
  896. const EncodedImage& encoded_image,
  897. const CodecSpecificInfo* codec_specific_info,
  898. const RTPFragmentationHeader* fragmentation) override {
  899. rtc::CritScope lock(&crit_);
  900. EXPECT_TRUE(expect_frames_);
  901. last_encoded_image_data_ = std::vector<uint8_t>(
  902. encoded_image.data(), encoded_image.data() + encoded_image.size());
  903. if (fragmentation) {
  904. last_fragmentation_.CopyFrom(*fragmentation);
  905. }
  906. uint32_t timestamp = encoded_image.Timestamp();
  907. if (last_timestamp_ != timestamp) {
  908. num_received_layers_ = 1;
  909. } else {
  910. ++num_received_layers_;
  911. }
  912. last_timestamp_ = timestamp;
  913. last_capture_time_ms_ = encoded_image.capture_time_ms_;
  914. last_width_ = encoded_image._encodedWidth;
  915. last_height_ = encoded_image._encodedHeight;
  916. last_rotation_ = encoded_image.rotation_;
  917. if (num_received_layers_ == num_expected_layers_) {
  918. encoded_frame_event_.Set();
  919. }
  920. return Result(Result::OK, last_timestamp_);
  921. }
  922. void OnEncoderConfigurationChanged(
  923. std::vector<VideoStream> streams,
  924. VideoEncoderConfig::ContentType content_type,
  925. int min_transmit_bitrate_bps) override {
  926. rtc::CritScope lock(&crit_);
  927. ++number_of_reconfigurations_;
  928. min_transmit_bitrate_bps_ = min_transmit_bitrate_bps;
  929. }
  930. rtc::CriticalSection crit_;
  931. TestEncoder* test_encoder_;
  932. rtc::Event encoded_frame_event_;
  933. std::vector<uint8_t> last_encoded_image_data_;
  934. RTPFragmentationHeader last_fragmentation_;
  935. uint32_t last_timestamp_ = 0;
  936. int64_t last_capture_time_ms_ = 0;
  937. uint32_t last_height_ = 0;
  938. uint32_t last_width_ = 0;
  939. VideoRotation last_rotation_ = kVideoRotation_0;
  940. size_t num_expected_layers_ = 1;
  941. size_t num_received_layers_ = 0;
  942. bool expect_frames_ = true;
  943. int number_of_reconfigurations_ = 0;
  944. int min_transmit_bitrate_bps_ = 0;
  945. };
  946. class VideoBitrateAllocatorProxyFactory
  947. : public VideoBitrateAllocatorFactory {
  948. public:
  949. VideoBitrateAllocatorProxyFactory()
  950. : bitrate_allocator_factory_(
  951. CreateBuiltinVideoBitrateAllocatorFactory()) {}
  952. std::unique_ptr<VideoBitrateAllocator> CreateVideoBitrateAllocator(
  953. const VideoCodec& codec) override {
  954. rtc::CritScope lock(&crit_);
  955. codec_config_ = codec;
  956. return bitrate_allocator_factory_->CreateVideoBitrateAllocator(codec);
  957. }
  958. VideoCodec codec_config() const {
  959. rtc::CritScope lock(&crit_);
  960. return codec_config_;
  961. }
  962. private:
  963. std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
  964. rtc::CriticalSection crit_;
  965. VideoCodec codec_config_ RTC_GUARDED_BY(crit_);
  966. };
  967. VideoSendStream::Config video_send_config_;
  968. VideoEncoderConfig video_encoder_config_;
  969. int codec_width_;
  970. int codec_height_;
  971. int max_framerate_;
  972. rtc::ScopedFakeClock fake_clock_;
  973. const std::unique_ptr<TaskQueueFactory> task_queue_factory_;
  974. TestEncoder fake_encoder_;
  975. test::VideoEncoderProxyFactory encoder_factory_;
  976. VideoBitrateAllocatorProxyFactory bitrate_allocator_factory_;
  977. std::unique_ptr<MockableSendStatisticsProxy> stats_proxy_;
  978. TestSink sink_;
  979. AdaptingFrameForwarder video_source_;
  980. std::unique_ptr<VideoStreamEncoderUnderTest> video_stream_encoder_;
  981. };
  982. TEST_F(VideoStreamEncoderTest, EncodeOneFrame) {
  983. video_stream_encoder_->OnBitrateUpdated(
  984. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  985. DataRate::bps(kTargetBitrateBps), 0, 0);
  986. rtc::Event frame_destroyed_event;
  987. video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
  988. WaitForEncodedFrame(1);
  989. EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
  990. video_stream_encoder_->Stop();
  991. }
  992. TEST_F(VideoStreamEncoderTest, DropsFramesBeforeFirstOnBitrateUpdated) {
  993. // Dropped since no target bitrate has been set.
  994. rtc::Event frame_destroyed_event;
  995. // The encoder will cache up to one frame for a short duration. Adding two
  996. // frames means that the first frame will be dropped and the second frame will
  997. // be sent when the encoder is enabled.
  998. video_source_.IncomingCapturedFrame(CreateFrame(1, &frame_destroyed_event));
  999. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1000. EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
  1001. video_stream_encoder_->OnBitrateUpdated(
  1002. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1003. DataRate::bps(kTargetBitrateBps), 0, 0);
  1004. // The pending frame should be received.
  1005. WaitForEncodedFrame(2);
  1006. video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
  1007. WaitForEncodedFrame(3);
  1008. video_stream_encoder_->Stop();
  1009. }
  1010. TEST_F(VideoStreamEncoderTest, DropsFramesWhenRateSetToZero) {
  1011. video_stream_encoder_->OnBitrateUpdated(
  1012. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1013. DataRate::bps(kTargetBitrateBps), 0, 0);
  1014. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1015. WaitForEncodedFrame(1);
  1016. video_stream_encoder_->OnBitrateUpdated(DataRate::bps(0), DataRate::bps(0),
  1017. DataRate::bps(0), 0, 0);
  1018. // The encoder will cache up to one frame for a short duration. Adding two
  1019. // frames means that the first frame will be dropped and the second frame will
  1020. // be sent when the encoder is resumed.
  1021. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1022. video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
  1023. video_stream_encoder_->OnBitrateUpdated(
  1024. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1025. DataRate::bps(kTargetBitrateBps), 0, 0);
  1026. WaitForEncodedFrame(3);
  1027. video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
  1028. WaitForEncodedFrame(4);
  1029. video_stream_encoder_->Stop();
  1030. }
  1031. TEST_F(VideoStreamEncoderTest, DropsFramesWithSameOrOldNtpTimestamp) {
  1032. video_stream_encoder_->OnBitrateUpdated(
  1033. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1034. DataRate::bps(kTargetBitrateBps), 0, 0);
  1035. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1036. WaitForEncodedFrame(1);
  1037. // This frame will be dropped since it has the same ntp timestamp.
  1038. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1039. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1040. WaitForEncodedFrame(2);
  1041. video_stream_encoder_->Stop();
  1042. }
  1043. TEST_F(VideoStreamEncoderTest, DropsFrameAfterStop) {
  1044. video_stream_encoder_->OnBitrateUpdated(
  1045. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1046. DataRate::bps(kTargetBitrateBps), 0, 0);
  1047. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1048. WaitForEncodedFrame(1);
  1049. video_stream_encoder_->Stop();
  1050. sink_.SetExpectNoFrames();
  1051. rtc::Event frame_destroyed_event;
  1052. video_source_.IncomingCapturedFrame(CreateFrame(2, &frame_destroyed_event));
  1053. EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
  1054. }
  1055. TEST_F(VideoStreamEncoderTest, DropsPendingFramesOnSlowEncode) {
  1056. video_stream_encoder_->OnBitrateUpdated(
  1057. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1058. DataRate::bps(kTargetBitrateBps), 0, 0);
  1059. fake_encoder_.BlockNextEncode();
  1060. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1061. WaitForEncodedFrame(1);
  1062. // Here, the encoder thread will be blocked in the TestEncoder waiting for a
  1063. // call to ContinueEncode.
  1064. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1065. video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
  1066. fake_encoder_.ContinueEncode();
  1067. WaitForEncodedFrame(3);
  1068. video_stream_encoder_->Stop();
  1069. }
  1070. TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420Conversion) {
  1071. video_stream_encoder_->OnBitrateUpdated(
  1072. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1073. DataRate::bps(kTargetBitrateBps), 0, 0);
  1074. rtc::Event frame_destroyed_event;
  1075. video_source_.IncomingCapturedFrame(
  1076. CreateFakeNativeFrame(1, &frame_destroyed_event));
  1077. ExpectDroppedFrame();
  1078. EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
  1079. video_stream_encoder_->Stop();
  1080. }
  1081. TEST_F(VideoStreamEncoderTest, DropFrameWithFailedI420ConversionWithCrop) {
  1082. // Use the cropping factory.
  1083. video_encoder_config_.video_stream_factory =
  1084. new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, 30);
  1085. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config_),
  1086. kMaxPayloadLength);
  1087. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  1088. // Capture a frame at codec_width_/codec_height_.
  1089. video_stream_encoder_->OnBitrateUpdated(
  1090. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1091. DataRate::bps(kTargetBitrateBps), 0, 0);
  1092. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1093. WaitForEncodedFrame(1);
  1094. // The encoder will have been configured once.
  1095. EXPECT_EQ(1, sink_.number_of_reconfigurations());
  1096. EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
  1097. EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
  1098. // Now send in a fake frame that needs to be cropped as the width/height
  1099. // aren't divisible by 4 (see CreateEncoderStreams above).
  1100. rtc::Event frame_destroyed_event;
  1101. video_source_.IncomingCapturedFrame(CreateFakeNativeFrame(
  1102. 2, &frame_destroyed_event, codec_width_ + 1, codec_height_ + 1));
  1103. ExpectDroppedFrame();
  1104. EXPECT_TRUE(frame_destroyed_event.Wait(kDefaultTimeoutMs));
  1105. video_stream_encoder_->Stop();
  1106. }
  1107. TEST_F(VideoStreamEncoderTest,
  1108. ConfigureEncoderTriggersOnEncoderConfigurationChanged) {
  1109. video_stream_encoder_->OnBitrateUpdated(
  1110. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1111. DataRate::bps(kTargetBitrateBps), 0, 0);
  1112. EXPECT_EQ(0, sink_.number_of_reconfigurations());
  1113. // Capture a frame and wait for it to synchronize with the encoder thread.
  1114. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1115. WaitForEncodedFrame(1);
  1116. // The encoder will have been configured once when the first frame is
  1117. // received.
  1118. EXPECT_EQ(1, sink_.number_of_reconfigurations());
  1119. VideoEncoderConfig video_encoder_config;
  1120. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  1121. video_encoder_config.min_transmit_bitrate_bps = 9999;
  1122. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  1123. kMaxPayloadLength);
  1124. // Capture a frame and wait for it to synchronize with the encoder thread.
  1125. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1126. WaitForEncodedFrame(2);
  1127. EXPECT_EQ(2, sink_.number_of_reconfigurations());
  1128. EXPECT_EQ(9999, sink_.last_min_transmit_bitrate());
  1129. video_stream_encoder_->Stop();
  1130. }
  1131. TEST_F(VideoStreamEncoderTest, FrameResolutionChangeReconfigureEncoder) {
  1132. video_stream_encoder_->OnBitrateUpdated(
  1133. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1134. DataRate::bps(kTargetBitrateBps), 0, 0);
  1135. // Capture a frame and wait for it to synchronize with the encoder thread.
  1136. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1137. WaitForEncodedFrame(1);
  1138. // The encoder will have been configured once.
  1139. EXPECT_EQ(1, sink_.number_of_reconfigurations());
  1140. EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
  1141. EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
  1142. codec_width_ *= 2;
  1143. codec_height_ *= 2;
  1144. // Capture a frame with a higher resolution and wait for it to synchronize
  1145. // with the encoder thread.
  1146. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1147. WaitForEncodedFrame(2);
  1148. EXPECT_EQ(codec_width_, fake_encoder_.codec_config().width);
  1149. EXPECT_EQ(codec_height_, fake_encoder_.codec_config().height);
  1150. EXPECT_EQ(2, sink_.number_of_reconfigurations());
  1151. video_stream_encoder_->Stop();
  1152. }
  1153. TEST_F(VideoStreamEncoderTest,
  1154. EncoderInstanceDestroyedBeforeAnotherInstanceCreated) {
  1155. video_stream_encoder_->OnBitrateUpdated(
  1156. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1157. DataRate::bps(kTargetBitrateBps), 0, 0);
  1158. // Capture a frame and wait for it to synchronize with the encoder thread.
  1159. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1160. WaitForEncodedFrame(1);
  1161. VideoEncoderConfig video_encoder_config;
  1162. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  1163. // Changing the max payload data length recreates encoder.
  1164. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  1165. kMaxPayloadLength / 2);
  1166. // Capture a frame and wait for it to synchronize with the encoder thread.
  1167. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1168. WaitForEncodedFrame(2);
  1169. EXPECT_EQ(1, encoder_factory_.GetMaxNumberOfSimultaneousEncoderInstances());
  1170. video_stream_encoder_->Stop();
  1171. }
  1172. TEST_F(VideoStreamEncoderTest, BitrateLimitsChangeReconfigureRateAllocator) {
  1173. video_stream_encoder_->OnBitrateUpdated(
  1174. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1175. DataRate::bps(kTargetBitrateBps), 0, 0);
  1176. VideoEncoderConfig video_encoder_config;
  1177. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  1178. video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
  1179. video_stream_encoder_->SetStartBitrate(kStartBitrateBps);
  1180. video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
  1181. kMaxPayloadLength);
  1182. // Capture a frame and wait for it to synchronize with the encoder thread.
  1183. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  1184. WaitForEncodedFrame(1);
  1185. // The encoder will have been configured once when the first frame is
  1186. // received.
  1187. EXPECT_EQ(1, sink_.number_of_reconfigurations());
  1188. EXPECT_EQ(kTargetBitrateBps,
  1189. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1190. EXPECT_EQ(kStartBitrateBps,
  1191. bitrate_allocator_factory_.codec_config().startBitrate * 1000);
  1192. test::FillEncoderConfiguration(kVideoCodecVP8, 1,
  1193. &video_encoder_config); //???
  1194. video_encoder_config.max_bitrate_bps = kTargetBitrateBps * 2;
  1195. video_stream_encoder_->SetStartBitrate(kStartBitrateBps * 2);
  1196. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  1197. kMaxPayloadLength);
  1198. // Capture a frame and wait for it to synchronize with the encoder thread.
  1199. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  1200. WaitForEncodedFrame(2);
  1201. EXPECT_EQ(2, sink_.number_of_reconfigurations());
  1202. // Bitrate limits have changed - rate allocator should be reconfigured,
  1203. // encoder should not be reconfigured.
  1204. EXPECT_EQ(kTargetBitrateBps * 2,
  1205. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1206. EXPECT_EQ(kStartBitrateBps * 2,
  1207. bitrate_allocator_factory_.codec_config().startBitrate * 1000);
  1208. EXPECT_EQ(1, fake_encoder_.GetNumEncoderInitializations());
  1209. video_stream_encoder_->Stop();
  1210. }
  1211. TEST_F(VideoStreamEncoderTest,
  1212. EncoderRecommendedBitrateLimitsDoNotOverrideAppBitrateLimits) {
  1213. video_stream_encoder_->OnBitrateUpdated(
  1214. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1215. DataRate::bps(kTargetBitrateBps), 0, 0);
  1216. VideoEncoderConfig video_encoder_config;
  1217. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  1218. video_encoder_config.max_bitrate_bps = 0;
  1219. video_encoder_config.simulcast_layers[0].min_bitrate_bps = 0;
  1220. video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
  1221. kMaxPayloadLength);
  1222. video_source_.IncomingCapturedFrame(CreateFrame(1, 360, 180));
  1223. WaitForEncodedFrame(1);
  1224. // Get the default bitrate limits and use them as baseline for custom
  1225. // application and encoder recommended limits.
  1226. const uint32_t kDefaultMinBitrateKbps =
  1227. bitrate_allocator_factory_.codec_config().minBitrate;
  1228. const uint32_t kDefaultMaxBitrateKbps =
  1229. bitrate_allocator_factory_.codec_config().maxBitrate;
  1230. const uint32_t kEncMinBitrateKbps = kDefaultMinBitrateKbps * 2;
  1231. const uint32_t kEncMaxBitrateKbps = kDefaultMaxBitrateKbps * 2;
  1232. const uint32_t kAppMinBitrateKbps = kDefaultMinBitrateKbps * 3;
  1233. const uint32_t kAppMaxBitrateKbps = kDefaultMaxBitrateKbps * 3;
  1234. const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
  1235. codec_width_ * codec_height_, kEncMinBitrateKbps * 1000,
  1236. kEncMinBitrateKbps * 1000, kEncMaxBitrateKbps * 1000);
  1237. fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
  1238. // Change resolution. This will trigger encoder re-configuration and video
  1239. // stream encoder will pick up the bitrate limits recommended by encoder.
  1240. video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
  1241. WaitForEncodedFrame(2);
  1242. video_source_.IncomingCapturedFrame(CreateFrame(3, 360, 180));
  1243. WaitForEncodedFrame(3);
  1244. // App bitrate limits are not set - bitrate limits recommended by encoder
  1245. // should be used.
  1246. EXPECT_EQ(kEncMaxBitrateKbps,
  1247. bitrate_allocator_factory_.codec_config().maxBitrate);
  1248. EXPECT_EQ(kEncMinBitrateKbps,
  1249. bitrate_allocator_factory_.codec_config().minBitrate);
  1250. video_encoder_config.max_bitrate_bps = kAppMaxBitrateKbps * 1000;
  1251. video_encoder_config.simulcast_layers[0].min_bitrate_bps = 0;
  1252. video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
  1253. kMaxPayloadLength);
  1254. video_source_.IncomingCapturedFrame(CreateFrame(4, nullptr));
  1255. WaitForEncodedFrame(4);
  1256. // App limited the max bitrate - bitrate limits recommended by encoder should
  1257. // not be applied.
  1258. EXPECT_EQ(kAppMaxBitrateKbps,
  1259. bitrate_allocator_factory_.codec_config().maxBitrate);
  1260. EXPECT_EQ(kDefaultMinBitrateKbps,
  1261. bitrate_allocator_factory_.codec_config().minBitrate);
  1262. video_encoder_config.max_bitrate_bps = 0;
  1263. video_encoder_config.simulcast_layers[0].min_bitrate_bps =
  1264. kAppMinBitrateKbps * 1000;
  1265. video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
  1266. kMaxPayloadLength);
  1267. video_source_.IncomingCapturedFrame(CreateFrame(5, nullptr));
  1268. WaitForEncodedFrame(5);
  1269. // App limited the min bitrate - bitrate limits recommended by encoder should
  1270. // not be applied.
  1271. EXPECT_EQ(kDefaultMaxBitrateKbps,
  1272. bitrate_allocator_factory_.codec_config().maxBitrate);
  1273. EXPECT_EQ(kAppMinBitrateKbps,
  1274. bitrate_allocator_factory_.codec_config().minBitrate);
  1275. video_encoder_config.max_bitrate_bps = kAppMaxBitrateKbps * 1000;
  1276. video_encoder_config.simulcast_layers[0].min_bitrate_bps =
  1277. kAppMinBitrateKbps * 1000;
  1278. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  1279. kMaxPayloadLength);
  1280. video_source_.IncomingCapturedFrame(CreateFrame(6, nullptr));
  1281. WaitForEncodedFrame(6);
  1282. // App limited both min and max bitrates - bitrate limits recommended by
  1283. // encoder should not be applied.
  1284. EXPECT_EQ(kAppMaxBitrateKbps,
  1285. bitrate_allocator_factory_.codec_config().maxBitrate);
  1286. EXPECT_EQ(kAppMinBitrateKbps,
  1287. bitrate_allocator_factory_.codec_config().minBitrate);
  1288. video_stream_encoder_->Stop();
  1289. }
  1290. TEST_F(VideoStreamEncoderTest,
  1291. EncoderRecommendedMaxAndMinBitratesUsedForGivenResolution) {
  1292. video_stream_encoder_->OnBitrateUpdated(
  1293. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1294. DataRate::bps(kTargetBitrateBps), 0, 0);
  1295. const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_270p(
  1296. 480 * 270, 34 * 1000, 12 * 1000, 1234 * 1000);
  1297. const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits_360p(
  1298. 640 * 360, 43 * 1000, 21 * 1000, 2345 * 1000);
  1299. fake_encoder_.SetResolutionBitrateLimits(
  1300. {encoder_bitrate_limits_270p, encoder_bitrate_limits_360p});
  1301. VideoEncoderConfig video_encoder_config;
  1302. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  1303. video_encoder_config.max_bitrate_bps = 0;
  1304. video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
  1305. kMaxPayloadLength);
  1306. // 270p. The bitrate limits recommended by encoder for 270p should be used.
  1307. video_source_.IncomingCapturedFrame(CreateFrame(1, 480, 270));
  1308. WaitForEncodedFrame(1);
  1309. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
  1310. bitrate_allocator_factory_.codec_config().minBitrate * 1000);
  1311. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
  1312. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1313. // 360p. The bitrate limits recommended by encoder for 360p should be used.
  1314. video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
  1315. WaitForEncodedFrame(2);
  1316. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
  1317. bitrate_allocator_factory_.codec_config().minBitrate * 1000);
  1318. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
  1319. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1320. // Resolution between 270p and 360p. The bitrate limits recommended by
  1321. // encoder for 360p should be used.
  1322. video_source_.IncomingCapturedFrame(
  1323. CreateFrame(3, (640 + 480) / 2, (360 + 270) / 2));
  1324. WaitForEncodedFrame(3);
  1325. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
  1326. bitrate_allocator_factory_.codec_config().minBitrate * 1000);
  1327. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
  1328. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1329. // Resolution higher than 360p. The caps recommended by encoder should be
  1330. // ignored.
  1331. video_source_.IncomingCapturedFrame(CreateFrame(4, 960, 540));
  1332. WaitForEncodedFrame(4);
  1333. EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
  1334. bitrate_allocator_factory_.codec_config().minBitrate * 1000);
  1335. EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
  1336. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1337. EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.min_bitrate_bps),
  1338. bitrate_allocator_factory_.codec_config().minBitrate * 1000);
  1339. EXPECT_NE(static_cast<uint32_t>(encoder_bitrate_limits_360p.max_bitrate_bps),
  1340. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1341. // Resolution lower than 270p. The max bitrate limit recommended by encoder
  1342. // for 270p should be used.
  1343. video_source_.IncomingCapturedFrame(CreateFrame(5, 320, 180));
  1344. WaitForEncodedFrame(5);
  1345. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.min_bitrate_bps),
  1346. bitrate_allocator_factory_.codec_config().minBitrate * 1000);
  1347. EXPECT_EQ(static_cast<uint32_t>(encoder_bitrate_limits_270p.max_bitrate_bps),
  1348. bitrate_allocator_factory_.codec_config().maxBitrate * 1000);
  1349. video_stream_encoder_->Stop();
  1350. }
  1351. TEST_F(VideoStreamEncoderTest, EncoderRecommendedMaxBitrateCapsTargetBitrate) {
  1352. video_stream_encoder_->OnBitrateUpdated(
  1353. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1354. DataRate::bps(kTargetBitrateBps), 0, 0);
  1355. VideoEncoderConfig video_encoder_config;
  1356. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  1357. video_encoder_config.max_bitrate_bps = 0;
  1358. video_stream_encoder_->ConfigureEncoder(video_encoder_config.Copy(),
  1359. kMaxPayloadLength);
  1360. // Encode 720p frame to get the default encoder target bitrate.
  1361. video_source_.IncomingCapturedFrame(CreateFrame(1, 1280, 720));
  1362. WaitForEncodedFrame(1);
  1363. const uint32_t kDefaultTargetBitrateFor720pKbps =
  1364. bitrate_allocator_factory_.codec_config()
  1365. .simulcastStream[0]
  1366. .targetBitrate;
  1367. // Set the max recommended encoder bitrate to something lower than the default
  1368. // target bitrate.
  1369. const VideoEncoder::ResolutionBitrateLimits encoder_bitrate_limits(
  1370. 1280 * 720, 10 * 1000, 10 * 1000,
  1371. kDefaultTargetBitrateFor720pKbps / 2 * 1000);
  1372. fake_encoder_.SetResolutionBitrateLimits({encoder_bitrate_limits});
  1373. // Change resolution to trigger encoder reinitialization.
  1374. video_source_.IncomingCapturedFrame(CreateFrame(2, 640, 360));
  1375. WaitForEncodedFrame(2);
  1376. video_source_.IncomingCapturedFrame(CreateFrame(3, 1280, 720));
  1377. WaitForEncodedFrame(3);
  1378. // Ensure the target bitrate is capped by the max bitrate.
  1379. EXPECT_EQ(bitrate_allocator_factory_.codec_config().maxBitrate * 1000,
  1380. static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
  1381. EXPECT_EQ(bitrate_allocator_factory_.codec_config()
  1382. .simulcastStream[0]
  1383. .targetBitrate *
  1384. 1000,
  1385. static_cast<uint32_t>(encoder_bitrate_limits.max_bitrate_bps));
  1386. video_stream_encoder_->Stop();
  1387. }
  1388. TEST_F(VideoStreamEncoderTest, SwitchSourceDeregisterEncoderAsSink) {
  1389. EXPECT_TRUE(video_source_.has_sinks());
  1390. test::FrameForwarder new_video_source;
  1391. video_stream_encoder_->SetSource(
  1392. &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  1393. EXPECT_FALSE(video_source_.has_sinks());
  1394. EXPECT_TRUE(new_video_source.has_sinks());
  1395. video_stream_encoder_->Stop();
  1396. }
  1397. TEST_F(VideoStreamEncoderTest, SinkWantsRotationApplied) {
  1398. EXPECT_FALSE(video_source_.sink_wants().rotation_applied);
  1399. video_stream_encoder_->SetSink(&sink_, true /*rotation_applied*/);
  1400. EXPECT_TRUE(video_source_.sink_wants().rotation_applied);
  1401. video_stream_encoder_->Stop();
  1402. }
  1403. TEST_F(VideoStreamEncoderTest, TestCpuDowngrades_BalancedMode) {
  1404. const int kFramerateFps = 30;
  1405. const int kWidth = 1280;
  1406. const int kHeight = 720;
  1407. // We rely on the automatic resolution adaptation, but we handle framerate
  1408. // adaptation manually by mocking the stats proxy.
  1409. video_source_.set_adaptation_enabled(true);
  1410. // Enable BALANCED preference, no initial limitation.
  1411. video_stream_encoder_->OnBitrateUpdated(
  1412. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1413. DataRate::bps(kTargetBitrateBps), 0, 0);
  1414. video_stream_encoder_->SetSource(&video_source_,
  1415. webrtc::DegradationPreference::BALANCED);
  1416. VerifyNoLimitation(video_source_.sink_wants());
  1417. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  1418. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  1419. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1420. // Adapt down as far as possible.
  1421. rtc::VideoSinkWants last_wants;
  1422. int64_t t = 1;
  1423. int loop_count = 0;
  1424. do {
  1425. ++loop_count;
  1426. last_wants = video_source_.sink_wants();
  1427. // Simulate the framerate we've been asked to adapt to.
  1428. const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
  1429. const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
  1430. VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
  1431. mock_stats.input_frame_rate = fps;
  1432. stats_proxy_->SetMockStats(mock_stats);
  1433. video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
  1434. sink_.WaitForEncodedFrame(t);
  1435. t += frame_interval_ms;
  1436. video_stream_encoder_->TriggerCpuOveruse();
  1437. VerifyBalancedModeFpsRange(
  1438. video_source_.sink_wants(),
  1439. *video_source_.last_sent_width() * *video_source_.last_sent_height());
  1440. } while (video_source_.sink_wants().max_pixel_count <
  1441. last_wants.max_pixel_count ||
  1442. video_source_.sink_wants().max_framerate_fps <
  1443. last_wants.max_framerate_fps);
  1444. // Verify that we've adapted all the way down.
  1445. stats_proxy_->ResetMockStats();
  1446. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  1447. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
  1448. EXPECT_EQ(loop_count - 1,
  1449. stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1450. EXPECT_EQ(kMinPixelsPerFrame, *video_source_.last_sent_width() *
  1451. *video_source_.last_sent_height());
  1452. EXPECT_EQ(kMinBalancedFramerateFps,
  1453. video_source_.sink_wants().max_framerate_fps);
  1454. // Adapt back up the same number of times we adapted down.
  1455. for (int i = 0; i < loop_count - 1; ++i) {
  1456. last_wants = video_source_.sink_wants();
  1457. // Simulate the framerate we've been asked to adapt to.
  1458. const int fps = std::min(kFramerateFps, last_wants.max_framerate_fps);
  1459. const int frame_interval_ms = rtc::kNumMillisecsPerSec / fps;
  1460. VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
  1461. mock_stats.input_frame_rate = fps;
  1462. stats_proxy_->SetMockStats(mock_stats);
  1463. video_source_.IncomingCapturedFrame(CreateFrame(t, kWidth, kHeight));
  1464. sink_.WaitForEncodedFrame(t);
  1465. t += frame_interval_ms;
  1466. video_stream_encoder_->TriggerCpuNormalUsage();
  1467. VerifyBalancedModeFpsRange(
  1468. video_source_.sink_wants(),
  1469. *video_source_.last_sent_width() * *video_source_.last_sent_height());
  1470. EXPECT_TRUE(video_source_.sink_wants().max_pixel_count >
  1471. last_wants.max_pixel_count ||
  1472. video_source_.sink_wants().max_framerate_fps >
  1473. last_wants.max_framerate_fps);
  1474. }
  1475. VerifyFpsMaxResolutionMax(video_source_.sink_wants());
  1476. stats_proxy_->ResetMockStats();
  1477. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  1478. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  1479. EXPECT_EQ((loop_count - 1) * 2,
  1480. stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1481. video_stream_encoder_->Stop();
  1482. }
  1483. TEST_F(VideoStreamEncoderTest, SinkWantsStoredByDegradationPreference) {
  1484. video_stream_encoder_->OnBitrateUpdated(
  1485. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1486. DataRate::bps(kTargetBitrateBps), 0, 0);
  1487. VerifyNoLimitation(video_source_.sink_wants());
  1488. const int kFrameWidth = 1280;
  1489. const int kFrameHeight = 720;
  1490. int64_t frame_timestamp = 1;
  1491. video_source_.IncomingCapturedFrame(
  1492. CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
  1493. WaitForEncodedFrame(frame_timestamp);
  1494. frame_timestamp += kFrameIntervalMs;
  1495. // Trigger CPU overuse.
  1496. video_stream_encoder_->TriggerCpuOveruse();
  1497. video_source_.IncomingCapturedFrame(
  1498. CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
  1499. WaitForEncodedFrame(frame_timestamp);
  1500. frame_timestamp += kFrameIntervalMs;
  1501. // Default degradation preference is maintain-framerate, so will lower max
  1502. // wanted resolution.
  1503. EXPECT_FALSE(video_source_.sink_wants().target_pixel_count);
  1504. EXPECT_LT(video_source_.sink_wants().max_pixel_count,
  1505. kFrameWidth * kFrameHeight);
  1506. EXPECT_EQ(kDefaultFramerate, video_source_.sink_wants().max_framerate_fps);
  1507. // Set new source, switch to maintain-resolution.
  1508. test::FrameForwarder new_video_source;
  1509. video_stream_encoder_->SetSource(
  1510. &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  1511. // Initially no degradation registered.
  1512. VerifyFpsMaxResolutionMax(new_video_source.sink_wants());
  1513. // Force an input frame rate to be available, or the adaptation call won't
  1514. // know what framerate to adapt form.
  1515. const int kInputFps = 30;
  1516. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  1517. stats.input_frame_rate = kInputFps;
  1518. stats_proxy_->SetMockStats(stats);
  1519. video_stream_encoder_->TriggerCpuOveruse();
  1520. new_video_source.IncomingCapturedFrame(
  1521. CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
  1522. WaitForEncodedFrame(frame_timestamp);
  1523. frame_timestamp += kFrameIntervalMs;
  1524. // Some framerate constraint should be set.
  1525. EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
  1526. EXPECT_EQ(std::numeric_limits<int>::max(),
  1527. new_video_source.sink_wants().max_pixel_count);
  1528. EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
  1529. // Turn off degradation completely.
  1530. video_stream_encoder_->SetSource(&new_video_source,
  1531. webrtc::DegradationPreference::DISABLED);
  1532. VerifyFpsMaxResolutionMax(new_video_source.sink_wants());
  1533. video_stream_encoder_->TriggerCpuOveruse();
  1534. new_video_source.IncomingCapturedFrame(
  1535. CreateFrame(frame_timestamp, kFrameWidth, kFrameHeight));
  1536. WaitForEncodedFrame(frame_timestamp);
  1537. frame_timestamp += kFrameIntervalMs;
  1538. // Still no degradation.
  1539. VerifyFpsMaxResolutionMax(new_video_source.sink_wants());
  1540. // Calling SetSource with resolution scaling enabled apply the old SinkWants.
  1541. video_stream_encoder_->SetSource(
  1542. &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  1543. EXPECT_LT(new_video_source.sink_wants().max_pixel_count,
  1544. kFrameWidth * kFrameHeight);
  1545. EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
  1546. EXPECT_EQ(kDefaultFramerate, new_video_source.sink_wants().max_framerate_fps);
  1547. // Calling SetSource with framerate scaling enabled apply the old SinkWants.
  1548. video_stream_encoder_->SetSource(
  1549. &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  1550. EXPECT_FALSE(new_video_source.sink_wants().target_pixel_count);
  1551. EXPECT_EQ(std::numeric_limits<int>::max(),
  1552. new_video_source.sink_wants().max_pixel_count);
  1553. EXPECT_LT(new_video_source.sink_wants().max_framerate_fps, kInputFps);
  1554. video_stream_encoder_->Stop();
  1555. }
  1556. TEST_F(VideoStreamEncoderTest, StatsTracksQualityAdaptationStats) {
  1557. video_stream_encoder_->OnBitrateUpdated(
  1558. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1559. DataRate::bps(kTargetBitrateBps), 0, 0);
  1560. const int kWidth = 1280;
  1561. const int kHeight = 720;
  1562. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  1563. WaitForEncodedFrame(1);
  1564. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  1565. EXPECT_FALSE(stats.bw_limited_resolution);
  1566. EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
  1567. // Trigger adapt down.
  1568. video_stream_encoder_->TriggerQualityLow();
  1569. video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  1570. WaitForEncodedFrame(2);
  1571. stats = stats_proxy_->GetStats();
  1572. EXPECT_TRUE(stats.bw_limited_resolution);
  1573. EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
  1574. // Trigger adapt up.
  1575. video_stream_encoder_->TriggerQualityHigh();
  1576. video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
  1577. WaitForEncodedFrame(3);
  1578. stats = stats_proxy_->GetStats();
  1579. EXPECT_FALSE(stats.bw_limited_resolution);
  1580. EXPECT_EQ(2, stats.number_of_quality_adapt_changes);
  1581. EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
  1582. video_stream_encoder_->Stop();
  1583. }
  1584. TEST_F(VideoStreamEncoderTest, StatsTracksCpuAdaptationStats) {
  1585. video_stream_encoder_->OnBitrateUpdated(
  1586. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1587. DataRate::bps(kTargetBitrateBps), 0, 0);
  1588. const int kWidth = 1280;
  1589. const int kHeight = 720;
  1590. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  1591. WaitForEncodedFrame(1);
  1592. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  1593. EXPECT_FALSE(stats.cpu_limited_resolution);
  1594. EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
  1595. // Trigger CPU overuse.
  1596. video_stream_encoder_->TriggerCpuOveruse();
  1597. video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  1598. WaitForEncodedFrame(2);
  1599. stats = stats_proxy_->GetStats();
  1600. EXPECT_TRUE(stats.cpu_limited_resolution);
  1601. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1602. // Trigger CPU normal use.
  1603. video_stream_encoder_->TriggerCpuNormalUsage();
  1604. video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
  1605. WaitForEncodedFrame(3);
  1606. stats = stats_proxy_->GetStats();
  1607. EXPECT_FALSE(stats.cpu_limited_resolution);
  1608. EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
  1609. EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
  1610. video_stream_encoder_->Stop();
  1611. }
  1612. TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsCpuAdaptation) {
  1613. video_stream_encoder_->OnBitrateUpdated(
  1614. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1615. DataRate::bps(kTargetBitrateBps), 0, 0);
  1616. const int kWidth = 1280;
  1617. const int kHeight = 720;
  1618. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  1619. WaitForEncodedFrame(1);
  1620. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  1621. EXPECT_FALSE(stats.bw_limited_resolution);
  1622. EXPECT_FALSE(stats.cpu_limited_resolution);
  1623. EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
  1624. // Trigger CPU overuse.
  1625. video_stream_encoder_->TriggerCpuOveruse();
  1626. video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  1627. WaitForEncodedFrame(2);
  1628. stats = stats_proxy_->GetStats();
  1629. EXPECT_FALSE(stats.bw_limited_resolution);
  1630. EXPECT_TRUE(stats.cpu_limited_resolution);
  1631. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1632. // Set new source with adaptation still enabled.
  1633. test::FrameForwarder new_video_source;
  1634. video_stream_encoder_->SetSource(
  1635. &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  1636. new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
  1637. WaitForEncodedFrame(3);
  1638. stats = stats_proxy_->GetStats();
  1639. EXPECT_FALSE(stats.bw_limited_resolution);
  1640. EXPECT_TRUE(stats.cpu_limited_resolution);
  1641. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1642. // Set adaptation disabled.
  1643. video_stream_encoder_->SetSource(&new_video_source,
  1644. webrtc::DegradationPreference::DISABLED);
  1645. new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
  1646. WaitForEncodedFrame(4);
  1647. stats = stats_proxy_->GetStats();
  1648. EXPECT_FALSE(stats.bw_limited_resolution);
  1649. EXPECT_FALSE(stats.cpu_limited_resolution);
  1650. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1651. // Set adaptation back to enabled.
  1652. video_stream_encoder_->SetSource(
  1653. &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  1654. new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
  1655. WaitForEncodedFrame(5);
  1656. stats = stats_proxy_->GetStats();
  1657. EXPECT_FALSE(stats.bw_limited_resolution);
  1658. EXPECT_TRUE(stats.cpu_limited_resolution);
  1659. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1660. // Trigger CPU normal use.
  1661. video_stream_encoder_->TriggerCpuNormalUsage();
  1662. new_video_source.IncomingCapturedFrame(CreateFrame(6, kWidth, kHeight));
  1663. WaitForEncodedFrame(6);
  1664. stats = stats_proxy_->GetStats();
  1665. EXPECT_FALSE(stats.bw_limited_resolution);
  1666. EXPECT_FALSE(stats.cpu_limited_resolution);
  1667. EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
  1668. EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
  1669. video_stream_encoder_->Stop();
  1670. }
  1671. TEST_F(VideoStreamEncoderTest, SwitchingSourceKeepsQualityAdaptation) {
  1672. video_stream_encoder_->OnBitrateUpdated(
  1673. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1674. DataRate::bps(kTargetBitrateBps), 0, 0);
  1675. const int kWidth = 1280;
  1676. const int kHeight = 720;
  1677. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  1678. WaitForEncodedFrame(1);
  1679. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  1680. EXPECT_FALSE(stats.bw_limited_resolution);
  1681. EXPECT_FALSE(stats.bw_limited_framerate);
  1682. EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
  1683. // Set new source with adaptation still enabled.
  1684. test::FrameForwarder new_video_source;
  1685. video_stream_encoder_->SetSource(&new_video_source,
  1686. webrtc::DegradationPreference::BALANCED);
  1687. new_video_source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  1688. WaitForEncodedFrame(2);
  1689. stats = stats_proxy_->GetStats();
  1690. EXPECT_FALSE(stats.bw_limited_resolution);
  1691. EXPECT_FALSE(stats.bw_limited_framerate);
  1692. EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
  1693. // Trigger adapt down.
  1694. video_stream_encoder_->TriggerQualityLow();
  1695. new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
  1696. WaitForEncodedFrame(3);
  1697. stats = stats_proxy_->GetStats();
  1698. EXPECT_TRUE(stats.bw_limited_resolution);
  1699. EXPECT_FALSE(stats.bw_limited_framerate);
  1700. EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
  1701. // Set new source with adaptation still enabled.
  1702. video_stream_encoder_->SetSource(&new_video_source,
  1703. webrtc::DegradationPreference::BALANCED);
  1704. new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
  1705. WaitForEncodedFrame(4);
  1706. stats = stats_proxy_->GetStats();
  1707. EXPECT_TRUE(stats.bw_limited_resolution);
  1708. EXPECT_FALSE(stats.bw_limited_framerate);
  1709. EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
  1710. // Disable resolution scaling.
  1711. video_stream_encoder_->SetSource(
  1712. &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  1713. new_video_source.IncomingCapturedFrame(CreateFrame(5, kWidth, kHeight));
  1714. WaitForEncodedFrame(5);
  1715. stats = stats_proxy_->GetStats();
  1716. EXPECT_FALSE(stats.bw_limited_resolution);
  1717. EXPECT_FALSE(stats.bw_limited_framerate);
  1718. EXPECT_EQ(1, stats.number_of_quality_adapt_changes);
  1719. EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
  1720. video_stream_encoder_->Stop();
  1721. }
  1722. TEST_F(VideoStreamEncoderTest,
  1723. QualityAdaptationStatsAreResetWhenScalerIsDisabled) {
  1724. video_stream_encoder_->OnBitrateUpdated(
  1725. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1726. DataRate::bps(kTargetBitrateBps), 0, 0);
  1727. const int kWidth = 1280;
  1728. const int kHeight = 720;
  1729. int64_t timestamp_ms = kFrameIntervalMs;
  1730. video_source_.set_adaptation_enabled(true);
  1731. video_source_.IncomingCapturedFrame(
  1732. CreateFrame(timestamp_ms, kWidth, kHeight));
  1733. WaitForEncodedFrame(timestamp_ms);
  1734. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  1735. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  1736. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1737. // Trigger adapt down.
  1738. video_stream_encoder_->TriggerQualityLow();
  1739. timestamp_ms += kFrameIntervalMs;
  1740. video_source_.IncomingCapturedFrame(
  1741. CreateFrame(timestamp_ms, kWidth, kHeight));
  1742. WaitForEncodedFrame(timestamp_ms);
  1743. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  1744. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  1745. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1746. // Trigger overuse.
  1747. video_stream_encoder_->TriggerCpuOveruse();
  1748. timestamp_ms += kFrameIntervalMs;
  1749. video_source_.IncomingCapturedFrame(
  1750. CreateFrame(timestamp_ms, kWidth, kHeight));
  1751. WaitForEncodedFrame(timestamp_ms);
  1752. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  1753. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  1754. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1755. // Leave source unchanged, but disable quality scaler.
  1756. fake_encoder_.SetQualityScaling(false);
  1757. VideoEncoderConfig video_encoder_config;
  1758. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  1759. // Make format different, to force recreation of encoder.
  1760. video_encoder_config.video_format.parameters["foo"] = "foo";
  1761. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  1762. kMaxPayloadLength);
  1763. timestamp_ms += kFrameIntervalMs;
  1764. video_source_.IncomingCapturedFrame(
  1765. CreateFrame(timestamp_ms, kWidth, kHeight));
  1766. WaitForEncodedFrame(timestamp_ms);
  1767. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  1768. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  1769. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1770. video_stream_encoder_->Stop();
  1771. }
  1772. TEST_F(VideoStreamEncoderTest,
  1773. StatsTracksCpuAdaptationStatsWhenSwitchingSource) {
  1774. video_stream_encoder_->OnBitrateUpdated(
  1775. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1776. DataRate::bps(kTargetBitrateBps), 0, 0);
  1777. const int kWidth = 1280;
  1778. const int kHeight = 720;
  1779. int sequence = 1;
  1780. video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
  1781. WaitForEncodedFrame(sequence++);
  1782. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  1783. EXPECT_FALSE(stats.cpu_limited_resolution);
  1784. EXPECT_FALSE(stats.cpu_limited_framerate);
  1785. EXPECT_EQ(0, stats.number_of_cpu_adapt_changes);
  1786. // Trigger CPU overuse, should now adapt down.
  1787. video_stream_encoder_->TriggerCpuOveruse();
  1788. video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
  1789. WaitForEncodedFrame(sequence++);
  1790. stats = stats_proxy_->GetStats();
  1791. EXPECT_TRUE(stats.cpu_limited_resolution);
  1792. EXPECT_FALSE(stats.cpu_limited_framerate);
  1793. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1794. // Set new source with adaptation still enabled.
  1795. test::FrameForwarder new_video_source;
  1796. video_stream_encoder_->SetSource(
  1797. &new_video_source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  1798. new_video_source.IncomingCapturedFrame(
  1799. CreateFrame(sequence, kWidth, kHeight));
  1800. WaitForEncodedFrame(sequence++);
  1801. stats = stats_proxy_->GetStats();
  1802. EXPECT_TRUE(stats.cpu_limited_resolution);
  1803. EXPECT_FALSE(stats.cpu_limited_framerate);
  1804. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1805. // Set cpu adaptation by frame dropping.
  1806. video_stream_encoder_->SetSource(
  1807. &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  1808. new_video_source.IncomingCapturedFrame(
  1809. CreateFrame(sequence, kWidth, kHeight));
  1810. WaitForEncodedFrame(sequence++);
  1811. stats = stats_proxy_->GetStats();
  1812. // Not adapted at first.
  1813. EXPECT_FALSE(stats.cpu_limited_resolution);
  1814. EXPECT_FALSE(stats.cpu_limited_framerate);
  1815. EXPECT_EQ(1, stats.number_of_cpu_adapt_changes);
  1816. // Force an input frame rate to be available, or the adaptation call won't
  1817. // know what framerate to adapt from.
  1818. VideoSendStream::Stats mock_stats = stats_proxy_->GetStats();
  1819. mock_stats.input_frame_rate = 30;
  1820. stats_proxy_->SetMockStats(mock_stats);
  1821. video_stream_encoder_->TriggerCpuOveruse();
  1822. stats_proxy_->ResetMockStats();
  1823. new_video_source.IncomingCapturedFrame(
  1824. CreateFrame(sequence, kWidth, kHeight));
  1825. WaitForEncodedFrame(sequence++);
  1826. // Framerate now adapted.
  1827. stats = stats_proxy_->GetStats();
  1828. EXPECT_FALSE(stats.cpu_limited_resolution);
  1829. EXPECT_TRUE(stats.cpu_limited_framerate);
  1830. EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
  1831. // Disable CPU adaptation.
  1832. video_stream_encoder_->SetSource(&new_video_source,
  1833. webrtc::DegradationPreference::DISABLED);
  1834. new_video_source.IncomingCapturedFrame(
  1835. CreateFrame(sequence, kWidth, kHeight));
  1836. WaitForEncodedFrame(sequence++);
  1837. stats = stats_proxy_->GetStats();
  1838. EXPECT_FALSE(stats.cpu_limited_resolution);
  1839. EXPECT_FALSE(stats.cpu_limited_framerate);
  1840. EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
  1841. // Try to trigger overuse. Should not succeed.
  1842. stats_proxy_->SetMockStats(mock_stats);
  1843. video_stream_encoder_->TriggerCpuOveruse();
  1844. stats_proxy_->ResetMockStats();
  1845. stats = stats_proxy_->GetStats();
  1846. EXPECT_FALSE(stats.cpu_limited_resolution);
  1847. EXPECT_FALSE(stats.cpu_limited_framerate);
  1848. EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
  1849. // Switch back the source with resolution adaptation enabled.
  1850. video_stream_encoder_->SetSource(
  1851. &video_source_, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  1852. video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
  1853. WaitForEncodedFrame(sequence++);
  1854. stats = stats_proxy_->GetStats();
  1855. EXPECT_TRUE(stats.cpu_limited_resolution);
  1856. EXPECT_FALSE(stats.cpu_limited_framerate);
  1857. EXPECT_EQ(2, stats.number_of_cpu_adapt_changes);
  1858. // Trigger CPU normal usage.
  1859. video_stream_encoder_->TriggerCpuNormalUsage();
  1860. video_source_.IncomingCapturedFrame(CreateFrame(sequence, kWidth, kHeight));
  1861. WaitForEncodedFrame(sequence++);
  1862. stats = stats_proxy_->GetStats();
  1863. EXPECT_FALSE(stats.cpu_limited_resolution);
  1864. EXPECT_FALSE(stats.cpu_limited_framerate);
  1865. EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
  1866. // Back to the source with adaptation off, set it back to maintain-resolution.
  1867. video_stream_encoder_->SetSource(
  1868. &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  1869. new_video_source.IncomingCapturedFrame(
  1870. CreateFrame(sequence, kWidth, kHeight));
  1871. WaitForEncodedFrame(sequence++);
  1872. stats = stats_proxy_->GetStats();
  1873. // Disabled, since we previously switched the source to disabled.
  1874. EXPECT_FALSE(stats.cpu_limited_resolution);
  1875. EXPECT_TRUE(stats.cpu_limited_framerate);
  1876. EXPECT_EQ(3, stats.number_of_cpu_adapt_changes);
  1877. // Trigger CPU normal usage.
  1878. video_stream_encoder_->TriggerCpuNormalUsage();
  1879. new_video_source.IncomingCapturedFrame(
  1880. CreateFrame(sequence, kWidth, kHeight));
  1881. WaitForEncodedFrame(sequence++);
  1882. stats = stats_proxy_->GetStats();
  1883. EXPECT_FALSE(stats.cpu_limited_resolution);
  1884. EXPECT_FALSE(stats.cpu_limited_framerate);
  1885. EXPECT_EQ(4, stats.number_of_cpu_adapt_changes);
  1886. EXPECT_EQ(0, stats.number_of_quality_adapt_changes);
  1887. video_stream_encoder_->Stop();
  1888. }
  1889. TEST_F(VideoStreamEncoderTest,
  1890. ScalingUpAndDownDoesNothingWithMaintainResolution) {
  1891. const int kWidth = 1280;
  1892. const int kHeight = 720;
  1893. video_stream_encoder_->OnBitrateUpdated(
  1894. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1895. DataRate::bps(kTargetBitrateBps), 0, 0);
  1896. // Expect no scaling to begin with.
  1897. VerifyNoLimitation(video_source_.sink_wants());
  1898. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  1899. WaitForEncodedFrame(1);
  1900. // Trigger scale down.
  1901. video_stream_encoder_->TriggerQualityLow();
  1902. video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  1903. WaitForEncodedFrame(2);
  1904. // Expect a scale down.
  1905. EXPECT_TRUE(video_source_.sink_wants().max_pixel_count);
  1906. EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
  1907. // Set resolution scaling disabled.
  1908. test::FrameForwarder new_video_source;
  1909. video_stream_encoder_->SetSource(
  1910. &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  1911. // Trigger scale down.
  1912. video_stream_encoder_->TriggerQualityLow();
  1913. new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
  1914. WaitForEncodedFrame(3);
  1915. // Expect no scaling.
  1916. EXPECT_EQ(std::numeric_limits<int>::max(),
  1917. new_video_source.sink_wants().max_pixel_count);
  1918. // Trigger scale up.
  1919. video_stream_encoder_->TriggerQualityHigh();
  1920. new_video_source.IncomingCapturedFrame(CreateFrame(4, kWidth, kHeight));
  1921. WaitForEncodedFrame(4);
  1922. // Expect nothing to change, still no scaling.
  1923. EXPECT_EQ(std::numeric_limits<int>::max(),
  1924. new_video_source.sink_wants().max_pixel_count);
  1925. video_stream_encoder_->Stop();
  1926. }
  1927. TEST_F(VideoStreamEncoderTest,
  1928. SkipsSameAdaptDownRequest_MaintainFramerateMode) {
  1929. const int kWidth = 1280;
  1930. const int kHeight = 720;
  1931. video_stream_encoder_->OnBitrateUpdated(
  1932. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1933. DataRate::bps(kTargetBitrateBps), 0, 0);
  1934. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  1935. test::FrameForwarder source;
  1936. video_stream_encoder_->SetSource(
  1937. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  1938. source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  1939. WaitForEncodedFrame(1);
  1940. VerifyFpsMaxResolutionMax(source.sink_wants());
  1941. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  1942. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1943. // Trigger adapt down, expect scaled down resolution.
  1944. video_stream_encoder_->TriggerCpuOveruse();
  1945. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  1946. const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
  1947. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  1948. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1949. // Trigger adapt down for same input resolution, expect no change.
  1950. video_stream_encoder_->TriggerCpuOveruse();
  1951. EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
  1952. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  1953. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  1954. video_stream_encoder_->Stop();
  1955. }
  1956. TEST_F(VideoStreamEncoderTest, SkipsSameOrLargerAdaptDownRequest_BalancedMode) {
  1957. const int kWidth = 1280;
  1958. const int kHeight = 720;
  1959. video_stream_encoder_->OnBitrateUpdated(
  1960. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1961. DataRate::bps(kTargetBitrateBps), 0, 0);
  1962. // Enable BALANCED preference, no initial limitation.
  1963. test::FrameForwarder source;
  1964. video_stream_encoder_->SetSource(&source,
  1965. webrtc::DegradationPreference::BALANCED);
  1966. source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  1967. sink_.WaitForEncodedFrame(1);
  1968. VerifyFpsMaxResolutionMax(source.sink_wants());
  1969. // Trigger adapt down, expect scaled down resolution.
  1970. video_stream_encoder_->TriggerQualityLow();
  1971. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  1972. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  1973. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  1974. const int kLastMaxPixelCount = source.sink_wants().max_pixel_count;
  1975. // Trigger adapt down for same input resolution, expect no change.
  1976. source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  1977. sink_.WaitForEncodedFrame(2);
  1978. video_stream_encoder_->TriggerQualityLow();
  1979. EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
  1980. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  1981. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  1982. // Trigger adapt down for larger input resolution, expect no change.
  1983. source.IncomingCapturedFrame(CreateFrame(3, kWidth + 1, kHeight + 1));
  1984. sink_.WaitForEncodedFrame(3);
  1985. video_stream_encoder_->TriggerQualityLow();
  1986. EXPECT_EQ(kLastMaxPixelCount, source.sink_wants().max_pixel_count);
  1987. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  1988. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  1989. video_stream_encoder_->Stop();
  1990. }
  1991. TEST_F(VideoStreamEncoderTest,
  1992. NoChangeForInitialNormalUsage_MaintainFramerateMode) {
  1993. const int kWidth = 1280;
  1994. const int kHeight = 720;
  1995. video_stream_encoder_->OnBitrateUpdated(
  1996. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  1997. DataRate::bps(kTargetBitrateBps), 0, 0);
  1998. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  1999. test::FrameForwarder source;
  2000. video_stream_encoder_->SetSource(
  2001. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  2002. source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  2003. WaitForEncodedFrame(kWidth, kHeight);
  2004. VerifyFpsMaxResolutionMax(source.sink_wants());
  2005. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2006. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2007. // Trigger adapt up, expect no change.
  2008. video_stream_encoder_->TriggerCpuNormalUsage();
  2009. VerifyFpsMaxResolutionMax(source.sink_wants());
  2010. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2011. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2012. video_stream_encoder_->Stop();
  2013. }
  2014. TEST_F(VideoStreamEncoderTest,
  2015. NoChangeForInitialNormalUsage_MaintainResolutionMode) {
  2016. const int kWidth = 1280;
  2017. const int kHeight = 720;
  2018. video_stream_encoder_->OnBitrateUpdated(
  2019. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2020. DataRate::bps(kTargetBitrateBps), 0, 0);
  2021. // Enable MAINTAIN_RESOLUTION preference, no initial limitation.
  2022. test::FrameForwarder source;
  2023. video_stream_encoder_->SetSource(
  2024. &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  2025. source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  2026. WaitForEncodedFrame(kWidth, kHeight);
  2027. VerifyFpsMaxResolutionMax(source.sink_wants());
  2028. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  2029. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2030. // Trigger adapt up, expect no change.
  2031. video_stream_encoder_->TriggerCpuNormalUsage();
  2032. VerifyFpsMaxResolutionMax(source.sink_wants());
  2033. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  2034. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2035. video_stream_encoder_->Stop();
  2036. }
  2037. TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_BalancedMode) {
  2038. const int kWidth = 1280;
  2039. const int kHeight = 720;
  2040. video_stream_encoder_->OnBitrateUpdated(
  2041. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2042. DataRate::bps(kTargetBitrateBps), 0, 0);
  2043. // Enable BALANCED preference, no initial limitation.
  2044. test::FrameForwarder source;
  2045. video_stream_encoder_->SetSource(&source,
  2046. webrtc::DegradationPreference::BALANCED);
  2047. source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  2048. sink_.WaitForEncodedFrame(kWidth, kHeight);
  2049. VerifyFpsMaxResolutionMax(source.sink_wants());
  2050. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2051. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  2052. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2053. // Trigger adapt up, expect no change.
  2054. video_stream_encoder_->TriggerQualityHigh();
  2055. VerifyFpsMaxResolutionMax(source.sink_wants());
  2056. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2057. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  2058. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2059. video_stream_encoder_->Stop();
  2060. }
  2061. TEST_F(VideoStreamEncoderTest, NoChangeForInitialNormalUsage_DisabledMode) {
  2062. const int kWidth = 1280;
  2063. const int kHeight = 720;
  2064. video_stream_encoder_->OnBitrateUpdated(
  2065. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2066. DataRate::bps(kTargetBitrateBps), 0, 0);
  2067. // Enable DISABLED preference, no initial limitation.
  2068. test::FrameForwarder source;
  2069. video_stream_encoder_->SetSource(&source,
  2070. webrtc::DegradationPreference::DISABLED);
  2071. source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  2072. sink_.WaitForEncodedFrame(kWidth, kHeight);
  2073. VerifyFpsMaxResolutionMax(source.sink_wants());
  2074. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2075. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  2076. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2077. // Trigger adapt up, expect no change.
  2078. video_stream_encoder_->TriggerQualityHigh();
  2079. VerifyFpsMaxResolutionMax(source.sink_wants());
  2080. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2081. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  2082. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2083. video_stream_encoder_->Stop();
  2084. }
  2085. TEST_F(VideoStreamEncoderTest,
  2086. AdaptsResolutionForLowQuality_MaintainFramerateMode) {
  2087. const int kWidth = 1280;
  2088. const int kHeight = 720;
  2089. video_stream_encoder_->OnBitrateUpdated(
  2090. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2091. DataRate::bps(kTargetBitrateBps), 0, 0);
  2092. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  2093. AdaptingFrameForwarder source;
  2094. source.set_adaptation_enabled(true);
  2095. video_stream_encoder_->SetSource(
  2096. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  2097. source.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  2098. WaitForEncodedFrame(1);
  2099. VerifyFpsMaxResolutionMax(source.sink_wants());
  2100. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2101. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2102. // Trigger adapt down, expect scaled down resolution.
  2103. video_stream_encoder_->TriggerQualityLow();
  2104. source.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  2105. WaitForEncodedFrame(2);
  2106. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  2107. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2108. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2109. // Trigger adapt up, expect no restriction.
  2110. video_stream_encoder_->TriggerQualityHigh();
  2111. VerifyFpsMaxResolutionMax(source.sink_wants());
  2112. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2113. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2114. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2115. video_stream_encoder_->Stop();
  2116. }
  2117. TEST_F(VideoStreamEncoderTest,
  2118. AdaptsFramerateForLowQuality_MaintainResolutionMode) {
  2119. const int kWidth = 1280;
  2120. const int kHeight = 720;
  2121. const int kInputFps = 30;
  2122. video_stream_encoder_->OnBitrateUpdated(
  2123. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2124. DataRate::bps(kTargetBitrateBps), 0, 0);
  2125. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  2126. stats.input_frame_rate = kInputFps;
  2127. stats_proxy_->SetMockStats(stats);
  2128. // Expect no scaling to begin with (preference: MAINTAIN_FRAMERATE).
  2129. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  2130. sink_.WaitForEncodedFrame(1);
  2131. VerifyFpsMaxResolutionMax(video_source_.sink_wants());
  2132. // Trigger adapt down, expect scaled down resolution.
  2133. video_stream_encoder_->TriggerQualityLow();
  2134. video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  2135. sink_.WaitForEncodedFrame(2);
  2136. VerifyFpsMaxResolutionLt(video_source_.sink_wants(), kWidth * kHeight);
  2137. // Enable MAINTAIN_RESOLUTION preference.
  2138. test::FrameForwarder new_video_source;
  2139. video_stream_encoder_->SetSource(
  2140. &new_video_source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  2141. VerifyFpsMaxResolutionMax(new_video_source.sink_wants());
  2142. // Trigger adapt down, expect reduced framerate.
  2143. video_stream_encoder_->TriggerQualityLow();
  2144. new_video_source.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
  2145. sink_.WaitForEncodedFrame(3);
  2146. VerifyFpsLtResolutionMax(new_video_source.sink_wants(), kInputFps);
  2147. // Trigger adapt up, expect no restriction.
  2148. video_stream_encoder_->TriggerQualityHigh();
  2149. VerifyFpsMaxResolutionMax(new_video_source.sink_wants());
  2150. video_stream_encoder_->Stop();
  2151. }
  2152. TEST_F(VideoStreamEncoderTest, DoesNotScaleBelowSetResolutionLimit) {
  2153. const int kWidth = 1280;
  2154. const int kHeight = 720;
  2155. const size_t kNumFrames = 10;
  2156. video_stream_encoder_->OnBitrateUpdated(
  2157. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2158. DataRate::bps(kTargetBitrateBps), 0, 0);
  2159. // Enable adapter, expected input resolutions when downscaling:
  2160. // 1280x720 -> 960x540 -> 640x360 -> 480x270 -> 320x180 (kMinPixelsPerFrame)
  2161. video_source_.set_adaptation_enabled(true);
  2162. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2163. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2164. int downscales = 0;
  2165. for (size_t i = 1; i <= kNumFrames; i++) {
  2166. video_source_.IncomingCapturedFrame(
  2167. CreateFrame(i * kFrameIntervalMs, kWidth, kHeight));
  2168. WaitForEncodedFrame(i * kFrameIntervalMs);
  2169. // Trigger scale down.
  2170. rtc::VideoSinkWants last_wants = video_source_.sink_wants();
  2171. video_stream_encoder_->TriggerQualityLow();
  2172. EXPECT_GE(video_source_.sink_wants().max_pixel_count, kMinPixelsPerFrame);
  2173. if (video_source_.sink_wants().max_pixel_count < last_wants.max_pixel_count)
  2174. ++downscales;
  2175. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2176. EXPECT_EQ(downscales,
  2177. stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2178. EXPECT_GT(downscales, 0);
  2179. }
  2180. video_stream_encoder_->Stop();
  2181. }
  2182. TEST_F(VideoStreamEncoderTest,
  2183. AdaptsResolutionUpAndDownTwiceOnOveruse_MaintainFramerateMode) {
  2184. const int kWidth = 1280;
  2185. const int kHeight = 720;
  2186. video_stream_encoder_->OnBitrateUpdated(
  2187. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2188. DataRate::bps(kTargetBitrateBps), 0, 0);
  2189. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  2190. AdaptingFrameForwarder source;
  2191. source.set_adaptation_enabled(true);
  2192. video_stream_encoder_->SetSource(
  2193. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  2194. int64_t timestamp_ms = kFrameIntervalMs;
  2195. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2196. WaitForEncodedFrame(kWidth, kHeight);
  2197. VerifyFpsMaxResolutionMax(source.sink_wants());
  2198. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2199. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2200. // Trigger adapt down, expect scaled down resolution.
  2201. video_stream_encoder_->TriggerCpuOveruse();
  2202. timestamp_ms += kFrameIntervalMs;
  2203. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2204. WaitForEncodedFrame(timestamp_ms);
  2205. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  2206. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2207. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2208. // Trigger adapt up, expect no restriction.
  2209. video_stream_encoder_->TriggerCpuNormalUsage();
  2210. timestamp_ms += kFrameIntervalMs;
  2211. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2212. WaitForEncodedFrame(kWidth, kHeight);
  2213. VerifyFpsMaxResolutionMax(source.sink_wants());
  2214. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2215. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2216. // Trigger adapt down, expect scaled down resolution.
  2217. video_stream_encoder_->TriggerCpuOveruse();
  2218. timestamp_ms += kFrameIntervalMs;
  2219. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2220. WaitForEncodedFrame(timestamp_ms);
  2221. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  2222. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2223. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2224. // Trigger adapt up, expect no restriction.
  2225. video_stream_encoder_->TriggerCpuNormalUsage();
  2226. timestamp_ms += kFrameIntervalMs;
  2227. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2228. sink_.WaitForEncodedFrame(kWidth, kHeight);
  2229. VerifyFpsMaxResolutionMax(source.sink_wants());
  2230. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2231. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2232. video_stream_encoder_->Stop();
  2233. }
  2234. TEST_F(VideoStreamEncoderTest,
  2235. AdaptsResolutionUpAndDownTwiceForLowQuality_BalancedMode_NoFpsLimit) {
  2236. const int kWidth = 1280;
  2237. const int kHeight = 720;
  2238. video_stream_encoder_->OnBitrateUpdated(
  2239. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2240. DataRate::bps(kTargetBitrateBps), 0, 0);
  2241. // Enable BALANCED preference, no initial limitation.
  2242. AdaptingFrameForwarder source;
  2243. source.set_adaptation_enabled(true);
  2244. video_stream_encoder_->SetSource(&source,
  2245. webrtc::DegradationPreference::BALANCED);
  2246. int64_t timestamp_ms = kFrameIntervalMs;
  2247. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2248. sink_.WaitForEncodedFrame(kWidth, kHeight);
  2249. VerifyFpsMaxResolutionMax(source.sink_wants());
  2250. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2251. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2252. // Trigger adapt down, expect scaled down resolution.
  2253. video_stream_encoder_->TriggerQualityLow();
  2254. timestamp_ms += kFrameIntervalMs;
  2255. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2256. sink_.WaitForEncodedFrame(timestamp_ms);
  2257. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  2258. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2259. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2260. // Trigger adapt up, expect no restriction.
  2261. video_stream_encoder_->TriggerQualityHigh();
  2262. timestamp_ms += kFrameIntervalMs;
  2263. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2264. sink_.WaitForEncodedFrame(kWidth, kHeight);
  2265. VerifyFpsMaxResolutionMax(source.sink_wants());
  2266. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2267. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2268. // Trigger adapt down, expect scaled down resolution.
  2269. video_stream_encoder_->TriggerQualityLow();
  2270. timestamp_ms += kFrameIntervalMs;
  2271. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2272. sink_.WaitForEncodedFrame(timestamp_ms);
  2273. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  2274. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2275. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2276. // Trigger adapt up, expect no restriction.
  2277. video_stream_encoder_->TriggerQualityHigh();
  2278. timestamp_ms += kFrameIntervalMs;
  2279. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2280. sink_.WaitForEncodedFrame(kWidth, kHeight);
  2281. VerifyFpsMaxResolutionMax(source.sink_wants());
  2282. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2283. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2284. video_stream_encoder_->Stop();
  2285. }
  2286. TEST_F(VideoStreamEncoderTest, AdaptUpIfBwEstimateIsHigherThanMinBitrate) {
  2287. fake_encoder_.SetResolutionBitrateLimits(
  2288. {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
  2289. video_stream_encoder_->OnBitrateUpdated(
  2290. DataRate::bps(kEncoderBitrateLimits720p.min_start_bitrate_bps),
  2291. DataRate::bps(kEncoderBitrateLimits720p.min_start_bitrate_bps),
  2292. DataRate::bps(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0, 0);
  2293. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  2294. AdaptingFrameForwarder source;
  2295. source.set_adaptation_enabled(true);
  2296. video_stream_encoder_->SetSource(
  2297. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  2298. // Insert 720p frame.
  2299. int64_t timestamp_ms = kFrameIntervalMs;
  2300. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
  2301. WaitForEncodedFrame(1280, 720);
  2302. // Reduce bitrate and trigger adapt down.
  2303. video_stream_encoder_->OnBitrateUpdated(
  2304. DataRate::bps(kEncoderBitrateLimits540p.min_start_bitrate_bps),
  2305. DataRate::bps(kEncoderBitrateLimits540p.min_start_bitrate_bps),
  2306. DataRate::bps(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0, 0);
  2307. video_stream_encoder_->TriggerQualityLow();
  2308. // Insert 720p frame. It should be downscaled and encoded.
  2309. timestamp_ms += kFrameIntervalMs;
  2310. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
  2311. WaitForEncodedFrame(960, 540);
  2312. // Trigger adapt up. Higher resolution should not be requested duo to lack
  2313. // of bitrate.
  2314. video_stream_encoder_->TriggerQualityHigh();
  2315. VerifyFpsMaxResolutionLt(source.sink_wants(), 1280 * 720);
  2316. // Increase bitrate.
  2317. video_stream_encoder_->OnBitrateUpdated(
  2318. DataRate::bps(kEncoderBitrateLimits720p.min_start_bitrate_bps),
  2319. DataRate::bps(kEncoderBitrateLimits720p.min_start_bitrate_bps),
  2320. DataRate::bps(kEncoderBitrateLimits720p.min_start_bitrate_bps), 0, 0);
  2321. // Trigger adapt up. Higher resolution should be requested.
  2322. video_stream_encoder_->TriggerQualityHigh();
  2323. VerifyFpsMaxResolutionMax(source.sink_wants());
  2324. video_stream_encoder_->Stop();
  2325. }
  2326. TEST_F(VideoStreamEncoderTest, DropFirstFramesIfBwEstimateIsTooLow) {
  2327. fake_encoder_.SetResolutionBitrateLimits(
  2328. {kEncoderBitrateLimits540p, kEncoderBitrateLimits720p});
  2329. // Set bitrate equal to min bitrate of 540p.
  2330. video_stream_encoder_->OnBitrateUpdated(
  2331. DataRate::bps(kEncoderBitrateLimits540p.min_start_bitrate_bps),
  2332. DataRate::bps(kEncoderBitrateLimits540p.min_start_bitrate_bps),
  2333. DataRate::bps(kEncoderBitrateLimits540p.min_start_bitrate_bps), 0, 0);
  2334. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  2335. AdaptingFrameForwarder source;
  2336. source.set_adaptation_enabled(true);
  2337. video_stream_encoder_->SetSource(
  2338. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  2339. // Insert 720p frame. It should be dropped and lower resolution should be
  2340. // requested.
  2341. int64_t timestamp_ms = kFrameIntervalMs;
  2342. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
  2343. ExpectDroppedFrame();
  2344. VerifyFpsMaxResolutionLt(source.sink_wants(), 1280 * 720);
  2345. // Insert 720p frame. It should be downscaled and encoded.
  2346. timestamp_ms += kFrameIntervalMs;
  2347. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, 1280, 720));
  2348. WaitForEncodedFrame(960, 540);
  2349. video_stream_encoder_->Stop();
  2350. }
  2351. class BalancedDegradationTest : public VideoStreamEncoderTest {
  2352. protected:
  2353. void SetupTest() {
  2354. // Reset encoder for field trials to take effect.
  2355. ConfigureEncoder(video_encoder_config_.Copy());
  2356. OnBitrateUpdated(kTargetBitrateBps);
  2357. // Enable BALANCED preference.
  2358. source_.set_adaptation_enabled(true);
  2359. video_stream_encoder_->SetSource(&source_, DegradationPreference::BALANCED);
  2360. }
  2361. void OnBitrateUpdated(int bitrate_bps) {
  2362. video_stream_encoder_->OnBitrateUpdated(DataRate::bps(bitrate_bps),
  2363. DataRate::bps(bitrate_bps),
  2364. DataRate::bps(bitrate_bps), 0, 0);
  2365. }
  2366. void InsertFrame() {
  2367. timestamp_ms_ += kFrameIntervalMs;
  2368. source_.IncomingCapturedFrame(CreateFrame(timestamp_ms_, kWidth, kHeight));
  2369. }
  2370. void InsertFrameAndWaitForEncoded() {
  2371. InsertFrame();
  2372. sink_.WaitForEncodedFrame(timestamp_ms_);
  2373. }
  2374. const int kWidth = 640; // pixels:640x360=230400
  2375. const int kHeight = 360;
  2376. const int64_t kFrameIntervalMs = 150; // Use low fps to not drop any frame.
  2377. int64_t timestamp_ms_ = 0;
  2378. AdaptingFrameForwarder source_;
  2379. };
  2380. TEST_F(BalancedDegradationTest, AdaptDownReturnsFalseIfFpsDiffLtThreshold) {
  2381. test::ScopedFieldTrials field_trials(
  2382. "WebRTC-Video-BalancedDegradationSettings/"
  2383. "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
  2384. SetupTest();
  2385. // Force input frame rate.
  2386. const int kInputFps = 24;
  2387. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  2388. stats.input_frame_rate = kInputFps;
  2389. stats_proxy_->SetMockStats(stats);
  2390. InsertFrameAndWaitForEncoded();
  2391. VerifyFpsMaxResolutionMax(source_.sink_wants());
  2392. // Trigger adapt down, expect scaled down framerate (640x360@24fps).
  2393. // Fps diff (input-requested:0) < threshold, expect AdaptDown to return false.
  2394. video_stream_encoder_->TriggerQualityLowExpectFalse();
  2395. VerifyFpsEqResolutionMax(source_.sink_wants(), 24);
  2396. video_stream_encoder_->Stop();
  2397. }
  2398. TEST_F(BalancedDegradationTest, AdaptDownReturnsTrueIfFpsDiffGeThreshold) {
  2399. test::ScopedFieldTrials field_trials(
  2400. "WebRTC-Video-BalancedDegradationSettings/"
  2401. "pixels:57600|129600|230400,fps:7|10|24,fps_diff:1|1|1/");
  2402. SetupTest();
  2403. // Force input frame rate.
  2404. const int kInputFps = 25;
  2405. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  2406. stats.input_frame_rate = kInputFps;
  2407. stats_proxy_->SetMockStats(stats);
  2408. InsertFrameAndWaitForEncoded();
  2409. VerifyFpsMaxResolutionMax(source_.sink_wants());
  2410. // Trigger adapt down, expect scaled down framerate (640x360@24fps).
  2411. // Fps diff (input-requested:1) == threshold, expect AdaptDown to return true.
  2412. video_stream_encoder_->TriggerQualityLow();
  2413. VerifyFpsEqResolutionMax(source_.sink_wants(), 24);
  2414. video_stream_encoder_->Stop();
  2415. }
  2416. TEST_F(BalancedDegradationTest, AdaptDownUsesCodecSpecificFps) {
  2417. test::ScopedFieldTrials field_trials(
  2418. "WebRTC-Video-BalancedDegradationSettings/"
  2419. "pixels:57600|129600|230400,fps:7|10|24,vp8_fps:8|11|22/");
  2420. SetupTest();
  2421. EXPECT_EQ(kVideoCodecVP8, video_encoder_config_.codec_type);
  2422. InsertFrameAndWaitForEncoded();
  2423. VerifyFpsMaxResolutionMax(source_.sink_wants());
  2424. // Trigger adapt down, expect scaled down framerate (640x360@22fps).
  2425. video_stream_encoder_->TriggerQualityLow();
  2426. VerifyFpsEqResolutionMax(source_.sink_wants(), 22);
  2427. video_stream_encoder_->Stop();
  2428. }
  2429. TEST_F(BalancedDegradationTest, NoAdaptUpIfBwEstimateIsLessThanMinBitrate) {
  2430. test::ScopedFieldTrials field_trials(
  2431. "WebRTC-Video-BalancedDegradationSettings/"
  2432. "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425/");
  2433. SetupTest();
  2434. const int kMinBitrateBps = 425000;
  2435. const int kTooLowMinBitrateBps = 424000;
  2436. OnBitrateUpdated(kTooLowMinBitrateBps);
  2437. InsertFrameAndWaitForEncoded();
  2438. VerifyFpsMaxResolutionMax(source_.sink_wants());
  2439. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2440. // Trigger adapt down, expect scaled down framerate (640x360@14fps).
  2441. video_stream_encoder_->TriggerQualityLow();
  2442. InsertFrameAndWaitForEncoded();
  2443. VerifyFpsEqResolutionMax(source_.sink_wants(), 14);
  2444. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2445. // Trigger adapt down, expect scaled down resolution (480x270@14fps).
  2446. video_stream_encoder_->TriggerQualityLow();
  2447. InsertFrameAndWaitForEncoded();
  2448. VerifyFpsEqResolutionLt(source_.sink_wants(), source_.last_wants());
  2449. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2450. // Trigger adapt down, expect scaled down framerate (480x270@10fps).
  2451. video_stream_encoder_->TriggerQualityLow();
  2452. InsertFrameAndWaitForEncoded();
  2453. VerifyFpsLtResolutionEq(source_.sink_wants(), source_.last_wants());
  2454. EXPECT_EQ(source_.sink_wants().max_framerate_fps, 10);
  2455. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2456. // Trigger adapt up, expect no upscale in fps (target bitrate < min bitrate).
  2457. video_stream_encoder_->TriggerQualityHigh();
  2458. InsertFrameAndWaitForEncoded();
  2459. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2460. // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
  2461. OnBitrateUpdated(kMinBitrateBps);
  2462. video_stream_encoder_->TriggerQualityHigh();
  2463. InsertFrameAndWaitForEncoded();
  2464. EXPECT_EQ(source_.sink_wants().max_framerate_fps, 14);
  2465. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2466. video_stream_encoder_->Stop();
  2467. }
  2468. TEST_F(BalancedDegradationTest,
  2469. InitialFrameDropAdaptsFpsAndResolutionInOneStep) {
  2470. test::ScopedFieldTrials field_trials(
  2471. "WebRTC-Video-BalancedDegradationSettings/"
  2472. "pixels:57600|129600|230400,fps:7|24|24/");
  2473. SetupTest();
  2474. OnBitrateUpdated(kLowTargetBitrateBps);
  2475. VerifyNoLimitation(source_.sink_wants());
  2476. // Insert frame, expect scaled down:
  2477. // framerate (640x360@24fps) -> resolution (480x270@24fps).
  2478. InsertFrame();
  2479. EXPECT_FALSE(WaitForFrame(1000));
  2480. EXPECT_LT(source_.sink_wants().max_pixel_count, kWidth * kHeight);
  2481. EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
  2482. // Insert frame, expect scaled down:
  2483. // resolution (320x180@24fps).
  2484. InsertFrame();
  2485. EXPECT_FALSE(WaitForFrame(1000));
  2486. EXPECT_LT(source_.sink_wants().max_pixel_count,
  2487. source_.last_wants().max_pixel_count);
  2488. EXPECT_EQ(source_.sink_wants().max_framerate_fps, 24);
  2489. // Frame should not be dropped (min pixels per frame reached).
  2490. InsertFrameAndWaitForEncoded();
  2491. video_stream_encoder_->Stop();
  2492. }
  2493. TEST_F(BalancedDegradationTest,
  2494. NoAdaptUpInResolutionIfBwEstimateIsLessThanMinBitrate) {
  2495. test::ScopedFieldTrials field_trials(
  2496. "WebRTC-Video-BalancedDegradationSettings/"
  2497. "pixels:57600|129600|230400,fps:7|10|14,kbps_res:0|0|435/");
  2498. SetupTest();
  2499. const int kResolutionMinBitrateBps = 435000;
  2500. const int kTooLowMinResolutionBitrateBps = 434000;
  2501. OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
  2502. InsertFrameAndWaitForEncoded();
  2503. VerifyFpsMaxResolutionMax(source_.sink_wants());
  2504. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2505. // Trigger adapt down, expect scaled down framerate (640x360@14fps).
  2506. video_stream_encoder_->TriggerQualityLow();
  2507. InsertFrameAndWaitForEncoded();
  2508. VerifyFpsEqResolutionMax(source_.sink_wants(), 14);
  2509. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2510. // Trigger adapt down, expect scaled down resolution (480x270@14fps).
  2511. video_stream_encoder_->TriggerQualityLow();
  2512. InsertFrameAndWaitForEncoded();
  2513. VerifyFpsEqResolutionLt(source_.sink_wants(), source_.last_wants());
  2514. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2515. // Trigger adapt down, expect scaled down framerate (480x270@10fps).
  2516. video_stream_encoder_->TriggerQualityLow();
  2517. InsertFrameAndWaitForEncoded();
  2518. VerifyFpsLtResolutionEq(source_.sink_wants(), source_.last_wants());
  2519. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2520. // Trigger adapt up, expect upscaled fps (no bitrate limit) (480x270@14fps).
  2521. video_stream_encoder_->TriggerQualityHigh();
  2522. InsertFrameAndWaitForEncoded();
  2523. VerifyFpsGtResolutionEq(source_.sink_wants(), source_.last_wants());
  2524. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2525. // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
  2526. video_stream_encoder_->TriggerQualityHigh();
  2527. InsertFrameAndWaitForEncoded();
  2528. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2529. // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
  2530. OnBitrateUpdated(kResolutionMinBitrateBps);
  2531. video_stream_encoder_->TriggerQualityHigh();
  2532. InsertFrameAndWaitForEncoded();
  2533. VerifyFpsEqResolutionGt(source_.sink_wants(), source_.last_wants());
  2534. EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2535. video_stream_encoder_->Stop();
  2536. }
  2537. TEST_F(BalancedDegradationTest,
  2538. NoAdaptUpInFpsAndResolutionIfBwEstimateIsLessThanMinBitrate) {
  2539. test::ScopedFieldTrials field_trials(
  2540. "WebRTC-Video-BalancedDegradationSettings/"
  2541. "pixels:57600|129600|230400,fps:7|10|14,kbps:0|0|425,kbps_res:0|0|435/");
  2542. SetupTest();
  2543. const int kMinBitrateBps = 425000;
  2544. const int kTooLowMinBitrateBps = 424000;
  2545. const int kResolutionMinBitrateBps = 435000;
  2546. const int kTooLowMinResolutionBitrateBps = 434000;
  2547. OnBitrateUpdated(kTooLowMinBitrateBps);
  2548. InsertFrameAndWaitForEncoded();
  2549. VerifyFpsMaxResolutionMax(source_.sink_wants());
  2550. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2551. // Trigger adapt down, expect scaled down framerate (640x360@14fps).
  2552. video_stream_encoder_->TriggerQualityLow();
  2553. InsertFrameAndWaitForEncoded();
  2554. VerifyFpsEqResolutionMax(source_.sink_wants(), 14);
  2555. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2556. // Trigger adapt down, expect scaled down resolution (480x270@14fps).
  2557. video_stream_encoder_->TriggerQualityLow();
  2558. InsertFrameAndWaitForEncoded();
  2559. VerifyFpsEqResolutionLt(source_.sink_wants(), source_.last_wants());
  2560. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2561. // Trigger adapt down, expect scaled down framerate (480x270@10fps).
  2562. video_stream_encoder_->TriggerQualityLow();
  2563. InsertFrameAndWaitForEncoded();
  2564. VerifyFpsLtResolutionEq(source_.sink_wants(), source_.last_wants());
  2565. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2566. // Trigger adapt up, expect no upscale (target bitrate < min bitrate).
  2567. video_stream_encoder_->TriggerQualityHigh();
  2568. InsertFrameAndWaitForEncoded();
  2569. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2570. // Trigger adapt up, expect upscaled fps (target bitrate == min bitrate).
  2571. OnBitrateUpdated(kMinBitrateBps);
  2572. video_stream_encoder_->TriggerQualityHigh();
  2573. InsertFrameAndWaitForEncoded();
  2574. VerifyFpsGtResolutionEq(source_.sink_wants(), source_.last_wants());
  2575. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2576. // Trigger adapt up, expect no upscale in res (target bitrate < min bitrate).
  2577. OnBitrateUpdated(kTooLowMinResolutionBitrateBps);
  2578. video_stream_encoder_->TriggerQualityHigh();
  2579. InsertFrameAndWaitForEncoded();
  2580. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2581. // Trigger adapt up, expect upscaled res (target bitrate == min bitrate).
  2582. OnBitrateUpdated(kResolutionMinBitrateBps);
  2583. video_stream_encoder_->TriggerQualityHigh();
  2584. InsertFrameAndWaitForEncoded();
  2585. VerifyFpsEqResolutionGt(source_.sink_wants(), source_.last_wants());
  2586. EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2587. video_stream_encoder_->Stop();
  2588. }
  2589. TEST_F(VideoStreamEncoderTest,
  2590. AdaptsResolutionOnOveruseAndLowQuality_MaintainFramerateMode) {
  2591. const int kWidth = 1280;
  2592. const int kHeight = 720;
  2593. video_stream_encoder_->OnBitrateUpdated(
  2594. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2595. DataRate::bps(kTargetBitrateBps), 0, 0);
  2596. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  2597. AdaptingFrameForwarder source;
  2598. source.set_adaptation_enabled(true);
  2599. video_stream_encoder_->SetSource(
  2600. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  2601. int64_t timestamp_ms = kFrameIntervalMs;
  2602. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2603. WaitForEncodedFrame(kWidth, kHeight);
  2604. VerifyFpsMaxResolutionMax(source.sink_wants());
  2605. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2606. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2607. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2608. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2609. // Trigger cpu adapt down, expect scaled down resolution (960x540).
  2610. video_stream_encoder_->TriggerCpuOveruse();
  2611. timestamp_ms += kFrameIntervalMs;
  2612. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2613. WaitForEncodedFrame(timestamp_ms);
  2614. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  2615. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2616. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2617. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2618. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2619. // Trigger cpu adapt down, expect scaled down resolution (640x360).
  2620. video_stream_encoder_->TriggerCpuOveruse();
  2621. timestamp_ms += kFrameIntervalMs;
  2622. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2623. WaitForEncodedFrame(timestamp_ms);
  2624. VerifyFpsMaxResolutionLt(source.sink_wants(), source.last_wants());
  2625. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2626. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2627. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2628. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2629. // Trigger cpu adapt down, expect scaled down resolution (480x270).
  2630. video_stream_encoder_->TriggerCpuOveruse();
  2631. timestamp_ms += kFrameIntervalMs;
  2632. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2633. WaitForEncodedFrame(timestamp_ms);
  2634. VerifyFpsMaxResolutionLt(source.sink_wants(), source.last_wants());
  2635. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2636. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2637. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2638. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2639. // Trigger quality adapt down, expect scaled down resolution (320x180).
  2640. video_stream_encoder_->TriggerQualityLow();
  2641. timestamp_ms += kFrameIntervalMs;
  2642. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2643. WaitForEncodedFrame(timestamp_ms);
  2644. VerifyFpsMaxResolutionLt(source.sink_wants(), source.last_wants());
  2645. rtc::VideoSinkWants last_wants = source.sink_wants();
  2646. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2647. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2648. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2649. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2650. // Trigger quality adapt down, expect no change (min resolution reached).
  2651. video_stream_encoder_->TriggerQualityLow();
  2652. timestamp_ms += kFrameIntervalMs;
  2653. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2654. WaitForEncodedFrame(timestamp_ms);
  2655. VerifyFpsMaxResolutionEq(source.sink_wants(), last_wants);
  2656. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2657. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2658. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2659. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2660. // Trigger cpu adapt up, expect upscaled resolution (480x270).
  2661. video_stream_encoder_->TriggerCpuNormalUsage();
  2662. timestamp_ms += kFrameIntervalMs;
  2663. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2664. WaitForEncodedFrame(timestamp_ms);
  2665. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  2666. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2667. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2668. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2669. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2670. // Trigger cpu adapt up, expect upscaled resolution (640x360).
  2671. video_stream_encoder_->TriggerCpuNormalUsage();
  2672. timestamp_ms += kFrameIntervalMs;
  2673. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2674. WaitForEncodedFrame(timestamp_ms);
  2675. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  2676. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  2677. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2678. EXPECT_EQ(5, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2679. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2680. // Trigger cpu adapt up, expect upscaled resolution (960x540).
  2681. video_stream_encoder_->TriggerCpuNormalUsage();
  2682. timestamp_ms += kFrameIntervalMs;
  2683. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2684. WaitForEncodedFrame(timestamp_ms);
  2685. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  2686. last_wants = source.sink_wants();
  2687. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2688. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2689. EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2690. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2691. // Trigger cpu adapt up, no cpu downgrades, expect no change (960x540).
  2692. video_stream_encoder_->TriggerCpuNormalUsage();
  2693. timestamp_ms += kFrameIntervalMs;
  2694. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2695. WaitForEncodedFrame(timestamp_ms);
  2696. VerifyFpsEqResolutionEq(source.sink_wants(), last_wants);
  2697. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2698. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  2699. EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2700. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2701. // Trigger quality adapt up, expect no restriction (1280x720).
  2702. video_stream_encoder_->TriggerQualityHigh();
  2703. timestamp_ms += kFrameIntervalMs;
  2704. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  2705. WaitForEncodedFrame(kWidth, kHeight);
  2706. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  2707. VerifyFpsMaxResolutionMax(source.sink_wants());
  2708. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  2709. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  2710. EXPECT_EQ(6, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  2711. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  2712. video_stream_encoder_->Stop();
  2713. }
  2714. TEST_F(VideoStreamEncoderTest, CpuLimitedHistogramIsReported) {
  2715. const int kWidth = 640;
  2716. const int kHeight = 360;
  2717. video_stream_encoder_->OnBitrateUpdated(
  2718. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2719. DataRate::bps(kTargetBitrateBps), 0, 0);
  2720. for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
  2721. video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
  2722. WaitForEncodedFrame(i);
  2723. }
  2724. video_stream_encoder_->TriggerCpuOveruse();
  2725. for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
  2726. video_source_.IncomingCapturedFrame(CreateFrame(
  2727. SendStatisticsProxy::kMinRequiredMetricsSamples + i, kWidth, kHeight));
  2728. WaitForEncodedFrame(SendStatisticsProxy::kMinRequiredMetricsSamples + i);
  2729. }
  2730. video_stream_encoder_->Stop();
  2731. video_stream_encoder_.reset();
  2732. stats_proxy_.reset();
  2733. EXPECT_EQ(1,
  2734. metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
  2735. EXPECT_EQ(
  2736. 1, metrics::NumEvents("WebRTC.Video.CpuLimitedResolutionInPercent", 50));
  2737. }
  2738. TEST_F(VideoStreamEncoderTest,
  2739. CpuLimitedHistogramIsNotReportedForDisabledDegradation) {
  2740. video_stream_encoder_->OnBitrateUpdated(
  2741. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2742. DataRate::bps(kTargetBitrateBps), 0, 0);
  2743. const int kWidth = 640;
  2744. const int kHeight = 360;
  2745. video_stream_encoder_->SetSource(&video_source_,
  2746. webrtc::DegradationPreference::DISABLED);
  2747. for (int i = 1; i <= SendStatisticsProxy::kMinRequiredMetricsSamples; ++i) {
  2748. video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
  2749. WaitForEncodedFrame(i);
  2750. }
  2751. video_stream_encoder_->Stop();
  2752. video_stream_encoder_.reset();
  2753. stats_proxy_.reset();
  2754. EXPECT_EQ(0,
  2755. metrics::NumSamples("WebRTC.Video.CpuLimitedResolutionInPercent"));
  2756. }
  2757. TEST_F(VideoStreamEncoderTest, CallsBitrateObserver) {
  2758. MockBitrateObserver bitrate_observer;
  2759. video_stream_encoder_->SetBitrateAllocationObserver(&bitrate_observer);
  2760. const int kDefaultFps = 30;
  2761. const VideoBitrateAllocation expected_bitrate =
  2762. DefaultVideoBitrateAllocator(fake_encoder_.codec_config())
  2763. .Allocate(VideoBitrateAllocationParameters(kLowTargetBitrateBps,
  2764. kDefaultFps));
  2765. EXPECT_CALL(bitrate_observer, OnBitrateAllocationUpdated(expected_bitrate))
  2766. .Times(1);
  2767. video_stream_encoder_->OnBitrateUpdated(
  2768. DataRate::bps(kLowTargetBitrateBps), DataRate::bps(kLowTargetBitrateBps),
  2769. DataRate::bps(kLowTargetBitrateBps), 0, 0);
  2770. video_source_.IncomingCapturedFrame(
  2771. CreateFrame(rtc::TimeMillis(), codec_width_, codec_height_));
  2772. WaitForEncodedFrame(rtc::TimeMillis());
  2773. VideoBitrateAllocation bitrate_allocation =
  2774. fake_encoder_.GetAndResetLastRateControlSettings()->bitrate;
  2775. // Check that encoder has been updated too, not just allocation observer.
  2776. EXPECT_EQ(bitrate_allocation.get_sum_bps(), kLowTargetBitrateBps);
  2777. // TODO(srte): The use of millisecs here looks like an error, but the tests
  2778. // fails using seconds, this should be investigated.
  2779. fake_clock_.AdvanceTime(TimeDelta::ms(1) / kDefaultFps);
  2780. // Not called on second frame.
  2781. EXPECT_CALL(bitrate_observer, OnBitrateAllocationUpdated(expected_bitrate))
  2782. .Times(0);
  2783. video_source_.IncomingCapturedFrame(
  2784. CreateFrame(rtc::TimeMillis(), codec_width_, codec_height_));
  2785. WaitForEncodedFrame(rtc::TimeMillis());
  2786. fake_clock_.AdvanceTime(TimeDelta::ms(1) / kDefaultFps);
  2787. // Called after a process interval.
  2788. EXPECT_CALL(bitrate_observer, OnBitrateAllocationUpdated(expected_bitrate))
  2789. .Times(1);
  2790. const int64_t start_time_ms = rtc::TimeMillis();
  2791. while (rtc::TimeMillis() - start_time_ms < kProcessIntervalMs) {
  2792. video_source_.IncomingCapturedFrame(
  2793. CreateFrame(rtc::TimeMillis(), codec_width_, codec_height_));
  2794. WaitForEncodedFrame(rtc::TimeMillis());
  2795. fake_clock_.AdvanceTime(TimeDelta::ms(1) / kDefaultFps);
  2796. }
  2797. // Since rates are unchanged, encoder should not be reconfigured.
  2798. EXPECT_FALSE(fake_encoder_.GetAndResetLastRateControlSettings().has_value());
  2799. video_stream_encoder_->Stop();
  2800. }
  2801. TEST_F(VideoStreamEncoderTest, TemporalLayersNotDisabledIfSupported) {
  2802. // 2 TLs configured, temporal layers supported by encoder.
  2803. const int kNumTemporalLayers = 2;
  2804. ResetEncoder("VP8", 1, kNumTemporalLayers, 1, /*screenshare*/ false);
  2805. fake_encoder_.SetTemporalLayersSupported(0, true);
  2806. // Bitrate allocated across temporal layers.
  2807. const int kTl0Bps = kTargetBitrateBps *
  2808. webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
  2809. kNumTemporalLayers, /*temporal_id*/ 0);
  2810. const int kTl1Bps = kTargetBitrateBps *
  2811. webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
  2812. kNumTemporalLayers, /*temporal_id*/ 1);
  2813. VideoBitrateAllocation expected_bitrate;
  2814. expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTl0Bps);
  2815. expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kTl1Bps - kTl0Bps);
  2816. VerifyAllocatedBitrate(expected_bitrate);
  2817. video_stream_encoder_->Stop();
  2818. }
  2819. TEST_F(VideoStreamEncoderTest, TemporalLayersDisabledIfNotSupported) {
  2820. // 2 TLs configured, temporal layers not supported by encoder.
  2821. ResetEncoder("VP8", 1, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false);
  2822. fake_encoder_.SetTemporalLayersSupported(0, false);
  2823. // Temporal layers not supported by the encoder.
  2824. // Total bitrate should be at ti:0.
  2825. VideoBitrateAllocation expected_bitrate;
  2826. expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kTargetBitrateBps);
  2827. VerifyAllocatedBitrate(expected_bitrate);
  2828. video_stream_encoder_->Stop();
  2829. }
  2830. TEST_F(VideoStreamEncoderTest, VerifyBitrateAllocationForTwoStreams) {
  2831. // 2 TLs configured, temporal layers only supported for first stream.
  2832. ResetEncoder("VP8", 2, /*num_temporal_layers*/ 2, 1, /*screenshare*/ false);
  2833. fake_encoder_.SetTemporalLayersSupported(0, true);
  2834. fake_encoder_.SetTemporalLayersSupported(1, false);
  2835. const int kS0Bps = 150000;
  2836. const int kS0Tl0Bps =
  2837. kS0Bps * webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
  2838. /*num_layers*/ 2, /*temporal_id*/ 0);
  2839. const int kS0Tl1Bps =
  2840. kS0Bps * webrtc::SimulcastRateAllocator::GetTemporalRateAllocation(
  2841. /*num_layers*/ 2, /*temporal_id*/ 1);
  2842. const int kS1Bps = kTargetBitrateBps - kS0Tl1Bps;
  2843. // Temporal layers not supported by si:1.
  2844. VideoBitrateAllocation expected_bitrate;
  2845. expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 0, kS0Tl0Bps);
  2846. expected_bitrate.SetBitrate(/*si*/ 0, /*ti*/ 1, kS0Tl1Bps - kS0Tl0Bps);
  2847. expected_bitrate.SetBitrate(/*si*/ 1, /*ti*/ 0, kS1Bps);
  2848. VerifyAllocatedBitrate(expected_bitrate);
  2849. video_stream_encoder_->Stop();
  2850. }
  2851. TEST_F(VideoStreamEncoderTest, OveruseDetectorUpdatedOnReconfigureAndAdaption) {
  2852. const int kFrameWidth = 1280;
  2853. const int kFrameHeight = 720;
  2854. const int kFramerate = 24;
  2855. video_stream_encoder_->OnBitrateUpdated(
  2856. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2857. DataRate::bps(kTargetBitrateBps), 0, 0);
  2858. test::FrameForwarder source;
  2859. video_stream_encoder_->SetSource(
  2860. &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  2861. // Insert a single frame, triggering initial configuration.
  2862. source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
  2863. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2864. EXPECT_EQ(
  2865. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  2866. kDefaultFramerate);
  2867. // Trigger reconfigure encoder (without resetting the entire instance).
  2868. VideoEncoderConfig video_encoder_config;
  2869. video_encoder_config.codec_type = kVideoCodecVP8;
  2870. video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
  2871. video_encoder_config.number_of_streams = 1;
  2872. video_encoder_config.video_stream_factory =
  2873. new rtc::RefCountedObject<VideoStreamFactory>(1, kFramerate);
  2874. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  2875. kMaxPayloadLength);
  2876. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2877. // Detector should be updated with fps limit from codec config.
  2878. EXPECT_EQ(
  2879. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  2880. kFramerate);
  2881. // Trigger overuse, max framerate should be reduced.
  2882. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  2883. stats.input_frame_rate = kFramerate;
  2884. stats_proxy_->SetMockStats(stats);
  2885. video_stream_encoder_->TriggerCpuOveruse();
  2886. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2887. int adapted_framerate =
  2888. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
  2889. EXPECT_LT(adapted_framerate, kFramerate);
  2890. // Trigger underuse, max framerate should go back to codec configured fps.
  2891. // Set extra low fps, to make sure it's actually reset, not just incremented.
  2892. stats = stats_proxy_->GetStats();
  2893. stats.input_frame_rate = adapted_framerate / 2;
  2894. stats_proxy_->SetMockStats(stats);
  2895. video_stream_encoder_->TriggerCpuNormalUsage();
  2896. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2897. EXPECT_EQ(
  2898. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  2899. kFramerate);
  2900. video_stream_encoder_->Stop();
  2901. }
  2902. TEST_F(VideoStreamEncoderTest,
  2903. OveruseDetectorUpdatedRespectsFramerateAfterUnderuse) {
  2904. const int kFrameWidth = 1280;
  2905. const int kFrameHeight = 720;
  2906. const int kLowFramerate = 15;
  2907. const int kHighFramerate = 25;
  2908. video_stream_encoder_->OnBitrateUpdated(
  2909. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2910. DataRate::bps(kTargetBitrateBps), 0, 0);
  2911. test::FrameForwarder source;
  2912. video_stream_encoder_->SetSource(
  2913. &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  2914. // Trigger initial configuration.
  2915. VideoEncoderConfig video_encoder_config;
  2916. video_encoder_config.codec_type = kVideoCodecVP8;
  2917. video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
  2918. video_encoder_config.number_of_streams = 1;
  2919. video_encoder_config.video_stream_factory =
  2920. new rtc::RefCountedObject<VideoStreamFactory>(1, kLowFramerate);
  2921. source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
  2922. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  2923. kMaxPayloadLength);
  2924. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2925. EXPECT_EQ(
  2926. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  2927. kLowFramerate);
  2928. // Trigger overuse, max framerate should be reduced.
  2929. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  2930. stats.input_frame_rate = kLowFramerate;
  2931. stats_proxy_->SetMockStats(stats);
  2932. video_stream_encoder_->TriggerCpuOveruse();
  2933. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2934. int adapted_framerate =
  2935. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
  2936. EXPECT_LT(adapted_framerate, kLowFramerate);
  2937. // Reconfigure the encoder with a new (higher max framerate), max fps should
  2938. // still respect the adaptation.
  2939. video_encoder_config.video_stream_factory =
  2940. new rtc::RefCountedObject<VideoStreamFactory>(1, kHighFramerate);
  2941. source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
  2942. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  2943. kMaxPayloadLength);
  2944. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2945. EXPECT_EQ(
  2946. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  2947. adapted_framerate);
  2948. // Trigger underuse, max framerate should go back to codec configured fps.
  2949. stats = stats_proxy_->GetStats();
  2950. stats.input_frame_rate = adapted_framerate;
  2951. stats_proxy_->SetMockStats(stats);
  2952. video_stream_encoder_->TriggerCpuNormalUsage();
  2953. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2954. EXPECT_EQ(
  2955. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  2956. kHighFramerate);
  2957. video_stream_encoder_->Stop();
  2958. }
  2959. TEST_F(VideoStreamEncoderTest,
  2960. OveruseDetectorUpdatedOnDegradationPreferenceChange) {
  2961. const int kFrameWidth = 1280;
  2962. const int kFrameHeight = 720;
  2963. const int kFramerate = 24;
  2964. video_stream_encoder_->OnBitrateUpdated(
  2965. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  2966. DataRate::bps(kTargetBitrateBps), 0, 0);
  2967. test::FrameForwarder source;
  2968. video_stream_encoder_->SetSource(
  2969. &source, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  2970. // Trigger initial configuration.
  2971. VideoEncoderConfig video_encoder_config;
  2972. video_encoder_config.codec_type = kVideoCodecVP8;
  2973. video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
  2974. video_encoder_config.number_of_streams = 1;
  2975. video_encoder_config.video_stream_factory =
  2976. new rtc::RefCountedObject<VideoStreamFactory>(1, kFramerate);
  2977. source.IncomingCapturedFrame(CreateFrame(1, kFrameWidth, kFrameHeight));
  2978. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  2979. kMaxPayloadLength);
  2980. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2981. EXPECT_EQ(
  2982. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  2983. kFramerate);
  2984. // Trigger overuse, max framerate should be reduced.
  2985. VideoSendStream::Stats stats = stats_proxy_->GetStats();
  2986. stats.input_frame_rate = kFramerate;
  2987. stats_proxy_->SetMockStats(stats);
  2988. video_stream_encoder_->TriggerCpuOveruse();
  2989. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2990. int adapted_framerate =
  2991. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate();
  2992. EXPECT_LT(adapted_framerate, kFramerate);
  2993. // Change degradation preference to not enable framerate scaling. Target
  2994. // framerate should be changed to codec defined limit.
  2995. video_stream_encoder_->SetSource(
  2996. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  2997. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  2998. EXPECT_EQ(
  2999. video_stream_encoder_->overuse_detector_proxy_->GetLastTargetFramerate(),
  3000. kFramerate);
  3001. video_stream_encoder_->Stop();
  3002. }
  3003. TEST_F(VideoStreamEncoderTest, DropsFramesAndScalesWhenBitrateIsTooLow) {
  3004. const int kTooLowBitrateForFrameSizeBps = 10000;
  3005. video_stream_encoder_->OnBitrateUpdated(
  3006. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3007. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3008. DataRate::bps(kTooLowBitrateForFrameSizeBps), 0, 0);
  3009. const int kWidth = 640;
  3010. const int kHeight = 360;
  3011. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  3012. // Expect to drop this frame, the wait should time out.
  3013. ExpectDroppedFrame();
  3014. // Expect the sink_wants to specify a scaled frame.
  3015. EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
  3016. int last_pixel_count = video_source_.sink_wants().max_pixel_count;
  3017. // Next frame is scaled.
  3018. video_source_.IncomingCapturedFrame(
  3019. CreateFrame(2, kWidth * 3 / 4, kHeight * 3 / 4));
  3020. // Expect to drop this frame, the wait should time out.
  3021. ExpectDroppedFrame();
  3022. EXPECT_LT(video_source_.sink_wants().max_pixel_count, last_pixel_count);
  3023. video_stream_encoder_->Stop();
  3024. }
  3025. TEST_F(VideoStreamEncoderTest,
  3026. NumberOfDroppedFramesLimitedWhenBitrateIsTooLow) {
  3027. const int kTooLowBitrateForFrameSizeBps = 10000;
  3028. video_stream_encoder_->OnBitrateUpdated(
  3029. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3030. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3031. DataRate::bps(kTooLowBitrateForFrameSizeBps), 0, 0);
  3032. const int kWidth = 640;
  3033. const int kHeight = 360;
  3034. // We expect the n initial frames to get dropped.
  3035. int i;
  3036. for (i = 1; i <= kMaxInitialFramedrop; ++i) {
  3037. video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
  3038. ExpectDroppedFrame();
  3039. }
  3040. // The n+1th frame should not be dropped, even though it's size is too large.
  3041. video_source_.IncomingCapturedFrame(CreateFrame(i, kWidth, kHeight));
  3042. WaitForEncodedFrame(i);
  3043. // Expect the sink_wants to specify a scaled frame.
  3044. EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
  3045. video_stream_encoder_->Stop();
  3046. }
  3047. TEST_F(VideoStreamEncoderTest,
  3048. InitialFrameDropOffWithMaintainResolutionPreference) {
  3049. const int kWidth = 640;
  3050. const int kHeight = 360;
  3051. video_stream_encoder_->OnBitrateUpdated(
  3052. DataRate::bps(kLowTargetBitrateBps), DataRate::bps(kLowTargetBitrateBps),
  3053. DataRate::bps(kLowTargetBitrateBps), 0, 0);
  3054. // Set degradation preference.
  3055. video_stream_encoder_->SetSource(
  3056. &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  3057. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  3058. // Frame should not be dropped, even if it's too large.
  3059. WaitForEncodedFrame(1);
  3060. video_stream_encoder_->Stop();
  3061. }
  3062. TEST_F(VideoStreamEncoderTest, InitialFrameDropOffWhenEncoderDisabledScaling) {
  3063. const int kWidth = 640;
  3064. const int kHeight = 360;
  3065. fake_encoder_.SetQualityScaling(false);
  3066. VideoEncoderConfig video_encoder_config;
  3067. test::FillEncoderConfiguration(kVideoCodecVP8, 1, &video_encoder_config);
  3068. // Make format different, to force recreation of encoder.
  3069. video_encoder_config.video_format.parameters["foo"] = "foo";
  3070. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  3071. kMaxPayloadLength);
  3072. video_stream_encoder_->OnBitrateUpdated(
  3073. DataRate::bps(kLowTargetBitrateBps), DataRate::bps(kLowTargetBitrateBps),
  3074. DataRate::bps(kLowTargetBitrateBps), 0, 0);
  3075. // Force quality scaler reconfiguration by resetting the source.
  3076. video_stream_encoder_->SetSource(&video_source_,
  3077. webrtc::DegradationPreference::BALANCED);
  3078. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  3079. // Frame should not be dropped, even if it's too large.
  3080. WaitForEncodedFrame(1);
  3081. video_stream_encoder_->Stop();
  3082. fake_encoder_.SetQualityScaling(true);
  3083. }
  3084. TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBWEstimateReady) {
  3085. webrtc::test::ScopedFieldTrials field_trials(
  3086. "WebRTC-InitialFramedrop/Enabled/");
  3087. // Reset encoder for field trials to take effect.
  3088. ConfigureEncoder(video_encoder_config_.Copy());
  3089. const int kTooLowBitrateForFrameSizeBps = 10000;
  3090. const int kWidth = 640;
  3091. const int kHeight = 360;
  3092. video_stream_encoder_->OnBitrateUpdated(
  3093. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3094. DataRate::bps(kTargetBitrateBps), 0, 0);
  3095. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  3096. // Frame should not be dropped.
  3097. WaitForEncodedFrame(1);
  3098. video_stream_encoder_->OnBitrateUpdated(
  3099. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3100. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3101. DataRate::bps(kTooLowBitrateForFrameSizeBps), 0, 0);
  3102. video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  3103. // Expect to drop this frame, the wait should time out.
  3104. ExpectDroppedFrame();
  3105. // Expect the sink_wants to specify a scaled frame.
  3106. EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
  3107. video_stream_encoder_->Stop();
  3108. }
  3109. TEST_F(VideoStreamEncoderTest, InitialFrameDropActivatesWhenBweDrops) {
  3110. webrtc::test::ScopedFieldTrials field_trials(
  3111. "WebRTC-Video-QualityScalerSettings/"
  3112. "initial_bitrate_interval_ms:1000,initial_bitrate_factor:0.2/");
  3113. // Reset encoder for field trials to take effect.
  3114. ConfigureEncoder(video_encoder_config_.Copy());
  3115. const int kNotTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.2;
  3116. const int kTooLowBitrateForFrameSizeBps = kTargetBitrateBps * 0.19;
  3117. const int kWidth = 640;
  3118. const int kHeight = 360;
  3119. video_stream_encoder_->OnBitrateUpdated(
  3120. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3121. DataRate::bps(kTargetBitrateBps), 0, 0);
  3122. video_source_.IncomingCapturedFrame(CreateFrame(1, kWidth, kHeight));
  3123. // Frame should not be dropped.
  3124. WaitForEncodedFrame(1);
  3125. video_stream_encoder_->OnBitrateUpdated(
  3126. DataRate::bps(kNotTooLowBitrateForFrameSizeBps),
  3127. DataRate::bps(kNotTooLowBitrateForFrameSizeBps),
  3128. DataRate::bps(kNotTooLowBitrateForFrameSizeBps), 0, 0);
  3129. video_source_.IncomingCapturedFrame(CreateFrame(2, kWidth, kHeight));
  3130. // Frame should not be dropped.
  3131. WaitForEncodedFrame(2);
  3132. video_stream_encoder_->OnBitrateUpdated(
  3133. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3134. DataRate::bps(kTooLowBitrateForFrameSizeBps),
  3135. DataRate::bps(kTooLowBitrateForFrameSizeBps), 0, 0);
  3136. video_source_.IncomingCapturedFrame(CreateFrame(3, kWidth, kHeight));
  3137. // Expect to drop this frame, the wait should time out.
  3138. ExpectDroppedFrame();
  3139. // Expect the sink_wants to specify a scaled frame.
  3140. EXPECT_LT(video_source_.sink_wants().max_pixel_count, kWidth * kHeight);
  3141. video_stream_encoder_->Stop();
  3142. }
  3143. TEST_F(VideoStreamEncoderTest,
  3144. ResolutionNotAdaptedForTooSmallFrame_MaintainFramerateMode) {
  3145. const int kTooSmallWidth = 10;
  3146. const int kTooSmallHeight = 10;
  3147. video_stream_encoder_->OnBitrateUpdated(
  3148. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3149. DataRate::bps(kTargetBitrateBps), 0, 0);
  3150. // Enable MAINTAIN_FRAMERATE preference, no initial limitation.
  3151. test::FrameForwarder source;
  3152. video_stream_encoder_->SetSource(
  3153. &source, webrtc::DegradationPreference::MAINTAIN_FRAMERATE);
  3154. VerifyNoLimitation(source.sink_wants());
  3155. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3156. // Trigger adapt down, too small frame, expect no change.
  3157. source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
  3158. WaitForEncodedFrame(1);
  3159. video_stream_encoder_->TriggerCpuOveruse();
  3160. VerifyFpsMaxResolutionMax(source.sink_wants());
  3161. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3162. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3163. video_stream_encoder_->Stop();
  3164. }
  3165. TEST_F(VideoStreamEncoderTest,
  3166. ResolutionNotAdaptedForTooSmallFrame_BalancedMode) {
  3167. const int kTooSmallWidth = 10;
  3168. const int kTooSmallHeight = 10;
  3169. const int kFpsLimit = 7;
  3170. video_stream_encoder_->OnBitrateUpdated(
  3171. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3172. DataRate::bps(kTargetBitrateBps), 0, 0);
  3173. // Enable BALANCED preference, no initial limitation.
  3174. test::FrameForwarder source;
  3175. video_stream_encoder_->SetSource(&source,
  3176. webrtc::DegradationPreference::BALANCED);
  3177. VerifyNoLimitation(source.sink_wants());
  3178. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3179. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3180. // Trigger adapt down, expect limited framerate.
  3181. source.IncomingCapturedFrame(CreateFrame(1, kTooSmallWidth, kTooSmallHeight));
  3182. WaitForEncodedFrame(1);
  3183. video_stream_encoder_->TriggerQualityLow();
  3184. VerifyFpsEqResolutionMax(source.sink_wants(), kFpsLimit);
  3185. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3186. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3187. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3188. // Trigger adapt down, too small frame, expect no change.
  3189. source.IncomingCapturedFrame(CreateFrame(2, kTooSmallWidth, kTooSmallHeight));
  3190. WaitForEncodedFrame(2);
  3191. video_stream_encoder_->TriggerQualityLow();
  3192. VerifyFpsEqResolutionMax(source.sink_wants(), kFpsLimit);
  3193. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3194. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3195. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3196. video_stream_encoder_->Stop();
  3197. }
  3198. TEST_F(VideoStreamEncoderTest, FailingInitEncodeDoesntCauseCrash) {
  3199. fake_encoder_.ForceInitEncodeFailure(true);
  3200. video_stream_encoder_->OnBitrateUpdated(
  3201. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3202. DataRate::bps(kTargetBitrateBps), 0, 0);
  3203. ResetEncoder("VP8", 2, 1, 1, false);
  3204. const int kFrameWidth = 1280;
  3205. const int kFrameHeight = 720;
  3206. video_source_.IncomingCapturedFrame(
  3207. CreateFrame(1, kFrameWidth, kFrameHeight));
  3208. ExpectDroppedFrame();
  3209. video_stream_encoder_->Stop();
  3210. }
  3211. // TODO(sprang): Extend this with fps throttling and any "balanced" extensions.
  3212. TEST_F(VideoStreamEncoderTest,
  3213. AdaptsResolutionOnOveruse_MaintainFramerateMode) {
  3214. video_stream_encoder_->OnBitrateUpdated(
  3215. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3216. DataRate::bps(kTargetBitrateBps), 0, 0);
  3217. const int kFrameWidth = 1280;
  3218. const int kFrameHeight = 720;
  3219. // Enabled default VideoAdapter downscaling. First step is 3/4, not 3/5 as
  3220. // requested by
  3221. // VideoStreamEncoder::VideoSourceProxy::RequestResolutionLowerThan().
  3222. video_source_.set_adaptation_enabled(true);
  3223. video_source_.IncomingCapturedFrame(
  3224. CreateFrame(1 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
  3225. WaitForEncodedFrame(kFrameWidth, kFrameHeight);
  3226. // Trigger CPU overuse, downscale by 3/4.
  3227. video_stream_encoder_->TriggerCpuOveruse();
  3228. video_source_.IncomingCapturedFrame(
  3229. CreateFrame(2 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
  3230. WaitForEncodedFrame((kFrameWidth * 3) / 4, (kFrameHeight * 3) / 4);
  3231. // Trigger CPU normal use, return to original resolution.
  3232. video_stream_encoder_->TriggerCpuNormalUsage();
  3233. video_source_.IncomingCapturedFrame(
  3234. CreateFrame(3 * kFrameIntervalMs, kFrameWidth, kFrameHeight));
  3235. WaitForEncodedFrame(kFrameWidth, kFrameHeight);
  3236. video_stream_encoder_->Stop();
  3237. }
  3238. TEST_F(VideoStreamEncoderTest,
  3239. AdaptsFramerateOnOveruse_MaintainResolutionMode) {
  3240. const int kFrameWidth = 1280;
  3241. const int kFrameHeight = 720;
  3242. video_stream_encoder_->OnBitrateUpdated(
  3243. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3244. DataRate::bps(kTargetBitrateBps), 0, 0);
  3245. video_stream_encoder_->SetSource(
  3246. &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  3247. video_source_.set_adaptation_enabled(true);
  3248. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  3249. video_source_.IncomingCapturedFrame(
  3250. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3251. WaitForEncodedFrame(timestamp_ms);
  3252. // Try to trigger overuse. No fps estimate available => no effect.
  3253. video_stream_encoder_->TriggerCpuOveruse();
  3254. // Insert frames for one second to get a stable estimate.
  3255. for (int i = 0; i < max_framerate_; ++i) {
  3256. timestamp_ms += kFrameIntervalMs;
  3257. video_source_.IncomingCapturedFrame(
  3258. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3259. WaitForEncodedFrame(timestamp_ms);
  3260. }
  3261. // Trigger CPU overuse, reduce framerate by 2/3.
  3262. video_stream_encoder_->TriggerCpuOveruse();
  3263. int num_frames_dropped = 0;
  3264. for (int i = 0; i < max_framerate_; ++i) {
  3265. timestamp_ms += kFrameIntervalMs;
  3266. video_source_.IncomingCapturedFrame(
  3267. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3268. if (!WaitForFrame(kFrameTimeoutMs)) {
  3269. ++num_frames_dropped;
  3270. } else {
  3271. sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
  3272. }
  3273. }
  3274. // Add some slack to account for frames dropped by the frame dropper.
  3275. const int kErrorMargin = 1;
  3276. EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
  3277. kErrorMargin);
  3278. // Trigger CPU overuse, reduce framerate by 2/3 again.
  3279. video_stream_encoder_->TriggerCpuOveruse();
  3280. num_frames_dropped = 0;
  3281. for (int i = 0; i <= max_framerate_; ++i) {
  3282. timestamp_ms += kFrameIntervalMs;
  3283. video_source_.IncomingCapturedFrame(
  3284. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3285. if (!WaitForFrame(kFrameTimeoutMs)) {
  3286. ++num_frames_dropped;
  3287. } else {
  3288. sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
  3289. }
  3290. }
  3291. EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 4 / 9),
  3292. kErrorMargin);
  3293. // Go back up one step.
  3294. video_stream_encoder_->TriggerCpuNormalUsage();
  3295. num_frames_dropped = 0;
  3296. for (int i = 0; i < max_framerate_; ++i) {
  3297. timestamp_ms += kFrameIntervalMs;
  3298. video_source_.IncomingCapturedFrame(
  3299. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3300. if (!WaitForFrame(kFrameTimeoutMs)) {
  3301. ++num_frames_dropped;
  3302. } else {
  3303. sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
  3304. }
  3305. }
  3306. EXPECT_NEAR(num_frames_dropped, max_framerate_ - (max_framerate_ * 2 / 3),
  3307. kErrorMargin);
  3308. // Go back up to original mode.
  3309. video_stream_encoder_->TriggerCpuNormalUsage();
  3310. num_frames_dropped = 0;
  3311. for (int i = 0; i < max_framerate_; ++i) {
  3312. timestamp_ms += kFrameIntervalMs;
  3313. video_source_.IncomingCapturedFrame(
  3314. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3315. if (!WaitForFrame(kFrameTimeoutMs)) {
  3316. ++num_frames_dropped;
  3317. } else {
  3318. sink_.CheckLastFrameSizeMatches(kFrameWidth, kFrameHeight);
  3319. }
  3320. }
  3321. EXPECT_NEAR(num_frames_dropped, 0, kErrorMargin);
  3322. video_stream_encoder_->Stop();
  3323. }
  3324. TEST_F(VideoStreamEncoderTest, DoesntAdaptDownPastMinFramerate) {
  3325. const int kFramerateFps = 5;
  3326. const int kFrameIntervalMs = rtc::kNumMillisecsPerSec / kFramerateFps;
  3327. const int kFrameWidth = 1280;
  3328. const int kFrameHeight = 720;
  3329. // Reconfigure encoder with two temporal layers and screensharing, which will
  3330. // disable frame dropping and make testing easier.
  3331. ResetEncoder("VP8", 1, 2, 1, true);
  3332. video_stream_encoder_->OnBitrateUpdated(
  3333. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3334. DataRate::bps(kTargetBitrateBps), 0, 0);
  3335. video_stream_encoder_->SetSource(
  3336. &video_source_, webrtc::DegradationPreference::MAINTAIN_RESOLUTION);
  3337. video_source_.set_adaptation_enabled(true);
  3338. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  3339. // Trigger overuse as much as we can.
  3340. rtc::VideoSinkWants last_wants;
  3341. do {
  3342. last_wants = video_source_.sink_wants();
  3343. // Insert frames to get a new fps estimate...
  3344. for (int j = 0; j < kFramerateFps; ++j) {
  3345. video_source_.IncomingCapturedFrame(
  3346. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3347. if (video_source_.last_sent_width()) {
  3348. sink_.WaitForEncodedFrame(timestamp_ms);
  3349. }
  3350. timestamp_ms += kFrameIntervalMs;
  3351. fake_clock_.AdvanceTime(TimeDelta::ms(kFrameIntervalMs));
  3352. }
  3353. // ...and then try to adapt again.
  3354. video_stream_encoder_->TriggerCpuOveruse();
  3355. } while (video_source_.sink_wants().max_framerate_fps <
  3356. last_wants.max_framerate_fps);
  3357. VerifyFpsEqResolutionMax(video_source_.sink_wants(), kMinFramerateFps);
  3358. video_stream_encoder_->Stop();
  3359. }
  3360. TEST_F(VideoStreamEncoderTest,
  3361. AdaptsResolutionAndFramerateForLowQuality_BalancedMode) {
  3362. const int kWidth = 1280;
  3363. const int kHeight = 720;
  3364. const int64_t kFrameIntervalMs = 150;
  3365. int64_t timestamp_ms = kFrameIntervalMs;
  3366. video_stream_encoder_->OnBitrateUpdated(
  3367. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3368. DataRate::bps(kTargetBitrateBps), 0, 0);
  3369. // Enable BALANCED preference, no initial limitation.
  3370. AdaptingFrameForwarder source;
  3371. source.set_adaptation_enabled(true);
  3372. video_stream_encoder_->SetSource(&source,
  3373. webrtc::DegradationPreference::BALANCED);
  3374. timestamp_ms += kFrameIntervalMs;
  3375. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3376. WaitForEncodedFrame(kWidth, kHeight);
  3377. VerifyFpsMaxResolutionMax(source.sink_wants());
  3378. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3379. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3380. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3381. // Trigger adapt down, expect scaled down resolution (960x540@30fps).
  3382. video_stream_encoder_->TriggerQualityLow();
  3383. timestamp_ms += kFrameIntervalMs;
  3384. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3385. WaitForEncodedFrame(timestamp_ms);
  3386. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  3387. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3388. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3389. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3390. // Trigger adapt down, expect scaled down resolution (640x360@30fps).
  3391. video_stream_encoder_->TriggerQualityLow();
  3392. timestamp_ms += kFrameIntervalMs;
  3393. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3394. WaitForEncodedFrame(timestamp_ms);
  3395. VerifyFpsMaxResolutionLt(source.sink_wants(), source.last_wants());
  3396. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3397. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3398. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3399. // Trigger adapt down, expect reduced fps (640x360@15fps).
  3400. video_stream_encoder_->TriggerQualityLow();
  3401. timestamp_ms += kFrameIntervalMs;
  3402. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3403. WaitForEncodedFrame(timestamp_ms);
  3404. VerifyFpsLtResolutionEq(source.sink_wants(), source.last_wants());
  3405. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3406. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3407. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3408. // Trigger adapt down, expect scaled down resolution (480x270@15fps).
  3409. video_stream_encoder_->TriggerQualityLow();
  3410. timestamp_ms += kFrameIntervalMs;
  3411. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3412. WaitForEncodedFrame(timestamp_ms);
  3413. VerifyFpsEqResolutionLt(source.sink_wants(), source.last_wants());
  3414. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3415. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3416. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3417. // Restrict bitrate, trigger adapt down, expect reduced fps (480x270@10fps).
  3418. video_stream_encoder_->TriggerQualityLow();
  3419. timestamp_ms += kFrameIntervalMs;
  3420. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3421. WaitForEncodedFrame(timestamp_ms);
  3422. VerifyFpsLtResolutionEq(source.sink_wants(), source.last_wants());
  3423. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3424. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3425. EXPECT_EQ(5, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3426. // Trigger adapt down, expect scaled down resolution (320x180@10fps).
  3427. video_stream_encoder_->TriggerQualityLow();
  3428. timestamp_ms += kFrameIntervalMs;
  3429. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3430. WaitForEncodedFrame(timestamp_ms);
  3431. VerifyFpsEqResolutionLt(source.sink_wants(), source.last_wants());
  3432. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3433. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3434. EXPECT_EQ(6, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3435. // Trigger adapt down, expect reduced fps (320x180@7fps).
  3436. video_stream_encoder_->TriggerQualityLow();
  3437. timestamp_ms += kFrameIntervalMs;
  3438. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3439. WaitForEncodedFrame(timestamp_ms);
  3440. VerifyFpsLtResolutionEq(source.sink_wants(), source.last_wants());
  3441. rtc::VideoSinkWants last_wants = source.sink_wants();
  3442. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3443. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3444. EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3445. // Trigger adapt down, min resolution reached, expect no change.
  3446. video_stream_encoder_->TriggerQualityLow();
  3447. timestamp_ms += kFrameIntervalMs;
  3448. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3449. WaitForEncodedFrame(timestamp_ms);
  3450. VerifyFpsEqResolutionEq(source.sink_wants(), last_wants);
  3451. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3452. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3453. EXPECT_EQ(7, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3454. // Trigger adapt down, expect expect increased fps (320x180@10fps).
  3455. video_stream_encoder_->TriggerQualityHigh();
  3456. timestamp_ms += kFrameIntervalMs;
  3457. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3458. WaitForEncodedFrame(timestamp_ms);
  3459. VerifyFpsGtResolutionEq(source.sink_wants(), source.last_wants());
  3460. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3461. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3462. EXPECT_EQ(8, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3463. // Trigger adapt up, expect upscaled resolution (480x270@10fps).
  3464. video_stream_encoder_->TriggerQualityHigh();
  3465. timestamp_ms += kFrameIntervalMs;
  3466. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3467. WaitForEncodedFrame(timestamp_ms);
  3468. VerifyFpsEqResolutionGt(source.sink_wants(), source.last_wants());
  3469. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3470. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3471. EXPECT_EQ(9, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3472. // Increase bitrate, trigger adapt up, expect increased fps (480x270@15fps).
  3473. video_stream_encoder_->TriggerQualityHigh();
  3474. timestamp_ms += kFrameIntervalMs;
  3475. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3476. WaitForEncodedFrame(timestamp_ms);
  3477. VerifyFpsGtResolutionEq(source.sink_wants(), source.last_wants());
  3478. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3479. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3480. EXPECT_EQ(10, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3481. // Trigger adapt up, expect upscaled resolution (640x360@15fps).
  3482. video_stream_encoder_->TriggerQualityHigh();
  3483. timestamp_ms += kFrameIntervalMs;
  3484. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3485. WaitForEncodedFrame(timestamp_ms);
  3486. VerifyFpsEqResolutionGt(source.sink_wants(), source.last_wants());
  3487. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3488. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3489. EXPECT_EQ(11, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3490. // Trigger adapt up, expect increased fps (640x360@30fps).
  3491. video_stream_encoder_->TriggerQualityHigh();
  3492. timestamp_ms += kFrameIntervalMs;
  3493. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3494. WaitForEncodedFrame(timestamp_ms);
  3495. VerifyFpsMaxResolutionEq(source.sink_wants(), source.last_wants());
  3496. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3497. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3498. EXPECT_EQ(12, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3499. // Trigger adapt up, expect upscaled resolution (960x540@30fps).
  3500. video_stream_encoder_->TriggerQualityHigh();
  3501. timestamp_ms += kFrameIntervalMs;
  3502. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3503. WaitForEncodedFrame(timestamp_ms);
  3504. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  3505. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3506. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3507. EXPECT_EQ(13, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3508. // Trigger adapt up, expect no restriction (1280x720fps@30fps).
  3509. video_stream_encoder_->TriggerQualityHigh();
  3510. timestamp_ms += kFrameIntervalMs;
  3511. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3512. WaitForEncodedFrame(kWidth, kHeight);
  3513. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  3514. VerifyFpsMaxResolutionMax(source.sink_wants());
  3515. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3516. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3517. EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3518. // Trigger adapt up, expect no change.
  3519. video_stream_encoder_->TriggerQualityHigh();
  3520. VerifyFpsMaxResolutionMax(source.sink_wants());
  3521. EXPECT_EQ(14, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3522. video_stream_encoder_->Stop();
  3523. }
  3524. TEST_F(VideoStreamEncoderTest, AdaptWithTwoReasonsAndDifferentOrder_Framerate) {
  3525. const int kWidth = 1280;
  3526. const int kHeight = 720;
  3527. const int64_t kFrameIntervalMs = 150;
  3528. int64_t timestamp_ms = kFrameIntervalMs;
  3529. video_stream_encoder_->OnBitrateUpdated(
  3530. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3531. DataRate::bps(kTargetBitrateBps), 0, 0);
  3532. // Enable BALANCED preference, no initial limitation.
  3533. AdaptingFrameForwarder source;
  3534. source.set_adaptation_enabled(true);
  3535. video_stream_encoder_->SetSource(&source,
  3536. webrtc::DegradationPreference::BALANCED);
  3537. timestamp_ms += kFrameIntervalMs;
  3538. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3539. WaitForEncodedFrame(kWidth, kHeight);
  3540. VerifyFpsMaxResolutionMax(source.sink_wants());
  3541. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3542. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3543. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3544. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3545. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3546. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3547. // Trigger cpu adapt down, expect scaled down resolution (960x540@30fps).
  3548. video_stream_encoder_->TriggerCpuOveruse();
  3549. timestamp_ms += kFrameIntervalMs;
  3550. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3551. WaitForEncodedFrame(timestamp_ms);
  3552. VerifyFpsMaxResolutionLt(source.sink_wants(), kWidth * kHeight);
  3553. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3554. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3555. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  3556. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3557. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3558. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3559. // Trigger cpu adapt down, expect scaled down resolution (640x360@30fps).
  3560. video_stream_encoder_->TriggerCpuOveruse();
  3561. timestamp_ms += kFrameIntervalMs;
  3562. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3563. WaitForEncodedFrame(timestamp_ms);
  3564. VerifyFpsMaxResolutionLt(source.sink_wants(), source.last_wants());
  3565. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3566. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3567. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  3568. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3569. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3570. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3571. // Trigger quality adapt down, expect reduced fps (640x360@15fps).
  3572. video_stream_encoder_->TriggerQualityLow();
  3573. timestamp_ms += kFrameIntervalMs;
  3574. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3575. WaitForEncodedFrame(timestamp_ms);
  3576. VerifyFpsLtResolutionEq(source.sink_wants(), source.last_wants());
  3577. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3578. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3579. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  3580. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3581. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3582. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3583. // Trigger cpu adapt up, expect increased fps (640x360@30fps).
  3584. video_stream_encoder_->TriggerCpuNormalUsage();
  3585. timestamp_ms += kFrameIntervalMs;
  3586. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3587. WaitForEncodedFrame(timestamp_ms);
  3588. VerifyFpsMaxResolutionEq(source.sink_wants(), source.last_wants());
  3589. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3590. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3591. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  3592. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3593. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3594. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3595. // Trigger quality adapt up, expect upscaled resolution (960x540@30fps).
  3596. video_stream_encoder_->TriggerQualityHigh();
  3597. timestamp_ms += kFrameIntervalMs;
  3598. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3599. WaitForEncodedFrame(timestamp_ms);
  3600. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  3601. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3602. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3603. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_resolution);
  3604. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3605. EXPECT_EQ(3, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3606. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3607. // Trigger cpu adapt up, expect no restriction (1280x720fps@30fps).
  3608. video_stream_encoder_->TriggerCpuNormalUsage();
  3609. timestamp_ms += kFrameIntervalMs;
  3610. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3611. WaitForEncodedFrame(kWidth, kHeight);
  3612. VerifyFpsMaxResolutionGt(source.sink_wants(), source.last_wants());
  3613. VerifyFpsMaxResolutionMax(source.sink_wants());
  3614. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3615. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3616. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3617. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3618. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3619. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3620. // Trigger adapt up, expect no change.
  3621. video_stream_encoder_->TriggerQualityHigh();
  3622. VerifyFpsMaxResolutionMax(source.sink_wants());
  3623. EXPECT_EQ(4, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3624. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3625. video_stream_encoder_->Stop();
  3626. }
  3627. TEST_F(VideoStreamEncoderTest,
  3628. AdaptWithTwoReasonsAndDifferentOrder_Resolution) {
  3629. const int kWidth = 640;
  3630. const int kHeight = 360;
  3631. const int kFpsLimit = 15;
  3632. const int64_t kFrameIntervalMs = 150;
  3633. int64_t timestamp_ms = kFrameIntervalMs;
  3634. video_stream_encoder_->OnBitrateUpdated(
  3635. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3636. DataRate::bps(kTargetBitrateBps), 0, 0);
  3637. // Enable BALANCED preference, no initial limitation.
  3638. AdaptingFrameForwarder source;
  3639. source.set_adaptation_enabled(true);
  3640. video_stream_encoder_->SetSource(&source,
  3641. webrtc::DegradationPreference::BALANCED);
  3642. timestamp_ms += kFrameIntervalMs;
  3643. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3644. WaitForEncodedFrame(kWidth, kHeight);
  3645. VerifyFpsMaxResolutionMax(source.sink_wants());
  3646. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3647. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3648. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3649. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3650. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3651. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3652. // Trigger cpu adapt down, expect scaled down framerate (640x360@15fps).
  3653. video_stream_encoder_->TriggerCpuOveruse();
  3654. timestamp_ms += kFrameIntervalMs;
  3655. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3656. WaitForEncodedFrame(timestamp_ms);
  3657. VerifyFpsEqResolutionMax(source.sink_wants(), kFpsLimit);
  3658. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3659. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3660. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3661. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
  3662. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3663. EXPECT_EQ(0, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3664. // Trigger quality adapt down, expect scaled down resolution (480x270@15fps).
  3665. video_stream_encoder_->TriggerQualityLow();
  3666. timestamp_ms += kFrameIntervalMs;
  3667. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3668. WaitForEncodedFrame(timestamp_ms);
  3669. VerifyFpsEqResolutionLt(source.sink_wants(), source.last_wants());
  3670. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_resolution);
  3671. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3672. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3673. EXPECT_TRUE(stats_proxy_->GetStats().cpu_limited_framerate);
  3674. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3675. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3676. // Trigger cpu adapt up, expect upscaled resolution (640x360@15fps).
  3677. video_stream_encoder_->TriggerCpuNormalUsage();
  3678. timestamp_ms += kFrameIntervalMs;
  3679. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3680. WaitForEncodedFrame(timestamp_ms);
  3681. VerifyFpsEqResolutionGt(source.sink_wants(), source.last_wants());
  3682. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3683. EXPECT_TRUE(stats_proxy_->GetStats().bw_limited_framerate);
  3684. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3685. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3686. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3687. EXPECT_EQ(1, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3688. // Trigger quality adapt up, expect increased fps (640x360@30fps).
  3689. video_stream_encoder_->TriggerQualityHigh();
  3690. timestamp_ms += kFrameIntervalMs;
  3691. source.IncomingCapturedFrame(CreateFrame(timestamp_ms, kWidth, kHeight));
  3692. WaitForEncodedFrame(timestamp_ms);
  3693. VerifyFpsMaxResolutionMax(source.sink_wants());
  3694. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_resolution);
  3695. EXPECT_FALSE(stats_proxy_->GetStats().bw_limited_framerate);
  3696. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_resolution);
  3697. EXPECT_FALSE(stats_proxy_->GetStats().cpu_limited_framerate);
  3698. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3699. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3700. // Trigger adapt up, expect no change.
  3701. video_stream_encoder_->TriggerQualityHigh();
  3702. VerifyFpsMaxResolutionMax(source.sink_wants());
  3703. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_cpu_adapt_changes);
  3704. EXPECT_EQ(2, stats_proxy_->GetStats().number_of_quality_adapt_changes);
  3705. video_stream_encoder_->Stop();
  3706. }
  3707. TEST_F(VideoStreamEncoderTest, AcceptsFullHdAdaptedDownSimulcastFrames) {
  3708. const int kFrameWidth = 1920;
  3709. const int kFrameHeight = 1080;
  3710. // 3/4 of 1920.
  3711. const int kAdaptedFrameWidth = 1440;
  3712. // 3/4 of 1080 rounded down to multiple of 4.
  3713. const int kAdaptedFrameHeight = 808;
  3714. const int kFramerate = 24;
  3715. video_stream_encoder_->OnBitrateUpdated(
  3716. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3717. DataRate::bps(kTargetBitrateBps), 0, 0);
  3718. // Trigger reconfigure encoder (without resetting the entire instance).
  3719. VideoEncoderConfig video_encoder_config;
  3720. video_encoder_config.codec_type = kVideoCodecVP8;
  3721. video_encoder_config.max_bitrate_bps = kTargetBitrateBps;
  3722. video_encoder_config.number_of_streams = 1;
  3723. video_encoder_config.video_stream_factory =
  3724. new rtc::RefCountedObject<CroppingVideoStreamFactory>(1, kFramerate);
  3725. video_stream_encoder_->ConfigureEncoder(std::move(video_encoder_config),
  3726. kMaxPayloadLength);
  3727. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  3728. video_source_.set_adaptation_enabled(true);
  3729. video_source_.IncomingCapturedFrame(
  3730. CreateFrame(1, kFrameWidth, kFrameHeight));
  3731. WaitForEncodedFrame(kFrameWidth, kFrameHeight);
  3732. // Trigger CPU overuse, downscale by 3/4.
  3733. video_stream_encoder_->TriggerCpuOveruse();
  3734. video_source_.IncomingCapturedFrame(
  3735. CreateFrame(2, kFrameWidth, kFrameHeight));
  3736. WaitForEncodedFrame(kAdaptedFrameWidth, kAdaptedFrameHeight);
  3737. video_stream_encoder_->Stop();
  3738. }
  3739. TEST_F(VideoStreamEncoderTest, PeriodicallyUpdatesChannelParameters) {
  3740. const int kFrameWidth = 1280;
  3741. const int kFrameHeight = 720;
  3742. const int kLowFps = 2;
  3743. const int kHighFps = 30;
  3744. video_stream_encoder_->OnBitrateUpdated(
  3745. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3746. DataRate::bps(kTargetBitrateBps), 0, 0);
  3747. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  3748. max_framerate_ = kLowFps;
  3749. // Insert 2 seconds of 2fps video.
  3750. for (int i = 0; i < kLowFps * 2; ++i) {
  3751. video_source_.IncomingCapturedFrame(
  3752. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3753. WaitForEncodedFrame(timestamp_ms);
  3754. timestamp_ms += 1000 / kLowFps;
  3755. }
  3756. // Make sure encoder is updated with new target.
  3757. video_stream_encoder_->OnBitrateUpdated(
  3758. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3759. DataRate::bps(kTargetBitrateBps), 0, 0);
  3760. video_source_.IncomingCapturedFrame(
  3761. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3762. WaitForEncodedFrame(timestamp_ms);
  3763. timestamp_ms += 1000 / kLowFps;
  3764. EXPECT_EQ(kLowFps, fake_encoder_.GetConfiguredInputFramerate());
  3765. // Insert 30fps frames for just a little more than the forced update period.
  3766. const int kVcmTimerIntervalFrames = (kProcessIntervalMs * kHighFps) / 1000;
  3767. const int kFrameIntervalMs = 1000 / kHighFps;
  3768. max_framerate_ = kHighFps;
  3769. for (int i = 0; i < kVcmTimerIntervalFrames + 2; ++i) {
  3770. video_source_.IncomingCapturedFrame(
  3771. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3772. // Wait for encoded frame, but skip ahead if it doesn't arrive as it might
  3773. // be dropped if the encoder hans't been updated with the new higher target
  3774. // framerate yet, causing it to overshoot the target bitrate and then
  3775. // suffering the wrath of the media optimizer.
  3776. TimedWaitForEncodedFrame(timestamp_ms, 2 * kFrameIntervalMs);
  3777. timestamp_ms += kFrameIntervalMs;
  3778. }
  3779. // Don expect correct measurement just yet, but it should be higher than
  3780. // before.
  3781. EXPECT_GT(fake_encoder_.GetConfiguredInputFramerate(), kLowFps);
  3782. video_stream_encoder_->Stop();
  3783. }
  3784. TEST_F(VideoStreamEncoderTest, DoesNotUpdateBitrateAllocationWhenSuspended) {
  3785. const int kFrameWidth = 1280;
  3786. const int kFrameHeight = 720;
  3787. const int kTargetBitrateBps = 1000000;
  3788. MockBitrateObserver bitrate_observer;
  3789. video_stream_encoder_->SetBitrateAllocationObserver(&bitrate_observer);
  3790. video_stream_encoder_->OnBitrateUpdated(
  3791. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3792. DataRate::bps(kTargetBitrateBps), 0, 0);
  3793. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  3794. // Insert a first video frame, causes another bitrate update.
  3795. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  3796. EXPECT_CALL(bitrate_observer, OnBitrateAllocationUpdated(_)).Times(1);
  3797. video_source_.IncomingCapturedFrame(
  3798. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3799. WaitForEncodedFrame(timestamp_ms);
  3800. // Next, simulate video suspension due to pacer queue overrun.
  3801. video_stream_encoder_->OnBitrateUpdated(DataRate::bps(0), DataRate::bps(0),
  3802. DataRate::bps(0), 0, 1);
  3803. // Skip ahead until a new periodic parameter update should have occured.
  3804. timestamp_ms += kProcessIntervalMs;
  3805. fake_clock_.AdvanceTime(TimeDelta::ms(kProcessIntervalMs));
  3806. // Bitrate observer should not be called.
  3807. EXPECT_CALL(bitrate_observer, OnBitrateAllocationUpdated(_)).Times(0);
  3808. video_source_.IncomingCapturedFrame(
  3809. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3810. ExpectDroppedFrame();
  3811. video_stream_encoder_->Stop();
  3812. }
  3813. TEST_F(VideoStreamEncoderTest,
  3814. DefaultCpuAdaptationThresholdsForSoftwareEncoder) {
  3815. const int kFrameWidth = 1280;
  3816. const int kFrameHeight = 720;
  3817. const CpuOveruseOptions default_options;
  3818. video_stream_encoder_->OnBitrateUpdated(
  3819. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3820. DataRate::bps(kTargetBitrateBps), 0, 0);
  3821. video_source_.IncomingCapturedFrame(
  3822. CreateFrame(1, kFrameWidth, kFrameHeight));
  3823. WaitForEncodedFrame(1);
  3824. EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
  3825. .low_encode_usage_threshold_percent,
  3826. default_options.low_encode_usage_threshold_percent);
  3827. EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
  3828. .high_encode_usage_threshold_percent,
  3829. default_options.high_encode_usage_threshold_percent);
  3830. video_stream_encoder_->Stop();
  3831. }
  3832. TEST_F(VideoStreamEncoderTest,
  3833. HigherCpuAdaptationThresholdsForHardwareEncoder) {
  3834. const int kFrameWidth = 1280;
  3835. const int kFrameHeight = 720;
  3836. CpuOveruseOptions hardware_options;
  3837. hardware_options.low_encode_usage_threshold_percent = 150;
  3838. hardware_options.high_encode_usage_threshold_percent = 200;
  3839. fake_encoder_.SetIsHardwareAccelerated(true);
  3840. video_stream_encoder_->OnBitrateUpdated(
  3841. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3842. DataRate::bps(kTargetBitrateBps), 0, 0);
  3843. video_source_.IncomingCapturedFrame(
  3844. CreateFrame(1, kFrameWidth, kFrameHeight));
  3845. WaitForEncodedFrame(1);
  3846. EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
  3847. .low_encode_usage_threshold_percent,
  3848. hardware_options.low_encode_usage_threshold_percent);
  3849. EXPECT_EQ(video_stream_encoder_->overuse_detector_proxy_->GetOptions()
  3850. .high_encode_usage_threshold_percent,
  3851. hardware_options.high_encode_usage_threshold_percent);
  3852. video_stream_encoder_->Stop();
  3853. }
  3854. TEST_F(VideoStreamEncoderTest, DropsFramesWhenEncoderOvershoots) {
  3855. const int kFrameWidth = 320;
  3856. const int kFrameHeight = 240;
  3857. const int kFps = 30;
  3858. const int kTargetBitrateBps = 120000;
  3859. const int kNumFramesInRun = kFps * 5; // Runs of five seconds.
  3860. video_stream_encoder_->OnBitrateUpdated(
  3861. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3862. DataRate::bps(kTargetBitrateBps), 0, 0);
  3863. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  3864. max_framerate_ = kFps;
  3865. // Insert 3 seconds of video, verify number of drops with normal bitrate.
  3866. fake_encoder_.SimulateOvershoot(1.0);
  3867. int num_dropped = 0;
  3868. for (int i = 0; i < kNumFramesInRun; ++i) {
  3869. video_source_.IncomingCapturedFrame(
  3870. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3871. // Wait up to two frame durations for a frame to arrive.
  3872. if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
  3873. ++num_dropped;
  3874. }
  3875. timestamp_ms += 1000 / kFps;
  3876. }
  3877. // Framerate should be measured to be near the expected target rate.
  3878. EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
  3879. // Frame drops should be within 5% of expected 0%.
  3880. EXPECT_NEAR(num_dropped, 0, 5 * kNumFramesInRun / 100);
  3881. // Make encoder produce frames at double the expected bitrate during 3 seconds
  3882. // of video, verify number of drops. Rate needs to be slightly changed in
  3883. // order to force the rate to be reconfigured.
  3884. double overshoot_factor = 2.0;
  3885. if (RateControlSettings::ParseFromFieldTrials().UseEncoderBitrateAdjuster()) {
  3886. // With bitrate adjuster, when need to overshoot even more to trigger
  3887. // frame dropping.
  3888. overshoot_factor *= 2;
  3889. }
  3890. fake_encoder_.SimulateOvershoot(overshoot_factor);
  3891. video_stream_encoder_->OnBitrateUpdated(
  3892. DataRate::bps(kTargetBitrateBps + 1000),
  3893. DataRate::bps(kTargetBitrateBps + 1000),
  3894. DataRate::bps(kTargetBitrateBps + 1000), 0, 0);
  3895. num_dropped = 0;
  3896. for (int i = 0; i < kNumFramesInRun; ++i) {
  3897. video_source_.IncomingCapturedFrame(
  3898. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3899. // Wait up to two frame durations for a frame to arrive.
  3900. if (!TimedWaitForEncodedFrame(timestamp_ms, 2 * 1000 / kFps)) {
  3901. ++num_dropped;
  3902. }
  3903. timestamp_ms += 1000 / kFps;
  3904. }
  3905. video_stream_encoder_->OnBitrateUpdated(
  3906. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3907. DataRate::bps(kTargetBitrateBps), 0, 0);
  3908. // Target framerate should be still be near the expected target, despite
  3909. // the frame drops.
  3910. EXPECT_NEAR(fake_encoder_.GetLastFramerate(), kFps, 1);
  3911. // Frame drops should be within 5% of expected 50%.
  3912. EXPECT_NEAR(num_dropped, kNumFramesInRun / 2, 5 * kNumFramesInRun / 100);
  3913. video_stream_encoder_->Stop();
  3914. }
  3915. TEST_F(VideoStreamEncoderTest, ConfiguresCorrectFrameRate) {
  3916. const int kFrameWidth = 320;
  3917. const int kFrameHeight = 240;
  3918. const int kActualInputFps = 24;
  3919. const int kTargetBitrateBps = 120000;
  3920. ASSERT_GT(max_framerate_, kActualInputFps);
  3921. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  3922. max_framerate_ = kActualInputFps;
  3923. video_stream_encoder_->OnBitrateUpdated(
  3924. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3925. DataRate::bps(kTargetBitrateBps), 0, 0);
  3926. // Insert 3 seconds of video, with an input fps lower than configured max.
  3927. for (int i = 0; i < kActualInputFps * 3; ++i) {
  3928. video_source_.IncomingCapturedFrame(
  3929. CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight));
  3930. // Wait up to two frame durations for a frame to arrive.
  3931. WaitForEncodedFrame(timestamp_ms);
  3932. timestamp_ms += 1000 / kActualInputFps;
  3933. }
  3934. EXPECT_NEAR(kActualInputFps, fake_encoder_.GetLastFramerate(), 1);
  3935. video_stream_encoder_->Stop();
  3936. }
  3937. TEST_F(VideoStreamEncoderTest, AccumulatesUpdateRectOnDroppedFrames) {
  3938. VideoFrame::UpdateRect rect;
  3939. video_stream_encoder_->OnBitrateUpdated(
  3940. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3941. DataRate::bps(kTargetBitrateBps), 0, 0);
  3942. fake_encoder_.BlockNextEncode();
  3943. video_source_.IncomingCapturedFrame(
  3944. CreateFrameWithUpdatedPixel(1, nullptr, 0));
  3945. WaitForEncodedFrame(1);
  3946. // On the very first frame full update should be forced.
  3947. rect = fake_encoder_.GetLastUpdateRect();
  3948. EXPECT_EQ(rect.offset_x, 0);
  3949. EXPECT_EQ(rect.offset_y, 0);
  3950. EXPECT_EQ(rect.height, codec_height_);
  3951. EXPECT_EQ(rect.width, codec_width_);
  3952. // Here, the encoder thread will be blocked in the TestEncoder waiting for a
  3953. // call to ContinueEncode.
  3954. video_source_.IncomingCapturedFrame(
  3955. CreateFrameWithUpdatedPixel(2, nullptr, 1));
  3956. ExpectDroppedFrame();
  3957. video_source_.IncomingCapturedFrame(
  3958. CreateFrameWithUpdatedPixel(3, nullptr, 10));
  3959. ExpectDroppedFrame();
  3960. fake_encoder_.ContinueEncode();
  3961. WaitForEncodedFrame(3);
  3962. // Updates to pixels 1 and 10 should be accumulated to one 10x1 rect.
  3963. rect = fake_encoder_.GetLastUpdateRect();
  3964. EXPECT_EQ(rect.offset_x, 1);
  3965. EXPECT_EQ(rect.offset_y, 0);
  3966. EXPECT_EQ(rect.width, 10);
  3967. EXPECT_EQ(rect.height, 1);
  3968. video_source_.IncomingCapturedFrame(
  3969. CreateFrameWithUpdatedPixel(4, nullptr, 0));
  3970. WaitForEncodedFrame(4);
  3971. // Previous frame was encoded, so no accumulation should happen.
  3972. rect = fake_encoder_.GetLastUpdateRect();
  3973. EXPECT_EQ(rect.offset_x, 0);
  3974. EXPECT_EQ(rect.offset_y, 0);
  3975. EXPECT_EQ(rect.width, 1);
  3976. EXPECT_EQ(rect.height, 1);
  3977. video_stream_encoder_->Stop();
  3978. }
  3979. TEST_F(VideoStreamEncoderTest, SetsFrameTypes) {
  3980. video_stream_encoder_->OnBitrateUpdated(
  3981. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  3982. DataRate::bps(kTargetBitrateBps), 0, 0);
  3983. // First frame is always keyframe.
  3984. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  3985. WaitForEncodedFrame(1);
  3986. EXPECT_THAT(
  3987. fake_encoder_.LastFrameTypes(),
  3988. ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
  3989. // Insert delta frame.
  3990. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  3991. WaitForEncodedFrame(2);
  3992. EXPECT_THAT(
  3993. fake_encoder_.LastFrameTypes(),
  3994. ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
  3995. // Request next frame be a key-frame.
  3996. video_stream_encoder_->SendKeyFrame();
  3997. video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
  3998. WaitForEncodedFrame(3);
  3999. EXPECT_THAT(
  4000. fake_encoder_.LastFrameTypes(),
  4001. ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
  4002. video_stream_encoder_->Stop();
  4003. }
  4004. TEST_F(VideoStreamEncoderTest, SetsFrameTypesSimulcast) {
  4005. // Setup simulcast with three streams.
  4006. ResetEncoder("VP8", 3, 1, 1, false);
  4007. video_stream_encoder_->OnBitrateUpdated(
  4008. DataRate::bps(kSimulcastTargetBitrateBps),
  4009. DataRate::bps(kSimulcastTargetBitrateBps),
  4010. DataRate::bps(kSimulcastTargetBitrateBps), 0, 0);
  4011. // Wait for all three layers before triggering event.
  4012. sink_.SetNumExpectedLayers(3);
  4013. // First frame is always keyframe.
  4014. video_source_.IncomingCapturedFrame(CreateFrame(1, nullptr));
  4015. WaitForEncodedFrame(1);
  4016. EXPECT_THAT(fake_encoder_.LastFrameTypes(),
  4017. ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
  4018. VideoFrameType::kVideoFrameKey,
  4019. VideoFrameType::kVideoFrameKey}));
  4020. // Insert delta frame.
  4021. video_source_.IncomingCapturedFrame(CreateFrame(2, nullptr));
  4022. WaitForEncodedFrame(2);
  4023. EXPECT_THAT(fake_encoder_.LastFrameTypes(),
  4024. ::testing::ElementsAreArray({VideoFrameType::kVideoFrameDelta,
  4025. VideoFrameType::kVideoFrameDelta,
  4026. VideoFrameType::kVideoFrameDelta}));
  4027. // Request next frame be a key-frame.
  4028. // Only first stream is configured to produce key-frame.
  4029. video_stream_encoder_->SendKeyFrame();
  4030. video_source_.IncomingCapturedFrame(CreateFrame(3, nullptr));
  4031. WaitForEncodedFrame(3);
  4032. // TODO(webrtc:10615): Map keyframe request to spatial layer. Currently
  4033. // keyframe request on any layer triggers keyframe on all layers.
  4034. EXPECT_THAT(fake_encoder_.LastFrameTypes(),
  4035. ::testing::ElementsAreArray({VideoFrameType::kVideoFrameKey,
  4036. VideoFrameType::kVideoFrameKey,
  4037. VideoFrameType::kVideoFrameKey}));
  4038. video_stream_encoder_->Stop();
  4039. }
  4040. TEST_F(VideoStreamEncoderTest, RequestKeyframeInternalSource) {
  4041. // Configure internal source factory and setup test again.
  4042. encoder_factory_.SetHasInternalSource(true);
  4043. ResetEncoder("VP8", 1, 1, 1, false);
  4044. video_stream_encoder_->OnBitrateUpdated(
  4045. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  4046. DataRate::bps(kTargetBitrateBps), 0, 0);
  4047. // Call encoder directly, simulating internal source where encoded frame
  4048. // callback in VideoStreamEncoder is called despite no OnFrame().
  4049. fake_encoder_.InjectFrame(CreateFrame(1, nullptr), true);
  4050. EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
  4051. EXPECT_THAT(
  4052. fake_encoder_.LastFrameTypes(),
  4053. ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
  4054. const std::vector<VideoFrameType> kDeltaFrame = {
  4055. VideoFrameType::kVideoFrameDelta};
  4056. // Need to set timestamp manually since manually for injected frame.
  4057. VideoFrame frame = CreateFrame(101, nullptr);
  4058. frame.set_timestamp(101);
  4059. fake_encoder_.InjectFrame(frame, false);
  4060. EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
  4061. EXPECT_THAT(
  4062. fake_encoder_.LastFrameTypes(),
  4063. ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameDelta}));
  4064. // Request key-frame. The forces a dummy frame down into the encoder.
  4065. fake_encoder_.ExpectNullFrame();
  4066. video_stream_encoder_->SendKeyFrame();
  4067. EXPECT_TRUE(WaitForFrame(kDefaultTimeoutMs));
  4068. EXPECT_THAT(
  4069. fake_encoder_.LastFrameTypes(),
  4070. ::testing::ElementsAre(VideoFrameType{VideoFrameType::kVideoFrameKey}));
  4071. video_stream_encoder_->Stop();
  4072. }
  4073. TEST_F(VideoStreamEncoderTest, AdjustsTimestampInternalSource) {
  4074. // Configure internal source factory and setup test again.
  4075. encoder_factory_.SetHasInternalSource(true);
  4076. ResetEncoder("VP8", 1, 1, 1, false);
  4077. video_stream_encoder_->OnBitrateUpdated(
  4078. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  4079. DataRate::bps(kTargetBitrateBps), 0, 0);
  4080. int64_t timestamp = 1;
  4081. EncodedImage image;
  4082. image.SetEncodedData(
  4083. EncodedImageBuffer::Create(kTargetBitrateBps / kDefaultFramerate / 8));
  4084. image.capture_time_ms_ = ++timestamp;
  4085. image.SetTimestamp(static_cast<uint32_t>(timestamp * 90));
  4086. const int64_t kEncodeFinishDelayMs = 10;
  4087. image.timing_.encode_start_ms = timestamp;
  4088. image.timing_.encode_finish_ms = timestamp + kEncodeFinishDelayMs;
  4089. fake_encoder_.InjectEncodedImage(image);
  4090. // Wait for frame without incrementing clock.
  4091. EXPECT_TRUE(sink_.WaitForFrame(kDefaultTimeoutMs));
  4092. // Frame is captured kEncodeFinishDelayMs before it's encoded, so restored
  4093. // capture timestamp should be kEncodeFinishDelayMs in the past.
  4094. EXPECT_EQ(sink_.GetLastCaptureTimeMs(),
  4095. fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec -
  4096. kEncodeFinishDelayMs);
  4097. video_stream_encoder_->Stop();
  4098. }
  4099. TEST_F(VideoStreamEncoderTest, DoesNotRewriteH264BitstreamWithOptimalSps) {
  4100. // Configure internal source factory and setup test again.
  4101. encoder_factory_.SetHasInternalSource(true);
  4102. ResetEncoder("H264", 1, 1, 1, false);
  4103. EncodedImage image(optimal_sps, sizeof(optimal_sps), sizeof(optimal_sps));
  4104. image._frameType = VideoFrameType::kVideoFrameKey;
  4105. CodecSpecificInfo codec_specific_info;
  4106. codec_specific_info.codecType = kVideoCodecH264;
  4107. RTPFragmentationHeader fragmentation;
  4108. fragmentation.VerifyAndAllocateFragmentationHeader(1);
  4109. fragmentation.fragmentationOffset[0] = 4;
  4110. fragmentation.fragmentationLength[0] = sizeof(optimal_sps) - 4;
  4111. fake_encoder_.InjectEncodedImage(image, &codec_specific_info, &fragmentation);
  4112. EXPECT_TRUE(sink_.WaitForFrame(kDefaultTimeoutMs));
  4113. EXPECT_THAT(sink_.GetLastEncodedImageData(),
  4114. testing::ElementsAreArray(optimal_sps));
  4115. RTPFragmentationHeader last_fragmentation = sink_.GetLastFragmentation();
  4116. ASSERT_THAT(last_fragmentation.fragmentationVectorSize, 1U);
  4117. EXPECT_EQ(last_fragmentation.fragmentationOffset[0], 4U);
  4118. EXPECT_EQ(last_fragmentation.fragmentationLength[0], sizeof(optimal_sps) - 4);
  4119. video_stream_encoder_->Stop();
  4120. }
  4121. TEST_F(VideoStreamEncoderTest, RewritesH264BitstreamWithNonOptimalSps) {
  4122. uint8_t original_sps[] = {0, 0, 0, 1, H264::NaluType::kSps,
  4123. 0x00, 0x00, 0x03, 0x03, 0xF4,
  4124. 0x05, 0x03, 0xC7, 0xC0};
  4125. // Configure internal source factory and setup test again.
  4126. encoder_factory_.SetHasInternalSource(true);
  4127. ResetEncoder("H264", 1, 1, 1, false);
  4128. EncodedImage image(original_sps, sizeof(original_sps), sizeof(original_sps));
  4129. image._frameType = VideoFrameType::kVideoFrameKey;
  4130. CodecSpecificInfo codec_specific_info;
  4131. codec_specific_info.codecType = kVideoCodecH264;
  4132. RTPFragmentationHeader fragmentation;
  4133. fragmentation.VerifyAndAllocateFragmentationHeader(1);
  4134. fragmentation.fragmentationOffset[0] = 4;
  4135. fragmentation.fragmentationLength[0] = sizeof(original_sps) - 4;
  4136. fake_encoder_.InjectEncodedImage(image, &codec_specific_info, &fragmentation);
  4137. EXPECT_TRUE(sink_.WaitForFrame(kDefaultTimeoutMs));
  4138. EXPECT_THAT(sink_.GetLastEncodedImageData(),
  4139. testing::ElementsAreArray(optimal_sps));
  4140. RTPFragmentationHeader last_fragmentation = sink_.GetLastFragmentation();
  4141. ASSERT_THAT(last_fragmentation.fragmentationVectorSize, 1U);
  4142. EXPECT_EQ(last_fragmentation.fragmentationOffset[0], 4U);
  4143. EXPECT_EQ(last_fragmentation.fragmentationLength[0], sizeof(optimal_sps) - 4);
  4144. video_stream_encoder_->Stop();
  4145. }
  4146. TEST_F(VideoStreamEncoderTest, CopiesVideoFrameMetadataAfterDownscale) {
  4147. const int kFrameWidth = 1280;
  4148. const int kFrameHeight = 720;
  4149. const int kTargetBitrateBps = 300000; // To low for HD resolution.
  4150. video_stream_encoder_->OnBitrateUpdated(
  4151. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  4152. DataRate::bps(kTargetBitrateBps), 0, 0);
  4153. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  4154. // Insert a first video frame. It should be dropped because of downscale in
  4155. // resolution.
  4156. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  4157. VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
  4158. frame.set_rotation(kVideoRotation_270);
  4159. video_source_.IncomingCapturedFrame(frame);
  4160. ExpectDroppedFrame();
  4161. // Second frame is downscaled.
  4162. timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  4163. frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
  4164. frame.set_rotation(kVideoRotation_90);
  4165. video_source_.IncomingCapturedFrame(frame);
  4166. WaitForEncodedFrame(timestamp_ms);
  4167. sink_.CheckLastFrameRotationMatches(kVideoRotation_90);
  4168. // Insert another frame, also downscaled.
  4169. timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  4170. frame = CreateFrame(timestamp_ms, kFrameWidth / 2, kFrameHeight / 2);
  4171. frame.set_rotation(kVideoRotation_180);
  4172. video_source_.IncomingCapturedFrame(frame);
  4173. WaitForEncodedFrame(timestamp_ms);
  4174. sink_.CheckLastFrameRotationMatches(kVideoRotation_180);
  4175. video_stream_encoder_->Stop();
  4176. }
  4177. TEST_F(VideoStreamEncoderTest, BandwidthAllocationLowerBound) {
  4178. const int kFrameWidth = 320;
  4179. const int kFrameHeight = 180;
  4180. // Initial rate.
  4181. video_stream_encoder_->OnBitrateUpdated(
  4182. /*target_bitrate=*/DataRate::kbps(300),
  4183. /*stable_target_bitrate=*/DataRate::kbps(300),
  4184. /*link_allocation=*/DataRate::kbps(300),
  4185. /*fraction_lost=*/0,
  4186. /*rtt_ms=*/0);
  4187. // Insert a first video frame so that encoder gets configured.
  4188. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  4189. VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
  4190. frame.set_rotation(kVideoRotation_270);
  4191. video_source_.IncomingCapturedFrame(frame);
  4192. WaitForEncodedFrame(timestamp_ms);
  4193. // Set a target rate below the minimum allowed by the codec settings.
  4194. VideoCodec codec_config = fake_encoder_.codec_config();
  4195. DataRate min_rate = DataRate::kbps(codec_config.minBitrate);
  4196. DataRate target_rate = min_rate - DataRate::kbps(1);
  4197. video_stream_encoder_->OnBitrateUpdated(
  4198. /*target_bitrate=*/target_rate,
  4199. /*stable_target_bitrate=*/target_rate,
  4200. /*link_allocation=*/target_rate,
  4201. /*fraction_lost=*/0,
  4202. /*rtt_ms=*/0);
  4203. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  4204. // Target bitrate and bandwidth allocation should both be capped at min_rate.
  4205. auto rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
  4206. ASSERT_TRUE(rate_settings.has_value());
  4207. DataRate allocation_sum = DataRate::bps(rate_settings->bitrate.get_sum_bps());
  4208. EXPECT_EQ(min_rate, allocation_sum);
  4209. EXPECT_EQ(rate_settings->bandwidth_allocation, min_rate);
  4210. video_stream_encoder_->Stop();
  4211. }
  4212. TEST_F(VideoStreamEncoderTest, EncoderRatesPropegatedOnReconfigure) {
  4213. video_stream_encoder_->OnBitrateUpdated(
  4214. DataRate::bps(kTargetBitrateBps), DataRate::bps(kTargetBitrateBps),
  4215. DataRate::bps(kTargetBitrateBps), 0, 0);
  4216. // Capture a frame and wait for it to synchronize with the encoder thread.
  4217. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  4218. video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
  4219. WaitForEncodedFrame(1);
  4220. auto prev_rate_settings = fake_encoder_.GetAndResetLastRateControlSettings();
  4221. ASSERT_TRUE(prev_rate_settings.has_value());
  4222. EXPECT_EQ(static_cast<int>(prev_rate_settings->framerate_fps),
  4223. kDefaultFramerate);
  4224. // Send 1s of video to ensure the framerate is stable at kDefaultFramerate.
  4225. for (int i = 0; i < 2 * kDefaultFramerate; i++) {
  4226. timestamp_ms += 1000 / kDefaultFramerate;
  4227. video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
  4228. WaitForEncodedFrame(timestamp_ms);
  4229. }
  4230. EXPECT_EQ(static_cast<int>(fake_encoder_.GetLastFramerate()),
  4231. kDefaultFramerate);
  4232. // Capture larger frame to trigger a reconfigure.
  4233. codec_height_ *= 2;
  4234. codec_width_ *= 2;
  4235. timestamp_ms += 1000 / kDefaultFramerate;
  4236. video_source_.IncomingCapturedFrame(CreateFrame(timestamp_ms, nullptr));
  4237. WaitForEncodedFrame(timestamp_ms);
  4238. EXPECT_EQ(2, sink_.number_of_reconfigurations());
  4239. auto current_rate_settings =
  4240. fake_encoder_.GetAndResetLastRateControlSettings();
  4241. // Ensure we have actually reconfigured twice
  4242. // The rate settings should have been set again even though
  4243. // they haven't changed.
  4244. ASSERT_TRUE(current_rate_settings.has_value());
  4245. EXPECT_EQ(prev_rate_settings, current_rate_settings);
  4246. video_stream_encoder_->Stop();
  4247. }
  4248. struct MockEncoderSwitchRequestCallback : public EncoderSwitchRequestCallback {
  4249. MOCK_METHOD0(RequestEncoderFallback, void());
  4250. MOCK_METHOD1(RequestEncoderSwitch, void(const Config& conf));
  4251. };
  4252. TEST_F(VideoStreamEncoderTest, BitrateEncoderSwitch) {
  4253. constexpr int kDontCare = 100;
  4254. StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
  4255. video_send_config_.encoder_settings.encoder_switch_request_callback =
  4256. &switch_callback;
  4257. VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
  4258. encoder_config.codec_type = kVideoCodecVP8;
  4259. webrtc::test::ScopedFieldTrials field_trial(
  4260. "WebRTC-NetworkCondition-EncoderSwitch/"
  4261. "codec_thresholds:VP8;100;-1|H264;-1;30000,"
  4262. "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
  4263. // Reset encoder for new configuration to take effect.
  4264. ConfigureEncoder(std::move(encoder_config));
  4265. // Send one frame to trigger ReconfigureEncoder.
  4266. video_source_.IncomingCapturedFrame(
  4267. CreateFrame(kDontCare, kDontCare, kDontCare));
  4268. using Config = EncoderSwitchRequestCallback::Config;
  4269. EXPECT_CALL(switch_callback,
  4270. RequestEncoderSwitch(AllOf(Field(&Config::codec_name, "AV1"),
  4271. Field(&Config::param, "ping"),
  4272. Field(&Config::value, "pong"))));
  4273. video_stream_encoder_->OnBitrateUpdated(
  4274. /*target_bitrate=*/DataRate::kbps(50),
  4275. /*stable_target_bitrate=*/DataRate::kbps(kDontCare),
  4276. /*link_allocation=*/DataRate::kbps(kDontCare),
  4277. /*fraction_lost=*/0,
  4278. /*rtt_ms=*/0);
  4279. video_stream_encoder_->Stop();
  4280. }
  4281. TEST_F(VideoStreamEncoderTest, ResolutionEncoderSwitch) {
  4282. constexpr int kSufficientBitrateToNotDrop = 1000;
  4283. constexpr int kHighRes = 500;
  4284. constexpr int kLowRes = 100;
  4285. StrictMock<MockEncoderSwitchRequestCallback> switch_callback;
  4286. video_send_config_.encoder_settings.encoder_switch_request_callback =
  4287. &switch_callback;
  4288. webrtc::test::ScopedFieldTrials field_trial(
  4289. "WebRTC-NetworkCondition-EncoderSwitch/"
  4290. "codec_thresholds:VP8;120;-1|H264;-1;30000,"
  4291. "to_codec:AV1,to_param:ping,to_value:pong,window:2.0/");
  4292. VideoEncoderConfig encoder_config = video_encoder_config_.Copy();
  4293. encoder_config.codec_type = kVideoCodecH264;
  4294. // Reset encoder for new configuration to take effect.
  4295. ConfigureEncoder(std::move(encoder_config));
  4296. // The VideoStreamEncoder needs some bitrate before it can start encoding,
  4297. // setting some bitrate so that subsequent calls to WaitForEncodedFrame does
  4298. // not fail.
  4299. video_stream_encoder_->OnBitrateUpdated(
  4300. /*target_bitrate=*/DataRate::kbps(kSufficientBitrateToNotDrop),
  4301. /*stable_target_bitrate=*/DataRate::kbps(kSufficientBitrateToNotDrop),
  4302. /*link_allocation=*/DataRate::kbps(kSufficientBitrateToNotDrop),
  4303. /*fraction_lost=*/0,
  4304. /*rtt_ms=*/0);
  4305. // Send one frame to trigger ReconfigureEncoder.
  4306. video_source_.IncomingCapturedFrame(CreateFrame(1, kHighRes, kHighRes));
  4307. WaitForEncodedFrame(1);
  4308. using Config = EncoderSwitchRequestCallback::Config;
  4309. EXPECT_CALL(switch_callback,
  4310. RequestEncoderSwitch(AllOf(Field(&Config::codec_name, "AV1"),
  4311. Field(&Config::param, "ping"),
  4312. Field(&Config::value, "pong"))));
  4313. video_source_.IncomingCapturedFrame(CreateFrame(2, kLowRes, kLowRes));
  4314. WaitForEncodedFrame(2);
  4315. video_stream_encoder_->Stop();
  4316. }
  4317. TEST_F(VideoStreamEncoderTest,
  4318. AllocationPropegratedToEncoderWhenTargetRateChanged) {
  4319. const int kFrameWidth = 320;
  4320. const int kFrameHeight = 180;
  4321. // Set initial rate.
  4322. auto rate = DataRate::kbps(100);
  4323. video_stream_encoder_->OnBitrateUpdated(
  4324. /*target_bitrate=*/rate,
  4325. /*stable_target_bitrate=*/rate,
  4326. /*link_allocation=*/rate,
  4327. /*fraction_lost=*/0,
  4328. /*rtt_ms=*/0);
  4329. // Insert a first video frame so that encoder gets configured.
  4330. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  4331. VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
  4332. frame.set_rotation(kVideoRotation_270);
  4333. video_source_.IncomingCapturedFrame(frame);
  4334. WaitForEncodedFrame(timestamp_ms);
  4335. EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
  4336. // Change of target bitrate propagates to the encoder.
  4337. auto new_stable_rate = rate - DataRate::kbps(5);
  4338. video_stream_encoder_->OnBitrateUpdated(
  4339. /*target_bitrate=*/new_stable_rate,
  4340. /*stable_target_bitrate=*/new_stable_rate,
  4341. /*link_allocation=*/rate,
  4342. /*fraction_lost=*/0,
  4343. /*rtt_ms=*/0);
  4344. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  4345. EXPECT_EQ(2, fake_encoder_.GetNumSetRates());
  4346. video_stream_encoder_->Stop();
  4347. }
  4348. TEST_F(VideoStreamEncoderTest,
  4349. AllocationNotPropegratedToEncoderWhenTargetRateUnchanged) {
  4350. const int kFrameWidth = 320;
  4351. const int kFrameHeight = 180;
  4352. // Set initial rate.
  4353. auto rate = DataRate::kbps(100);
  4354. video_stream_encoder_->OnBitrateUpdated(
  4355. /*target_bitrate=*/rate,
  4356. /*stable_target_bitrate=*/rate,
  4357. /*link_allocation=*/rate,
  4358. /*fraction_lost=*/0,
  4359. /*rtt_ms=*/0);
  4360. // Insert a first video frame so that encoder gets configured.
  4361. int64_t timestamp_ms = fake_clock_.TimeNanos() / rtc::kNumNanosecsPerMillisec;
  4362. VideoFrame frame = CreateFrame(timestamp_ms, kFrameWidth, kFrameHeight);
  4363. frame.set_rotation(kVideoRotation_270);
  4364. video_source_.IncomingCapturedFrame(frame);
  4365. WaitForEncodedFrame(timestamp_ms);
  4366. EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
  4367. // Set a higher target rate without changing the link_allocation. Should not
  4368. // reset encoder's rate.
  4369. auto new_stable_rate = rate - DataRate::kbps(5);
  4370. video_stream_encoder_->OnBitrateUpdated(
  4371. /*target_bitrate=*/rate,
  4372. /*stable_target_bitrate=*/new_stable_rate,
  4373. /*link_allocation=*/rate,
  4374. /*fraction_lost=*/0,
  4375. /*rtt_ms=*/0);
  4376. video_stream_encoder_->WaitUntilTaskQueueIsIdle();
  4377. EXPECT_EQ(1, fake_encoder_.GetNumSetRates());
  4378. video_stream_encoder_->Stop();
  4379. }
  4380. } // namespace webrtc