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.

6270 lines
267 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2012 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. // Disable for TSan v2, see
  11. // https://code.google.com/p/webrtc/issues/detail?id=1205 for details.
  12. #if !defined(THREAD_SANITIZER)
  13. #include <stdio.h>
  14. #include <functional>
  15. #include <list>
  16. #include <map>
  17. #include <memory>
  18. #include <utility>
  19. #include <vector>
  20. #include "absl/algorithm/container.h"
  21. #include "api/media_stream_interface.h"
  22. #include "api/peer_connection_interface.h"
  23. #include "api/peer_connection_proxy.h"
  24. #include "api/rtc_event_log/rtc_event_log_factory.h"
  25. #include "api/rtp_receiver_interface.h"
  26. #include "api/task_queue/default_task_queue_factory.h"
  27. #include "api/test/loopback_media_transport.h"
  28. #include "api/uma_metrics.h"
  29. #include "api/video_codecs/sdp_video_format.h"
  30. #include "call/call.h"
  31. #include "logging/rtc_event_log/fake_rtc_event_log_factory.h"
  32. #include "media/engine/fake_webrtc_video_engine.h"
  33. #include "media/engine/webrtc_media_engine.h"
  34. #include "media/engine/webrtc_media_engine_defaults.h"
  35. #include "p2p/base/mock_async_resolver.h"
  36. #include "p2p/base/p2p_constants.h"
  37. #include "p2p/base/port_interface.h"
  38. #include "p2p/base/test_stun_server.h"
  39. #include "p2p/base/test_turn_customizer.h"
  40. #include "p2p/base/test_turn_server.h"
  41. #include "p2p/client/basic_port_allocator.h"
  42. #include "pc/dtmf_sender.h"
  43. #include "pc/local_audio_source.h"
  44. #include "pc/media_session.h"
  45. #include "pc/peer_connection.h"
  46. #include "pc/peer_connection_factory.h"
  47. #include "pc/rtp_media_utils.h"
  48. #include "pc/session_description.h"
  49. #include "pc/test/fake_audio_capture_module.h"
  50. #include "pc/test/fake_periodic_video_track_source.h"
  51. #include "pc/test/fake_rtc_certificate_generator.h"
  52. #include "pc/test/fake_video_track_renderer.h"
  53. #include "pc/test/mock_peer_connection_observers.h"
  54. #include "rtc_base/fake_clock.h"
  55. #include "rtc_base/fake_mdns_responder.h"
  56. #include "rtc_base/fake_network.h"
  57. #include "rtc_base/firewall_socket_server.h"
  58. #include "rtc_base/gunit.h"
  59. #include "rtc_base/numerics/safe_conversions.h"
  60. #include "rtc_base/test_certificate_verifier.h"
  61. #include "rtc_base/time_utils.h"
  62. #include "rtc_base/virtual_socket_server.h"
  63. #include "system_wrappers/include/metrics.h"
  64. #include "test/field_trial.h"
  65. #include "test/gmock.h"
  66. namespace webrtc {
  67. namespace {
  68. using ::cricket::ContentInfo;
  69. using ::cricket::StreamParams;
  70. using ::rtc::SocketAddress;
  71. using ::testing::_;
  72. using ::testing::Combine;
  73. using ::testing::Contains;
  74. using ::testing::DoAll;
  75. using ::testing::ElementsAre;
  76. using ::testing::NiceMock;
  77. using ::testing::Return;
  78. using ::testing::SetArgPointee;
  79. using ::testing::UnorderedElementsAreArray;
  80. using ::testing::Values;
  81. using RTCConfiguration = PeerConnectionInterface::RTCConfiguration;
  82. static const int kDefaultTimeout = 10000;
  83. static const int kMaxWaitForStatsMs = 3000;
  84. static const int kMaxWaitForActivationMs = 5000;
  85. static const int kMaxWaitForFramesMs = 10000;
  86. // Default number of audio/video frames to wait for before considering a test
  87. // successful.
  88. static const int kDefaultExpectedAudioFrameCount = 3;
  89. static const int kDefaultExpectedVideoFrameCount = 3;
  90. static const char kDataChannelLabel[] = "data_channel";
  91. // SRTP cipher name negotiated by the tests. This must be updated if the
  92. // default changes.
  93. static const int kDefaultSrtpCryptoSuite = rtc::SRTP_AES128_CM_SHA1_80;
  94. static const int kDefaultSrtpCryptoSuiteGcm = rtc::SRTP_AEAD_AES_256_GCM;
  95. static const SocketAddress kDefaultLocalAddress("192.168.1.1", 0);
  96. // Helper function for constructing offer/answer options to initiate an ICE
  97. // restart.
  98. PeerConnectionInterface::RTCOfferAnswerOptions IceRestartOfferAnswerOptions() {
  99. PeerConnectionInterface::RTCOfferAnswerOptions options;
  100. options.ice_restart = true;
  101. return options;
  102. }
  103. // Remove all stream information (SSRCs, track IDs, etc.) and "msid-semantic"
  104. // attribute from received SDP, simulating a legacy endpoint.
  105. void RemoveSsrcsAndMsids(cricket::SessionDescription* desc) {
  106. for (ContentInfo& content : desc->contents()) {
  107. content.media_description()->mutable_streams().clear();
  108. }
  109. desc->set_msid_supported(false);
  110. desc->set_msid_signaling(0);
  111. }
  112. // Removes all stream information besides the stream ids, simulating an
  113. // endpoint that only signals a=msid lines to convey stream_ids.
  114. void RemoveSsrcsAndKeepMsids(cricket::SessionDescription* desc) {
  115. for (ContentInfo& content : desc->contents()) {
  116. std::string track_id;
  117. std::vector<std::string> stream_ids;
  118. if (!content.media_description()->streams().empty()) {
  119. const StreamParams& first_stream =
  120. content.media_description()->streams()[0];
  121. track_id = first_stream.id;
  122. stream_ids = first_stream.stream_ids();
  123. }
  124. content.media_description()->mutable_streams().clear();
  125. StreamParams new_stream;
  126. new_stream.id = track_id;
  127. new_stream.set_stream_ids(stream_ids);
  128. content.media_description()->AddStream(new_stream);
  129. }
  130. }
  131. int FindFirstMediaStatsIndexByKind(
  132. const std::string& kind,
  133. const std::vector<const webrtc::RTCMediaStreamTrackStats*>&
  134. media_stats_vec) {
  135. for (size_t i = 0; i < media_stats_vec.size(); i++) {
  136. if (media_stats_vec[i]->kind.ValueToString() == kind) {
  137. return i;
  138. }
  139. }
  140. return -1;
  141. }
  142. class SignalingMessageReceiver {
  143. public:
  144. virtual void ReceiveSdpMessage(SdpType type, const std::string& msg) = 0;
  145. virtual void ReceiveIceMessage(const std::string& sdp_mid,
  146. int sdp_mline_index,
  147. const std::string& msg) = 0;
  148. protected:
  149. SignalingMessageReceiver() {}
  150. virtual ~SignalingMessageReceiver() {}
  151. };
  152. class MockRtpReceiverObserver : public webrtc::RtpReceiverObserverInterface {
  153. public:
  154. explicit MockRtpReceiverObserver(cricket::MediaType media_type)
  155. : expected_media_type_(media_type) {}
  156. void OnFirstPacketReceived(cricket::MediaType media_type) override {
  157. ASSERT_EQ(expected_media_type_, media_type);
  158. first_packet_received_ = true;
  159. }
  160. bool first_packet_received() const { return first_packet_received_; }
  161. virtual ~MockRtpReceiverObserver() {}
  162. private:
  163. bool first_packet_received_ = false;
  164. cricket::MediaType expected_media_type_;
  165. };
  166. // Helper class that wraps a peer connection, observes it, and can accept
  167. // signaling messages from another wrapper.
  168. //
  169. // Uses a fake network, fake A/V capture, and optionally fake
  170. // encoders/decoders, though they aren't used by default since they don't
  171. // advertise support of any codecs.
  172. // TODO(steveanton): See how this could become a subclass of
  173. // PeerConnectionWrapper defined in peerconnectionwrapper.h.
  174. class PeerConnectionWrapper : public webrtc::PeerConnectionObserver,
  175. public SignalingMessageReceiver {
  176. public:
  177. // Different factory methods for convenience.
  178. // TODO(deadbeef): Could use the pattern of:
  179. //
  180. // PeerConnectionWrapper =
  181. // WrapperBuilder.WithConfig(...).WithOptions(...).build();
  182. //
  183. // To reduce some code duplication.
  184. static PeerConnectionWrapper* CreateWithDtlsIdentityStore(
  185. const std::string& debug_name,
  186. std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
  187. rtc::Thread* network_thread,
  188. rtc::Thread* worker_thread) {
  189. PeerConnectionWrapper* client(new PeerConnectionWrapper(debug_name));
  190. webrtc::PeerConnectionDependencies dependencies(nullptr);
  191. dependencies.cert_generator = std::move(cert_generator);
  192. if (!client->Init(nullptr, nullptr, std::move(dependencies), network_thread,
  193. worker_thread, nullptr,
  194. /*media_transport_factory=*/nullptr)) {
  195. delete client;
  196. return nullptr;
  197. }
  198. return client;
  199. }
  200. webrtc::PeerConnectionFactoryInterface* pc_factory() const {
  201. return peer_connection_factory_.get();
  202. }
  203. webrtc::PeerConnectionInterface* pc() const { return peer_connection_.get(); }
  204. // If a signaling message receiver is set (via ConnectFakeSignaling), this
  205. // will set the whole offer/answer exchange in motion. Just need to wait for
  206. // the signaling state to reach "stable".
  207. void CreateAndSetAndSignalOffer() {
  208. auto offer = CreateOfferAndWait();
  209. ASSERT_NE(nullptr, offer);
  210. EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(offer)));
  211. }
  212. // Sets the options to be used when CreateAndSetAndSignalOffer is called, or
  213. // when a remote offer is received (via fake signaling) and an answer is
  214. // generated. By default, uses default options.
  215. void SetOfferAnswerOptions(
  216. const PeerConnectionInterface::RTCOfferAnswerOptions& options) {
  217. offer_answer_options_ = options;
  218. }
  219. // Set a callback to be invoked when SDP is received via the fake signaling
  220. // channel, which provides an opportunity to munge (modify) the SDP. This is
  221. // used to test SDP being applied that a PeerConnection would normally not
  222. // generate, but a non-JSEP endpoint might.
  223. void SetReceivedSdpMunger(
  224. std::function<void(cricket::SessionDescription*)> munger) {
  225. received_sdp_munger_ = std::move(munger);
  226. }
  227. // Similar to the above, but this is run on SDP immediately after it's
  228. // generated.
  229. void SetGeneratedSdpMunger(
  230. std::function<void(cricket::SessionDescription*)> munger) {
  231. generated_sdp_munger_ = std::move(munger);
  232. }
  233. // Set a callback to be invoked when a remote offer is received via the fake
  234. // signaling channel. This provides an opportunity to change the
  235. // PeerConnection state before an answer is created and sent to the caller.
  236. void SetRemoteOfferHandler(std::function<void()> handler) {
  237. remote_offer_handler_ = std::move(handler);
  238. }
  239. void SetRemoteAsyncResolver(rtc::MockAsyncResolver* resolver) {
  240. remote_async_resolver_ = resolver;
  241. }
  242. // Every ICE connection state in order that has been seen by the observer.
  243. std::vector<PeerConnectionInterface::IceConnectionState>
  244. ice_connection_state_history() const {
  245. return ice_connection_state_history_;
  246. }
  247. void clear_ice_connection_state_history() {
  248. ice_connection_state_history_.clear();
  249. }
  250. // Every standardized ICE connection state in order that has been seen by the
  251. // observer.
  252. std::vector<PeerConnectionInterface::IceConnectionState>
  253. standardized_ice_connection_state_history() const {
  254. return standardized_ice_connection_state_history_;
  255. }
  256. // Every PeerConnection state in order that has been seen by the observer.
  257. std::vector<PeerConnectionInterface::PeerConnectionState>
  258. peer_connection_state_history() const {
  259. return peer_connection_state_history_;
  260. }
  261. // Every ICE gathering state in order that has been seen by the observer.
  262. std::vector<PeerConnectionInterface::IceGatheringState>
  263. ice_gathering_state_history() const {
  264. return ice_gathering_state_history_;
  265. }
  266. std::vector<cricket::CandidatePairChangeEvent>
  267. ice_candidate_pair_change_history() const {
  268. return ice_candidate_pair_change_history_;
  269. }
  270. // Every PeerConnection signaling state in order that has been seen by the
  271. // observer.
  272. std::vector<PeerConnectionInterface::SignalingState>
  273. peer_connection_signaling_state_history() const {
  274. return peer_connection_signaling_state_history_;
  275. }
  276. void AddAudioVideoTracks() {
  277. AddAudioTrack();
  278. AddVideoTrack();
  279. }
  280. rtc::scoped_refptr<RtpSenderInterface> AddAudioTrack() {
  281. return AddTrack(CreateLocalAudioTrack());
  282. }
  283. rtc::scoped_refptr<RtpSenderInterface> AddVideoTrack() {
  284. return AddTrack(CreateLocalVideoTrack());
  285. }
  286. rtc::scoped_refptr<webrtc::AudioTrackInterface> CreateLocalAudioTrack() {
  287. cricket::AudioOptions options;
  288. // Disable highpass filter so that we can get all the test audio frames.
  289. options.highpass_filter = false;
  290. rtc::scoped_refptr<webrtc::AudioSourceInterface> source =
  291. peer_connection_factory_->CreateAudioSource(options);
  292. // TODO(perkj): Test audio source when it is implemented. Currently audio
  293. // always use the default input.
  294. return peer_connection_factory_->CreateAudioTrack(rtc::CreateRandomUuid(),
  295. source);
  296. }
  297. rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrack() {
  298. webrtc::FakePeriodicVideoSource::Config config;
  299. config.timestamp_offset_ms = rtc::TimeMillis();
  300. return CreateLocalVideoTrackInternal(config);
  301. }
  302. rtc::scoped_refptr<webrtc::VideoTrackInterface>
  303. CreateLocalVideoTrackWithConfig(
  304. webrtc::FakePeriodicVideoSource::Config config) {
  305. return CreateLocalVideoTrackInternal(config);
  306. }
  307. rtc::scoped_refptr<webrtc::VideoTrackInterface>
  308. CreateLocalVideoTrackWithRotation(webrtc::VideoRotation rotation) {
  309. webrtc::FakePeriodicVideoSource::Config config;
  310. config.rotation = rotation;
  311. config.timestamp_offset_ms = rtc::TimeMillis();
  312. return CreateLocalVideoTrackInternal(config);
  313. }
  314. rtc::scoped_refptr<RtpSenderInterface> AddTrack(
  315. rtc::scoped_refptr<MediaStreamTrackInterface> track,
  316. const std::vector<std::string>& stream_ids = {}) {
  317. auto result = pc()->AddTrack(track, stream_ids);
  318. EXPECT_EQ(RTCErrorType::NONE, result.error().type());
  319. return result.MoveValue();
  320. }
  321. std::vector<rtc::scoped_refptr<RtpReceiverInterface>> GetReceiversOfType(
  322. cricket::MediaType media_type) {
  323. std::vector<rtc::scoped_refptr<RtpReceiverInterface>> receivers;
  324. for (const auto& receiver : pc()->GetReceivers()) {
  325. if (receiver->media_type() == media_type) {
  326. receivers.push_back(receiver);
  327. }
  328. }
  329. return receivers;
  330. }
  331. rtc::scoped_refptr<RtpTransceiverInterface> GetFirstTransceiverOfType(
  332. cricket::MediaType media_type) {
  333. for (auto transceiver : pc()->GetTransceivers()) {
  334. if (transceiver->receiver()->media_type() == media_type) {
  335. return transceiver;
  336. }
  337. }
  338. return nullptr;
  339. }
  340. bool SignalingStateStable() {
  341. return pc()->signaling_state() == webrtc::PeerConnectionInterface::kStable;
  342. }
  343. void CreateDataChannel() { CreateDataChannel(nullptr); }
  344. void CreateDataChannel(const webrtc::DataChannelInit* init) {
  345. CreateDataChannel(kDataChannelLabel, init);
  346. }
  347. void CreateDataChannel(const std::string& label,
  348. const webrtc::DataChannelInit* init) {
  349. data_channel_ = pc()->CreateDataChannel(label, init);
  350. ASSERT_TRUE(data_channel_.get() != nullptr);
  351. data_observer_.reset(new MockDataChannelObserver(data_channel_));
  352. }
  353. DataChannelInterface* data_channel() { return data_channel_; }
  354. const MockDataChannelObserver* data_observer() const {
  355. return data_observer_.get();
  356. }
  357. int audio_frames_received() const {
  358. return fake_audio_capture_module_->frames_received();
  359. }
  360. // Takes minimum of video frames received for each track.
  361. //
  362. // Can be used like:
  363. // EXPECT_GE(expected_frames, min_video_frames_received_per_track());
  364. //
  365. // To ensure that all video tracks received at least a certain number of
  366. // frames.
  367. int min_video_frames_received_per_track() const {
  368. int min_frames = INT_MAX;
  369. if (fake_video_renderers_.empty()) {
  370. return 0;
  371. }
  372. for (const auto& pair : fake_video_renderers_) {
  373. min_frames = std::min(min_frames, pair.second->num_rendered_frames());
  374. }
  375. return min_frames;
  376. }
  377. // Returns a MockStatsObserver in a state after stats gathering finished,
  378. // which can be used to access the gathered stats.
  379. rtc::scoped_refptr<MockStatsObserver> OldGetStatsForTrack(
  380. webrtc::MediaStreamTrackInterface* track) {
  381. rtc::scoped_refptr<MockStatsObserver> observer(
  382. new rtc::RefCountedObject<MockStatsObserver>());
  383. EXPECT_TRUE(peer_connection_->GetStats(
  384. observer, nullptr, PeerConnectionInterface::kStatsOutputLevelStandard));
  385. EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
  386. return observer;
  387. }
  388. // Version that doesn't take a track "filter", and gathers all stats.
  389. rtc::scoped_refptr<MockStatsObserver> OldGetStats() {
  390. return OldGetStatsForTrack(nullptr);
  391. }
  392. // Synchronously gets stats and returns them. If it times out, fails the test
  393. // and returns null.
  394. rtc::scoped_refptr<const webrtc::RTCStatsReport> NewGetStats() {
  395. rtc::scoped_refptr<webrtc::MockRTCStatsCollectorCallback> callback(
  396. new rtc::RefCountedObject<webrtc::MockRTCStatsCollectorCallback>());
  397. peer_connection_->GetStats(callback);
  398. EXPECT_TRUE_WAIT(callback->called(), kDefaultTimeout);
  399. return callback->report();
  400. }
  401. int rendered_width() {
  402. EXPECT_FALSE(fake_video_renderers_.empty());
  403. return fake_video_renderers_.empty()
  404. ? 0
  405. : fake_video_renderers_.begin()->second->width();
  406. }
  407. int rendered_height() {
  408. EXPECT_FALSE(fake_video_renderers_.empty());
  409. return fake_video_renderers_.empty()
  410. ? 0
  411. : fake_video_renderers_.begin()->second->height();
  412. }
  413. double rendered_aspect_ratio() {
  414. if (rendered_height() == 0) {
  415. return 0.0;
  416. }
  417. return static_cast<double>(rendered_width()) / rendered_height();
  418. }
  419. webrtc::VideoRotation rendered_rotation() {
  420. EXPECT_FALSE(fake_video_renderers_.empty());
  421. return fake_video_renderers_.empty()
  422. ? webrtc::kVideoRotation_0
  423. : fake_video_renderers_.begin()->second->rotation();
  424. }
  425. int local_rendered_width() {
  426. return local_video_renderer_ ? local_video_renderer_->width() : 0;
  427. }
  428. int local_rendered_height() {
  429. return local_video_renderer_ ? local_video_renderer_->height() : 0;
  430. }
  431. double local_rendered_aspect_ratio() {
  432. if (local_rendered_height() == 0) {
  433. return 0.0;
  434. }
  435. return static_cast<double>(local_rendered_width()) /
  436. local_rendered_height();
  437. }
  438. size_t number_of_remote_streams() {
  439. if (!pc()) {
  440. return 0;
  441. }
  442. return pc()->remote_streams()->count();
  443. }
  444. StreamCollectionInterface* remote_streams() const {
  445. if (!pc()) {
  446. ADD_FAILURE();
  447. return nullptr;
  448. }
  449. return pc()->remote_streams();
  450. }
  451. StreamCollectionInterface* local_streams() {
  452. if (!pc()) {
  453. ADD_FAILURE();
  454. return nullptr;
  455. }
  456. return pc()->local_streams();
  457. }
  458. webrtc::PeerConnectionInterface::SignalingState signaling_state() {
  459. return pc()->signaling_state();
  460. }
  461. webrtc::PeerConnectionInterface::IceConnectionState ice_connection_state() {
  462. return pc()->ice_connection_state();
  463. }
  464. webrtc::PeerConnectionInterface::IceConnectionState
  465. standardized_ice_connection_state() {
  466. return pc()->standardized_ice_connection_state();
  467. }
  468. webrtc::PeerConnectionInterface::IceGatheringState ice_gathering_state() {
  469. return pc()->ice_gathering_state();
  470. }
  471. // Returns a MockRtpReceiverObserver for each RtpReceiver returned by
  472. // GetReceivers. They're updated automatically when a remote offer/answer
  473. // from the fake signaling channel is applied, or when
  474. // ResetRtpReceiverObservers below is called.
  475. const std::vector<std::unique_ptr<MockRtpReceiverObserver>>&
  476. rtp_receiver_observers() {
  477. return rtp_receiver_observers_;
  478. }
  479. void ResetRtpReceiverObservers() {
  480. rtp_receiver_observers_.clear();
  481. for (const rtc::scoped_refptr<RtpReceiverInterface>& receiver :
  482. pc()->GetReceivers()) {
  483. std::unique_ptr<MockRtpReceiverObserver> observer(
  484. new MockRtpReceiverObserver(receiver->media_type()));
  485. receiver->SetObserver(observer.get());
  486. rtp_receiver_observers_.push_back(std::move(observer));
  487. }
  488. }
  489. rtc::FakeNetworkManager* network_manager() const {
  490. return fake_network_manager_.get();
  491. }
  492. cricket::PortAllocator* port_allocator() const { return port_allocator_; }
  493. webrtc::FakeRtcEventLogFactory* event_log_factory() const {
  494. return event_log_factory_;
  495. }
  496. const cricket::Candidate& last_candidate_gathered() const {
  497. return last_candidate_gathered_;
  498. }
  499. const cricket::IceCandidateErrorEvent& error_event() const {
  500. return error_event_;
  501. }
  502. // Sets the mDNS responder for the owned fake network manager and keeps a
  503. // reference to the responder.
  504. void SetMdnsResponder(
  505. std::unique_ptr<webrtc::FakeMdnsResponder> mdns_responder) {
  506. RTC_DCHECK(mdns_responder != nullptr);
  507. mdns_responder_ = mdns_responder.get();
  508. network_manager()->set_mdns_responder(std::move(mdns_responder));
  509. }
  510. // Returns null on failure.
  511. std::unique_ptr<SessionDescriptionInterface> CreateOfferAndWait() {
  512. rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
  513. new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
  514. pc()->CreateOffer(observer, offer_answer_options_);
  515. return WaitForDescriptionFromObserver(observer);
  516. }
  517. private:
  518. explicit PeerConnectionWrapper(const std::string& debug_name)
  519. : debug_name_(debug_name) {}
  520. bool Init(
  521. const PeerConnectionFactory::Options* options,
  522. const PeerConnectionInterface::RTCConfiguration* config,
  523. webrtc::PeerConnectionDependencies dependencies,
  524. rtc::Thread* network_thread,
  525. rtc::Thread* worker_thread,
  526. std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
  527. std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
  528. // There's an error in this test code if Init ends up being called twice.
  529. RTC_DCHECK(!peer_connection_);
  530. RTC_DCHECK(!peer_connection_factory_);
  531. fake_network_manager_.reset(new rtc::FakeNetworkManager());
  532. fake_network_manager_->AddInterface(kDefaultLocalAddress);
  533. std::unique_ptr<cricket::PortAllocator> port_allocator(
  534. new cricket::BasicPortAllocator(fake_network_manager_.get()));
  535. port_allocator_ = port_allocator.get();
  536. fake_audio_capture_module_ = FakeAudioCaptureModule::Create();
  537. if (!fake_audio_capture_module_) {
  538. return false;
  539. }
  540. rtc::Thread* const signaling_thread = rtc::Thread::Current();
  541. webrtc::PeerConnectionFactoryDependencies pc_factory_dependencies;
  542. pc_factory_dependencies.network_thread = network_thread;
  543. pc_factory_dependencies.worker_thread = worker_thread;
  544. pc_factory_dependencies.signaling_thread = signaling_thread;
  545. pc_factory_dependencies.task_queue_factory =
  546. webrtc::CreateDefaultTaskQueueFactory();
  547. cricket::MediaEngineDependencies media_deps;
  548. media_deps.task_queue_factory =
  549. pc_factory_dependencies.task_queue_factory.get();
  550. media_deps.adm = fake_audio_capture_module_;
  551. webrtc::SetMediaEngineDefaults(&media_deps);
  552. pc_factory_dependencies.media_engine =
  553. cricket::CreateMediaEngine(std::move(media_deps));
  554. pc_factory_dependencies.call_factory = webrtc::CreateCallFactory();
  555. if (event_log_factory) {
  556. event_log_factory_ = event_log_factory.get();
  557. pc_factory_dependencies.event_log_factory = std::move(event_log_factory);
  558. } else {
  559. pc_factory_dependencies.event_log_factory =
  560. std::make_unique<webrtc::RtcEventLogFactory>(
  561. pc_factory_dependencies.task_queue_factory.get());
  562. }
  563. if (media_transport_factory) {
  564. pc_factory_dependencies.media_transport_factory =
  565. std::move(media_transport_factory);
  566. }
  567. peer_connection_factory_ = webrtc::CreateModularPeerConnectionFactory(
  568. std::move(pc_factory_dependencies));
  569. if (!peer_connection_factory_) {
  570. return false;
  571. }
  572. if (options) {
  573. peer_connection_factory_->SetOptions(*options);
  574. }
  575. if (config) {
  576. sdp_semantics_ = config->sdp_semantics;
  577. }
  578. dependencies.allocator = std::move(port_allocator);
  579. peer_connection_ = CreatePeerConnection(config, std::move(dependencies));
  580. return peer_connection_.get() != nullptr;
  581. }
  582. rtc::scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
  583. const PeerConnectionInterface::RTCConfiguration* config,
  584. webrtc::PeerConnectionDependencies dependencies) {
  585. PeerConnectionInterface::RTCConfiguration modified_config;
  586. // If |config| is null, this will result in a default configuration being
  587. // used.
  588. if (config) {
  589. modified_config = *config;
  590. }
  591. // Disable resolution adaptation; we don't want it interfering with the
  592. // test results.
  593. // TODO(deadbeef): Do something more robust. Since we're testing for aspect
  594. // ratios and not specific resolutions, is this even necessary?
  595. modified_config.set_cpu_adaptation(false);
  596. dependencies.observer = this;
  597. return peer_connection_factory_->CreatePeerConnection(
  598. modified_config, std::move(dependencies));
  599. }
  600. void set_signaling_message_receiver(
  601. SignalingMessageReceiver* signaling_message_receiver) {
  602. signaling_message_receiver_ = signaling_message_receiver;
  603. }
  604. void set_signaling_delay_ms(int delay_ms) { signaling_delay_ms_ = delay_ms; }
  605. void set_signal_ice_candidates(bool signal) {
  606. signal_ice_candidates_ = signal;
  607. }
  608. rtc::scoped_refptr<webrtc::VideoTrackInterface> CreateLocalVideoTrackInternal(
  609. webrtc::FakePeriodicVideoSource::Config config) {
  610. // Set max frame rate to 10fps to reduce the risk of test flakiness.
  611. // TODO(deadbeef): Do something more robust.
  612. config.frame_interval_ms = 100;
  613. video_track_sources_.emplace_back(
  614. new rtc::RefCountedObject<webrtc::FakePeriodicVideoTrackSource>(
  615. config, false /* remote */));
  616. rtc::scoped_refptr<webrtc::VideoTrackInterface> track(
  617. peer_connection_factory_->CreateVideoTrack(
  618. rtc::CreateRandomUuid(), video_track_sources_.back()));
  619. if (!local_video_renderer_) {
  620. local_video_renderer_.reset(new webrtc::FakeVideoTrackRenderer(track));
  621. }
  622. return track;
  623. }
  624. void HandleIncomingOffer(const std::string& msg) {
  625. RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingOffer";
  626. std::unique_ptr<SessionDescriptionInterface> desc =
  627. webrtc::CreateSessionDescription(SdpType::kOffer, msg);
  628. if (received_sdp_munger_) {
  629. received_sdp_munger_(desc->description());
  630. }
  631. EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
  632. // Setting a remote description may have changed the number of receivers,
  633. // so reset the receiver observers.
  634. ResetRtpReceiverObservers();
  635. if (remote_offer_handler_) {
  636. remote_offer_handler_();
  637. }
  638. auto answer = CreateAnswer();
  639. ASSERT_NE(nullptr, answer);
  640. EXPECT_TRUE(SetLocalDescriptionAndSendSdpMessage(std::move(answer)));
  641. }
  642. void HandleIncomingAnswer(const std::string& msg) {
  643. RTC_LOG(LS_INFO) << debug_name_ << ": HandleIncomingAnswer";
  644. std::unique_ptr<SessionDescriptionInterface> desc =
  645. webrtc::CreateSessionDescription(SdpType::kAnswer, msg);
  646. if (received_sdp_munger_) {
  647. received_sdp_munger_(desc->description());
  648. }
  649. EXPECT_TRUE(SetRemoteDescription(std::move(desc)));
  650. // Set the RtpReceiverObserver after receivers are created.
  651. ResetRtpReceiverObservers();
  652. }
  653. // Returns null on failure.
  654. std::unique_ptr<SessionDescriptionInterface> CreateAnswer() {
  655. rtc::scoped_refptr<MockCreateSessionDescriptionObserver> observer(
  656. new rtc::RefCountedObject<MockCreateSessionDescriptionObserver>());
  657. pc()->CreateAnswer(observer, offer_answer_options_);
  658. return WaitForDescriptionFromObserver(observer);
  659. }
  660. std::unique_ptr<SessionDescriptionInterface> WaitForDescriptionFromObserver(
  661. MockCreateSessionDescriptionObserver* observer) {
  662. EXPECT_EQ_WAIT(true, observer->called(), kDefaultTimeout);
  663. if (!observer->result()) {
  664. return nullptr;
  665. }
  666. auto description = observer->MoveDescription();
  667. if (generated_sdp_munger_) {
  668. generated_sdp_munger_(description->description());
  669. }
  670. return description;
  671. }
  672. // Setting the local description and sending the SDP message over the fake
  673. // signaling channel are combined into the same method because the SDP
  674. // message needs to be sent as soon as SetLocalDescription finishes, without
  675. // waiting for the observer to be called. This ensures that ICE candidates
  676. // don't outrace the description.
  677. bool SetLocalDescriptionAndSendSdpMessage(
  678. std::unique_ptr<SessionDescriptionInterface> desc) {
  679. rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
  680. new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
  681. RTC_LOG(LS_INFO) << debug_name_ << ": SetLocalDescriptionAndSendSdpMessage";
  682. SdpType type = desc->GetType();
  683. std::string sdp;
  684. EXPECT_TRUE(desc->ToString(&sdp));
  685. RTC_LOG(LS_INFO) << debug_name_ << ": local SDP contents=\n" << sdp;
  686. pc()->SetLocalDescription(observer, desc.release());
  687. if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
  688. RemoveUnusedVideoRenderers();
  689. }
  690. // As mentioned above, we need to send the message immediately after
  691. // SetLocalDescription.
  692. SendSdpMessage(type, sdp);
  693. EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
  694. return true;
  695. }
  696. bool SetRemoteDescription(std::unique_ptr<SessionDescriptionInterface> desc) {
  697. rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
  698. new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
  699. RTC_LOG(LS_INFO) << debug_name_ << ": SetRemoteDescription";
  700. pc()->SetRemoteDescription(observer, desc.release());
  701. if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
  702. RemoveUnusedVideoRenderers();
  703. }
  704. EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
  705. return observer->result();
  706. }
  707. // This is a work around to remove unused fake_video_renderers from
  708. // transceivers that have either stopped or are no longer receiving.
  709. void RemoveUnusedVideoRenderers() {
  710. auto transceivers = pc()->GetTransceivers();
  711. for (auto& transceiver : transceivers) {
  712. if (transceiver->receiver()->media_type() != cricket::MEDIA_TYPE_VIDEO) {
  713. continue;
  714. }
  715. // Remove fake video renderers from any stopped transceivers.
  716. if (transceiver->stopped()) {
  717. auto it =
  718. fake_video_renderers_.find(transceiver->receiver()->track()->id());
  719. if (it != fake_video_renderers_.end()) {
  720. fake_video_renderers_.erase(it);
  721. }
  722. }
  723. // Remove fake video renderers from any transceivers that are no longer
  724. // receiving.
  725. if ((transceiver->current_direction() &&
  726. !webrtc::RtpTransceiverDirectionHasRecv(
  727. *transceiver->current_direction()))) {
  728. auto it =
  729. fake_video_renderers_.find(transceiver->receiver()->track()->id());
  730. if (it != fake_video_renderers_.end()) {
  731. fake_video_renderers_.erase(it);
  732. }
  733. }
  734. }
  735. }
  736. // Simulate sending a blob of SDP with delay |signaling_delay_ms_| (0 by
  737. // default).
  738. void SendSdpMessage(SdpType type, const std::string& msg) {
  739. if (signaling_delay_ms_ == 0) {
  740. RelaySdpMessageIfReceiverExists(type, msg);
  741. } else {
  742. invoker_.AsyncInvokeDelayed<void>(
  743. RTC_FROM_HERE, rtc::Thread::Current(),
  744. rtc::Bind(&PeerConnectionWrapper::RelaySdpMessageIfReceiverExists,
  745. this, type, msg),
  746. signaling_delay_ms_);
  747. }
  748. }
  749. void RelaySdpMessageIfReceiverExists(SdpType type, const std::string& msg) {
  750. if (signaling_message_receiver_) {
  751. signaling_message_receiver_->ReceiveSdpMessage(type, msg);
  752. }
  753. }
  754. // Simulate trickling an ICE candidate with delay |signaling_delay_ms_| (0 by
  755. // default).
  756. void SendIceMessage(const std::string& sdp_mid,
  757. int sdp_mline_index,
  758. const std::string& msg) {
  759. if (signaling_delay_ms_ == 0) {
  760. RelayIceMessageIfReceiverExists(sdp_mid, sdp_mline_index, msg);
  761. } else {
  762. invoker_.AsyncInvokeDelayed<void>(
  763. RTC_FROM_HERE, rtc::Thread::Current(),
  764. rtc::Bind(&PeerConnectionWrapper::RelayIceMessageIfReceiverExists,
  765. this, sdp_mid, sdp_mline_index, msg),
  766. signaling_delay_ms_);
  767. }
  768. }
  769. void RelayIceMessageIfReceiverExists(const std::string& sdp_mid,
  770. int sdp_mline_index,
  771. const std::string& msg) {
  772. if (signaling_message_receiver_) {
  773. signaling_message_receiver_->ReceiveIceMessage(sdp_mid, sdp_mline_index,
  774. msg);
  775. }
  776. }
  777. // SignalingMessageReceiver callbacks.
  778. void ReceiveSdpMessage(SdpType type, const std::string& msg) override {
  779. if (type == SdpType::kOffer) {
  780. HandleIncomingOffer(msg);
  781. } else {
  782. HandleIncomingAnswer(msg);
  783. }
  784. }
  785. void ReceiveIceMessage(const std::string& sdp_mid,
  786. int sdp_mline_index,
  787. const std::string& msg) override {
  788. RTC_LOG(LS_INFO) << debug_name_ << ": ReceiveIceMessage";
  789. std::unique_ptr<webrtc::IceCandidateInterface> candidate(
  790. webrtc::CreateIceCandidate(sdp_mid, sdp_mline_index, msg, nullptr));
  791. EXPECT_TRUE(pc()->AddIceCandidate(candidate.get()));
  792. }
  793. // PeerConnectionObserver callbacks.
  794. void OnSignalingChange(
  795. webrtc::PeerConnectionInterface::SignalingState new_state) override {
  796. EXPECT_EQ(pc()->signaling_state(), new_state);
  797. peer_connection_signaling_state_history_.push_back(new_state);
  798. }
  799. void OnAddTrack(rtc::scoped_refptr<RtpReceiverInterface> receiver,
  800. const std::vector<rtc::scoped_refptr<MediaStreamInterface>>&
  801. streams) override {
  802. if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
  803. rtc::scoped_refptr<VideoTrackInterface> video_track(
  804. static_cast<VideoTrackInterface*>(receiver->track().get()));
  805. ASSERT_TRUE(fake_video_renderers_.find(video_track->id()) ==
  806. fake_video_renderers_.end());
  807. fake_video_renderers_[video_track->id()] =
  808. std::make_unique<FakeVideoTrackRenderer>(video_track);
  809. }
  810. }
  811. void OnRemoveTrack(
  812. rtc::scoped_refptr<RtpReceiverInterface> receiver) override {
  813. if (receiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
  814. auto it = fake_video_renderers_.find(receiver->track()->id());
  815. RTC_DCHECK(it != fake_video_renderers_.end());
  816. fake_video_renderers_.erase(it);
  817. }
  818. }
  819. void OnRenegotiationNeeded() override {}
  820. void OnIceConnectionChange(
  821. webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
  822. EXPECT_EQ(pc()->ice_connection_state(), new_state);
  823. ice_connection_state_history_.push_back(new_state);
  824. }
  825. void OnStandardizedIceConnectionChange(
  826. webrtc::PeerConnectionInterface::IceConnectionState new_state) override {
  827. standardized_ice_connection_state_history_.push_back(new_state);
  828. }
  829. void OnConnectionChange(
  830. webrtc::PeerConnectionInterface::PeerConnectionState new_state) override {
  831. peer_connection_state_history_.push_back(new_state);
  832. }
  833. void OnIceGatheringChange(
  834. webrtc::PeerConnectionInterface::IceGatheringState new_state) override {
  835. EXPECT_EQ(pc()->ice_gathering_state(), new_state);
  836. ice_gathering_state_history_.push_back(new_state);
  837. }
  838. void OnIceSelectedCandidatePairChanged(
  839. const cricket::CandidatePairChangeEvent& event) {
  840. ice_candidate_pair_change_history_.push_back(event);
  841. }
  842. void OnIceCandidate(const webrtc::IceCandidateInterface* candidate) override {
  843. RTC_LOG(LS_INFO) << debug_name_ << ": OnIceCandidate";
  844. if (remote_async_resolver_) {
  845. const auto& local_candidate = candidate->candidate();
  846. if (local_candidate.address().IsUnresolvedIP()) {
  847. RTC_DCHECK(local_candidate.type() == cricket::LOCAL_PORT_TYPE);
  848. rtc::SocketAddress resolved_addr(local_candidate.address());
  849. const auto resolved_ip = mdns_responder_->GetMappedAddressForName(
  850. local_candidate.address().hostname());
  851. RTC_DCHECK(!resolved_ip.IsNil());
  852. resolved_addr.SetResolvedIP(resolved_ip);
  853. EXPECT_CALL(*remote_async_resolver_, GetResolvedAddress(_, _))
  854. .WillOnce(DoAll(SetArgPointee<1>(resolved_addr), Return(true)));
  855. EXPECT_CALL(*remote_async_resolver_, Destroy(_));
  856. }
  857. }
  858. std::string ice_sdp;
  859. EXPECT_TRUE(candidate->ToString(&ice_sdp));
  860. if (signaling_message_receiver_ == nullptr || !signal_ice_candidates_) {
  861. // Remote party may be deleted.
  862. return;
  863. }
  864. SendIceMessage(candidate->sdp_mid(), candidate->sdp_mline_index(), ice_sdp);
  865. last_candidate_gathered_ = candidate->candidate();
  866. }
  867. void OnIceCandidateError(const std::string& host_candidate,
  868. const std::string& url,
  869. int error_code,
  870. const std::string& error_text) override {
  871. error_event_ = cricket::IceCandidateErrorEvent(host_candidate, url,
  872. error_code, error_text);
  873. }
  874. void OnDataChannel(
  875. rtc::scoped_refptr<DataChannelInterface> data_channel) override {
  876. RTC_LOG(LS_INFO) << debug_name_ << ": OnDataChannel";
  877. data_channel_ = data_channel;
  878. data_observer_.reset(new MockDataChannelObserver(data_channel));
  879. }
  880. std::string debug_name_;
  881. std::unique_ptr<rtc::FakeNetworkManager> fake_network_manager_;
  882. // Reference to the mDNS responder owned by |fake_network_manager_| after set.
  883. webrtc::FakeMdnsResponder* mdns_responder_ = nullptr;
  884. rtc::scoped_refptr<webrtc::PeerConnectionInterface> peer_connection_;
  885. rtc::scoped_refptr<webrtc::PeerConnectionFactoryInterface>
  886. peer_connection_factory_;
  887. cricket::PortAllocator* port_allocator_;
  888. // Needed to keep track of number of frames sent.
  889. rtc::scoped_refptr<FakeAudioCaptureModule> fake_audio_capture_module_;
  890. // Needed to keep track of number of frames received.
  891. std::map<std::string, std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
  892. fake_video_renderers_;
  893. // Needed to ensure frames aren't received for removed tracks.
  894. std::vector<std::unique_ptr<webrtc::FakeVideoTrackRenderer>>
  895. removed_fake_video_renderers_;
  896. // For remote peer communication.
  897. SignalingMessageReceiver* signaling_message_receiver_ = nullptr;
  898. int signaling_delay_ms_ = 0;
  899. bool signal_ice_candidates_ = true;
  900. cricket::Candidate last_candidate_gathered_;
  901. cricket::IceCandidateErrorEvent error_event_;
  902. // Store references to the video sources we've created, so that we can stop
  903. // them, if required.
  904. std::vector<rtc::scoped_refptr<webrtc::VideoTrackSource>>
  905. video_track_sources_;
  906. // |local_video_renderer_| attached to the first created local video track.
  907. std::unique_ptr<webrtc::FakeVideoTrackRenderer> local_video_renderer_;
  908. SdpSemantics sdp_semantics_;
  909. PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options_;
  910. std::function<void(cricket::SessionDescription*)> received_sdp_munger_;
  911. std::function<void(cricket::SessionDescription*)> generated_sdp_munger_;
  912. std::function<void()> remote_offer_handler_;
  913. rtc::MockAsyncResolver* remote_async_resolver_ = nullptr;
  914. rtc::scoped_refptr<DataChannelInterface> data_channel_;
  915. std::unique_ptr<MockDataChannelObserver> data_observer_;
  916. std::vector<std::unique_ptr<MockRtpReceiverObserver>> rtp_receiver_observers_;
  917. std::vector<PeerConnectionInterface::IceConnectionState>
  918. ice_connection_state_history_;
  919. std::vector<PeerConnectionInterface::IceConnectionState>
  920. standardized_ice_connection_state_history_;
  921. std::vector<PeerConnectionInterface::PeerConnectionState>
  922. peer_connection_state_history_;
  923. std::vector<PeerConnectionInterface::IceGatheringState>
  924. ice_gathering_state_history_;
  925. std::vector<cricket::CandidatePairChangeEvent>
  926. ice_candidate_pair_change_history_;
  927. std::vector<PeerConnectionInterface::SignalingState>
  928. peer_connection_signaling_state_history_;
  929. webrtc::FakeRtcEventLogFactory* event_log_factory_;
  930. rtc::AsyncInvoker invoker_;
  931. friend class PeerConnectionIntegrationBaseTest;
  932. };
  933. class MockRtcEventLogOutput : public webrtc::RtcEventLogOutput {
  934. public:
  935. virtual ~MockRtcEventLogOutput() = default;
  936. MOCK_CONST_METHOD0(IsActive, bool());
  937. MOCK_METHOD1(Write, bool(const std::string&));
  938. };
  939. // This helper object is used for both specifying how many audio/video frames
  940. // are expected to be received for a caller/callee. It provides helper functions
  941. // to specify these expectations. The object initially starts in a state of no
  942. // expectations.
  943. class MediaExpectations {
  944. public:
  945. enum ExpectFrames {
  946. kExpectSomeFrames,
  947. kExpectNoFrames,
  948. kNoExpectation,
  949. };
  950. void ExpectBidirectionalAudioAndVideo() {
  951. ExpectBidirectionalAudio();
  952. ExpectBidirectionalVideo();
  953. }
  954. void ExpectBidirectionalAudio() {
  955. CallerExpectsSomeAudio();
  956. CalleeExpectsSomeAudio();
  957. }
  958. void ExpectNoAudio() {
  959. CallerExpectsNoAudio();
  960. CalleeExpectsNoAudio();
  961. }
  962. void ExpectBidirectionalVideo() {
  963. CallerExpectsSomeVideo();
  964. CalleeExpectsSomeVideo();
  965. }
  966. void ExpectNoVideo() {
  967. CallerExpectsNoVideo();
  968. CalleeExpectsNoVideo();
  969. }
  970. void CallerExpectsSomeAudioAndVideo() {
  971. CallerExpectsSomeAudio();
  972. CallerExpectsSomeVideo();
  973. }
  974. void CalleeExpectsSomeAudioAndVideo() {
  975. CalleeExpectsSomeAudio();
  976. CalleeExpectsSomeVideo();
  977. }
  978. // Caller's audio functions.
  979. void CallerExpectsSomeAudio(
  980. int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
  981. caller_audio_expectation_ = kExpectSomeFrames;
  982. caller_audio_frames_expected_ = expected_audio_frames;
  983. }
  984. void CallerExpectsNoAudio() {
  985. caller_audio_expectation_ = kExpectNoFrames;
  986. caller_audio_frames_expected_ = 0;
  987. }
  988. // Caller's video functions.
  989. void CallerExpectsSomeVideo(
  990. int expected_video_frames = kDefaultExpectedVideoFrameCount) {
  991. caller_video_expectation_ = kExpectSomeFrames;
  992. caller_video_frames_expected_ = expected_video_frames;
  993. }
  994. void CallerExpectsNoVideo() {
  995. caller_video_expectation_ = kExpectNoFrames;
  996. caller_video_frames_expected_ = 0;
  997. }
  998. // Callee's audio functions.
  999. void CalleeExpectsSomeAudio(
  1000. int expected_audio_frames = kDefaultExpectedAudioFrameCount) {
  1001. callee_audio_expectation_ = kExpectSomeFrames;
  1002. callee_audio_frames_expected_ = expected_audio_frames;
  1003. }
  1004. void CalleeExpectsNoAudio() {
  1005. callee_audio_expectation_ = kExpectNoFrames;
  1006. callee_audio_frames_expected_ = 0;
  1007. }
  1008. // Callee's video functions.
  1009. void CalleeExpectsSomeVideo(
  1010. int expected_video_frames = kDefaultExpectedVideoFrameCount) {
  1011. callee_video_expectation_ = kExpectSomeFrames;
  1012. callee_video_frames_expected_ = expected_video_frames;
  1013. }
  1014. void CalleeExpectsNoVideo() {
  1015. callee_video_expectation_ = kExpectNoFrames;
  1016. callee_video_frames_expected_ = 0;
  1017. }
  1018. ExpectFrames caller_audio_expectation_ = kNoExpectation;
  1019. ExpectFrames caller_video_expectation_ = kNoExpectation;
  1020. ExpectFrames callee_audio_expectation_ = kNoExpectation;
  1021. ExpectFrames callee_video_expectation_ = kNoExpectation;
  1022. int caller_audio_frames_expected_ = 0;
  1023. int caller_video_frames_expected_ = 0;
  1024. int callee_audio_frames_expected_ = 0;
  1025. int callee_video_frames_expected_ = 0;
  1026. };
  1027. // Tests two PeerConnections connecting to each other end-to-end, using a
  1028. // virtual network, fake A/V capture and fake encoder/decoders. The
  1029. // PeerConnections share the threads/socket servers, but use separate versions
  1030. // of everything else (including "PeerConnectionFactory"s).
  1031. class PeerConnectionIntegrationBaseTest : public ::testing::Test {
  1032. public:
  1033. explicit PeerConnectionIntegrationBaseTest(SdpSemantics sdp_semantics)
  1034. : sdp_semantics_(sdp_semantics),
  1035. ss_(new rtc::VirtualSocketServer()),
  1036. fss_(new rtc::FirewallSocketServer(ss_.get())),
  1037. network_thread_(new rtc::Thread(fss_.get())),
  1038. worker_thread_(rtc::Thread::Create()),
  1039. loopback_media_transports_(network_thread_.get()) {
  1040. network_thread_->SetName("PCNetworkThread", this);
  1041. worker_thread_->SetName("PCWorkerThread", this);
  1042. RTC_CHECK(network_thread_->Start());
  1043. RTC_CHECK(worker_thread_->Start());
  1044. webrtc::metrics::Reset();
  1045. }
  1046. ~PeerConnectionIntegrationBaseTest() {
  1047. // The PeerConnections should deleted before the TurnCustomizers.
  1048. // A TurnPort is created with a raw pointer to a TurnCustomizer. The
  1049. // TurnPort has the same lifetime as the PeerConnection, so it's expected
  1050. // that the TurnCustomizer outlives the life of the PeerConnection or else
  1051. // when Send() is called it will hit a seg fault.
  1052. if (caller_) {
  1053. caller_->set_signaling_message_receiver(nullptr);
  1054. delete SetCallerPcWrapperAndReturnCurrent(nullptr);
  1055. }
  1056. if (callee_) {
  1057. callee_->set_signaling_message_receiver(nullptr);
  1058. delete SetCalleePcWrapperAndReturnCurrent(nullptr);
  1059. }
  1060. // If turn servers were created for the test they need to be destroyed on
  1061. // the network thread.
  1062. network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
  1063. turn_servers_.clear();
  1064. turn_customizers_.clear();
  1065. });
  1066. }
  1067. bool SignalingStateStable() {
  1068. return caller_->SignalingStateStable() && callee_->SignalingStateStable();
  1069. }
  1070. bool DtlsConnected() {
  1071. // TODO(deadbeef): kIceConnectionConnected currently means both ICE and DTLS
  1072. // are connected. This is an important distinction. Once we have separate
  1073. // ICE and DTLS state, this check needs to use the DTLS state.
  1074. return (callee()->ice_connection_state() ==
  1075. webrtc::PeerConnectionInterface::kIceConnectionConnected ||
  1076. callee()->ice_connection_state() ==
  1077. webrtc::PeerConnectionInterface::kIceConnectionCompleted) &&
  1078. (caller()->ice_connection_state() ==
  1079. webrtc::PeerConnectionInterface::kIceConnectionConnected ||
  1080. caller()->ice_connection_state() ==
  1081. webrtc::PeerConnectionInterface::kIceConnectionCompleted);
  1082. }
  1083. // When |event_log_factory| is null, the default implementation of the event
  1084. // log factory will be used.
  1085. std::unique_ptr<PeerConnectionWrapper> CreatePeerConnectionWrapper(
  1086. const std::string& debug_name,
  1087. const PeerConnectionFactory::Options* options,
  1088. const RTCConfiguration* config,
  1089. webrtc::PeerConnectionDependencies dependencies,
  1090. std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory,
  1091. std::unique_ptr<webrtc::MediaTransportFactory> media_transport_factory) {
  1092. RTCConfiguration modified_config;
  1093. if (config) {
  1094. modified_config = *config;
  1095. }
  1096. modified_config.sdp_semantics = sdp_semantics_;
  1097. if (!dependencies.cert_generator) {
  1098. dependencies.cert_generator =
  1099. std::make_unique<FakeRTCCertificateGenerator>();
  1100. }
  1101. std::unique_ptr<PeerConnectionWrapper> client(
  1102. new PeerConnectionWrapper(debug_name));
  1103. if (!client->Init(options, &modified_config, std::move(dependencies),
  1104. network_thread_.get(), worker_thread_.get(),
  1105. std::move(event_log_factory),
  1106. std::move(media_transport_factory))) {
  1107. return nullptr;
  1108. }
  1109. return client;
  1110. }
  1111. std::unique_ptr<PeerConnectionWrapper>
  1112. CreatePeerConnectionWrapperWithFakeRtcEventLog(
  1113. const std::string& debug_name,
  1114. const PeerConnectionFactory::Options* options,
  1115. const RTCConfiguration* config,
  1116. webrtc::PeerConnectionDependencies dependencies) {
  1117. std::unique_ptr<webrtc::FakeRtcEventLogFactory> event_log_factory(
  1118. new webrtc::FakeRtcEventLogFactory(rtc::Thread::Current()));
  1119. return CreatePeerConnectionWrapper(debug_name, options, config,
  1120. std::move(dependencies),
  1121. std::move(event_log_factory),
  1122. /*media_transport_factory=*/nullptr);
  1123. }
  1124. bool CreatePeerConnectionWrappers() {
  1125. return CreatePeerConnectionWrappersWithConfig(
  1126. PeerConnectionInterface::RTCConfiguration(),
  1127. PeerConnectionInterface::RTCConfiguration());
  1128. }
  1129. bool CreatePeerConnectionWrappersWithSdpSemantics(
  1130. SdpSemantics caller_semantics,
  1131. SdpSemantics callee_semantics) {
  1132. // Can't specify the sdp_semantics in the passed-in configuration since it
  1133. // will be overwritten by CreatePeerConnectionWrapper with whatever is
  1134. // stored in sdp_semantics_. So get around this by modifying the instance
  1135. // variable before calling CreatePeerConnectionWrapper for the caller and
  1136. // callee PeerConnections.
  1137. SdpSemantics original_semantics = sdp_semantics_;
  1138. sdp_semantics_ = caller_semantics;
  1139. caller_ = CreatePeerConnectionWrapper(
  1140. "Caller", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
  1141. nullptr, /*media_transport_factory=*/nullptr);
  1142. sdp_semantics_ = callee_semantics;
  1143. callee_ = CreatePeerConnectionWrapper(
  1144. "Callee", nullptr, nullptr, webrtc::PeerConnectionDependencies(nullptr),
  1145. nullptr, /*media_transport_factory=*/nullptr);
  1146. sdp_semantics_ = original_semantics;
  1147. return caller_ && callee_;
  1148. }
  1149. bool CreatePeerConnectionWrappersWithConfig(
  1150. const PeerConnectionInterface::RTCConfiguration& caller_config,
  1151. const PeerConnectionInterface::RTCConfiguration& callee_config) {
  1152. caller_ = CreatePeerConnectionWrapper(
  1153. "Caller", nullptr, &caller_config,
  1154. webrtc::PeerConnectionDependencies(nullptr), nullptr,
  1155. /*media_transport_factory=*/nullptr);
  1156. callee_ = CreatePeerConnectionWrapper(
  1157. "Callee", nullptr, &callee_config,
  1158. webrtc::PeerConnectionDependencies(nullptr), nullptr,
  1159. /*media_transport_factory=*/nullptr);
  1160. return caller_ && callee_;
  1161. }
  1162. bool CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  1163. const PeerConnectionInterface::RTCConfiguration& caller_config,
  1164. const PeerConnectionInterface::RTCConfiguration& callee_config,
  1165. std::unique_ptr<webrtc::MediaTransportFactory> caller_factory,
  1166. std::unique_ptr<webrtc::MediaTransportFactory> callee_factory) {
  1167. caller_ =
  1168. CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
  1169. webrtc::PeerConnectionDependencies(nullptr),
  1170. nullptr, std::move(caller_factory));
  1171. callee_ =
  1172. CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
  1173. webrtc::PeerConnectionDependencies(nullptr),
  1174. nullptr, std::move(callee_factory));
  1175. return caller_ && callee_;
  1176. }
  1177. bool CreatePeerConnectionWrappersWithConfigAndDeps(
  1178. const PeerConnectionInterface::RTCConfiguration& caller_config,
  1179. webrtc::PeerConnectionDependencies caller_dependencies,
  1180. const PeerConnectionInterface::RTCConfiguration& callee_config,
  1181. webrtc::PeerConnectionDependencies callee_dependencies) {
  1182. caller_ =
  1183. CreatePeerConnectionWrapper("Caller", nullptr, &caller_config,
  1184. std::move(caller_dependencies), nullptr,
  1185. /*media_transport_factory=*/nullptr);
  1186. callee_ =
  1187. CreatePeerConnectionWrapper("Callee", nullptr, &callee_config,
  1188. std::move(callee_dependencies), nullptr,
  1189. /*media_transport_factory=*/nullptr);
  1190. return caller_ && callee_;
  1191. }
  1192. bool CreatePeerConnectionWrappersWithOptions(
  1193. const PeerConnectionFactory::Options& caller_options,
  1194. const PeerConnectionFactory::Options& callee_options) {
  1195. caller_ = CreatePeerConnectionWrapper(
  1196. "Caller", &caller_options, nullptr,
  1197. webrtc::PeerConnectionDependencies(nullptr), nullptr,
  1198. /*media_transport_factory=*/nullptr);
  1199. callee_ = CreatePeerConnectionWrapper(
  1200. "Callee", &callee_options, nullptr,
  1201. webrtc::PeerConnectionDependencies(nullptr), nullptr,
  1202. /*media_transport_factory=*/nullptr);
  1203. return caller_ && callee_;
  1204. }
  1205. bool CreatePeerConnectionWrappersWithFakeRtcEventLog() {
  1206. PeerConnectionInterface::RTCConfiguration default_config;
  1207. caller_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
  1208. "Caller", nullptr, &default_config,
  1209. webrtc::PeerConnectionDependencies(nullptr));
  1210. callee_ = CreatePeerConnectionWrapperWithFakeRtcEventLog(
  1211. "Callee", nullptr, &default_config,
  1212. webrtc::PeerConnectionDependencies(nullptr));
  1213. return caller_ && callee_;
  1214. }
  1215. std::unique_ptr<PeerConnectionWrapper>
  1216. CreatePeerConnectionWrapperWithAlternateKey() {
  1217. std::unique_ptr<FakeRTCCertificateGenerator> cert_generator(
  1218. new FakeRTCCertificateGenerator());
  1219. cert_generator->use_alternate_key();
  1220. webrtc::PeerConnectionDependencies dependencies(nullptr);
  1221. dependencies.cert_generator = std::move(cert_generator);
  1222. return CreatePeerConnectionWrapper("New Peer", nullptr, nullptr,
  1223. std::move(dependencies), nullptr,
  1224. /*media_transport_factory=*/nullptr);
  1225. }
  1226. cricket::TestTurnServer* CreateTurnServer(
  1227. rtc::SocketAddress internal_address,
  1228. rtc::SocketAddress external_address,
  1229. cricket::ProtocolType type = cricket::ProtocolType::PROTO_UDP,
  1230. const std::string& common_name = "test turn server") {
  1231. rtc::Thread* thread = network_thread();
  1232. std::unique_ptr<cricket::TestTurnServer> turn_server =
  1233. network_thread()->Invoke<std::unique_ptr<cricket::TestTurnServer>>(
  1234. RTC_FROM_HERE,
  1235. [thread, internal_address, external_address, type, common_name] {
  1236. return std::make_unique<cricket::TestTurnServer>(
  1237. thread, internal_address, external_address, type,
  1238. /*ignore_bad_certs=*/true, common_name);
  1239. });
  1240. turn_servers_.push_back(std::move(turn_server));
  1241. // Interactions with the turn server should be done on the network thread.
  1242. return turn_servers_.back().get();
  1243. }
  1244. cricket::TestTurnCustomizer* CreateTurnCustomizer() {
  1245. std::unique_ptr<cricket::TestTurnCustomizer> turn_customizer =
  1246. network_thread()->Invoke<std::unique_ptr<cricket::TestTurnCustomizer>>(
  1247. RTC_FROM_HERE,
  1248. [] { return std::make_unique<cricket::TestTurnCustomizer>(); });
  1249. turn_customizers_.push_back(std::move(turn_customizer));
  1250. // Interactions with the turn customizer should be done on the network
  1251. // thread.
  1252. return turn_customizers_.back().get();
  1253. }
  1254. // Checks that the function counters for a TestTurnCustomizer are greater than
  1255. // 0.
  1256. void ExpectTurnCustomizerCountersIncremented(
  1257. cricket::TestTurnCustomizer* turn_customizer) {
  1258. unsigned int allow_channel_data_counter =
  1259. network_thread()->Invoke<unsigned int>(
  1260. RTC_FROM_HERE, [turn_customizer] {
  1261. return turn_customizer->allow_channel_data_cnt_;
  1262. });
  1263. EXPECT_GT(allow_channel_data_counter, 0u);
  1264. unsigned int modify_counter = network_thread()->Invoke<unsigned int>(
  1265. RTC_FROM_HERE,
  1266. [turn_customizer] { return turn_customizer->modify_cnt_; });
  1267. EXPECT_GT(modify_counter, 0u);
  1268. }
  1269. // Once called, SDP blobs and ICE candidates will be automatically signaled
  1270. // between PeerConnections.
  1271. void ConnectFakeSignaling() {
  1272. caller_->set_signaling_message_receiver(callee_.get());
  1273. callee_->set_signaling_message_receiver(caller_.get());
  1274. }
  1275. // Once called, SDP blobs will be automatically signaled between
  1276. // PeerConnections. Note that ICE candidates will not be signaled unless they
  1277. // are in the exchanged SDP blobs.
  1278. void ConnectFakeSignalingForSdpOnly() {
  1279. ConnectFakeSignaling();
  1280. SetSignalIceCandidates(false);
  1281. }
  1282. void SetSignalingDelayMs(int delay_ms) {
  1283. caller_->set_signaling_delay_ms(delay_ms);
  1284. callee_->set_signaling_delay_ms(delay_ms);
  1285. }
  1286. void SetSignalIceCandidates(bool signal) {
  1287. caller_->set_signal_ice_candidates(signal);
  1288. callee_->set_signal_ice_candidates(signal);
  1289. }
  1290. // Messages may get lost on the unreliable DataChannel, so we send multiple
  1291. // times to avoid test flakiness.
  1292. void SendRtpDataWithRetries(webrtc::DataChannelInterface* dc,
  1293. const std::string& data,
  1294. int retries) {
  1295. for (int i = 0; i < retries; ++i) {
  1296. dc->Send(DataBuffer(data));
  1297. }
  1298. }
  1299. rtc::Thread* network_thread() { return network_thread_.get(); }
  1300. rtc::VirtualSocketServer* virtual_socket_server() { return ss_.get(); }
  1301. webrtc::MediaTransportPair* loopback_media_transports() {
  1302. return &loopback_media_transports_;
  1303. }
  1304. PeerConnectionWrapper* caller() { return caller_.get(); }
  1305. // Set the |caller_| to the |wrapper| passed in and return the
  1306. // original |caller_|.
  1307. PeerConnectionWrapper* SetCallerPcWrapperAndReturnCurrent(
  1308. PeerConnectionWrapper* wrapper) {
  1309. PeerConnectionWrapper* old = caller_.release();
  1310. caller_.reset(wrapper);
  1311. return old;
  1312. }
  1313. PeerConnectionWrapper* callee() { return callee_.get(); }
  1314. // Set the |callee_| to the |wrapper| passed in and return the
  1315. // original |callee_|.
  1316. PeerConnectionWrapper* SetCalleePcWrapperAndReturnCurrent(
  1317. PeerConnectionWrapper* wrapper) {
  1318. PeerConnectionWrapper* old = callee_.release();
  1319. callee_.reset(wrapper);
  1320. return old;
  1321. }
  1322. void SetPortAllocatorFlags(uint32_t caller_flags, uint32_t callee_flags) {
  1323. network_thread()->Invoke<void>(
  1324. RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
  1325. caller()->port_allocator(), caller_flags));
  1326. network_thread()->Invoke<void>(
  1327. RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::set_flags,
  1328. callee()->port_allocator(), callee_flags));
  1329. }
  1330. rtc::FirewallSocketServer* firewall() const { return fss_.get(); }
  1331. // Expects the provided number of new frames to be received within
  1332. // kMaxWaitForFramesMs. The new expected frames are specified in
  1333. // |media_expectations|. Returns false if any of the expectations were
  1334. // not met.
  1335. bool ExpectNewFrames(const MediaExpectations& media_expectations) {
  1336. // First initialize the expected frame counts based upon the current
  1337. // frame count.
  1338. int total_caller_audio_frames_expected = caller()->audio_frames_received();
  1339. if (media_expectations.caller_audio_expectation_ ==
  1340. MediaExpectations::kExpectSomeFrames) {
  1341. total_caller_audio_frames_expected +=
  1342. media_expectations.caller_audio_frames_expected_;
  1343. }
  1344. int total_caller_video_frames_expected =
  1345. caller()->min_video_frames_received_per_track();
  1346. if (media_expectations.caller_video_expectation_ ==
  1347. MediaExpectations::kExpectSomeFrames) {
  1348. total_caller_video_frames_expected +=
  1349. media_expectations.caller_video_frames_expected_;
  1350. }
  1351. int total_callee_audio_frames_expected = callee()->audio_frames_received();
  1352. if (media_expectations.callee_audio_expectation_ ==
  1353. MediaExpectations::kExpectSomeFrames) {
  1354. total_callee_audio_frames_expected +=
  1355. media_expectations.callee_audio_frames_expected_;
  1356. }
  1357. int total_callee_video_frames_expected =
  1358. callee()->min_video_frames_received_per_track();
  1359. if (media_expectations.callee_video_expectation_ ==
  1360. MediaExpectations::kExpectSomeFrames) {
  1361. total_callee_video_frames_expected +=
  1362. media_expectations.callee_video_frames_expected_;
  1363. }
  1364. // Wait for the expected frames.
  1365. EXPECT_TRUE_WAIT(caller()->audio_frames_received() >=
  1366. total_caller_audio_frames_expected &&
  1367. caller()->min_video_frames_received_per_track() >=
  1368. total_caller_video_frames_expected &&
  1369. callee()->audio_frames_received() >=
  1370. total_callee_audio_frames_expected &&
  1371. callee()->min_video_frames_received_per_track() >=
  1372. total_callee_video_frames_expected,
  1373. kMaxWaitForFramesMs);
  1374. bool expectations_correct =
  1375. caller()->audio_frames_received() >=
  1376. total_caller_audio_frames_expected &&
  1377. caller()->min_video_frames_received_per_track() >=
  1378. total_caller_video_frames_expected &&
  1379. callee()->audio_frames_received() >=
  1380. total_callee_audio_frames_expected &&
  1381. callee()->min_video_frames_received_per_track() >=
  1382. total_callee_video_frames_expected;
  1383. // After the combined wait, print out a more detailed message upon
  1384. // failure.
  1385. EXPECT_GE(caller()->audio_frames_received(),
  1386. total_caller_audio_frames_expected);
  1387. EXPECT_GE(caller()->min_video_frames_received_per_track(),
  1388. total_caller_video_frames_expected);
  1389. EXPECT_GE(callee()->audio_frames_received(),
  1390. total_callee_audio_frames_expected);
  1391. EXPECT_GE(callee()->min_video_frames_received_per_track(),
  1392. total_callee_video_frames_expected);
  1393. // We want to make sure nothing unexpected was received.
  1394. if (media_expectations.caller_audio_expectation_ ==
  1395. MediaExpectations::kExpectNoFrames) {
  1396. EXPECT_EQ(caller()->audio_frames_received(),
  1397. total_caller_audio_frames_expected);
  1398. if (caller()->audio_frames_received() !=
  1399. total_caller_audio_frames_expected) {
  1400. expectations_correct = false;
  1401. }
  1402. }
  1403. if (media_expectations.caller_video_expectation_ ==
  1404. MediaExpectations::kExpectNoFrames) {
  1405. EXPECT_EQ(caller()->min_video_frames_received_per_track(),
  1406. total_caller_video_frames_expected);
  1407. if (caller()->min_video_frames_received_per_track() !=
  1408. total_caller_video_frames_expected) {
  1409. expectations_correct = false;
  1410. }
  1411. }
  1412. if (media_expectations.callee_audio_expectation_ ==
  1413. MediaExpectations::kExpectNoFrames) {
  1414. EXPECT_EQ(callee()->audio_frames_received(),
  1415. total_callee_audio_frames_expected);
  1416. if (callee()->audio_frames_received() !=
  1417. total_callee_audio_frames_expected) {
  1418. expectations_correct = false;
  1419. }
  1420. }
  1421. if (media_expectations.callee_video_expectation_ ==
  1422. MediaExpectations::kExpectNoFrames) {
  1423. EXPECT_EQ(callee()->min_video_frames_received_per_track(),
  1424. total_callee_video_frames_expected);
  1425. if (callee()->min_video_frames_received_per_track() !=
  1426. total_callee_video_frames_expected) {
  1427. expectations_correct = false;
  1428. }
  1429. }
  1430. return expectations_correct;
  1431. }
  1432. void ClosePeerConnections() {
  1433. caller()->pc()->Close();
  1434. callee()->pc()->Close();
  1435. }
  1436. void TestNegotiatedCipherSuite(
  1437. const PeerConnectionFactory::Options& caller_options,
  1438. const PeerConnectionFactory::Options& callee_options,
  1439. int expected_cipher_suite) {
  1440. ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(caller_options,
  1441. callee_options));
  1442. ConnectFakeSignaling();
  1443. caller()->AddAudioVideoTracks();
  1444. callee()->AddAudioVideoTracks();
  1445. caller()->CreateAndSetAndSignalOffer();
  1446. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  1447. EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(expected_cipher_suite),
  1448. caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
  1449. // TODO(bugs.webrtc.org/9456): Fix it.
  1450. EXPECT_EQ(1, webrtc::metrics::NumEvents(
  1451. "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
  1452. expected_cipher_suite));
  1453. }
  1454. void TestGcmNegotiationUsesCipherSuite(bool local_gcm_enabled,
  1455. bool remote_gcm_enabled,
  1456. int expected_cipher_suite) {
  1457. PeerConnectionFactory::Options caller_options;
  1458. caller_options.crypto_options.srtp.enable_gcm_crypto_suites =
  1459. local_gcm_enabled;
  1460. PeerConnectionFactory::Options callee_options;
  1461. callee_options.crypto_options.srtp.enable_gcm_crypto_suites =
  1462. remote_gcm_enabled;
  1463. TestNegotiatedCipherSuite(caller_options, callee_options,
  1464. expected_cipher_suite);
  1465. }
  1466. protected:
  1467. SdpSemantics sdp_semantics_;
  1468. private:
  1469. // |ss_| is used by |network_thread_| so it must be destroyed later.
  1470. std::unique_ptr<rtc::VirtualSocketServer> ss_;
  1471. std::unique_ptr<rtc::FirewallSocketServer> fss_;
  1472. // |network_thread_| and |worker_thread_| are used by both
  1473. // |caller_| and |callee_| so they must be destroyed
  1474. // later.
  1475. std::unique_ptr<rtc::Thread> network_thread_;
  1476. std::unique_ptr<rtc::Thread> worker_thread_;
  1477. // The turn servers and turn customizers should be accessed & deleted on the
  1478. // network thread to avoid a race with the socket read/write that occurs
  1479. // on the network thread.
  1480. std::vector<std::unique_ptr<cricket::TestTurnServer>> turn_servers_;
  1481. std::vector<std::unique_ptr<cricket::TestTurnCustomizer>> turn_customizers_;
  1482. webrtc::MediaTransportPair loopback_media_transports_;
  1483. std::unique_ptr<PeerConnectionWrapper> caller_;
  1484. std::unique_ptr<PeerConnectionWrapper> callee_;
  1485. };
  1486. class PeerConnectionIntegrationTest
  1487. : public PeerConnectionIntegrationBaseTest,
  1488. public ::testing::WithParamInterface<SdpSemantics> {
  1489. protected:
  1490. PeerConnectionIntegrationTest()
  1491. : PeerConnectionIntegrationBaseTest(GetParam()) {}
  1492. };
  1493. class PeerConnectionIntegrationTestPlanB
  1494. : public PeerConnectionIntegrationBaseTest {
  1495. protected:
  1496. PeerConnectionIntegrationTestPlanB()
  1497. : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB) {}
  1498. };
  1499. class PeerConnectionIntegrationTestUnifiedPlan
  1500. : public PeerConnectionIntegrationBaseTest {
  1501. protected:
  1502. PeerConnectionIntegrationTestUnifiedPlan()
  1503. : PeerConnectionIntegrationBaseTest(SdpSemantics::kUnifiedPlan) {}
  1504. };
  1505. // Test the OnFirstPacketReceived callback from audio/video RtpReceivers. This
  1506. // includes testing that the callback is invoked if an observer is connected
  1507. // after the first packet has already been received.
  1508. TEST_P(PeerConnectionIntegrationTest,
  1509. RtpReceiverObserverOnFirstPacketReceived) {
  1510. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1511. ConnectFakeSignaling();
  1512. caller()->AddAudioVideoTracks();
  1513. callee()->AddAudioVideoTracks();
  1514. // Start offer/answer exchange and wait for it to complete.
  1515. caller()->CreateAndSetAndSignalOffer();
  1516. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1517. // Should be one receiver each for audio/video.
  1518. EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
  1519. EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
  1520. // Wait for all "first packet received" callbacks to be fired.
  1521. EXPECT_TRUE_WAIT(
  1522. absl::c_all_of(caller()->rtp_receiver_observers(),
  1523. [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
  1524. return o->first_packet_received();
  1525. }),
  1526. kMaxWaitForFramesMs);
  1527. EXPECT_TRUE_WAIT(
  1528. absl::c_all_of(callee()->rtp_receiver_observers(),
  1529. [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
  1530. return o->first_packet_received();
  1531. }),
  1532. kMaxWaitForFramesMs);
  1533. // If new observers are set after the first packet was already received, the
  1534. // callback should still be invoked.
  1535. caller()->ResetRtpReceiverObservers();
  1536. callee()->ResetRtpReceiverObservers();
  1537. EXPECT_EQ(2U, caller()->rtp_receiver_observers().size());
  1538. EXPECT_EQ(2U, callee()->rtp_receiver_observers().size());
  1539. EXPECT_TRUE(
  1540. absl::c_all_of(caller()->rtp_receiver_observers(),
  1541. [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
  1542. return o->first_packet_received();
  1543. }));
  1544. EXPECT_TRUE(
  1545. absl::c_all_of(callee()->rtp_receiver_observers(),
  1546. [](const std::unique_ptr<MockRtpReceiverObserver>& o) {
  1547. return o->first_packet_received();
  1548. }));
  1549. }
  1550. class DummyDtmfObserver : public DtmfSenderObserverInterface {
  1551. public:
  1552. DummyDtmfObserver() : completed_(false) {}
  1553. // Implements DtmfSenderObserverInterface.
  1554. void OnToneChange(const std::string& tone) override {
  1555. tones_.push_back(tone);
  1556. if (tone.empty()) {
  1557. completed_ = true;
  1558. }
  1559. }
  1560. const std::vector<std::string>& tones() const { return tones_; }
  1561. bool completed() const { return completed_; }
  1562. private:
  1563. bool completed_;
  1564. std::vector<std::string> tones_;
  1565. };
  1566. // Assumes |sender| already has an audio track added and the offer/answer
  1567. // exchange is done.
  1568. void TestDtmfFromSenderToReceiver(PeerConnectionWrapper* sender,
  1569. PeerConnectionWrapper* receiver) {
  1570. // We should be able to get a DTMF sender from the local sender.
  1571. rtc::scoped_refptr<DtmfSenderInterface> dtmf_sender =
  1572. sender->pc()->GetSenders().at(0)->GetDtmfSender();
  1573. ASSERT_TRUE(dtmf_sender);
  1574. DummyDtmfObserver observer;
  1575. dtmf_sender->RegisterObserver(&observer);
  1576. // Test the DtmfSender object just created.
  1577. EXPECT_TRUE(dtmf_sender->CanInsertDtmf());
  1578. EXPECT_TRUE(dtmf_sender->InsertDtmf("1a", 100, 50));
  1579. EXPECT_TRUE_WAIT(observer.completed(), kDefaultTimeout);
  1580. std::vector<std::string> tones = {"1", "a", ""};
  1581. EXPECT_EQ(tones, observer.tones());
  1582. dtmf_sender->UnregisterObserver();
  1583. // TODO(deadbeef): Verify the tones were actually received end-to-end.
  1584. }
  1585. // Verifies the DtmfSenderObserver callbacks for a DtmfSender (one in each
  1586. // direction).
  1587. TEST_P(PeerConnectionIntegrationTest, DtmfSenderObserver) {
  1588. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1589. ConnectFakeSignaling();
  1590. // Only need audio for DTMF.
  1591. caller()->AddAudioTrack();
  1592. callee()->AddAudioTrack();
  1593. caller()->CreateAndSetAndSignalOffer();
  1594. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1595. // DTLS must finish before the DTMF sender can be used reliably.
  1596. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  1597. TestDtmfFromSenderToReceiver(caller(), callee());
  1598. TestDtmfFromSenderToReceiver(callee(), caller());
  1599. }
  1600. // Basic end-to-end test, verifying media can be encoded/transmitted/decoded
  1601. // between two connections, using DTLS-SRTP.
  1602. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls) {
  1603. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1604. ConnectFakeSignaling();
  1605. // Do normal offer/answer and wait for some frames to be received in each
  1606. // direction.
  1607. caller()->AddAudioVideoTracks();
  1608. callee()->AddAudioVideoTracks();
  1609. caller()->CreateAndSetAndSignalOffer();
  1610. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1611. MediaExpectations media_expectations;
  1612. media_expectations.ExpectBidirectionalAudioAndVideo();
  1613. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1614. EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
  1615. webrtc::kEnumCounterKeyProtocolDtls));
  1616. EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
  1617. webrtc::kEnumCounterKeyProtocolSdes));
  1618. }
  1619. // Uses SDES instead of DTLS for key agreement.
  1620. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSdes) {
  1621. PeerConnectionInterface::RTCConfiguration sdes_config;
  1622. sdes_config.enable_dtls_srtp.emplace(false);
  1623. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(sdes_config, sdes_config));
  1624. ConnectFakeSignaling();
  1625. // Do normal offer/answer and wait for some frames to be received in each
  1626. // direction.
  1627. caller()->AddAudioVideoTracks();
  1628. callee()->AddAudioVideoTracks();
  1629. caller()->CreateAndSetAndSignalOffer();
  1630. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1631. MediaExpectations media_expectations;
  1632. media_expectations.ExpectBidirectionalAudioAndVideo();
  1633. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1634. EXPECT_LE(2, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
  1635. webrtc::kEnumCounterKeyProtocolSdes));
  1636. EXPECT_EQ(0, webrtc::metrics::NumEvents("WebRTC.PeerConnection.KeyProtocol",
  1637. webrtc::kEnumCounterKeyProtocolDtls));
  1638. }
  1639. // Basic end-to-end test specifying the |enable_encrypted_rtp_header_extensions|
  1640. // option to offer encrypted versions of all header extensions alongside the
  1641. // unencrypted versions.
  1642. TEST_P(PeerConnectionIntegrationTest,
  1643. EndToEndCallWithEncryptedRtpHeaderExtensions) {
  1644. CryptoOptions crypto_options;
  1645. crypto_options.srtp.enable_encrypted_rtp_header_extensions = true;
  1646. PeerConnectionInterface::RTCConfiguration config;
  1647. config.crypto_options = crypto_options;
  1648. // Note: This allows offering >14 RTP header extensions.
  1649. config.offer_extmap_allow_mixed = true;
  1650. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
  1651. ConnectFakeSignaling();
  1652. // Do normal offer/answer and wait for some frames to be received in each
  1653. // direction.
  1654. caller()->AddAudioVideoTracks();
  1655. callee()->AddAudioVideoTracks();
  1656. caller()->CreateAndSetAndSignalOffer();
  1657. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1658. MediaExpectations media_expectations;
  1659. media_expectations.ExpectBidirectionalAudioAndVideo();
  1660. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1661. }
  1662. // Tests that the GetRemoteAudioSSLCertificate method returns the remote DTLS
  1663. // certificate once the DTLS handshake has finished.
  1664. TEST_P(PeerConnectionIntegrationTest,
  1665. GetRemoteAudioSSLCertificateReturnsExchangedCertificate) {
  1666. auto GetRemoteAudioSSLCertificate = [](PeerConnectionWrapper* wrapper) {
  1667. auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
  1668. auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
  1669. return pc->GetRemoteAudioSSLCertificate();
  1670. };
  1671. auto GetRemoteAudioSSLCertChain = [](PeerConnectionWrapper* wrapper) {
  1672. auto pci = reinterpret_cast<PeerConnectionProxy*>(wrapper->pc());
  1673. auto pc = reinterpret_cast<PeerConnection*>(pci->internal());
  1674. return pc->GetRemoteAudioSSLCertChain();
  1675. };
  1676. auto caller_cert = rtc::RTCCertificate::FromPEM(kRsaPems[0]);
  1677. auto callee_cert = rtc::RTCCertificate::FromPEM(kRsaPems[1]);
  1678. // Configure each side with a known certificate so they can be compared later.
  1679. PeerConnectionInterface::RTCConfiguration caller_config;
  1680. caller_config.enable_dtls_srtp.emplace(true);
  1681. caller_config.certificates.push_back(caller_cert);
  1682. PeerConnectionInterface::RTCConfiguration callee_config;
  1683. callee_config.enable_dtls_srtp.emplace(true);
  1684. callee_config.certificates.push_back(callee_cert);
  1685. ASSERT_TRUE(
  1686. CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
  1687. ConnectFakeSignaling();
  1688. // When first initialized, there should not be a remote SSL certificate (and
  1689. // calling this method should not crash).
  1690. EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(caller()));
  1691. EXPECT_EQ(nullptr, GetRemoteAudioSSLCertificate(callee()));
  1692. EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(caller()));
  1693. EXPECT_EQ(nullptr, GetRemoteAudioSSLCertChain(callee()));
  1694. caller()->AddAudioTrack();
  1695. callee()->AddAudioTrack();
  1696. caller()->CreateAndSetAndSignalOffer();
  1697. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1698. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  1699. // Once DTLS has been connected, each side should return the other's SSL
  1700. // certificate when calling GetRemoteAudioSSLCertificate.
  1701. auto caller_remote_cert = GetRemoteAudioSSLCertificate(caller());
  1702. ASSERT_TRUE(caller_remote_cert);
  1703. EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
  1704. caller_remote_cert->ToPEMString());
  1705. auto callee_remote_cert = GetRemoteAudioSSLCertificate(callee());
  1706. ASSERT_TRUE(callee_remote_cert);
  1707. EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
  1708. callee_remote_cert->ToPEMString());
  1709. auto caller_remote_cert_chain = GetRemoteAudioSSLCertChain(caller());
  1710. ASSERT_TRUE(caller_remote_cert_chain);
  1711. ASSERT_EQ(1U, caller_remote_cert_chain->GetSize());
  1712. auto remote_cert = &caller_remote_cert_chain->Get(0);
  1713. EXPECT_EQ(callee_cert->GetSSLCertificate().ToPEMString(),
  1714. remote_cert->ToPEMString());
  1715. auto callee_remote_cert_chain = GetRemoteAudioSSLCertChain(callee());
  1716. ASSERT_TRUE(callee_remote_cert_chain);
  1717. ASSERT_EQ(1U, callee_remote_cert_chain->GetSize());
  1718. remote_cert = &callee_remote_cert_chain->Get(0);
  1719. EXPECT_EQ(caller_cert->GetSSLCertificate().ToPEMString(),
  1720. remote_cert->ToPEMString());
  1721. }
  1722. // This test sets up a call between two parties with a source resolution of
  1723. // 1280x720 and verifies that a 16:9 aspect ratio is received.
  1724. TEST_P(PeerConnectionIntegrationTest,
  1725. Send1280By720ResolutionAndReceive16To9AspectRatio) {
  1726. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1727. ConnectFakeSignaling();
  1728. // Add video tracks with 16:9 aspect ratio, size 1280 x 720.
  1729. webrtc::FakePeriodicVideoSource::Config config;
  1730. config.width = 1280;
  1731. config.height = 720;
  1732. config.timestamp_offset_ms = rtc::TimeMillis();
  1733. caller()->AddTrack(caller()->CreateLocalVideoTrackWithConfig(config));
  1734. callee()->AddTrack(callee()->CreateLocalVideoTrackWithConfig(config));
  1735. // Do normal offer/answer and wait for at least one frame to be received in
  1736. // each direction.
  1737. caller()->CreateAndSetAndSignalOffer();
  1738. ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
  1739. callee()->min_video_frames_received_per_track() > 0,
  1740. kMaxWaitForFramesMs);
  1741. // Check rendered aspect ratio.
  1742. EXPECT_EQ(16.0 / 9, caller()->local_rendered_aspect_ratio());
  1743. EXPECT_EQ(16.0 / 9, caller()->rendered_aspect_ratio());
  1744. EXPECT_EQ(16.0 / 9, callee()->local_rendered_aspect_ratio());
  1745. EXPECT_EQ(16.0 / 9, callee()->rendered_aspect_ratio());
  1746. }
  1747. // This test sets up an one-way call, with media only from caller to
  1748. // callee.
  1749. TEST_P(PeerConnectionIntegrationTest, OneWayMediaCall) {
  1750. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1751. ConnectFakeSignaling();
  1752. caller()->AddAudioVideoTracks();
  1753. caller()->CreateAndSetAndSignalOffer();
  1754. MediaExpectations media_expectations;
  1755. media_expectations.CalleeExpectsSomeAudioAndVideo();
  1756. media_expectations.CallerExpectsNoAudio();
  1757. media_expectations.CallerExpectsNoVideo();
  1758. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1759. }
  1760. // This test sets up a audio call initially, with the callee rejecting video
  1761. // initially. Then later the callee decides to upgrade to audio/video, and
  1762. // initiates a new offer/answer exchange.
  1763. TEST_P(PeerConnectionIntegrationTest, AudioToVideoUpgrade) {
  1764. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1765. ConnectFakeSignaling();
  1766. // Initially, offer an audio/video stream from the caller, but refuse to
  1767. // send/receive video on the callee side.
  1768. caller()->AddAudioVideoTracks();
  1769. callee()->AddAudioTrack();
  1770. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  1771. PeerConnectionInterface::RTCOfferAnswerOptions options;
  1772. options.offer_to_receive_video = 0;
  1773. callee()->SetOfferAnswerOptions(options);
  1774. } else {
  1775. callee()->SetRemoteOfferHandler([this] {
  1776. callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
  1777. });
  1778. }
  1779. // Do offer/answer and make sure audio is still received end-to-end.
  1780. caller()->CreateAndSetAndSignalOffer();
  1781. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1782. {
  1783. MediaExpectations media_expectations;
  1784. media_expectations.ExpectBidirectionalAudio();
  1785. media_expectations.ExpectNoVideo();
  1786. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1787. }
  1788. // Sanity check that the callee's description has a rejected video section.
  1789. ASSERT_NE(nullptr, callee()->pc()->local_description());
  1790. const ContentInfo* callee_video_content =
  1791. GetFirstVideoContent(callee()->pc()->local_description()->description());
  1792. ASSERT_NE(nullptr, callee_video_content);
  1793. EXPECT_TRUE(callee_video_content->rejected);
  1794. // Now negotiate with video and ensure negotiation succeeds, with video
  1795. // frames and additional audio frames being received.
  1796. callee()->AddVideoTrack();
  1797. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  1798. PeerConnectionInterface::RTCOfferAnswerOptions options;
  1799. options.offer_to_receive_video = 1;
  1800. callee()->SetOfferAnswerOptions(options);
  1801. } else {
  1802. callee()->SetRemoteOfferHandler(nullptr);
  1803. caller()->SetRemoteOfferHandler([this] {
  1804. // The caller creates a new transceiver to receive video on when receiving
  1805. // the offer, but by default it is send only.
  1806. auto transceivers = caller()->pc()->GetTransceivers();
  1807. ASSERT_EQ(3U, transceivers.size());
  1808. ASSERT_EQ(cricket::MEDIA_TYPE_VIDEO,
  1809. transceivers[2]->receiver()->media_type());
  1810. transceivers[2]->sender()->SetTrack(caller()->CreateLocalVideoTrack());
  1811. transceivers[2]->SetDirection(RtpTransceiverDirection::kSendRecv);
  1812. });
  1813. }
  1814. callee()->CreateAndSetAndSignalOffer();
  1815. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1816. {
  1817. // Expect additional audio frames to be received after the upgrade.
  1818. MediaExpectations media_expectations;
  1819. media_expectations.ExpectBidirectionalAudioAndVideo();
  1820. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1821. }
  1822. }
  1823. // Simpler than the above test; just add an audio track to an established
  1824. // video-only connection.
  1825. TEST_P(PeerConnectionIntegrationTest, AddAudioToVideoOnlyCall) {
  1826. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1827. ConnectFakeSignaling();
  1828. // Do initial offer/answer with just a video track.
  1829. caller()->AddVideoTrack();
  1830. callee()->AddVideoTrack();
  1831. caller()->CreateAndSetAndSignalOffer();
  1832. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1833. // Now add an audio track and do another offer/answer.
  1834. caller()->AddAudioTrack();
  1835. callee()->AddAudioTrack();
  1836. caller()->CreateAndSetAndSignalOffer();
  1837. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1838. // Ensure both audio and video frames are received end-to-end.
  1839. MediaExpectations media_expectations;
  1840. media_expectations.ExpectBidirectionalAudioAndVideo();
  1841. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1842. }
  1843. // This test sets up a call that's transferred to a new caller with a different
  1844. // DTLS fingerprint.
  1845. TEST_P(PeerConnectionIntegrationTest, CallTransferredForCallee) {
  1846. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1847. ConnectFakeSignaling();
  1848. caller()->AddAudioVideoTracks();
  1849. callee()->AddAudioVideoTracks();
  1850. caller()->CreateAndSetAndSignalOffer();
  1851. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1852. // Keep the original peer around which will still send packets to the
  1853. // receiving client. These SRTP packets will be dropped.
  1854. std::unique_ptr<PeerConnectionWrapper> original_peer(
  1855. SetCallerPcWrapperAndReturnCurrent(
  1856. CreatePeerConnectionWrapperWithAlternateKey().release()));
  1857. // TODO(deadbeef): Why do we call Close here? That goes against the comment
  1858. // directly above.
  1859. original_peer->pc()->Close();
  1860. ConnectFakeSignaling();
  1861. caller()->AddAudioVideoTracks();
  1862. caller()->CreateAndSetAndSignalOffer();
  1863. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1864. // Wait for some additional frames to be transmitted end-to-end.
  1865. MediaExpectations media_expectations;
  1866. media_expectations.ExpectBidirectionalAudioAndVideo();
  1867. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1868. }
  1869. // This test sets up a call that's transferred to a new callee with a different
  1870. // DTLS fingerprint.
  1871. TEST_P(PeerConnectionIntegrationTest, CallTransferredForCaller) {
  1872. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1873. ConnectFakeSignaling();
  1874. caller()->AddAudioVideoTracks();
  1875. callee()->AddAudioVideoTracks();
  1876. caller()->CreateAndSetAndSignalOffer();
  1877. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1878. // Keep the original peer around which will still send packets to the
  1879. // receiving client. These SRTP packets will be dropped.
  1880. std::unique_ptr<PeerConnectionWrapper> original_peer(
  1881. SetCalleePcWrapperAndReturnCurrent(
  1882. CreatePeerConnectionWrapperWithAlternateKey().release()));
  1883. // TODO(deadbeef): Why do we call Close here? That goes against the comment
  1884. // directly above.
  1885. original_peer->pc()->Close();
  1886. ConnectFakeSignaling();
  1887. callee()->AddAudioVideoTracks();
  1888. caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
  1889. caller()->CreateAndSetAndSignalOffer();
  1890. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1891. // Wait for some additional frames to be transmitted end-to-end.
  1892. MediaExpectations media_expectations;
  1893. media_expectations.ExpectBidirectionalAudioAndVideo();
  1894. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1895. }
  1896. // This test sets up a non-bundled call and negotiates bundling at the same
  1897. // time as starting an ICE restart. When bundling is in effect in the restart,
  1898. // the DTLS-SRTP context should be successfully reset.
  1899. TEST_P(PeerConnectionIntegrationTest, BundlingEnabledWhileIceRestartOccurs) {
  1900. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1901. ConnectFakeSignaling();
  1902. caller()->AddAudioVideoTracks();
  1903. callee()->AddAudioVideoTracks();
  1904. // Remove the bundle group from the SDP received by the callee.
  1905. callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
  1906. desc->RemoveGroupByName("BUNDLE");
  1907. });
  1908. caller()->CreateAndSetAndSignalOffer();
  1909. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1910. {
  1911. MediaExpectations media_expectations;
  1912. media_expectations.ExpectBidirectionalAudioAndVideo();
  1913. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1914. }
  1915. // Now stop removing the BUNDLE group, and trigger an ICE restart.
  1916. callee()->SetReceivedSdpMunger(nullptr);
  1917. caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
  1918. caller()->CreateAndSetAndSignalOffer();
  1919. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1920. // Expect additional frames to be received after the ICE restart.
  1921. {
  1922. MediaExpectations media_expectations;
  1923. media_expectations.ExpectBidirectionalAudioAndVideo();
  1924. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  1925. }
  1926. }
  1927. // Test CVO (Coordination of Video Orientation). If a video source is rotated
  1928. // and both peers support the CVO RTP header extension, the actual video frames
  1929. // don't need to be encoded in different resolutions, since the rotation is
  1930. // communicated through the RTP header extension.
  1931. TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithCVOExtension) {
  1932. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1933. ConnectFakeSignaling();
  1934. // Add rotated video tracks.
  1935. caller()->AddTrack(
  1936. caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
  1937. callee()->AddTrack(
  1938. callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
  1939. // Wait for video frames to be received by both sides.
  1940. caller()->CreateAndSetAndSignalOffer();
  1941. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1942. ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
  1943. callee()->min_video_frames_received_per_track() > 0,
  1944. kMaxWaitForFramesMs);
  1945. // Ensure that the aspect ratio is unmodified.
  1946. // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
  1947. // not just assumed.
  1948. EXPECT_EQ(4.0 / 3, caller()->local_rendered_aspect_ratio());
  1949. EXPECT_EQ(4.0 / 3, caller()->rendered_aspect_ratio());
  1950. EXPECT_EQ(4.0 / 3, callee()->local_rendered_aspect_ratio());
  1951. EXPECT_EQ(4.0 / 3, callee()->rendered_aspect_ratio());
  1952. // Ensure that the CVO bits were surfaced to the renderer.
  1953. EXPECT_EQ(webrtc::kVideoRotation_270, caller()->rendered_rotation());
  1954. EXPECT_EQ(webrtc::kVideoRotation_90, callee()->rendered_rotation());
  1955. }
  1956. // Test that when the CVO extension isn't supported, video is rotated the
  1957. // old-fashioned way, by encoding rotated frames.
  1958. TEST_P(PeerConnectionIntegrationTest, RotatedVideoWithoutCVOExtension) {
  1959. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1960. ConnectFakeSignaling();
  1961. // Add rotated video tracks.
  1962. caller()->AddTrack(
  1963. caller()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_90));
  1964. callee()->AddTrack(
  1965. callee()->CreateLocalVideoTrackWithRotation(webrtc::kVideoRotation_270));
  1966. // Remove the CVO extension from the offered SDP.
  1967. callee()->SetReceivedSdpMunger([](cricket::SessionDescription* desc) {
  1968. cricket::VideoContentDescription* video =
  1969. GetFirstVideoContentDescription(desc);
  1970. video->ClearRtpHeaderExtensions();
  1971. });
  1972. // Wait for video frames to be received by both sides.
  1973. caller()->CreateAndSetAndSignalOffer();
  1974. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  1975. ASSERT_TRUE_WAIT(caller()->min_video_frames_received_per_track() > 0 &&
  1976. callee()->min_video_frames_received_per_track() > 0,
  1977. kMaxWaitForFramesMs);
  1978. // Expect that the aspect ratio is inversed to account for the 90/270 degree
  1979. // rotation.
  1980. // TODO(deadbeef): Where does 4:3 come from? Should be explicit in the test,
  1981. // not just assumed.
  1982. EXPECT_EQ(3.0 / 4, caller()->local_rendered_aspect_ratio());
  1983. EXPECT_EQ(3.0 / 4, caller()->rendered_aspect_ratio());
  1984. EXPECT_EQ(3.0 / 4, callee()->local_rendered_aspect_ratio());
  1985. EXPECT_EQ(3.0 / 4, callee()->rendered_aspect_ratio());
  1986. // Expect that each endpoint is unaware of the rotation of the other endpoint.
  1987. EXPECT_EQ(webrtc::kVideoRotation_0, caller()->rendered_rotation());
  1988. EXPECT_EQ(webrtc::kVideoRotation_0, callee()->rendered_rotation());
  1989. }
  1990. // Test that if the answerer rejects the audio m= section, no audio is sent or
  1991. // received, but video still can be.
  1992. TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioSection) {
  1993. ASSERT_TRUE(CreatePeerConnectionWrappers());
  1994. ConnectFakeSignaling();
  1995. caller()->AddAudioVideoTracks();
  1996. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  1997. // Only add video track for callee, and set offer_to_receive_audio to 0, so
  1998. // it will reject the audio m= section completely.
  1999. PeerConnectionInterface::RTCOfferAnswerOptions options;
  2000. options.offer_to_receive_audio = 0;
  2001. callee()->SetOfferAnswerOptions(options);
  2002. } else {
  2003. // Stopping the audio RtpTransceiver will cause the media section to be
  2004. // rejected in the answer.
  2005. callee()->SetRemoteOfferHandler([this] {
  2006. callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)->Stop();
  2007. });
  2008. }
  2009. callee()->AddTrack(callee()->CreateLocalVideoTrack());
  2010. // Do offer/answer and wait for successful end-to-end video frames.
  2011. caller()->CreateAndSetAndSignalOffer();
  2012. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2013. MediaExpectations media_expectations;
  2014. media_expectations.ExpectBidirectionalVideo();
  2015. media_expectations.ExpectNoAudio();
  2016. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2017. // Sanity check that the callee's description has a rejected audio section.
  2018. ASSERT_NE(nullptr, callee()->pc()->local_description());
  2019. const ContentInfo* callee_audio_content =
  2020. GetFirstAudioContent(callee()->pc()->local_description()->description());
  2021. ASSERT_NE(nullptr, callee_audio_content);
  2022. EXPECT_TRUE(callee_audio_content->rejected);
  2023. if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
  2024. // The caller's transceiver should have stopped after receiving the answer.
  2025. EXPECT_TRUE(caller()
  2026. ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_AUDIO)
  2027. ->stopped());
  2028. }
  2029. }
  2030. // Test that if the answerer rejects the video m= section, no video is sent or
  2031. // received, but audio still can be.
  2032. TEST_P(PeerConnectionIntegrationTest, AnswererRejectsVideoSection) {
  2033. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2034. ConnectFakeSignaling();
  2035. caller()->AddAudioVideoTracks();
  2036. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  2037. // Only add audio track for callee, and set offer_to_receive_video to 0, so
  2038. // it will reject the video m= section completely.
  2039. PeerConnectionInterface::RTCOfferAnswerOptions options;
  2040. options.offer_to_receive_video = 0;
  2041. callee()->SetOfferAnswerOptions(options);
  2042. } else {
  2043. // Stopping the video RtpTransceiver will cause the media section to be
  2044. // rejected in the answer.
  2045. callee()->SetRemoteOfferHandler([this] {
  2046. callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
  2047. });
  2048. }
  2049. callee()->AddTrack(callee()->CreateLocalAudioTrack());
  2050. // Do offer/answer and wait for successful end-to-end audio frames.
  2051. caller()->CreateAndSetAndSignalOffer();
  2052. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2053. MediaExpectations media_expectations;
  2054. media_expectations.ExpectBidirectionalAudio();
  2055. media_expectations.ExpectNoVideo();
  2056. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2057. // Sanity check that the callee's description has a rejected video section.
  2058. ASSERT_NE(nullptr, callee()->pc()->local_description());
  2059. const ContentInfo* callee_video_content =
  2060. GetFirstVideoContent(callee()->pc()->local_description()->description());
  2061. ASSERT_NE(nullptr, callee_video_content);
  2062. EXPECT_TRUE(callee_video_content->rejected);
  2063. if (sdp_semantics_ == SdpSemantics::kUnifiedPlan) {
  2064. // The caller's transceiver should have stopped after receiving the answer.
  2065. EXPECT_TRUE(caller()
  2066. ->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)
  2067. ->stopped());
  2068. }
  2069. }
  2070. // Test that if the answerer rejects both audio and video m= sections, nothing
  2071. // bad happens.
  2072. // TODO(deadbeef): Test that a data channel still works. Currently this doesn't
  2073. // test anything but the fact that negotiation succeeds, which doesn't mean
  2074. // much.
  2075. TEST_P(PeerConnectionIntegrationTest, AnswererRejectsAudioAndVideoSections) {
  2076. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2077. ConnectFakeSignaling();
  2078. caller()->AddAudioVideoTracks();
  2079. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  2080. // Don't give the callee any tracks, and set offer_to_receive_X to 0, so it
  2081. // will reject both audio and video m= sections.
  2082. PeerConnectionInterface::RTCOfferAnswerOptions options;
  2083. options.offer_to_receive_audio = 0;
  2084. options.offer_to_receive_video = 0;
  2085. callee()->SetOfferAnswerOptions(options);
  2086. } else {
  2087. callee()->SetRemoteOfferHandler([this] {
  2088. // Stopping all transceivers will cause all media sections to be rejected.
  2089. for (const auto& transceiver : callee()->pc()->GetTransceivers()) {
  2090. transceiver->Stop();
  2091. }
  2092. });
  2093. }
  2094. // Do offer/answer and wait for stable signaling state.
  2095. caller()->CreateAndSetAndSignalOffer();
  2096. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2097. // Sanity check that the callee's description has rejected m= sections.
  2098. ASSERT_NE(nullptr, callee()->pc()->local_description());
  2099. const ContentInfo* callee_audio_content =
  2100. GetFirstAudioContent(callee()->pc()->local_description()->description());
  2101. ASSERT_NE(nullptr, callee_audio_content);
  2102. EXPECT_TRUE(callee_audio_content->rejected);
  2103. const ContentInfo* callee_video_content =
  2104. GetFirstVideoContent(callee()->pc()->local_description()->description());
  2105. ASSERT_NE(nullptr, callee_video_content);
  2106. EXPECT_TRUE(callee_video_content->rejected);
  2107. }
  2108. // This test sets up an audio and video call between two parties. After the
  2109. // call runs for a while, the caller sends an updated offer with video being
  2110. // rejected. Once the re-negotiation is done, the video flow should stop and
  2111. // the audio flow should continue.
  2112. TEST_P(PeerConnectionIntegrationTest, VideoRejectedInSubsequentOffer) {
  2113. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2114. ConnectFakeSignaling();
  2115. caller()->AddAudioVideoTracks();
  2116. callee()->AddAudioVideoTracks();
  2117. caller()->CreateAndSetAndSignalOffer();
  2118. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2119. {
  2120. MediaExpectations media_expectations;
  2121. media_expectations.ExpectBidirectionalAudioAndVideo();
  2122. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2123. }
  2124. // Renegotiate, rejecting the video m= section.
  2125. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  2126. caller()->SetGeneratedSdpMunger(
  2127. [](cricket::SessionDescription* description) {
  2128. for (cricket::ContentInfo& content : description->contents()) {
  2129. if (cricket::IsVideoContent(&content)) {
  2130. content.rejected = true;
  2131. }
  2132. }
  2133. });
  2134. } else {
  2135. caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
  2136. }
  2137. caller()->CreateAndSetAndSignalOffer();
  2138. ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
  2139. // Sanity check that the caller's description has a rejected video section.
  2140. ASSERT_NE(nullptr, caller()->pc()->local_description());
  2141. const ContentInfo* caller_video_content =
  2142. GetFirstVideoContent(caller()->pc()->local_description()->description());
  2143. ASSERT_NE(nullptr, caller_video_content);
  2144. EXPECT_TRUE(caller_video_content->rejected);
  2145. // Wait for some additional audio frames to be received.
  2146. {
  2147. MediaExpectations media_expectations;
  2148. media_expectations.ExpectBidirectionalAudio();
  2149. media_expectations.ExpectNoVideo();
  2150. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2151. }
  2152. }
  2153. // Do one offer/answer with audio, another that disables it (rejecting the m=
  2154. // section), and another that re-enables it. Regression test for:
  2155. // bugs.webrtc.org/6023
  2156. TEST_F(PeerConnectionIntegrationTestPlanB, EnableAudioAfterRejecting) {
  2157. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2158. ConnectFakeSignaling();
  2159. // Add audio track, do normal offer/answer.
  2160. rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
  2161. caller()->CreateLocalAudioTrack();
  2162. rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
  2163. caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
  2164. caller()->CreateAndSetAndSignalOffer();
  2165. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2166. // Remove audio track, and set offer_to_receive_audio to false to cause the
  2167. // m= section to be completely disabled, not just "recvonly".
  2168. caller()->pc()->RemoveTrack(sender);
  2169. PeerConnectionInterface::RTCOfferAnswerOptions options;
  2170. options.offer_to_receive_audio = 0;
  2171. caller()->SetOfferAnswerOptions(options);
  2172. caller()->CreateAndSetAndSignalOffer();
  2173. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2174. // Add the audio track again, expecting negotiation to succeed and frames to
  2175. // flow.
  2176. sender = caller()->pc()->AddTrack(track, {"stream"}).MoveValue();
  2177. options.offer_to_receive_audio = 1;
  2178. caller()->SetOfferAnswerOptions(options);
  2179. caller()->CreateAndSetAndSignalOffer();
  2180. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2181. MediaExpectations media_expectations;
  2182. media_expectations.CalleeExpectsSomeAudio();
  2183. EXPECT_TRUE(ExpectNewFrames(media_expectations));
  2184. }
  2185. // Basic end-to-end test, but without SSRC/MSID signaling. This functionality
  2186. // is needed to support legacy endpoints.
  2187. // TODO(deadbeef): When we support the MID extension and demuxing on MID, also
  2188. // add a test for an end-to-end test without MID signaling either (basically,
  2189. // the minimum acceptable SDP).
  2190. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithoutSsrcOrMsidSignaling) {
  2191. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2192. ConnectFakeSignaling();
  2193. // Add audio and video, testing that packets can be demuxed on payload type.
  2194. caller()->AddAudioVideoTracks();
  2195. callee()->AddAudioVideoTracks();
  2196. // Remove SSRCs and MSIDs from the received offer SDP.
  2197. callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
  2198. caller()->CreateAndSetAndSignalOffer();
  2199. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2200. MediaExpectations media_expectations;
  2201. media_expectations.ExpectBidirectionalAudioAndVideo();
  2202. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2203. }
  2204. // Basic end-to-end test, without SSRC signaling. This means that the track
  2205. // was created properly and frames are delivered when the MSIDs are communicated
  2206. // with a=msid lines and no a=ssrc lines.
  2207. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  2208. EndToEndCallWithoutSsrcSignaling) {
  2209. const char kStreamId[] = "streamId";
  2210. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2211. ConnectFakeSignaling();
  2212. // Add just audio tracks.
  2213. caller()->AddTrack(caller()->CreateLocalAudioTrack(), {kStreamId});
  2214. callee()->AddAudioTrack();
  2215. // Remove SSRCs from the received offer SDP.
  2216. callee()->SetReceivedSdpMunger(RemoveSsrcsAndKeepMsids);
  2217. caller()->CreateAndSetAndSignalOffer();
  2218. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2219. MediaExpectations media_expectations;
  2220. media_expectations.ExpectBidirectionalAudio();
  2221. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2222. }
  2223. // Tests that video flows between multiple video tracks when SSRCs are not
  2224. // signaled. This exercises the MID RTP header extension which is needed to
  2225. // demux the incoming video tracks.
  2226. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  2227. EndToEndCallWithTwoVideoTracksAndNoSignaledSsrc) {
  2228. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2229. ConnectFakeSignaling();
  2230. caller()->AddVideoTrack();
  2231. caller()->AddVideoTrack();
  2232. callee()->AddVideoTrack();
  2233. callee()->AddVideoTrack();
  2234. caller()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
  2235. callee()->SetReceivedSdpMunger(&RemoveSsrcsAndKeepMsids);
  2236. caller()->CreateAndSetAndSignalOffer();
  2237. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2238. ASSERT_EQ(2u, caller()->pc()->GetReceivers().size());
  2239. ASSERT_EQ(2u, callee()->pc()->GetReceivers().size());
  2240. // Expect video to be received in both directions on both tracks.
  2241. MediaExpectations media_expectations;
  2242. media_expectations.ExpectBidirectionalVideo();
  2243. EXPECT_TRUE(ExpectNewFrames(media_expectations));
  2244. }
  2245. TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLinePresent) {
  2246. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2247. ConnectFakeSignaling();
  2248. caller()->AddAudioTrack();
  2249. caller()->AddVideoTrack();
  2250. caller()->CreateAndSetAndSignalOffer();
  2251. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2252. auto callee_receivers = callee()->pc()->GetReceivers();
  2253. ASSERT_EQ(2u, callee_receivers.size());
  2254. EXPECT_TRUE(callee_receivers[0]->stream_ids().empty());
  2255. EXPECT_TRUE(callee_receivers[1]->stream_ids().empty());
  2256. }
  2257. TEST_F(PeerConnectionIntegrationTestUnifiedPlan, NoStreamsMsidLineMissing) {
  2258. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2259. ConnectFakeSignaling();
  2260. caller()->AddAudioTrack();
  2261. caller()->AddVideoTrack();
  2262. callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
  2263. caller()->CreateAndSetAndSignalOffer();
  2264. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2265. auto callee_receivers = callee()->pc()->GetReceivers();
  2266. ASSERT_EQ(2u, callee_receivers.size());
  2267. ASSERT_EQ(1u, callee_receivers[0]->stream_ids().size());
  2268. ASSERT_EQ(1u, callee_receivers[1]->stream_ids().size());
  2269. EXPECT_EQ(callee_receivers[0]->stream_ids()[0],
  2270. callee_receivers[1]->stream_ids()[0]);
  2271. EXPECT_EQ(callee_receivers[0]->streams()[0],
  2272. callee_receivers[1]->streams()[0]);
  2273. }
  2274. // Test that if two video tracks are sent (from caller to callee, in this test),
  2275. // they're transmitted correctly end-to-end.
  2276. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithTwoVideoTracks) {
  2277. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2278. ConnectFakeSignaling();
  2279. // Add one audio/video stream, and one video-only stream.
  2280. caller()->AddAudioVideoTracks();
  2281. caller()->AddVideoTrack();
  2282. caller()->CreateAndSetAndSignalOffer();
  2283. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2284. ASSERT_EQ(3u, callee()->pc()->GetReceivers().size());
  2285. MediaExpectations media_expectations;
  2286. media_expectations.CalleeExpectsSomeAudioAndVideo();
  2287. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2288. }
  2289. static void MakeSpecCompliantMaxBundleOffer(cricket::SessionDescription* desc) {
  2290. bool first = true;
  2291. for (cricket::ContentInfo& content : desc->contents()) {
  2292. if (first) {
  2293. first = false;
  2294. continue;
  2295. }
  2296. content.bundle_only = true;
  2297. }
  2298. first = true;
  2299. for (cricket::TransportInfo& transport : desc->transport_infos()) {
  2300. if (first) {
  2301. first = false;
  2302. continue;
  2303. }
  2304. transport.description.ice_ufrag.clear();
  2305. transport.description.ice_pwd.clear();
  2306. transport.description.connection_role = cricket::CONNECTIONROLE_NONE;
  2307. transport.description.identity_fingerprint.reset(nullptr);
  2308. }
  2309. }
  2310. // Test that if applying a true "max bundle" offer, which uses ports of 0,
  2311. // "a=bundle-only", omitting "a=fingerprint", "a=setup", "a=ice-ufrag" and
  2312. // "a=ice-pwd" for all but the audio "m=" section, negotiation still completes
  2313. // successfully and media flows.
  2314. // TODO(deadbeef): Update this test to also omit "a=rtcp-mux", once that works.
  2315. // TODO(deadbeef): Won't need this test once we start generating actual
  2316. // standards-compliant SDP.
  2317. TEST_P(PeerConnectionIntegrationTest,
  2318. EndToEndCallWithSpecCompliantMaxBundleOffer) {
  2319. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2320. ConnectFakeSignaling();
  2321. caller()->AddAudioVideoTracks();
  2322. callee()->AddAudioVideoTracks();
  2323. // Do the equivalent of setting the port to 0, adding a=bundle-only, and
  2324. // removing a=ice-ufrag, a=ice-pwd, a=fingerprint and a=setup from all
  2325. // but the first m= section.
  2326. callee()->SetReceivedSdpMunger(MakeSpecCompliantMaxBundleOffer);
  2327. caller()->CreateAndSetAndSignalOffer();
  2328. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2329. MediaExpectations media_expectations;
  2330. media_expectations.ExpectBidirectionalAudioAndVideo();
  2331. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2332. }
  2333. // Test that we can receive the audio output level from a remote audio track.
  2334. // TODO(deadbeef): Use a fake audio source and verify that the output level is
  2335. // exactly what the source on the other side was configured with.
  2336. TEST_P(PeerConnectionIntegrationTest, GetAudioOutputLevelStatsWithOldStatsApi) {
  2337. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2338. ConnectFakeSignaling();
  2339. // Just add an audio track.
  2340. caller()->AddAudioTrack();
  2341. caller()->CreateAndSetAndSignalOffer();
  2342. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2343. // Get the audio output level stats. Note that the level is not available
  2344. // until an RTCP packet has been received.
  2345. EXPECT_TRUE_WAIT(callee()->OldGetStats()->AudioOutputLevel() > 0,
  2346. kMaxWaitForFramesMs);
  2347. }
  2348. // Test that an audio input level is reported.
  2349. // TODO(deadbeef): Use a fake audio source and verify that the input level is
  2350. // exactly what the source was configured with.
  2351. TEST_P(PeerConnectionIntegrationTest, GetAudioInputLevelStatsWithOldStatsApi) {
  2352. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2353. ConnectFakeSignaling();
  2354. // Just add an audio track.
  2355. caller()->AddAudioTrack();
  2356. caller()->CreateAndSetAndSignalOffer();
  2357. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2358. // Get the audio input level stats. The level should be available very
  2359. // soon after the test starts.
  2360. EXPECT_TRUE_WAIT(caller()->OldGetStats()->AudioInputLevel() > 0,
  2361. kMaxWaitForStatsMs);
  2362. }
  2363. // Test that we can get incoming byte counts from both audio and video tracks.
  2364. TEST_P(PeerConnectionIntegrationTest, GetBytesReceivedStatsWithOldStatsApi) {
  2365. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2366. ConnectFakeSignaling();
  2367. caller()->AddAudioVideoTracks();
  2368. // Do offer/answer, wait for the callee to receive some frames.
  2369. caller()->CreateAndSetAndSignalOffer();
  2370. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2371. MediaExpectations media_expectations;
  2372. media_expectations.CalleeExpectsSomeAudioAndVideo();
  2373. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2374. // Get a handle to the remote tracks created, so they can be used as GetStats
  2375. // filters.
  2376. for (const auto& receiver : callee()->pc()->GetReceivers()) {
  2377. // We received frames, so we definitely should have nonzero "received bytes"
  2378. // stats at this point.
  2379. EXPECT_GT(callee()->OldGetStatsForTrack(receiver->track())->BytesReceived(),
  2380. 0);
  2381. }
  2382. }
  2383. // Test that we can get outgoing byte counts from both audio and video tracks.
  2384. TEST_P(PeerConnectionIntegrationTest, GetBytesSentStatsWithOldStatsApi) {
  2385. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2386. ConnectFakeSignaling();
  2387. auto audio_track = caller()->CreateLocalAudioTrack();
  2388. auto video_track = caller()->CreateLocalVideoTrack();
  2389. caller()->AddTrack(audio_track);
  2390. caller()->AddTrack(video_track);
  2391. // Do offer/answer, wait for the callee to receive some frames.
  2392. caller()->CreateAndSetAndSignalOffer();
  2393. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2394. MediaExpectations media_expectations;
  2395. media_expectations.CalleeExpectsSomeAudioAndVideo();
  2396. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2397. // The callee received frames, so we definitely should have nonzero "sent
  2398. // bytes" stats at this point.
  2399. EXPECT_GT(caller()->OldGetStatsForTrack(audio_track)->BytesSent(), 0);
  2400. EXPECT_GT(caller()->OldGetStatsForTrack(video_track)->BytesSent(), 0);
  2401. }
  2402. // Test that we can get capture start ntp time.
  2403. TEST_P(PeerConnectionIntegrationTest, GetCaptureStartNtpTimeWithOldStatsApi) {
  2404. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2405. ConnectFakeSignaling();
  2406. caller()->AddAudioTrack();
  2407. callee()->AddAudioTrack();
  2408. // Do offer/answer, wait for the callee to receive some frames.
  2409. caller()->CreateAndSetAndSignalOffer();
  2410. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2411. // Get the remote audio track created on the receiver, so they can be used as
  2412. // GetStats filters.
  2413. auto receivers = callee()->pc()->GetReceivers();
  2414. ASSERT_EQ(1u, receivers.size());
  2415. auto remote_audio_track = receivers[0]->track();
  2416. // Get the audio output level stats. Note that the level is not available
  2417. // until an RTCP packet has been received.
  2418. EXPECT_TRUE_WAIT(
  2419. callee()->OldGetStatsForTrack(remote_audio_track)->CaptureStartNtpTime() >
  2420. 0,
  2421. 2 * kMaxWaitForFramesMs);
  2422. }
  2423. // Test that the track ID is associated with all local and remote SSRC stats
  2424. // using the old GetStats() and more than 1 audio and more than 1 video track.
  2425. // This is a regression test for crbug.com/906988
  2426. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  2427. OldGetStatsAssociatesTrackIdForManyMediaSections) {
  2428. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2429. ConnectFakeSignaling();
  2430. auto audio_sender_1 = caller()->AddAudioTrack();
  2431. auto video_sender_1 = caller()->AddVideoTrack();
  2432. auto audio_sender_2 = caller()->AddAudioTrack();
  2433. auto video_sender_2 = caller()->AddVideoTrack();
  2434. caller()->CreateAndSetAndSignalOffer();
  2435. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2436. MediaExpectations media_expectations;
  2437. media_expectations.CalleeExpectsSomeAudioAndVideo();
  2438. ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
  2439. std::vector<std::string> track_ids = {
  2440. audio_sender_1->track()->id(), video_sender_1->track()->id(),
  2441. audio_sender_2->track()->id(), video_sender_2->track()->id()};
  2442. auto caller_stats = caller()->OldGetStats();
  2443. EXPECT_THAT(caller_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
  2444. auto callee_stats = callee()->OldGetStats();
  2445. EXPECT_THAT(callee_stats->TrackIds(), UnorderedElementsAreArray(track_ids));
  2446. }
  2447. // Test that the new GetStats() returns stats for all outgoing/incoming streams
  2448. // with the correct track IDs if there are more than one audio and more than one
  2449. // video senders/receivers.
  2450. TEST_P(PeerConnectionIntegrationTest, NewGetStatsManyAudioAndManyVideoStreams) {
  2451. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2452. ConnectFakeSignaling();
  2453. auto audio_sender_1 = caller()->AddAudioTrack();
  2454. auto video_sender_1 = caller()->AddVideoTrack();
  2455. auto audio_sender_2 = caller()->AddAudioTrack();
  2456. auto video_sender_2 = caller()->AddVideoTrack();
  2457. caller()->CreateAndSetAndSignalOffer();
  2458. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2459. MediaExpectations media_expectations;
  2460. media_expectations.CalleeExpectsSomeAudioAndVideo();
  2461. ASSERT_TRUE_WAIT(ExpectNewFrames(media_expectations), kDefaultTimeout);
  2462. std::vector<std::string> track_ids = {
  2463. audio_sender_1->track()->id(), video_sender_1->track()->id(),
  2464. audio_sender_2->track()->id(), video_sender_2->track()->id()};
  2465. rtc::scoped_refptr<const webrtc::RTCStatsReport> caller_report =
  2466. caller()->NewGetStats();
  2467. ASSERT_TRUE(caller_report);
  2468. auto outbound_stream_stats =
  2469. caller_report->GetStatsOfType<webrtc::RTCOutboundRTPStreamStats>();
  2470. ASSERT_EQ(4u, outbound_stream_stats.size());
  2471. std::vector<std::string> outbound_track_ids;
  2472. for (const auto& stat : outbound_stream_stats) {
  2473. ASSERT_TRUE(stat->bytes_sent.is_defined());
  2474. EXPECT_LT(0u, *stat->bytes_sent);
  2475. if (*stat->kind == "video") {
  2476. ASSERT_TRUE(stat->key_frames_encoded.is_defined());
  2477. EXPECT_GT(*stat->key_frames_encoded, 0u);
  2478. ASSERT_TRUE(stat->frames_encoded.is_defined());
  2479. EXPECT_GE(*stat->frames_encoded, *stat->key_frames_encoded);
  2480. }
  2481. ASSERT_TRUE(stat->track_id.is_defined());
  2482. const auto* track_stat =
  2483. caller_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
  2484. ASSERT_TRUE(track_stat);
  2485. outbound_track_ids.push_back(*track_stat->track_identifier);
  2486. }
  2487. EXPECT_THAT(outbound_track_ids, UnorderedElementsAreArray(track_ids));
  2488. rtc::scoped_refptr<const webrtc::RTCStatsReport> callee_report =
  2489. callee()->NewGetStats();
  2490. ASSERT_TRUE(callee_report);
  2491. auto inbound_stream_stats =
  2492. callee_report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
  2493. ASSERT_EQ(4u, inbound_stream_stats.size());
  2494. std::vector<std::string> inbound_track_ids;
  2495. for (const auto& stat : inbound_stream_stats) {
  2496. ASSERT_TRUE(stat->bytes_received.is_defined());
  2497. EXPECT_LT(0u, *stat->bytes_received);
  2498. if (*stat->kind == "video") {
  2499. ASSERT_TRUE(stat->key_frames_decoded.is_defined());
  2500. EXPECT_GT(*stat->key_frames_decoded, 0u);
  2501. ASSERT_TRUE(stat->frames_decoded.is_defined());
  2502. EXPECT_GE(*stat->frames_decoded, *stat->key_frames_decoded);
  2503. }
  2504. ASSERT_TRUE(stat->track_id.is_defined());
  2505. const auto* track_stat =
  2506. callee_report->GetAs<webrtc::RTCMediaStreamTrackStats>(*stat->track_id);
  2507. ASSERT_TRUE(track_stat);
  2508. inbound_track_ids.push_back(*track_stat->track_identifier);
  2509. }
  2510. EXPECT_THAT(inbound_track_ids, UnorderedElementsAreArray(track_ids));
  2511. }
  2512. // Test that we can get stats (using the new stats implementation) for
  2513. // unsignaled streams. Meaning when SSRCs/MSIDs aren't signaled explicitly in
  2514. // SDP.
  2515. TEST_P(PeerConnectionIntegrationTest,
  2516. GetStatsForUnsignaledStreamWithNewStatsApi) {
  2517. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2518. ConnectFakeSignaling();
  2519. caller()->AddAudioTrack();
  2520. // Remove SSRCs and MSIDs from the received offer SDP.
  2521. callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
  2522. caller()->CreateAndSetAndSignalOffer();
  2523. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2524. MediaExpectations media_expectations;
  2525. media_expectations.CalleeExpectsSomeAudio(1);
  2526. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2527. // We received a frame, so we should have nonzero "bytes received" stats for
  2528. // the unsignaled stream, if stats are working for it.
  2529. rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
  2530. callee()->NewGetStats();
  2531. ASSERT_NE(nullptr, report);
  2532. auto inbound_stream_stats =
  2533. report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
  2534. ASSERT_EQ(1U, inbound_stream_stats.size());
  2535. ASSERT_TRUE(inbound_stream_stats[0]->bytes_received.is_defined());
  2536. ASSERT_GT(*inbound_stream_stats[0]->bytes_received, 0U);
  2537. ASSERT_TRUE(inbound_stream_stats[0]->track_id.is_defined());
  2538. }
  2539. // Same as above but for the legacy stats implementation.
  2540. TEST_P(PeerConnectionIntegrationTest,
  2541. GetStatsForUnsignaledStreamWithOldStatsApi) {
  2542. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2543. ConnectFakeSignaling();
  2544. caller()->AddAudioTrack();
  2545. // Remove SSRCs and MSIDs from the received offer SDP.
  2546. callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
  2547. caller()->CreateAndSetAndSignalOffer();
  2548. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2549. // Note that, since the old stats implementation associates SSRCs with tracks
  2550. // using SDP, when SSRCs aren't signaled in SDP these stats won't have an
  2551. // associated track ID. So we can't use the track "selector" argument.
  2552. //
  2553. // Also, we use "EXPECT_TRUE_WAIT" because the stats collector may decide to
  2554. // return cached stats if not enough time has passed since the last update.
  2555. EXPECT_TRUE_WAIT(callee()->OldGetStats()->BytesReceived() > 0,
  2556. kDefaultTimeout);
  2557. }
  2558. // Test that we can successfully get the media related stats (audio level
  2559. // etc.) for the unsignaled stream.
  2560. TEST_P(PeerConnectionIntegrationTest,
  2561. GetMediaStatsForUnsignaledStreamWithNewStatsApi) {
  2562. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2563. ConnectFakeSignaling();
  2564. caller()->AddAudioVideoTracks();
  2565. // Remove SSRCs and MSIDs from the received offer SDP.
  2566. callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
  2567. caller()->CreateAndSetAndSignalOffer();
  2568. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2569. MediaExpectations media_expectations;
  2570. media_expectations.CalleeExpectsSomeAudio(1);
  2571. media_expectations.CalleeExpectsSomeVideo(1);
  2572. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2573. rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
  2574. callee()->NewGetStats();
  2575. ASSERT_NE(nullptr, report);
  2576. auto media_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
  2577. auto audio_index = FindFirstMediaStatsIndexByKind("audio", media_stats);
  2578. ASSERT_GE(audio_index, 0);
  2579. EXPECT_TRUE(media_stats[audio_index]->audio_level.is_defined());
  2580. }
  2581. // Helper for test below.
  2582. void ModifySsrcs(cricket::SessionDescription* desc) {
  2583. for (ContentInfo& content : desc->contents()) {
  2584. for (StreamParams& stream :
  2585. content.media_description()->mutable_streams()) {
  2586. for (uint32_t& ssrc : stream.ssrcs) {
  2587. ssrc = rtc::CreateRandomId();
  2588. }
  2589. }
  2590. }
  2591. }
  2592. // Test that the "RTCMediaSteamTrackStats" object is updated correctly when
  2593. // SSRCs are unsignaled, and the SSRC of the received (audio) stream changes.
  2594. // This should result in two "RTCInboundRTPStreamStats", but only one
  2595. // "RTCMediaStreamTrackStats", whose counters go up continuously rather than
  2596. // being reset to 0 once the SSRC change occurs.
  2597. //
  2598. // Regression test for this bug:
  2599. // https://bugs.chromium.org/p/webrtc/issues/detail?id=8158
  2600. //
  2601. // The bug causes the track stats to only represent one of the two streams:
  2602. // whichever one has the higher SSRC. So with this bug, there was a 50% chance
  2603. // that the track stat counters would reset to 0 when the new stream is
  2604. // received, and a 50% chance that they'll stop updating (while
  2605. // "concealed_samples" continues increasing, due to silence being generated for
  2606. // the inactive stream).
  2607. TEST_P(PeerConnectionIntegrationTest,
  2608. TrackStatsUpdatedCorrectlyWhenUnsignaledSsrcChanges) {
  2609. ASSERT_TRUE(CreatePeerConnectionWrappers());
  2610. ConnectFakeSignaling();
  2611. caller()->AddAudioTrack();
  2612. // Remove SSRCs and MSIDs from the received offer SDP, simulating an endpoint
  2613. // that doesn't signal SSRCs (from the callee's perspective).
  2614. callee()->SetReceivedSdpMunger(RemoveSsrcsAndMsids);
  2615. caller()->CreateAndSetAndSignalOffer();
  2616. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2617. // Wait for 50 audio frames (500ms of audio) to be received by the callee.
  2618. {
  2619. MediaExpectations media_expectations;
  2620. media_expectations.CalleeExpectsSomeAudio(50);
  2621. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2622. }
  2623. // Some audio frames were received, so we should have nonzero "samples
  2624. // received" for the track.
  2625. rtc::scoped_refptr<const webrtc::RTCStatsReport> report =
  2626. callee()->NewGetStats();
  2627. ASSERT_NE(nullptr, report);
  2628. auto track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
  2629. ASSERT_EQ(1U, track_stats.size());
  2630. ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
  2631. ASSERT_GT(*track_stats[0]->total_samples_received, 0U);
  2632. // uint64_t prev_samples_received = *track_stats[0]->total_samples_received;
  2633. // Create a new offer and munge it to cause the caller to use a new SSRC.
  2634. caller()->SetGeneratedSdpMunger(ModifySsrcs);
  2635. caller()->CreateAndSetAndSignalOffer();
  2636. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2637. // Wait for 25 more audio frames (250ms of audio) to be received, from the new
  2638. // SSRC.
  2639. {
  2640. MediaExpectations media_expectations;
  2641. media_expectations.CalleeExpectsSomeAudio(25);
  2642. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2643. }
  2644. report = callee()->NewGetStats();
  2645. ASSERT_NE(nullptr, report);
  2646. track_stats = report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
  2647. ASSERT_EQ(1U, track_stats.size());
  2648. ASSERT_TRUE(track_stats[0]->total_samples_received.is_defined());
  2649. // The "total samples received" stat should only be greater than it was
  2650. // before.
  2651. // TODO(deadbeef): Uncomment this assertion once the bug is completely fixed.
  2652. // Right now, the new SSRC will cause the counters to reset to 0.
  2653. // EXPECT_GT(*track_stats[0]->total_samples_received, prev_samples_received);
  2654. // Additionally, the percentage of concealed samples (samples generated to
  2655. // conceal packet loss) should be less than 50%. If it's greater, that's a
  2656. // good sign that we're seeing stats from the old stream that's no longer
  2657. // receiving packets, and is generating concealed samples of silence.
  2658. constexpr double kAcceptableConcealedSamplesPercentage = 0.50;
  2659. ASSERT_TRUE(track_stats[0]->concealed_samples.is_defined());
  2660. EXPECT_LT(*track_stats[0]->concealed_samples,
  2661. *track_stats[0]->total_samples_received *
  2662. kAcceptableConcealedSamplesPercentage);
  2663. // Also ensure that we have two "RTCInboundRTPStreamStats" as expected, as a
  2664. // sanity check that the SSRC really changed.
  2665. // TODO(deadbeef): This isn't working right now, because we're not returning
  2666. // *any* stats for the inactive stream. Uncomment when the bug is completely
  2667. // fixed.
  2668. // auto inbound_stream_stats =
  2669. // report->GetStatsOfType<webrtc::RTCInboundRTPStreamStats>();
  2670. // ASSERT_EQ(2U, inbound_stream_stats.size());
  2671. }
  2672. // Test that DTLS 1.0 is used if both sides only support DTLS 1.0.
  2673. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithDtls10) {
  2674. PeerConnectionFactory::Options dtls_10_options;
  2675. dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
  2676. ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
  2677. dtls_10_options));
  2678. ConnectFakeSignaling();
  2679. // Do normal offer/answer and wait for some frames to be received in each
  2680. // direction.
  2681. caller()->AddAudioVideoTracks();
  2682. callee()->AddAudioVideoTracks();
  2683. caller()->CreateAndSetAndSignalOffer();
  2684. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2685. MediaExpectations media_expectations;
  2686. media_expectations.ExpectBidirectionalAudioAndVideo();
  2687. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2688. }
  2689. // Test getting cipher stats and UMA metrics when DTLS 1.0 is negotiated.
  2690. TEST_P(PeerConnectionIntegrationTest, Dtls10CipherStatsAndUmaMetrics) {
  2691. PeerConnectionFactory::Options dtls_10_options;
  2692. dtls_10_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
  2693. ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_10_options,
  2694. dtls_10_options));
  2695. ConnectFakeSignaling();
  2696. caller()->AddAudioVideoTracks();
  2697. callee()->AddAudioVideoTracks();
  2698. caller()->CreateAndSetAndSignalOffer();
  2699. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  2700. EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
  2701. caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
  2702. kDefaultTimeout);
  2703. EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
  2704. caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
  2705. // TODO(bugs.webrtc.org/9456): Fix it.
  2706. EXPECT_EQ(1, webrtc::metrics::NumEvents(
  2707. "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
  2708. kDefaultSrtpCryptoSuite));
  2709. }
  2710. // Test getting cipher stats and UMA metrics when DTLS 1.2 is negotiated.
  2711. TEST_P(PeerConnectionIntegrationTest, Dtls12CipherStatsAndUmaMetrics) {
  2712. PeerConnectionFactory::Options dtls_12_options;
  2713. dtls_12_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
  2714. ASSERT_TRUE(CreatePeerConnectionWrappersWithOptions(dtls_12_options,
  2715. dtls_12_options));
  2716. ConnectFakeSignaling();
  2717. caller()->AddAudioVideoTracks();
  2718. callee()->AddAudioVideoTracks();
  2719. caller()->CreateAndSetAndSignalOffer();
  2720. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  2721. EXPECT_TRUE_WAIT(rtc::SSLStreamAdapter::IsAcceptableCipher(
  2722. caller()->OldGetStats()->DtlsCipher(), rtc::KT_DEFAULT),
  2723. kDefaultTimeout);
  2724. EXPECT_EQ_WAIT(rtc::SrtpCryptoSuiteToName(kDefaultSrtpCryptoSuite),
  2725. caller()->OldGetStats()->SrtpCipher(), kDefaultTimeout);
  2726. // TODO(bugs.webrtc.org/9456): Fix it.
  2727. EXPECT_EQ(1, webrtc::metrics::NumEvents(
  2728. "WebRTC.PeerConnection.SrtpCryptoSuite.Audio",
  2729. kDefaultSrtpCryptoSuite));
  2730. }
  2731. // Test that DTLS 1.0 can be used if the caller supports DTLS 1.2 and the
  2732. // callee only supports 1.0.
  2733. TEST_P(PeerConnectionIntegrationTest, CallerDtls12ToCalleeDtls10) {
  2734. PeerConnectionFactory::Options caller_options;
  2735. caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
  2736. PeerConnectionFactory::Options callee_options;
  2737. callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
  2738. ASSERT_TRUE(
  2739. CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
  2740. ConnectFakeSignaling();
  2741. // Do normal offer/answer and wait for some frames to be received in each
  2742. // direction.
  2743. caller()->AddAudioVideoTracks();
  2744. callee()->AddAudioVideoTracks();
  2745. caller()->CreateAndSetAndSignalOffer();
  2746. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2747. MediaExpectations media_expectations;
  2748. media_expectations.ExpectBidirectionalAudioAndVideo();
  2749. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2750. }
  2751. // Test that DTLS 1.0 can be used if the caller only supports DTLS 1.0 and the
  2752. // callee supports 1.2.
  2753. TEST_P(PeerConnectionIntegrationTest, CallerDtls10ToCalleeDtls12) {
  2754. PeerConnectionFactory::Options caller_options;
  2755. caller_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_10;
  2756. PeerConnectionFactory::Options callee_options;
  2757. callee_options.ssl_max_version = rtc::SSL_PROTOCOL_DTLS_12;
  2758. ASSERT_TRUE(
  2759. CreatePeerConnectionWrappersWithOptions(caller_options, callee_options));
  2760. ConnectFakeSignaling();
  2761. // Do normal offer/answer and wait for some frames to be received in each
  2762. // direction.
  2763. caller()->AddAudioVideoTracks();
  2764. callee()->AddAudioVideoTracks();
  2765. caller()->CreateAndSetAndSignalOffer();
  2766. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2767. MediaExpectations media_expectations;
  2768. media_expectations.ExpectBidirectionalAudioAndVideo();
  2769. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2770. }
  2771. // The three tests below verify that "enable_aes128_sha1_32_crypto_cipher"
  2772. // works as expected; the cipher should only be used if enabled by both sides.
  2773. TEST_P(PeerConnectionIntegrationTest,
  2774. Aes128Sha1_32_CipherNotUsedWhenOnlyCallerSupported) {
  2775. PeerConnectionFactory::Options caller_options;
  2776. caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
  2777. PeerConnectionFactory::Options callee_options;
  2778. callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
  2779. false;
  2780. int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
  2781. TestNegotiatedCipherSuite(caller_options, callee_options,
  2782. expected_cipher_suite);
  2783. }
  2784. TEST_P(PeerConnectionIntegrationTest,
  2785. Aes128Sha1_32_CipherNotUsedWhenOnlyCalleeSupported) {
  2786. PeerConnectionFactory::Options caller_options;
  2787. caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher =
  2788. false;
  2789. PeerConnectionFactory::Options callee_options;
  2790. callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
  2791. int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_80;
  2792. TestNegotiatedCipherSuite(caller_options, callee_options,
  2793. expected_cipher_suite);
  2794. }
  2795. TEST_P(PeerConnectionIntegrationTest, Aes128Sha1_32_CipherUsedWhenSupported) {
  2796. PeerConnectionFactory::Options caller_options;
  2797. caller_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
  2798. PeerConnectionFactory::Options callee_options;
  2799. callee_options.crypto_options.srtp.enable_aes128_sha1_32_crypto_cipher = true;
  2800. int expected_cipher_suite = rtc::SRTP_AES128_CM_SHA1_32;
  2801. TestNegotiatedCipherSuite(caller_options, callee_options,
  2802. expected_cipher_suite);
  2803. }
  2804. // Test that a non-GCM cipher is used if both sides only support non-GCM.
  2805. TEST_P(PeerConnectionIntegrationTest, NonGcmCipherUsedWhenGcmNotSupported) {
  2806. bool local_gcm_enabled = false;
  2807. bool remote_gcm_enabled = false;
  2808. int expected_cipher_suite = kDefaultSrtpCryptoSuite;
  2809. TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
  2810. expected_cipher_suite);
  2811. }
  2812. // Test that a GCM cipher is used if both ends support it.
  2813. TEST_P(PeerConnectionIntegrationTest, GcmCipherUsedWhenGcmSupported) {
  2814. bool local_gcm_enabled = true;
  2815. bool remote_gcm_enabled = true;
  2816. int expected_cipher_suite = kDefaultSrtpCryptoSuiteGcm;
  2817. TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
  2818. expected_cipher_suite);
  2819. }
  2820. // Test that GCM isn't used if only the offerer supports it.
  2821. TEST_P(PeerConnectionIntegrationTest,
  2822. NonGcmCipherUsedWhenOnlyCallerSupportsGcm) {
  2823. bool local_gcm_enabled = true;
  2824. bool remote_gcm_enabled = false;
  2825. int expected_cipher_suite = kDefaultSrtpCryptoSuite;
  2826. TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
  2827. expected_cipher_suite);
  2828. }
  2829. // Test that GCM isn't used if only the answerer supports it.
  2830. TEST_P(PeerConnectionIntegrationTest,
  2831. NonGcmCipherUsedWhenOnlyCalleeSupportsGcm) {
  2832. bool local_gcm_enabled = false;
  2833. bool remote_gcm_enabled = true;
  2834. int expected_cipher_suite = kDefaultSrtpCryptoSuite;
  2835. TestGcmNegotiationUsesCipherSuite(local_gcm_enabled, remote_gcm_enabled,
  2836. expected_cipher_suite);
  2837. }
  2838. // Verify that media can be transmitted end-to-end when GCM crypto suites are
  2839. // enabled. Note that the above tests, such as GcmCipherUsedWhenGcmSupported,
  2840. // only verify that a GCM cipher is negotiated, and not necessarily that SRTP
  2841. // works with it.
  2842. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithGcmCipher) {
  2843. PeerConnectionFactory::Options gcm_options;
  2844. gcm_options.crypto_options.srtp.enable_gcm_crypto_suites = true;
  2845. ASSERT_TRUE(
  2846. CreatePeerConnectionWrappersWithOptions(gcm_options, gcm_options));
  2847. ConnectFakeSignaling();
  2848. // Do normal offer/answer and wait for some frames to be received in each
  2849. // direction.
  2850. caller()->AddAudioVideoTracks();
  2851. callee()->AddAudioVideoTracks();
  2852. caller()->CreateAndSetAndSignalOffer();
  2853. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2854. MediaExpectations media_expectations;
  2855. media_expectations.ExpectBidirectionalAudioAndVideo();
  2856. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2857. }
  2858. // This test sets up a call between two parties with audio, video and an RTP
  2859. // data channel.
  2860. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithRtpDataChannel) {
  2861. PeerConnectionInterface::RTCConfiguration rtc_config;
  2862. rtc_config.enable_rtp_data_channel = true;
  2863. rtc_config.enable_dtls_srtp = false;
  2864. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
  2865. ConnectFakeSignaling();
  2866. // Expect that data channel created on caller side will show up for callee as
  2867. // well.
  2868. caller()->CreateDataChannel();
  2869. caller()->AddAudioVideoTracks();
  2870. callee()->AddAudioVideoTracks();
  2871. caller()->CreateAndSetAndSignalOffer();
  2872. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2873. // Ensure the existence of the RTP data channel didn't impede audio/video.
  2874. MediaExpectations media_expectations;
  2875. media_expectations.ExpectBidirectionalAudioAndVideo();
  2876. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  2877. ASSERT_NE(nullptr, caller()->data_channel());
  2878. ASSERT_NE(nullptr, callee()->data_channel());
  2879. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  2880. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  2881. // Ensure data can be sent in both directions.
  2882. std::string data = "hello world";
  2883. SendRtpDataWithRetries(caller()->data_channel(), data, 5);
  2884. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  2885. kDefaultTimeout);
  2886. SendRtpDataWithRetries(callee()->data_channel(), data, 5);
  2887. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  2888. kDefaultTimeout);
  2889. }
  2890. // Ensure that an RTP data channel is signaled as closed for the caller when
  2891. // the callee rejects it in a subsequent offer.
  2892. TEST_P(PeerConnectionIntegrationTest,
  2893. RtpDataChannelSignaledClosedInCalleeOffer) {
  2894. // Same procedure as above test.
  2895. PeerConnectionInterface::RTCConfiguration rtc_config;
  2896. rtc_config.enable_rtp_data_channel = true;
  2897. rtc_config.enable_dtls_srtp = false;
  2898. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
  2899. ConnectFakeSignaling();
  2900. caller()->CreateDataChannel();
  2901. caller()->AddAudioVideoTracks();
  2902. callee()->AddAudioVideoTracks();
  2903. caller()->CreateAndSetAndSignalOffer();
  2904. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2905. ASSERT_NE(nullptr, caller()->data_channel());
  2906. ASSERT_NE(nullptr, callee()->data_channel());
  2907. ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  2908. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  2909. // Close the data channel on the callee, and do an updated offer/answer.
  2910. callee()->data_channel()->Close();
  2911. callee()->CreateAndSetAndSignalOffer();
  2912. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2913. EXPECT_FALSE(caller()->data_observer()->IsOpen());
  2914. EXPECT_FALSE(callee()->data_observer()->IsOpen());
  2915. }
  2916. // Tests that data is buffered in an RTP data channel until an observer is
  2917. // registered for it.
  2918. //
  2919. // NOTE: RTP data channels can receive data before the underlying
  2920. // transport has detected that a channel is writable and thus data can be
  2921. // received before the data channel state changes to open. That is hard to test
  2922. // but the same buffering is expected to be used in that case.
  2923. TEST_P(PeerConnectionIntegrationTest,
  2924. DataBufferedUntilRtpDataChannelObserverRegistered) {
  2925. // Use fake clock and simulated network delay so that we predictably can wait
  2926. // until an SCTP message has been delivered without "sleep()"ing.
  2927. rtc::ScopedFakeClock fake_clock;
  2928. // Some things use a time of "0" as a special value, so we need to start out
  2929. // the fake clock at a nonzero time.
  2930. // TODO(deadbeef): Fix this.
  2931. fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
  2932. virtual_socket_server()->set_delay_mean(5); // 5 ms per hop.
  2933. virtual_socket_server()->UpdateDelayDistribution();
  2934. PeerConnectionInterface::RTCConfiguration rtc_config;
  2935. rtc_config.enable_rtp_data_channel = true;
  2936. rtc_config.enable_dtls_srtp = false;
  2937. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
  2938. ConnectFakeSignaling();
  2939. caller()->CreateDataChannel();
  2940. caller()->CreateAndSetAndSignalOffer();
  2941. ASSERT_TRUE(caller()->data_channel() != nullptr);
  2942. ASSERT_TRUE_SIMULATED_WAIT(callee()->data_channel() != nullptr,
  2943. kDefaultTimeout, fake_clock);
  2944. ASSERT_TRUE_SIMULATED_WAIT(caller()->data_observer()->IsOpen(),
  2945. kDefaultTimeout, fake_clock);
  2946. ASSERT_EQ_SIMULATED_WAIT(DataChannelInterface::kOpen,
  2947. callee()->data_channel()->state(), kDefaultTimeout,
  2948. fake_clock);
  2949. // Unregister the observer which is normally automatically registered.
  2950. callee()->data_channel()->UnregisterObserver();
  2951. // Send data and advance fake clock until it should have been received.
  2952. std::string data = "hello world";
  2953. caller()->data_channel()->Send(DataBuffer(data));
  2954. SIMULATED_WAIT(false, 50, fake_clock);
  2955. // Attach data channel and expect data to be received immediately. Note that
  2956. // EXPECT_EQ_WAIT is used, such that the simulated clock is not advanced any
  2957. // further, but data can be received even if the callback is asynchronous.
  2958. MockDataChannelObserver new_observer(callee()->data_channel());
  2959. EXPECT_EQ_SIMULATED_WAIT(data, new_observer.last_message(), kDefaultTimeout,
  2960. fake_clock);
  2961. // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
  2962. // If this is not done a DCHECK can be hit in ports.cc, because a large
  2963. // negative number is calculated for the rtt due to the global clock changing.
  2964. ClosePeerConnections();
  2965. }
  2966. // This test sets up a call between two parties with audio, video and but only
  2967. // the caller client supports RTP data channels.
  2968. TEST_P(PeerConnectionIntegrationTest, RtpDataChannelsRejectedByCallee) {
  2969. PeerConnectionInterface::RTCConfiguration rtc_config_1;
  2970. rtc_config_1.enable_rtp_data_channel = true;
  2971. // Must disable DTLS to make negotiation succeed.
  2972. rtc_config_1.enable_dtls_srtp = false;
  2973. PeerConnectionInterface::RTCConfiguration rtc_config_2;
  2974. rtc_config_2.enable_dtls_srtp = false;
  2975. rtc_config_2.enable_dtls_srtp = false;
  2976. ASSERT_TRUE(
  2977. CreatePeerConnectionWrappersWithConfig(rtc_config_1, rtc_config_2));
  2978. ConnectFakeSignaling();
  2979. caller()->CreateDataChannel();
  2980. ASSERT_TRUE(caller()->data_channel() != nullptr);
  2981. caller()->AddAudioVideoTracks();
  2982. callee()->AddAudioVideoTracks();
  2983. caller()->CreateAndSetAndSignalOffer();
  2984. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  2985. // The caller should still have a data channel, but it should be closed, and
  2986. // one should ever have been created for the callee.
  2987. EXPECT_TRUE(caller()->data_channel() != nullptr);
  2988. EXPECT_FALSE(caller()->data_observer()->IsOpen());
  2989. EXPECT_EQ(nullptr, callee()->data_channel());
  2990. }
  2991. // This test sets up a call between two parties with audio, and video. When
  2992. // audio and video is setup and flowing, an RTP data channel is negotiated.
  2993. TEST_P(PeerConnectionIntegrationTest, AddRtpDataChannelInSubsequentOffer) {
  2994. PeerConnectionInterface::RTCConfiguration rtc_config;
  2995. rtc_config.enable_rtp_data_channel = true;
  2996. rtc_config.enable_dtls_srtp = false;
  2997. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(rtc_config, rtc_config));
  2998. ConnectFakeSignaling();
  2999. // Do initial offer/answer with audio/video.
  3000. caller()->AddAudioVideoTracks();
  3001. callee()->AddAudioVideoTracks();
  3002. caller()->CreateAndSetAndSignalOffer();
  3003. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3004. // Create data channel and do new offer and answer.
  3005. caller()->CreateDataChannel();
  3006. caller()->CreateAndSetAndSignalOffer();
  3007. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3008. ASSERT_NE(nullptr, caller()->data_channel());
  3009. ASSERT_NE(nullptr, callee()->data_channel());
  3010. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3011. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3012. // Ensure data can be sent in both directions.
  3013. std::string data = "hello world";
  3014. SendRtpDataWithRetries(caller()->data_channel(), data, 5);
  3015. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3016. kDefaultTimeout);
  3017. SendRtpDataWithRetries(callee()->data_channel(), data, 5);
  3018. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3019. kDefaultTimeout);
  3020. }
  3021. #ifdef HAVE_SCTP
  3022. // This test sets up a call between two parties with audio, video and an SCTP
  3023. // data channel.
  3024. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithSctpDataChannel) {
  3025. ASSERT_TRUE(CreatePeerConnectionWrappers());
  3026. ConnectFakeSignaling();
  3027. // Expect that data channel created on caller side will show up for callee as
  3028. // well.
  3029. caller()->CreateDataChannel();
  3030. caller()->AddAudioVideoTracks();
  3031. callee()->AddAudioVideoTracks();
  3032. caller()->CreateAndSetAndSignalOffer();
  3033. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3034. // Ensure the existence of the SCTP data channel didn't impede audio/video.
  3035. MediaExpectations media_expectations;
  3036. media_expectations.ExpectBidirectionalAudioAndVideo();
  3037. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3038. // Caller data channel should already exist (it created one). Callee data
  3039. // channel may not exist yet, since negotiation happens in-band, not in SDP.
  3040. ASSERT_NE(nullptr, caller()->data_channel());
  3041. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3042. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3043. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3044. // Ensure data can be sent in both directions.
  3045. std::string data = "hello world";
  3046. caller()->data_channel()->Send(DataBuffer(data));
  3047. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3048. kDefaultTimeout);
  3049. callee()->data_channel()->Send(DataBuffer(data));
  3050. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3051. kDefaultTimeout);
  3052. }
  3053. // Ensure that when the callee closes an SCTP data channel, the closing
  3054. // procedure results in the data channel being closed for the caller as well.
  3055. TEST_P(PeerConnectionIntegrationTest, CalleeClosesSctpDataChannel) {
  3056. // Same procedure as above test.
  3057. ASSERT_TRUE(CreatePeerConnectionWrappers());
  3058. ConnectFakeSignaling();
  3059. caller()->CreateDataChannel();
  3060. caller()->AddAudioVideoTracks();
  3061. callee()->AddAudioVideoTracks();
  3062. caller()->CreateAndSetAndSignalOffer();
  3063. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3064. ASSERT_NE(nullptr, caller()->data_channel());
  3065. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3066. ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3067. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3068. // Close the data channel on the callee side, and wait for it to reach the
  3069. // "closed" state on both sides.
  3070. callee()->data_channel()->Close();
  3071. EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3072. EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3073. }
  3074. TEST_P(PeerConnectionIntegrationTest, SctpDataChannelConfigSentToOtherSide) {
  3075. ASSERT_TRUE(CreatePeerConnectionWrappers());
  3076. ConnectFakeSignaling();
  3077. webrtc::DataChannelInit init;
  3078. init.id = 53;
  3079. init.maxRetransmits = 52;
  3080. caller()->CreateDataChannel("data-channel", &init);
  3081. caller()->AddAudioVideoTracks();
  3082. callee()->AddAudioVideoTracks();
  3083. caller()->CreateAndSetAndSignalOffer();
  3084. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3085. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3086. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3087. // Since "negotiated" is false, the "id" parameter should be ignored.
  3088. EXPECT_NE(init.id, callee()->data_channel()->id());
  3089. EXPECT_EQ("data-channel", callee()->data_channel()->label());
  3090. EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
  3091. EXPECT_FALSE(callee()->data_channel()->negotiated());
  3092. }
  3093. // Test usrsctp's ability to process unordered data stream, where data actually
  3094. // arrives out of order using simulated delays. Previously there have been some
  3095. // bugs in this area.
  3096. TEST_P(PeerConnectionIntegrationTest, StressTestUnorderedSctpDataChannel) {
  3097. // Introduce random network delays.
  3098. // Otherwise it's not a true "unordered" test.
  3099. virtual_socket_server()->set_delay_mean(20);
  3100. virtual_socket_server()->set_delay_stddev(5);
  3101. virtual_socket_server()->UpdateDelayDistribution();
  3102. // Normal procedure, but with unordered data channel config.
  3103. ASSERT_TRUE(CreatePeerConnectionWrappers());
  3104. ConnectFakeSignaling();
  3105. webrtc::DataChannelInit init;
  3106. init.ordered = false;
  3107. caller()->CreateDataChannel(&init);
  3108. caller()->CreateAndSetAndSignalOffer();
  3109. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3110. ASSERT_NE(nullptr, caller()->data_channel());
  3111. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3112. ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3113. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3114. static constexpr int kNumMessages = 100;
  3115. // Deliberately chosen to be larger than the MTU so messages get fragmented.
  3116. static constexpr size_t kMaxMessageSize = 4096;
  3117. // Create and send random messages.
  3118. std::vector<std::string> sent_messages;
  3119. for (int i = 0; i < kNumMessages; ++i) {
  3120. size_t length =
  3121. (rand() % kMaxMessageSize) + 1; // NOLINT (rand_r instead of rand)
  3122. std::string message;
  3123. ASSERT_TRUE(rtc::CreateRandomString(length, &message));
  3124. caller()->data_channel()->Send(DataBuffer(message));
  3125. callee()->data_channel()->Send(DataBuffer(message));
  3126. sent_messages.push_back(message);
  3127. }
  3128. // Wait for all messages to be received.
  3129. EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
  3130. caller()->data_observer()->received_message_count(),
  3131. kDefaultTimeout);
  3132. EXPECT_EQ_WAIT(rtc::checked_cast<size_t>(kNumMessages),
  3133. callee()->data_observer()->received_message_count(),
  3134. kDefaultTimeout);
  3135. // Sort and compare to make sure none of the messages were corrupted.
  3136. std::vector<std::string> caller_received_messages =
  3137. caller()->data_observer()->messages();
  3138. std::vector<std::string> callee_received_messages =
  3139. callee()->data_observer()->messages();
  3140. absl::c_sort(sent_messages);
  3141. absl::c_sort(caller_received_messages);
  3142. absl::c_sort(callee_received_messages);
  3143. EXPECT_EQ(sent_messages, caller_received_messages);
  3144. EXPECT_EQ(sent_messages, callee_received_messages);
  3145. }
  3146. // This test sets up a call between two parties with audio, and video. When
  3147. // audio and video are setup and flowing, an SCTP data channel is negotiated.
  3148. TEST_P(PeerConnectionIntegrationTest, AddSctpDataChannelInSubsequentOffer) {
  3149. ASSERT_TRUE(CreatePeerConnectionWrappers());
  3150. ConnectFakeSignaling();
  3151. // Do initial offer/answer with audio/video.
  3152. caller()->AddAudioVideoTracks();
  3153. callee()->AddAudioVideoTracks();
  3154. caller()->CreateAndSetAndSignalOffer();
  3155. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3156. // Create data channel and do new offer and answer.
  3157. caller()->CreateDataChannel();
  3158. caller()->CreateAndSetAndSignalOffer();
  3159. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3160. // Caller data channel should already exist (it created one). Callee data
  3161. // channel may not exist yet, since negotiation happens in-band, not in SDP.
  3162. ASSERT_NE(nullptr, caller()->data_channel());
  3163. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3164. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3165. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3166. // Ensure data can be sent in both directions.
  3167. std::string data = "hello world";
  3168. caller()->data_channel()->Send(DataBuffer(data));
  3169. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3170. kDefaultTimeout);
  3171. callee()->data_channel()->Send(DataBuffer(data));
  3172. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3173. kDefaultTimeout);
  3174. }
  3175. // Set up a connection initially just using SCTP data channels, later upgrading
  3176. // to audio/video, ensuring frames are received end-to-end. Effectively the
  3177. // inverse of the test above.
  3178. // This was broken in M57; see https://crbug.com/711243
  3179. TEST_P(PeerConnectionIntegrationTest, SctpDataChannelToAudioVideoUpgrade) {
  3180. ASSERT_TRUE(CreatePeerConnectionWrappers());
  3181. ConnectFakeSignaling();
  3182. // Do initial offer/answer with just data channel.
  3183. caller()->CreateDataChannel();
  3184. caller()->CreateAndSetAndSignalOffer();
  3185. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3186. // Wait until data can be sent over the data channel.
  3187. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3188. ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3189. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3190. // Do subsequent offer/answer with two-way audio and video. Audio and video
  3191. // should end up bundled on the DTLS/ICE transport already used for data.
  3192. caller()->AddAudioVideoTracks();
  3193. callee()->AddAudioVideoTracks();
  3194. caller()->CreateAndSetAndSignalOffer();
  3195. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3196. MediaExpectations media_expectations;
  3197. media_expectations.ExpectBidirectionalAudioAndVideo();
  3198. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3199. }
  3200. static void MakeSpecCompliantSctpOffer(cricket::SessionDescription* desc) {
  3201. cricket::SctpDataContentDescription* dcd_offer =
  3202. GetFirstSctpDataContentDescription(desc);
  3203. ASSERT_TRUE(dcd_offer);
  3204. dcd_offer->set_use_sctpmap(false);
  3205. dcd_offer->set_protocol("UDP/DTLS/SCTP");
  3206. }
  3207. // Test that the data channel works when a spec-compliant SCTP m= section is
  3208. // offered (using "a=sctp-port" instead of "a=sctpmap", and using
  3209. // "UDP/DTLS/SCTP" as the protocol).
  3210. TEST_P(PeerConnectionIntegrationTest,
  3211. DataChannelWorksWhenSpecCompliantSctpOfferReceived) {
  3212. ASSERT_TRUE(CreatePeerConnectionWrappers());
  3213. ConnectFakeSignaling();
  3214. caller()->CreateDataChannel();
  3215. caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
  3216. caller()->CreateAndSetAndSignalOffer();
  3217. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3218. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3219. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3220. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3221. // Ensure data can be sent in both directions.
  3222. std::string data = "hello world";
  3223. caller()->data_channel()->Send(DataBuffer(data));
  3224. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3225. kDefaultTimeout);
  3226. callee()->data_channel()->Send(DataBuffer(data));
  3227. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3228. kDefaultTimeout);
  3229. }
  3230. // Tests that the datagram transport to SCTP fallback works correctly when
  3231. // datagram transport negotiation fails.
  3232. TEST_P(PeerConnectionIntegrationTest,
  3233. DatagramTransportDataChannelFallbackToSctp) {
  3234. PeerConnectionInterface::RTCConfiguration rtc_config;
  3235. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3236. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3237. rtc_config.use_datagram_transport_for_data_channels = true;
  3238. // Configure one endpoint to use datagram transport for data channels while
  3239. // the other does not.
  3240. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3241. rtc_config, RTCConfiguration(),
  3242. loopback_media_transports()->first_factory(), nullptr));
  3243. ConnectFakeSignaling();
  3244. // The caller offers a data channel using either datagram transport or SCTP.
  3245. caller()->CreateDataChannel();
  3246. caller()->AddAudioVideoTracks();
  3247. callee()->AddAudioVideoTracks();
  3248. caller()->CreateAndSetAndSignalOffer();
  3249. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3250. // Negotiation should fallback to SCTP, allowing the data channel to be
  3251. // established.
  3252. ASSERT_NE(nullptr, caller()->data_channel());
  3253. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3254. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3255. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3256. // Ensure data can be sent in both directions.
  3257. std::string data = "hello world";
  3258. caller()->data_channel()->Send(DataBuffer(data));
  3259. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3260. kDefaultTimeout);
  3261. callee()->data_channel()->Send(DataBuffer(data));
  3262. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3263. kDefaultTimeout);
  3264. // Ensure that failure of the datagram negotiation doesn't impede media flow.
  3265. MediaExpectations media_expectations;
  3266. media_expectations.ExpectBidirectionalAudioAndVideo();
  3267. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3268. }
  3269. // Tests that the data channel transport works correctly when datagram transport
  3270. // negotiation succeeds and does not fall back to SCTP.
  3271. TEST_P(PeerConnectionIntegrationTest,
  3272. DatagramTransportDataChannelDoesNotFallbackToSctp) {
  3273. PeerConnectionInterface::RTCConfiguration rtc_config;
  3274. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3275. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3276. rtc_config.use_datagram_transport_for_data_channels = true;
  3277. // Configure one endpoint to use datagram transport for data channels while
  3278. // the other does not.
  3279. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3280. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3281. loopback_media_transports()->second_factory()));
  3282. ConnectFakeSignaling();
  3283. // The caller offers a data channel using either datagram transport or SCTP.
  3284. caller()->CreateDataChannel();
  3285. caller()->AddAudioVideoTracks();
  3286. callee()->AddAudioVideoTracks();
  3287. caller()->CreateAndSetAndSignalOffer();
  3288. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3289. // Ensure that the data channel transport is ready.
  3290. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3291. loopback_media_transports()->FlushAsyncInvokes();
  3292. // Negotiation should succeed, allowing the data channel to be established.
  3293. ASSERT_NE(nullptr, caller()->data_channel());
  3294. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3295. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3296. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3297. // Ensure data can be sent in both directions.
  3298. std::string data = "hello world";
  3299. caller()->data_channel()->Send(DataBuffer(data));
  3300. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3301. kDefaultTimeout);
  3302. callee()->data_channel()->Send(DataBuffer(data));
  3303. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3304. kDefaultTimeout);
  3305. // Ensure that failure of the datagram negotiation doesn't impede media flow.
  3306. MediaExpectations media_expectations;
  3307. media_expectations.ExpectBidirectionalAudioAndVideo();
  3308. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3309. }
  3310. TEST_P(PeerConnectionIntegrationTest,
  3311. DatagramTransportDataChannelWithMediaOnCaller) {
  3312. // Configure the caller to attempt use of datagram transport for media and
  3313. // data channels.
  3314. PeerConnectionInterface::RTCConfiguration offerer_config;
  3315. offerer_config.rtcp_mux_policy =
  3316. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3317. offerer_config.bundle_policy =
  3318. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3319. offerer_config.use_datagram_transport_for_data_channels = true;
  3320. offerer_config.use_datagram_transport = true;
  3321. // Configure the callee to only use datagram transport for data channels.
  3322. PeerConnectionInterface::RTCConfiguration answerer_config;
  3323. answerer_config.rtcp_mux_policy =
  3324. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3325. answerer_config.bundle_policy =
  3326. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3327. answerer_config.use_datagram_transport_for_data_channels = true;
  3328. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3329. offerer_config, answerer_config,
  3330. loopback_media_transports()->first_factory(),
  3331. loopback_media_transports()->second_factory()));
  3332. ConnectFakeSignaling();
  3333. // Offer both media and data.
  3334. caller()->AddAudioVideoTracks();
  3335. callee()->AddAudioVideoTracks();
  3336. caller()->CreateDataChannel();
  3337. caller()->CreateAndSetAndSignalOffer();
  3338. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3339. // Ensure that the data channel transport is ready.
  3340. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3341. loopback_media_transports()->FlushAsyncInvokes();
  3342. ASSERT_NE(nullptr, caller()->data_channel());
  3343. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3344. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3345. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3346. // Both endpoints should agree to use datagram transport for data channels.
  3347. EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
  3348. EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
  3349. // Ensure data can be sent in both directions.
  3350. std::string data = "hello world";
  3351. caller()->data_channel()->Send(DataBuffer(data));
  3352. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3353. kDefaultTimeout);
  3354. callee()->data_channel()->Send(DataBuffer(data));
  3355. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3356. kDefaultTimeout);
  3357. // Media flow should not be impacted.
  3358. MediaExpectations media_expectations;
  3359. media_expectations.ExpectBidirectionalAudioAndVideo();
  3360. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3361. }
  3362. TEST_P(PeerConnectionIntegrationTest,
  3363. DatagramTransportMediaWithDataChannelOnCaller) {
  3364. // Configure the caller to attempt use of datagram transport for media and
  3365. // data channels.
  3366. PeerConnectionInterface::RTCConfiguration offerer_config;
  3367. offerer_config.rtcp_mux_policy =
  3368. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3369. offerer_config.bundle_policy =
  3370. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3371. offerer_config.use_datagram_transport_for_data_channels = true;
  3372. offerer_config.use_datagram_transport = true;
  3373. // Configure the callee to only use datagram transport for media.
  3374. PeerConnectionInterface::RTCConfiguration answerer_config;
  3375. answerer_config.rtcp_mux_policy =
  3376. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3377. answerer_config.bundle_policy =
  3378. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3379. answerer_config.use_datagram_transport = true;
  3380. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3381. offerer_config, answerer_config,
  3382. loopback_media_transports()->first_factory(),
  3383. loopback_media_transports()->second_factory()));
  3384. ConnectFakeSignaling();
  3385. // Offer both media and data.
  3386. caller()->AddAudioVideoTracks();
  3387. callee()->AddAudioVideoTracks();
  3388. caller()->CreateDataChannel();
  3389. caller()->CreateAndSetAndSignalOffer();
  3390. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3391. // Ensure that the data channel transport is ready.
  3392. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3393. loopback_media_transports()->FlushAsyncInvokes();
  3394. ASSERT_NE(nullptr, caller()->data_channel());
  3395. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3396. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3397. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3398. // Both endpoints should agree to use SCTP for data channels.
  3399. EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
  3400. EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
  3401. // Ensure data can be sent in both directions.
  3402. std::string data = "hello world";
  3403. caller()->data_channel()->Send(DataBuffer(data));
  3404. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3405. kDefaultTimeout);
  3406. callee()->data_channel()->Send(DataBuffer(data));
  3407. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3408. kDefaultTimeout);
  3409. // Media flow should not be impacted.
  3410. MediaExpectations media_expectations;
  3411. media_expectations.ExpectBidirectionalAudioAndVideo();
  3412. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3413. }
  3414. TEST_P(PeerConnectionIntegrationTest,
  3415. DatagramTransportDataChannelWithMediaOnCallee) {
  3416. // Configure the caller to attempt use of datagram transport for data
  3417. // channels.
  3418. PeerConnectionInterface::RTCConfiguration offerer_config;
  3419. offerer_config.rtcp_mux_policy =
  3420. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3421. offerer_config.bundle_policy =
  3422. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3423. offerer_config.use_datagram_transport_for_data_channels = true;
  3424. // Configure the callee to use datagram transport for data channels and media.
  3425. PeerConnectionInterface::RTCConfiguration answerer_config;
  3426. answerer_config.rtcp_mux_policy =
  3427. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3428. answerer_config.bundle_policy =
  3429. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3430. answerer_config.use_datagram_transport_for_data_channels = true;
  3431. answerer_config.use_datagram_transport = true;
  3432. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3433. offerer_config, answerer_config,
  3434. loopback_media_transports()->first_factory(),
  3435. loopback_media_transports()->second_factory()));
  3436. ConnectFakeSignaling();
  3437. // Offer both media and data.
  3438. caller()->AddAudioVideoTracks();
  3439. callee()->AddAudioVideoTracks();
  3440. caller()->CreateDataChannel();
  3441. caller()->CreateAndSetAndSignalOffer();
  3442. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3443. // Ensure that the data channel transport is ready.
  3444. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3445. loopback_media_transports()->FlushAsyncInvokes();
  3446. ASSERT_NE(nullptr, caller()->data_channel());
  3447. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3448. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3449. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3450. // Both endpoints should agree to use datagram transport for data channels.
  3451. EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
  3452. EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
  3453. // Ensure data can be sent in both directions.
  3454. std::string data = "hello world";
  3455. caller()->data_channel()->Send(DataBuffer(data));
  3456. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3457. kDefaultTimeout);
  3458. callee()->data_channel()->Send(DataBuffer(data));
  3459. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3460. kDefaultTimeout);
  3461. // Media flow should not be impacted.
  3462. MediaExpectations media_expectations;
  3463. media_expectations.ExpectBidirectionalAudioAndVideo();
  3464. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3465. }
  3466. TEST_P(PeerConnectionIntegrationTest,
  3467. DatagramTransportMediaWithDataChannelOnCallee) {
  3468. // Configure the caller to attempt use of datagram transport for media.
  3469. PeerConnectionInterface::RTCConfiguration offerer_config;
  3470. offerer_config.rtcp_mux_policy =
  3471. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3472. offerer_config.bundle_policy =
  3473. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3474. offerer_config.use_datagram_transport = true;
  3475. // Configure the callee to only use datagram transport for media and data
  3476. // channels.
  3477. PeerConnectionInterface::RTCConfiguration answerer_config;
  3478. answerer_config.rtcp_mux_policy =
  3479. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3480. answerer_config.bundle_policy =
  3481. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3482. answerer_config.use_datagram_transport = true;
  3483. answerer_config.use_datagram_transport_for_data_channels = true;
  3484. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3485. offerer_config, answerer_config,
  3486. loopback_media_transports()->first_factory(),
  3487. loopback_media_transports()->second_factory()));
  3488. ConnectFakeSignaling();
  3489. // Offer both media and data.
  3490. caller()->AddAudioVideoTracks();
  3491. callee()->AddAudioVideoTracks();
  3492. caller()->CreateDataChannel();
  3493. caller()->CreateAndSetAndSignalOffer();
  3494. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3495. // Ensure that the data channel transport is ready.
  3496. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3497. loopback_media_transports()->FlushAsyncInvokes();
  3498. ASSERT_NE(nullptr, caller()->data_channel());
  3499. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3500. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3501. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3502. // Both endpoints should agree to use SCTP for data channels.
  3503. EXPECT_NE(nullptr, caller()->pc()->GetSctpTransport());
  3504. EXPECT_NE(nullptr, callee()->pc()->GetSctpTransport());
  3505. // Ensure data can be sent in both directions.
  3506. std::string data = "hello world";
  3507. caller()->data_channel()->Send(DataBuffer(data));
  3508. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3509. kDefaultTimeout);
  3510. callee()->data_channel()->Send(DataBuffer(data));
  3511. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3512. kDefaultTimeout);
  3513. // Media flow should not be impacted.
  3514. MediaExpectations media_expectations;
  3515. media_expectations.ExpectBidirectionalAudioAndVideo();
  3516. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3517. }
  3518. TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelAndMedia) {
  3519. // Configure the caller to use datagram transport for data channels and media.
  3520. PeerConnectionInterface::RTCConfiguration offerer_config;
  3521. offerer_config.rtcp_mux_policy =
  3522. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3523. offerer_config.bundle_policy =
  3524. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3525. offerer_config.use_datagram_transport_for_data_channels = true;
  3526. offerer_config.use_datagram_transport = true;
  3527. // Configure the callee to use datagram transport for data channels and media.
  3528. PeerConnectionInterface::RTCConfiguration answerer_config;
  3529. answerer_config.rtcp_mux_policy =
  3530. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3531. answerer_config.bundle_policy =
  3532. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3533. answerer_config.use_datagram_transport_for_data_channels = true;
  3534. answerer_config.use_datagram_transport = true;
  3535. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3536. offerer_config, answerer_config,
  3537. loopback_media_transports()->first_factory(),
  3538. loopback_media_transports()->second_factory()));
  3539. ConnectFakeSignaling();
  3540. // Offer both media and data.
  3541. caller()->AddAudioVideoTracks();
  3542. callee()->AddAudioVideoTracks();
  3543. caller()->CreateDataChannel();
  3544. caller()->CreateAndSetAndSignalOffer();
  3545. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3546. // Ensure that the data channel transport is ready.
  3547. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3548. loopback_media_transports()->FlushAsyncInvokes();
  3549. ASSERT_NE(nullptr, caller()->data_channel());
  3550. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3551. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3552. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3553. // Both endpoints should agree to use datagram transport for data channels.
  3554. EXPECT_EQ(nullptr, caller()->pc()->GetSctpTransport());
  3555. EXPECT_EQ(nullptr, callee()->pc()->GetSctpTransport());
  3556. // Ensure data can be sent in both directions.
  3557. std::string data = "hello world";
  3558. caller()->data_channel()->Send(DataBuffer(data));
  3559. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3560. kDefaultTimeout);
  3561. callee()->data_channel()->Send(DataBuffer(data));
  3562. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3563. kDefaultTimeout);
  3564. // Media flow should not be impacted.
  3565. MediaExpectations media_expectations;
  3566. media_expectations.ExpectBidirectionalAudioAndVideo();
  3567. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3568. }
  3569. // Tests that data channels use SCTP instead of datagram transport if datagram
  3570. // transport is configured in receive-only mode on the caller.
  3571. TEST_P(PeerConnectionIntegrationTest,
  3572. DatagramTransportDataChannelReceiveOnlyOnCallerUsesSctp) {
  3573. PeerConnectionInterface::RTCConfiguration rtc_config;
  3574. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3575. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3576. rtc_config.use_datagram_transport_for_data_channels = true;
  3577. rtc_config.use_datagram_transport_for_data_channels_receive_only = true;
  3578. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3579. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3580. loopback_media_transports()->second_factory()));
  3581. ConnectFakeSignaling();
  3582. // The caller should offer a data channel using SCTP.
  3583. caller()->CreateDataChannel();
  3584. caller()->AddAudioVideoTracks();
  3585. callee()->AddAudioVideoTracks();
  3586. caller()->CreateAndSetAndSignalOffer();
  3587. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3588. ASSERT_NE(nullptr, caller()->data_channel());
  3589. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3590. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3591. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3592. // SCTP transports should be present, since they are in use.
  3593. EXPECT_NE(caller()->pc()->GetSctpTransport(), nullptr);
  3594. EXPECT_NE(callee()->pc()->GetSctpTransport(), nullptr);
  3595. // Ensure data can be sent in both directions.
  3596. std::string data = "hello world";
  3597. caller()->data_channel()->Send(DataBuffer(data));
  3598. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3599. kDefaultTimeout);
  3600. callee()->data_channel()->Send(DataBuffer(data));
  3601. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3602. kDefaultTimeout);
  3603. }
  3604. #endif // HAVE_SCTP
  3605. // Tests that a callee configured for receive-only use of datagram transport
  3606. // data channels accepts them on incoming calls.
  3607. TEST_P(PeerConnectionIntegrationTest,
  3608. DatagramTransportDataChannelReceiveOnlyOnCallee) {
  3609. PeerConnectionInterface::RTCConfiguration offerer_config;
  3610. offerer_config.rtcp_mux_policy =
  3611. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3612. offerer_config.bundle_policy =
  3613. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3614. offerer_config.use_datagram_transport_for_data_channels = true;
  3615. PeerConnectionInterface::RTCConfiguration answerer_config;
  3616. answerer_config.rtcp_mux_policy =
  3617. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3618. answerer_config.bundle_policy =
  3619. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3620. answerer_config.use_datagram_transport_for_data_channels = true;
  3621. answerer_config.use_datagram_transport_for_data_channels_receive_only = true;
  3622. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3623. offerer_config, answerer_config,
  3624. loopback_media_transports()->first_factory(),
  3625. loopback_media_transports()->second_factory()));
  3626. ConnectFakeSignaling();
  3627. caller()->CreateDataChannel();
  3628. caller()->CreateAndSetAndSignalOffer();
  3629. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3630. // Ensure that the data channel transport is ready.
  3631. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3632. loopback_media_transports()->FlushAsyncInvokes();
  3633. ASSERT_NE(nullptr, caller()->data_channel());
  3634. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3635. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3636. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3637. // SCTP transports should not be present, since datagram transport is used.
  3638. EXPECT_EQ(caller()->pc()->GetSctpTransport(), nullptr);
  3639. EXPECT_EQ(callee()->pc()->GetSctpTransport(), nullptr);
  3640. // Ensure data can be sent in both directions.
  3641. std::string data = "hello world";
  3642. caller()->data_channel()->Send(DataBuffer(data));
  3643. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3644. kDefaultTimeout);
  3645. callee()->data_channel()->Send(DataBuffer(data));
  3646. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3647. kDefaultTimeout);
  3648. }
  3649. // This test sets up a call between two parties with a datagram transport data
  3650. // channel.
  3651. TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelEndToEnd) {
  3652. PeerConnectionInterface::RTCConfiguration rtc_config;
  3653. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3654. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3655. rtc_config.use_datagram_transport_for_data_channels = true;
  3656. rtc_config.enable_dtls_srtp = false;
  3657. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3658. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3659. loopback_media_transports()->second_factory()));
  3660. ConnectFakeSignaling();
  3661. // Expect that data channel created on caller side will show up for callee as
  3662. // well.
  3663. caller()->CreateDataChannel();
  3664. caller()->CreateAndSetAndSignalOffer();
  3665. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3666. // Ensure that the data channel transport is ready.
  3667. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3668. loopback_media_transports()->FlushAsyncInvokes();
  3669. // Caller data channel should already exist (it created one). Callee data
  3670. // channel may not exist yet, since negotiation happens in-band, not in SDP.
  3671. ASSERT_NE(nullptr, caller()->data_channel());
  3672. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3673. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3674. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3675. // Ensure data can be sent in both directions.
  3676. std::string data = "hello world";
  3677. caller()->data_channel()->Send(DataBuffer(data));
  3678. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3679. kDefaultTimeout);
  3680. callee()->data_channel()->Send(DataBuffer(data));
  3681. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3682. kDefaultTimeout);
  3683. }
  3684. // Tests that 'zero-rtt' data channel transports (which are ready-to-send as
  3685. // soon as they're created) work correctly.
  3686. TEST_P(PeerConnectionIntegrationTest, DatagramTransportDataChannelZeroRtt) {
  3687. PeerConnectionInterface::RTCConfiguration rtc_config;
  3688. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3689. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3690. rtc_config.use_datagram_transport_for_data_channels = true;
  3691. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  3692. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3693. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3694. loopback_media_transports()->second_factory()));
  3695. ConnectFakeSignaling();
  3696. // Ensure that the callee's media transport is ready-to-send immediately.
  3697. // Note that only the callee can become writable in zero RTTs. The caller
  3698. // must wait for the callee's answer.
  3699. loopback_media_transports()->SetSecondStateAfterConnect(
  3700. webrtc::MediaTransportState::kWritable);
  3701. loopback_media_transports()->FlushAsyncInvokes();
  3702. // Expect that data channel created on caller side will show up for callee as
  3703. // well.
  3704. caller()->CreateDataChannel();
  3705. caller()->CreateAndSetAndSignalOffer();
  3706. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3707. loopback_media_transports()->SetFirstState(
  3708. webrtc::MediaTransportState::kWritable);
  3709. loopback_media_transports()->FlushAsyncInvokes();
  3710. // Caller data channel should already exist (it created one). Callee data
  3711. // channel may not exist yet, since negotiation happens in-band, not in SDP.
  3712. ASSERT_NE(nullptr, caller()->data_channel());
  3713. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3714. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3715. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3716. // Ensure data can be sent in both directions.
  3717. std::string data = "hello world";
  3718. caller()->data_channel()->Send(DataBuffer(data));
  3719. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3720. kDefaultTimeout);
  3721. callee()->data_channel()->Send(DataBuffer(data));
  3722. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3723. kDefaultTimeout);
  3724. }
  3725. // Ensures that when the callee closes a datagram transport data channel, the
  3726. // closing procedure results in the data channel being closed for the caller
  3727. // as well.
  3728. TEST_P(PeerConnectionIntegrationTest,
  3729. DatagramTransportDataChannelCalleeCloses) {
  3730. PeerConnectionInterface::RTCConfiguration rtc_config;
  3731. rtc_config.use_datagram_transport_for_data_channels = true;
  3732. rtc_config.enable_dtls_srtp = false;
  3733. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3734. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3735. loopback_media_transports()->second_factory()));
  3736. ConnectFakeSignaling();
  3737. // Create a data channel on the caller and signal it to the callee.
  3738. caller()->CreateDataChannel();
  3739. caller()->CreateAndSetAndSignalOffer();
  3740. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3741. // Ensure that the data channel transport is ready.
  3742. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3743. loopback_media_transports()->FlushAsyncInvokes();
  3744. // Data channels exist and open on both ends of the connection.
  3745. ASSERT_NE(nullptr, caller()->data_channel());
  3746. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3747. ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3748. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3749. // Close the data channel on the callee side, and wait for it to reach the
  3750. // "closed" state on both sides.
  3751. callee()->data_channel()->Close();
  3752. EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3753. EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3754. }
  3755. // Tests that datagram transport data channels can do in-band negotiation.
  3756. TEST_P(PeerConnectionIntegrationTest,
  3757. DatagramTransportDataChannelConfigSentToOtherSide) {
  3758. PeerConnectionInterface::RTCConfiguration rtc_config;
  3759. rtc_config.use_datagram_transport_for_data_channels = true;
  3760. rtc_config.enable_dtls_srtp = false;
  3761. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3762. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3763. loopback_media_transports()->second_factory()));
  3764. ConnectFakeSignaling();
  3765. // Create a data channel with a non-default configuration and signal it to the
  3766. // callee.
  3767. webrtc::DataChannelInit init;
  3768. init.id = 53;
  3769. init.maxRetransmits = 52;
  3770. caller()->CreateDataChannel("data-channel", &init);
  3771. caller()->CreateAndSetAndSignalOffer();
  3772. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3773. // Ensure that the data channel transport is ready.
  3774. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3775. loopback_media_transports()->FlushAsyncInvokes();
  3776. // Ensure that the data channel exists on the callee with the correct
  3777. // configuration.
  3778. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3779. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3780. // Since "negotiate" is false, the "id" parameter is ignored.
  3781. EXPECT_NE(init.id, callee()->data_channel()->id());
  3782. EXPECT_EQ("data-channel", callee()->data_channel()->label());
  3783. EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
  3784. EXPECT_FALSE(callee()->data_channel()->negotiated());
  3785. }
  3786. TEST_P(PeerConnectionIntegrationTest,
  3787. DatagramTransportDataChannelRejectedWithNoFallback) {
  3788. PeerConnectionInterface::RTCConfiguration offerer_config;
  3789. offerer_config.rtcp_mux_policy =
  3790. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3791. offerer_config.bundle_policy =
  3792. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3793. offerer_config.use_datagram_transport_for_data_channels = true;
  3794. // Disabling DTLS precludes a fallback to SCTP.
  3795. offerer_config.enable_dtls_srtp = false;
  3796. PeerConnectionInterface::RTCConfiguration answerer_config;
  3797. answerer_config.rtcp_mux_policy =
  3798. PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3799. answerer_config.bundle_policy =
  3800. PeerConnectionInterface::kBundlePolicyMaxBundle;
  3801. // Both endpoints must disable DTLS or SetRemoteDescription will fail.
  3802. answerer_config.enable_dtls_srtp = false;
  3803. // Configure one endpoint to use datagram transport for data channels while
  3804. // the other does not.
  3805. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3806. offerer_config, answerer_config,
  3807. loopback_media_transports()->first_factory(), nullptr));
  3808. ConnectFakeSignaling();
  3809. // The caller offers a data channel using either datagram transport or SCTP.
  3810. caller()->CreateDataChannel();
  3811. caller()->AddAudioVideoTracks();
  3812. callee()->AddAudioVideoTracks();
  3813. caller()->CreateAndSetAndSignalOffer();
  3814. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3815. // Caller data channel should already exist (it created one). Callee data
  3816. // channel should not exist, since negotiation happens in-band, not in SDP.
  3817. EXPECT_NE(nullptr, caller()->data_channel());
  3818. EXPECT_EQ(nullptr, callee()->data_channel());
  3819. // The caller's data channel should close when the datagram transport is
  3820. // rejected.
  3821. EXPECT_FALSE(caller()->data_observer()->IsOpen());
  3822. // Media flow should not be impacted by the failed data channel.
  3823. MediaExpectations media_expectations;
  3824. media_expectations.ExpectBidirectionalAudioAndVideo();
  3825. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3826. }
  3827. // This test sets up a call between two parties with a media transport data
  3828. // channel.
  3829. TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelEndToEnd) {
  3830. PeerConnectionInterface::RTCConfiguration rtc_config;
  3831. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3832. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3833. rtc_config.use_media_transport_for_data_channels = true;
  3834. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  3835. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3836. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3837. loopback_media_transports()->second_factory()));
  3838. ConnectFakeSignaling();
  3839. // Expect that data channel created on caller side will show up for callee as
  3840. // well.
  3841. caller()->CreateDataChannel();
  3842. caller()->CreateAndSetAndSignalOffer();
  3843. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3844. // Ensure that the media transport is ready.
  3845. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3846. loopback_media_transports()->FlushAsyncInvokes();
  3847. // Caller data channel should already exist (it created one). Callee data
  3848. // channel may not exist yet, since negotiation happens in-band, not in SDP.
  3849. ASSERT_NE(nullptr, caller()->data_channel());
  3850. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3851. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3852. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3853. // Ensure data can be sent in both directions.
  3854. std::string data = "hello world";
  3855. caller()->data_channel()->Send(DataBuffer(data));
  3856. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3857. kDefaultTimeout);
  3858. callee()->data_channel()->Send(DataBuffer(data));
  3859. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3860. kDefaultTimeout);
  3861. }
  3862. // Tests that 'zero-rtt' data channel transports (which are ready-to-send as
  3863. // soon as they're created) work correctly.
  3864. TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelZeroRtt) {
  3865. PeerConnectionInterface::RTCConfiguration rtc_config;
  3866. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3867. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3868. rtc_config.use_media_transport_for_data_channels = true;
  3869. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  3870. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3871. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3872. loopback_media_transports()->second_factory()));
  3873. ConnectFakeSignaling();
  3874. // Ensure that the callee's media transport is ready-to-send immediately.
  3875. // Note that only the callee can become writable in zero RTTs. The caller
  3876. // must wait for the callee's answer.
  3877. loopback_media_transports()->SetSecondStateAfterConnect(
  3878. webrtc::MediaTransportState::kWritable);
  3879. loopback_media_transports()->FlushAsyncInvokes();
  3880. // Expect that data channel created on caller side will show up for callee as
  3881. // well.
  3882. caller()->CreateDataChannel();
  3883. caller()->CreateAndSetAndSignalOffer();
  3884. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3885. loopback_media_transports()->SetFirstState(
  3886. webrtc::MediaTransportState::kWritable);
  3887. loopback_media_transports()->FlushAsyncInvokes();
  3888. // Caller data channel should already exist (it created one). Callee data
  3889. // channel may not exist yet, since negotiation happens in-band, not in SDP.
  3890. ASSERT_NE(nullptr, caller()->data_channel());
  3891. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3892. EXPECT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3893. EXPECT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3894. // Ensure data can be sent in both directions.
  3895. std::string data = "hello world";
  3896. caller()->data_channel()->Send(DataBuffer(data));
  3897. EXPECT_EQ_WAIT(data, callee()->data_observer()->last_message(),
  3898. kDefaultTimeout);
  3899. callee()->data_channel()->Send(DataBuffer(data));
  3900. EXPECT_EQ_WAIT(data, caller()->data_observer()->last_message(),
  3901. kDefaultTimeout);
  3902. }
  3903. // Ensure that when the callee closes a media transport data channel, the
  3904. // closing procedure results in the data channel being closed for the caller
  3905. // as well.
  3906. TEST_P(PeerConnectionIntegrationTest, MediaTransportDataChannelCalleeCloses) {
  3907. PeerConnectionInterface::RTCConfiguration rtc_config;
  3908. rtc_config.use_media_transport_for_data_channels = true;
  3909. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  3910. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3911. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3912. loopback_media_transports()->second_factory()));
  3913. ConnectFakeSignaling();
  3914. // Create a data channel on the caller and signal it to the callee.
  3915. caller()->CreateDataChannel();
  3916. caller()->CreateAndSetAndSignalOffer();
  3917. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3918. // Ensure that the media transport is ready.
  3919. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3920. loopback_media_transports()->FlushAsyncInvokes();
  3921. // Data channels exist and open on both ends of the connection.
  3922. ASSERT_NE(nullptr, caller()->data_channel());
  3923. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3924. ASSERT_TRUE_WAIT(caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3925. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3926. // Close the data channel on the callee side, and wait for it to reach the
  3927. // "closed" state on both sides.
  3928. callee()->data_channel()->Close();
  3929. EXPECT_TRUE_WAIT(!caller()->data_observer()->IsOpen(), kDefaultTimeout);
  3930. EXPECT_TRUE_WAIT(!callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3931. }
  3932. TEST_P(PeerConnectionIntegrationTest,
  3933. MediaTransportDataChannelConfigSentToOtherSide) {
  3934. PeerConnectionInterface::RTCConfiguration rtc_config;
  3935. rtc_config.use_media_transport_for_data_channels = true;
  3936. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  3937. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3938. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3939. loopback_media_transports()->second_factory()));
  3940. ConnectFakeSignaling();
  3941. // Create a data channel with a non-default configuration and signal it to the
  3942. // callee.
  3943. webrtc::DataChannelInit init;
  3944. init.id = 53;
  3945. init.maxRetransmits = 52;
  3946. caller()->CreateDataChannel("data-channel", &init);
  3947. caller()->CreateAndSetAndSignalOffer();
  3948. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3949. // Ensure that the media transport is ready.
  3950. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3951. loopback_media_transports()->FlushAsyncInvokes();
  3952. // Ensure that the data channel exists on the callee with the correct
  3953. // configuration.
  3954. ASSERT_TRUE_WAIT(callee()->data_channel() != nullptr, kDefaultTimeout);
  3955. ASSERT_TRUE_WAIT(callee()->data_observer()->IsOpen(), kDefaultTimeout);
  3956. // Since "negotiate" is false, the "id" parameter is ignored.
  3957. EXPECT_NE(init.id, callee()->data_channel()->id());
  3958. EXPECT_EQ("data-channel", callee()->data_channel()->label());
  3959. EXPECT_EQ(init.maxRetransmits, callee()->data_channel()->maxRetransmits());
  3960. EXPECT_FALSE(callee()->data_channel()->negotiated());
  3961. }
  3962. TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgrade) {
  3963. PeerConnectionInterface::RTCConfiguration rtc_config;
  3964. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3965. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3966. rtc_config.use_media_transport = true;
  3967. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  3968. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  3969. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  3970. loopback_media_transports()->second_factory()));
  3971. ConnectFakeSignaling();
  3972. // Do initial offer/answer with just a video track.
  3973. caller()->AddVideoTrack();
  3974. callee()->AddVideoTrack();
  3975. caller()->CreateAndSetAndSignalOffer();
  3976. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3977. // Ensure that the media transport is ready.
  3978. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  3979. loopback_media_transports()->FlushAsyncInvokes();
  3980. // Now add an audio track and do another offer/answer.
  3981. caller()->AddAudioTrack();
  3982. callee()->AddAudioTrack();
  3983. caller()->CreateAndSetAndSignalOffer();
  3984. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  3985. // Ensure both audio and video frames are received end-to-end.
  3986. MediaExpectations media_expectations;
  3987. media_expectations.ExpectBidirectionalAudioAndVideo();
  3988. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  3989. // The second offer should not have generated another media transport.
  3990. // Media transport was kept alive, and was not recreated.
  3991. EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
  3992. EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
  3993. }
  3994. TEST_P(PeerConnectionIntegrationTest, MediaTransportOfferUpgradeOnTheCallee) {
  3995. PeerConnectionInterface::RTCConfiguration rtc_config;
  3996. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  3997. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  3998. rtc_config.use_media_transport = true;
  3999. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  4000. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  4001. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  4002. loopback_media_transports()->second_factory()));
  4003. ConnectFakeSignaling();
  4004. // Do initial offer/answer with just a video track.
  4005. caller()->AddVideoTrack();
  4006. callee()->AddVideoTrack();
  4007. caller()->CreateAndSetAndSignalOffer();
  4008. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4009. // Ensure that the media transport is ready.
  4010. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  4011. loopback_media_transports()->FlushAsyncInvokes();
  4012. // Now add an audio track and do another offer/answer.
  4013. caller()->AddAudioTrack();
  4014. callee()->AddAudioTrack();
  4015. callee()->CreateAndSetAndSignalOffer();
  4016. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4017. // Ensure both audio and video frames are received end-to-end.
  4018. MediaExpectations media_expectations;
  4019. media_expectations.ExpectBidirectionalAudioAndVideo();
  4020. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4021. // The second offer should not have generated another media transport.
  4022. // Media transport was kept alive, and was not recreated.
  4023. EXPECT_EQ(1, loopback_media_transports()->first_factory_transport_count());
  4024. EXPECT_EQ(1, loopback_media_transports()->second_factory_transport_count());
  4025. }
  4026. TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalAudio) {
  4027. PeerConnectionInterface::RTCConfiguration rtc_config;
  4028. rtc_config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  4029. rtc_config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  4030. rtc_config.use_media_transport = true;
  4031. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  4032. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  4033. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  4034. loopback_media_transports()->second_factory()));
  4035. ConnectFakeSignaling();
  4036. caller()->AddAudioTrack();
  4037. callee()->AddAudioTrack();
  4038. // Start offer/answer exchange and wait for it to complete.
  4039. caller()->CreateAndSetAndSignalOffer();
  4040. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4041. // Ensure that the media transport is ready.
  4042. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  4043. loopback_media_transports()->FlushAsyncInvokes();
  4044. MediaExpectations media_expectations;
  4045. media_expectations.ExpectBidirectionalAudio();
  4046. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4047. webrtc::MediaTransportPair::Stats first_stats =
  4048. loopback_media_transports()->FirstStats();
  4049. webrtc::MediaTransportPair::Stats second_stats =
  4050. loopback_media_transports()->SecondStats();
  4051. EXPECT_GT(first_stats.received_audio_frames, 0);
  4052. EXPECT_GE(second_stats.sent_audio_frames, first_stats.received_audio_frames);
  4053. EXPECT_GT(second_stats.received_audio_frames, 0);
  4054. EXPECT_GE(first_stats.sent_audio_frames, second_stats.received_audio_frames);
  4055. }
  4056. TEST_P(PeerConnectionIntegrationTest, MediaTransportBidirectionalVideo) {
  4057. PeerConnectionInterface::RTCConfiguration rtc_config;
  4058. rtc_config.use_media_transport = true;
  4059. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  4060. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  4061. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  4062. loopback_media_transports()->second_factory()));
  4063. ConnectFakeSignaling();
  4064. caller()->AddVideoTrack();
  4065. callee()->AddVideoTrack();
  4066. // Start offer/answer exchange and wait for it to complete.
  4067. caller()->CreateAndSetAndSignalOffer();
  4068. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4069. // Ensure that the media transport is ready.
  4070. loopback_media_transports()->SetState(webrtc::MediaTransportState::kWritable);
  4071. loopback_media_transports()->FlushAsyncInvokes();
  4072. MediaExpectations media_expectations;
  4073. media_expectations.ExpectBidirectionalVideo();
  4074. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4075. webrtc::MediaTransportPair::Stats first_stats =
  4076. loopback_media_transports()->FirstStats();
  4077. webrtc::MediaTransportPair::Stats second_stats =
  4078. loopback_media_transports()->SecondStats();
  4079. EXPECT_GT(first_stats.received_video_frames, 0);
  4080. EXPECT_GE(second_stats.sent_video_frames, first_stats.received_video_frames);
  4081. EXPECT_GT(second_stats.received_video_frames, 0);
  4082. EXPECT_GE(first_stats.sent_video_frames, second_stats.received_video_frames);
  4083. }
  4084. TEST_P(PeerConnectionIntegrationTest,
  4085. MediaTransportDataChannelUsesRtpBidirectionalVideo) {
  4086. PeerConnectionInterface::RTCConfiguration rtc_config;
  4087. rtc_config.use_media_transport = false;
  4088. rtc_config.use_media_transport_for_data_channels = true;
  4089. rtc_config.enable_dtls_srtp = false; // SDES is required for media transport.
  4090. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndMediaTransportFactory(
  4091. rtc_config, rtc_config, loopback_media_transports()->first_factory(),
  4092. loopback_media_transports()->second_factory()));
  4093. ConnectFakeSignaling();
  4094. caller()->AddVideoTrack();
  4095. callee()->AddVideoTrack();
  4096. // Start offer/answer exchange and wait for it to complete.
  4097. caller()->CreateAndSetAndSignalOffer();
  4098. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4099. MediaExpectations media_expectations;
  4100. media_expectations.ExpectBidirectionalVideo();
  4101. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4102. }
  4103. // Test that the ICE connection and gathering states eventually reach
  4104. // "complete".
  4105. TEST_P(PeerConnectionIntegrationTest, IceStatesReachCompletion) {
  4106. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4107. ConnectFakeSignaling();
  4108. // Do normal offer/answer.
  4109. caller()->AddAudioVideoTracks();
  4110. callee()->AddAudioVideoTracks();
  4111. caller()->CreateAndSetAndSignalOffer();
  4112. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4113. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
  4114. caller()->ice_gathering_state(), kMaxWaitForFramesMs);
  4115. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceGatheringComplete,
  4116. callee()->ice_gathering_state(), kMaxWaitForFramesMs);
  4117. // After the best candidate pair is selected and all candidates are signaled,
  4118. // the ICE connection state should reach "complete".
  4119. // TODO(deadbeef): Currently, the ICE "controlled" agent (the
  4120. // answerer/"callee" by default) only reaches "connected". When this is
  4121. // fixed, this test should be updated.
  4122. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
  4123. caller()->ice_connection_state(), kDefaultTimeout);
  4124. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  4125. callee()->ice_connection_state(), kDefaultTimeout);
  4126. }
  4127. constexpr int kOnlyLocalPorts = cricket::PORTALLOCATOR_DISABLE_STUN |
  4128. cricket::PORTALLOCATOR_DISABLE_RELAY |
  4129. cricket::PORTALLOCATOR_DISABLE_TCP;
  4130. // Use a mock resolver to resolve the hostname back to the original IP on both
  4131. // sides and check that the ICE connection connects.
  4132. TEST_P(PeerConnectionIntegrationTest,
  4133. IceStatesReachCompletionWithRemoteHostname) {
  4134. auto caller_resolver_factory =
  4135. std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
  4136. auto callee_resolver_factory =
  4137. std::make_unique<NiceMock<webrtc::MockAsyncResolverFactory>>();
  4138. NiceMock<rtc::MockAsyncResolver> callee_async_resolver;
  4139. NiceMock<rtc::MockAsyncResolver> caller_async_resolver;
  4140. // This also verifies that the injected AsyncResolverFactory is used by
  4141. // P2PTransportChannel.
  4142. EXPECT_CALL(*caller_resolver_factory, Create())
  4143. .WillOnce(Return(&caller_async_resolver));
  4144. webrtc::PeerConnectionDependencies caller_deps(nullptr);
  4145. caller_deps.async_resolver_factory = std::move(caller_resolver_factory);
  4146. EXPECT_CALL(*callee_resolver_factory, Create())
  4147. .WillOnce(Return(&callee_async_resolver));
  4148. webrtc::PeerConnectionDependencies callee_deps(nullptr);
  4149. callee_deps.async_resolver_factory = std::move(callee_resolver_factory);
  4150. PeerConnectionInterface::RTCConfiguration config;
  4151. config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  4152. config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  4153. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
  4154. config, std::move(caller_deps), config, std::move(callee_deps)));
  4155. caller()->SetRemoteAsyncResolver(&callee_async_resolver);
  4156. callee()->SetRemoteAsyncResolver(&caller_async_resolver);
  4157. // Enable hostname candidates with mDNS names.
  4158. caller()->SetMdnsResponder(
  4159. std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
  4160. callee()->SetMdnsResponder(
  4161. std::make_unique<webrtc::FakeMdnsResponder>(network_thread()));
  4162. SetPortAllocatorFlags(kOnlyLocalPorts, kOnlyLocalPorts);
  4163. ConnectFakeSignaling();
  4164. caller()->AddAudioVideoTracks();
  4165. callee()->AddAudioVideoTracks();
  4166. caller()->CreateAndSetAndSignalOffer();
  4167. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4168. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
  4169. caller()->ice_connection_state(), kDefaultTimeout);
  4170. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  4171. callee()->ice_connection_state(), kDefaultTimeout);
  4172. EXPECT_EQ(1, webrtc::metrics::NumEvents(
  4173. "WebRTC.PeerConnection.CandidatePairType_UDP",
  4174. webrtc::kIceCandidatePairHostNameHostName));
  4175. }
  4176. // Test that firewalling the ICE connection causes the clients to identify the
  4177. // disconnected state and then removing the firewall causes them to reconnect.
  4178. class PeerConnectionIntegrationIceStatesTest
  4179. : public PeerConnectionIntegrationBaseTest,
  4180. public ::testing::WithParamInterface<
  4181. std::tuple<SdpSemantics, std::tuple<std::string, uint32_t>>> {
  4182. protected:
  4183. PeerConnectionIntegrationIceStatesTest()
  4184. : PeerConnectionIntegrationBaseTest(std::get<0>(GetParam())) {
  4185. port_allocator_flags_ = std::get<1>(std::get<1>(GetParam()));
  4186. }
  4187. void StartStunServer(const SocketAddress& server_address) {
  4188. stun_server_.reset(
  4189. cricket::TestStunServer::Create(network_thread(), server_address));
  4190. }
  4191. bool TestIPv6() {
  4192. return (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6);
  4193. }
  4194. void SetPortAllocatorFlags() {
  4195. PeerConnectionIntegrationBaseTest::SetPortAllocatorFlags(
  4196. port_allocator_flags_, port_allocator_flags_);
  4197. }
  4198. std::vector<SocketAddress> CallerAddresses() {
  4199. std::vector<SocketAddress> addresses;
  4200. addresses.push_back(SocketAddress("1.1.1.1", 0));
  4201. if (TestIPv6()) {
  4202. addresses.push_back(SocketAddress("1111:0:a:b:c:d:e:f", 0));
  4203. }
  4204. return addresses;
  4205. }
  4206. std::vector<SocketAddress> CalleeAddresses() {
  4207. std::vector<SocketAddress> addresses;
  4208. addresses.push_back(SocketAddress("2.2.2.2", 0));
  4209. if (TestIPv6()) {
  4210. addresses.push_back(SocketAddress("2222:0:a:b:c:d:e:f", 0));
  4211. }
  4212. return addresses;
  4213. }
  4214. void SetUpNetworkInterfaces() {
  4215. // Remove the default interfaces added by the test infrastructure.
  4216. caller()->network_manager()->RemoveInterface(kDefaultLocalAddress);
  4217. callee()->network_manager()->RemoveInterface(kDefaultLocalAddress);
  4218. // Add network addresses for test.
  4219. for (const auto& caller_address : CallerAddresses()) {
  4220. caller()->network_manager()->AddInterface(caller_address);
  4221. }
  4222. for (const auto& callee_address : CalleeAddresses()) {
  4223. callee()->network_manager()->AddInterface(callee_address);
  4224. }
  4225. }
  4226. private:
  4227. uint32_t port_allocator_flags_;
  4228. std::unique_ptr<cricket::TestStunServer> stun_server_;
  4229. };
  4230. // Tests that the PeerConnection goes through all the ICE gathering/connection
  4231. // states over the duration of the call. This includes Disconnected and Failed
  4232. // states, induced by putting a firewall between the peers and waiting for them
  4233. // to time out.
  4234. TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyIceStates) {
  4235. rtc::ScopedFakeClock fake_clock;
  4236. // Some things use a time of "0" as a special value, so we need to start out
  4237. // the fake clock at a nonzero time.
  4238. fake_clock.AdvanceTime(TimeDelta::seconds(1));
  4239. const SocketAddress kStunServerAddress =
  4240. SocketAddress("99.99.99.1", cricket::STUN_SERVER_PORT);
  4241. StartStunServer(kStunServerAddress);
  4242. PeerConnectionInterface::RTCConfiguration config;
  4243. PeerConnectionInterface::IceServer ice_stun_server;
  4244. ice_stun_server.urls.push_back(
  4245. "stun:" + kStunServerAddress.HostAsURIString() + ":" +
  4246. kStunServerAddress.PortAsString());
  4247. config.servers.push_back(ice_stun_server);
  4248. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
  4249. ConnectFakeSignaling();
  4250. SetPortAllocatorFlags();
  4251. SetUpNetworkInterfaces();
  4252. caller()->AddAudioVideoTracks();
  4253. callee()->AddAudioVideoTracks();
  4254. // Initial state before anything happens.
  4255. ASSERT_EQ(PeerConnectionInterface::kIceGatheringNew,
  4256. caller()->ice_gathering_state());
  4257. ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
  4258. caller()->ice_connection_state());
  4259. ASSERT_EQ(PeerConnectionInterface::kIceConnectionNew,
  4260. caller()->standardized_ice_connection_state());
  4261. // Start the call by creating the offer, setting it as the local description,
  4262. // then sending it to the peer who will respond with an answer. This happens
  4263. // asynchronously so that we can watch the states as it runs in the
  4264. // background.
  4265. caller()->CreateAndSetAndSignalOffer();
  4266. ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
  4267. caller()->ice_connection_state());
  4268. ASSERT_EQ(PeerConnectionInterface::kIceConnectionCompleted,
  4269. caller()->standardized_ice_connection_state());
  4270. // Verify that the observer was notified of the intermediate transitions.
  4271. EXPECT_THAT(caller()->ice_connection_state_history(),
  4272. ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
  4273. PeerConnectionInterface::kIceConnectionConnected,
  4274. PeerConnectionInterface::kIceConnectionCompleted));
  4275. EXPECT_THAT(caller()->standardized_ice_connection_state_history(),
  4276. ElementsAre(PeerConnectionInterface::kIceConnectionChecking,
  4277. PeerConnectionInterface::kIceConnectionConnected,
  4278. PeerConnectionInterface::kIceConnectionCompleted));
  4279. EXPECT_THAT(
  4280. caller()->peer_connection_state_history(),
  4281. ElementsAre(PeerConnectionInterface::PeerConnectionState::kConnecting,
  4282. PeerConnectionInterface::PeerConnectionState::kConnected));
  4283. EXPECT_THAT(caller()->ice_gathering_state_history(),
  4284. ElementsAre(PeerConnectionInterface::kIceGatheringGathering,
  4285. PeerConnectionInterface::kIceGatheringComplete));
  4286. // Block connections to/from the caller and wait for ICE to become
  4287. // disconnected.
  4288. for (const auto& caller_address : CallerAddresses()) {
  4289. firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
  4290. }
  4291. RTC_LOG(LS_INFO) << "Firewall rules applied";
  4292. ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
  4293. caller()->ice_connection_state(), kDefaultTimeout,
  4294. fake_clock);
  4295. ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionDisconnected,
  4296. caller()->standardized_ice_connection_state(),
  4297. kDefaultTimeout, fake_clock);
  4298. // Let ICE re-establish by removing the firewall rules.
  4299. firewall()->ClearRules();
  4300. RTC_LOG(LS_INFO) << "Firewall rules cleared";
  4301. ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
  4302. caller()->ice_connection_state(), kDefaultTimeout,
  4303. fake_clock);
  4304. ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
  4305. caller()->standardized_ice_connection_state(),
  4306. kDefaultTimeout, fake_clock);
  4307. // According to RFC7675, if there is no response within 30 seconds then the
  4308. // peer should consider the other side to have rejected the connection. This
  4309. // is signaled by the state transitioning to "failed".
  4310. constexpr int kConsentTimeout = 30000;
  4311. for (const auto& caller_address : CallerAddresses()) {
  4312. firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
  4313. }
  4314. RTC_LOG(LS_INFO) << "Firewall rules applied again";
  4315. ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
  4316. caller()->ice_connection_state(), kConsentTimeout,
  4317. fake_clock);
  4318. ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
  4319. caller()->standardized_ice_connection_state(),
  4320. kConsentTimeout, fake_clock);
  4321. // We need to manually close the peerconnections before the fake clock goes
  4322. // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
  4323. // return to using non-faked time.
  4324. delete SetCallerPcWrapperAndReturnCurrent(nullptr);
  4325. delete SetCalleePcWrapperAndReturnCurrent(nullptr);
  4326. }
  4327. // Tests that if the connection doesn't get set up properly we eventually reach
  4328. // the "failed" iceConnectionState.
  4329. TEST_P(PeerConnectionIntegrationIceStatesTest, IceStateSetupFailure) {
  4330. rtc::ScopedFakeClock fake_clock;
  4331. // Some things use a time of "0" as a special value, so we need to start out
  4332. // the fake clock at a nonzero time.
  4333. fake_clock.AdvanceTime(TimeDelta::seconds(1));
  4334. // Block connections to/from the caller and wait for ICE to become
  4335. // disconnected.
  4336. for (const auto& caller_address : CallerAddresses()) {
  4337. firewall()->AddRule(false, rtc::FP_ANY, rtc::FD_ANY, caller_address);
  4338. }
  4339. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4340. ConnectFakeSignaling();
  4341. SetPortAllocatorFlags();
  4342. SetUpNetworkInterfaces();
  4343. caller()->AddAudioVideoTracks();
  4344. caller()->CreateAndSetAndSignalOffer();
  4345. // According to RFC7675, if there is no response within 30 seconds then the
  4346. // peer should consider the other side to have rejected the connection. This
  4347. // is signaled by the state transitioning to "failed".
  4348. constexpr int kConsentTimeout = 30000;
  4349. ASSERT_EQ_SIMULATED_WAIT(PeerConnectionInterface::kIceConnectionFailed,
  4350. caller()->standardized_ice_connection_state(),
  4351. kConsentTimeout, fake_clock);
  4352. // We need to manually close the peerconnections before the fake clock goes
  4353. // out of scope, or we trigger a DCHECK in rtp_sender.cc when we briefly
  4354. // return to using non-faked time.
  4355. delete SetCallerPcWrapperAndReturnCurrent(nullptr);
  4356. delete SetCalleePcWrapperAndReturnCurrent(nullptr);
  4357. }
  4358. // Tests that the best connection is set to the appropriate IPv4/IPv6 connection
  4359. // and that the statistics in the metric observers are updated correctly.
  4360. TEST_P(PeerConnectionIntegrationIceStatesTest, VerifyBestConnection) {
  4361. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4362. ConnectFakeSignaling();
  4363. SetPortAllocatorFlags();
  4364. SetUpNetworkInterfaces();
  4365. caller()->AddAudioVideoTracks();
  4366. callee()->AddAudioVideoTracks();
  4367. caller()->CreateAndSetAndSignalOffer();
  4368. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4369. // TODO(bugs.webrtc.org/9456): Fix it.
  4370. const int num_best_ipv4 = webrtc::metrics::NumEvents(
  4371. "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv4);
  4372. const int num_best_ipv6 = webrtc::metrics::NumEvents(
  4373. "WebRTC.PeerConnection.IPMetrics", webrtc::kBestConnections_IPv6);
  4374. if (TestIPv6()) {
  4375. // When IPv6 is enabled, we should prefer an IPv6 connection over an IPv4
  4376. // connection.
  4377. EXPECT_EQ(0, num_best_ipv4);
  4378. EXPECT_EQ(1, num_best_ipv6);
  4379. } else {
  4380. EXPECT_EQ(1, num_best_ipv4);
  4381. EXPECT_EQ(0, num_best_ipv6);
  4382. }
  4383. EXPECT_EQ(0, webrtc::metrics::NumEvents(
  4384. "WebRTC.PeerConnection.CandidatePairType_UDP",
  4385. webrtc::kIceCandidatePairHostHost));
  4386. EXPECT_EQ(1, webrtc::metrics::NumEvents(
  4387. "WebRTC.PeerConnection.CandidatePairType_UDP",
  4388. webrtc::kIceCandidatePairHostPublicHostPublic));
  4389. }
  4390. constexpr uint32_t kFlagsIPv4NoStun = cricket::PORTALLOCATOR_DISABLE_TCP |
  4391. cricket::PORTALLOCATOR_DISABLE_STUN |
  4392. cricket::PORTALLOCATOR_DISABLE_RELAY;
  4393. constexpr uint32_t kFlagsIPv6NoStun =
  4394. cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_STUN |
  4395. cricket::PORTALLOCATOR_ENABLE_IPV6 | cricket::PORTALLOCATOR_DISABLE_RELAY;
  4396. constexpr uint32_t kFlagsIPv4Stun =
  4397. cricket::PORTALLOCATOR_DISABLE_TCP | cricket::PORTALLOCATOR_DISABLE_RELAY;
  4398. INSTANTIATE_TEST_SUITE_P(
  4399. PeerConnectionIntegrationTest,
  4400. PeerConnectionIntegrationIceStatesTest,
  4401. Combine(Values(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
  4402. Values(std::make_pair("IPv4 no STUN", kFlagsIPv4NoStun),
  4403. std::make_pair("IPv6 no STUN", kFlagsIPv6NoStun),
  4404. std::make_pair("IPv4 with STUN", kFlagsIPv4Stun))));
  4405. // This test sets up a call between two parties with audio and video.
  4406. // During the call, the caller restarts ICE and the test verifies that
  4407. // new ICE candidates are generated and audio and video still can flow, and the
  4408. // ICE state reaches completed again.
  4409. TEST_P(PeerConnectionIntegrationTest, MediaContinuesFlowingAfterIceRestart) {
  4410. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4411. ConnectFakeSignaling();
  4412. // Do normal offer/answer and wait for ICE to complete.
  4413. caller()->AddAudioVideoTracks();
  4414. callee()->AddAudioVideoTracks();
  4415. caller()->CreateAndSetAndSignalOffer();
  4416. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4417. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
  4418. caller()->ice_connection_state(), kMaxWaitForFramesMs);
  4419. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  4420. callee()->ice_connection_state(), kMaxWaitForFramesMs);
  4421. // To verify that the ICE restart actually occurs, get
  4422. // ufrag/password/candidates before and after restart.
  4423. // Create an SDP string of the first audio candidate for both clients.
  4424. const webrtc::IceCandidateCollection* audio_candidates_caller =
  4425. caller()->pc()->local_description()->candidates(0);
  4426. const webrtc::IceCandidateCollection* audio_candidates_callee =
  4427. callee()->pc()->local_description()->candidates(0);
  4428. ASSERT_GT(audio_candidates_caller->count(), 0u);
  4429. ASSERT_GT(audio_candidates_callee->count(), 0u);
  4430. std::string caller_candidate_pre_restart;
  4431. ASSERT_TRUE(
  4432. audio_candidates_caller->at(0)->ToString(&caller_candidate_pre_restart));
  4433. std::string callee_candidate_pre_restart;
  4434. ASSERT_TRUE(
  4435. audio_candidates_callee->at(0)->ToString(&callee_candidate_pre_restart));
  4436. const cricket::SessionDescription* desc =
  4437. caller()->pc()->local_description()->description();
  4438. std::string caller_ufrag_pre_restart =
  4439. desc->transport_infos()[0].description.ice_ufrag;
  4440. desc = callee()->pc()->local_description()->description();
  4441. std::string callee_ufrag_pre_restart =
  4442. desc->transport_infos()[0].description.ice_ufrag;
  4443. EXPECT_EQ(caller()->ice_candidate_pair_change_history().size(), 1u);
  4444. // Have the caller initiate an ICE restart.
  4445. caller()->SetOfferAnswerOptions(IceRestartOfferAnswerOptions());
  4446. caller()->CreateAndSetAndSignalOffer();
  4447. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4448. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
  4449. caller()->ice_connection_state(), kMaxWaitForFramesMs);
  4450. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  4451. callee()->ice_connection_state(), kMaxWaitForFramesMs);
  4452. // Grab the ufrags/candidates again.
  4453. audio_candidates_caller = caller()->pc()->local_description()->candidates(0);
  4454. audio_candidates_callee = callee()->pc()->local_description()->candidates(0);
  4455. ASSERT_GT(audio_candidates_caller->count(), 0u);
  4456. ASSERT_GT(audio_candidates_callee->count(), 0u);
  4457. std::string caller_candidate_post_restart;
  4458. ASSERT_TRUE(
  4459. audio_candidates_caller->at(0)->ToString(&caller_candidate_post_restart));
  4460. std::string callee_candidate_post_restart;
  4461. ASSERT_TRUE(
  4462. audio_candidates_callee->at(0)->ToString(&callee_candidate_post_restart));
  4463. desc = caller()->pc()->local_description()->description();
  4464. std::string caller_ufrag_post_restart =
  4465. desc->transport_infos()[0].description.ice_ufrag;
  4466. desc = callee()->pc()->local_description()->description();
  4467. std::string callee_ufrag_post_restart =
  4468. desc->transport_infos()[0].description.ice_ufrag;
  4469. // Sanity check that an ICE restart was actually negotiated in SDP.
  4470. ASSERT_NE(caller_candidate_pre_restart, caller_candidate_post_restart);
  4471. ASSERT_NE(callee_candidate_pre_restart, callee_candidate_post_restart);
  4472. ASSERT_NE(caller_ufrag_pre_restart, caller_ufrag_post_restart);
  4473. ASSERT_NE(callee_ufrag_pre_restart, callee_ufrag_post_restart);
  4474. EXPECT_GT(caller()->ice_candidate_pair_change_history().size(), 1u);
  4475. // Ensure that additional frames are received after the ICE restart.
  4476. MediaExpectations media_expectations;
  4477. media_expectations.ExpectBidirectionalAudioAndVideo();
  4478. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4479. }
  4480. // Verify that audio/video can be received end-to-end when ICE renomination is
  4481. // enabled.
  4482. TEST_P(PeerConnectionIntegrationTest, EndToEndCallWithIceRenomination) {
  4483. PeerConnectionInterface::RTCConfiguration config;
  4484. config.enable_ice_renomination = true;
  4485. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
  4486. ConnectFakeSignaling();
  4487. // Do normal offer/answer and wait for some frames to be received in each
  4488. // direction.
  4489. caller()->AddAudioVideoTracks();
  4490. callee()->AddAudioVideoTracks();
  4491. caller()->CreateAndSetAndSignalOffer();
  4492. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4493. // Sanity check that ICE renomination was actually negotiated.
  4494. const cricket::SessionDescription* desc =
  4495. caller()->pc()->local_description()->description();
  4496. for (const cricket::TransportInfo& info : desc->transport_infos()) {
  4497. ASSERT_THAT(info.description.transport_options, Contains("renomination"));
  4498. }
  4499. desc = callee()->pc()->local_description()->description();
  4500. for (const cricket::TransportInfo& info : desc->transport_infos()) {
  4501. ASSERT_THAT(info.description.transport_options, Contains("renomination"));
  4502. }
  4503. MediaExpectations media_expectations;
  4504. media_expectations.ExpectBidirectionalAudioAndVideo();
  4505. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4506. }
  4507. // With a max bundle policy and RTCP muxing, adding a new media description to
  4508. // the connection should not affect ICE at all because the new media will use
  4509. // the existing connection.
  4510. TEST_P(PeerConnectionIntegrationTest,
  4511. AddMediaToConnectedBundleDoesNotRestartIce) {
  4512. PeerConnectionInterface::RTCConfiguration config;
  4513. config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  4514. config.rtcp_mux_policy = PeerConnectionInterface::kRtcpMuxPolicyRequire;
  4515. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(
  4516. config, PeerConnectionInterface::RTCConfiguration()));
  4517. ConnectFakeSignaling();
  4518. caller()->AddAudioTrack();
  4519. caller()->CreateAndSetAndSignalOffer();
  4520. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4521. ASSERT_EQ_WAIT(PeerConnectionInterface::kIceConnectionCompleted,
  4522. caller()->ice_connection_state(), kDefaultTimeout);
  4523. caller()->clear_ice_connection_state_history();
  4524. caller()->AddVideoTrack();
  4525. caller()->CreateAndSetAndSignalOffer();
  4526. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4527. EXPECT_EQ(0u, caller()->ice_connection_state_history().size());
  4528. }
  4529. // This test sets up a call between two parties with audio and video. It then
  4530. // renegotiates setting the video m-line to "port 0", then later renegotiates
  4531. // again, enabling video.
  4532. TEST_P(PeerConnectionIntegrationTest,
  4533. VideoFlowsAfterMediaSectionIsRejectedAndRecycled) {
  4534. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4535. ConnectFakeSignaling();
  4536. // Do initial negotiation, only sending media from the caller. Will result in
  4537. // video and audio recvonly "m=" sections.
  4538. caller()->AddAudioVideoTracks();
  4539. caller()->CreateAndSetAndSignalOffer();
  4540. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4541. // Negotiate again, disabling the video "m=" section (the callee will set the
  4542. // port to 0 due to offer_to_receive_video = 0).
  4543. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  4544. PeerConnectionInterface::RTCOfferAnswerOptions options;
  4545. options.offer_to_receive_video = 0;
  4546. callee()->SetOfferAnswerOptions(options);
  4547. } else {
  4548. callee()->SetRemoteOfferHandler([this] {
  4549. callee()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO)->Stop();
  4550. });
  4551. }
  4552. caller()->CreateAndSetAndSignalOffer();
  4553. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4554. // Sanity check that video "m=" section was actually rejected.
  4555. const ContentInfo* answer_video_content = cricket::GetFirstVideoContent(
  4556. callee()->pc()->local_description()->description());
  4557. ASSERT_NE(nullptr, answer_video_content);
  4558. ASSERT_TRUE(answer_video_content->rejected);
  4559. // Enable video and do negotiation again, making sure video is received
  4560. // end-to-end, also adding media stream to callee.
  4561. if (sdp_semantics_ == SdpSemantics::kPlanB) {
  4562. PeerConnectionInterface::RTCOfferAnswerOptions options;
  4563. options.offer_to_receive_video = 1;
  4564. callee()->SetOfferAnswerOptions(options);
  4565. } else {
  4566. // The caller's transceiver is stopped, so we need to add another track.
  4567. auto caller_transceiver =
  4568. caller()->GetFirstTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
  4569. EXPECT_TRUE(caller_transceiver->stopped());
  4570. caller()->AddVideoTrack();
  4571. }
  4572. callee()->AddVideoTrack();
  4573. callee()->SetRemoteOfferHandler(nullptr);
  4574. caller()->CreateAndSetAndSignalOffer();
  4575. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4576. // Verify the caller receives frames from the newly added stream, and the
  4577. // callee receives additional frames from the re-enabled video m= section.
  4578. MediaExpectations media_expectations;
  4579. media_expectations.CalleeExpectsSomeAudio();
  4580. media_expectations.ExpectBidirectionalVideo();
  4581. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4582. }
  4583. // This tests that if we negotiate after calling CreateSender but before we
  4584. // have a track, then set a track later, frames from the newly-set track are
  4585. // received end-to-end.
  4586. TEST_F(PeerConnectionIntegrationTestPlanB,
  4587. MediaFlowsAfterEarlyWarmupWithCreateSender) {
  4588. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4589. ConnectFakeSignaling();
  4590. auto caller_audio_sender =
  4591. caller()->pc()->CreateSender("audio", "caller_stream");
  4592. auto caller_video_sender =
  4593. caller()->pc()->CreateSender("video", "caller_stream");
  4594. auto callee_audio_sender =
  4595. callee()->pc()->CreateSender("audio", "callee_stream");
  4596. auto callee_video_sender =
  4597. callee()->pc()->CreateSender("video", "callee_stream");
  4598. caller()->CreateAndSetAndSignalOffer();
  4599. ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
  4600. // Wait for ICE to complete, without any tracks being set.
  4601. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
  4602. caller()->ice_connection_state(), kMaxWaitForFramesMs);
  4603. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  4604. callee()->ice_connection_state(), kMaxWaitForFramesMs);
  4605. // Now set the tracks, and expect frames to immediately start flowing.
  4606. EXPECT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
  4607. EXPECT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
  4608. EXPECT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
  4609. EXPECT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
  4610. MediaExpectations media_expectations;
  4611. media_expectations.ExpectBidirectionalAudioAndVideo();
  4612. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4613. }
  4614. // This tests that if we negotiate after calling AddTransceiver but before we
  4615. // have a track, then set a track later, frames from the newly-set tracks are
  4616. // received end-to-end.
  4617. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  4618. MediaFlowsAfterEarlyWarmupWithAddTransceiver) {
  4619. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4620. ConnectFakeSignaling();
  4621. auto audio_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_AUDIO);
  4622. ASSERT_EQ(RTCErrorType::NONE, audio_result.error().type());
  4623. auto caller_audio_sender = audio_result.MoveValue()->sender();
  4624. auto video_result = caller()->pc()->AddTransceiver(cricket::MEDIA_TYPE_VIDEO);
  4625. ASSERT_EQ(RTCErrorType::NONE, video_result.error().type());
  4626. auto caller_video_sender = video_result.MoveValue()->sender();
  4627. callee()->SetRemoteOfferHandler([this] {
  4628. ASSERT_EQ(2u, callee()->pc()->GetTransceivers().size());
  4629. callee()->pc()->GetTransceivers()[0]->SetDirection(
  4630. RtpTransceiverDirection::kSendRecv);
  4631. callee()->pc()->GetTransceivers()[1]->SetDirection(
  4632. RtpTransceiverDirection::kSendRecv);
  4633. });
  4634. caller()->CreateAndSetAndSignalOffer();
  4635. ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
  4636. // Wait for ICE to complete, without any tracks being set.
  4637. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionCompleted,
  4638. caller()->ice_connection_state(), kMaxWaitForFramesMs);
  4639. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  4640. callee()->ice_connection_state(), kMaxWaitForFramesMs);
  4641. // Now set the tracks, and expect frames to immediately start flowing.
  4642. auto callee_audio_sender = callee()->pc()->GetSenders()[0];
  4643. auto callee_video_sender = callee()->pc()->GetSenders()[1];
  4644. ASSERT_TRUE(caller_audio_sender->SetTrack(caller()->CreateLocalAudioTrack()));
  4645. ASSERT_TRUE(caller_video_sender->SetTrack(caller()->CreateLocalVideoTrack()));
  4646. ASSERT_TRUE(callee_audio_sender->SetTrack(callee()->CreateLocalAudioTrack()));
  4647. ASSERT_TRUE(callee_video_sender->SetTrack(callee()->CreateLocalVideoTrack()));
  4648. MediaExpectations media_expectations;
  4649. media_expectations.ExpectBidirectionalAudioAndVideo();
  4650. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4651. }
  4652. // This test verifies that a remote video track can be added via AddStream,
  4653. // and sent end-to-end. For this particular test, it's simply echoed back
  4654. // from the caller to the callee, rather than being forwarded to a third
  4655. // PeerConnection.
  4656. TEST_F(PeerConnectionIntegrationTestPlanB, CanSendRemoteVideoTrack) {
  4657. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4658. ConnectFakeSignaling();
  4659. // Just send a video track from the caller.
  4660. caller()->AddVideoTrack();
  4661. caller()->CreateAndSetAndSignalOffer();
  4662. ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
  4663. ASSERT_EQ(1U, callee()->remote_streams()->count());
  4664. // Echo the stream back, and do a new offer/anwer (initiated by callee this
  4665. // time).
  4666. callee()->pc()->AddStream(callee()->remote_streams()->at(0));
  4667. callee()->CreateAndSetAndSignalOffer();
  4668. ASSERT_TRUE_WAIT(SignalingStateStable(), kMaxWaitForActivationMs);
  4669. MediaExpectations media_expectations;
  4670. media_expectations.ExpectBidirectionalVideo();
  4671. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4672. }
  4673. // Test that we achieve the expected end-to-end connection time, using a
  4674. // fake clock and simulated latency on the media and signaling paths.
  4675. // We use a TURN<->TURN connection because this is usually the quickest to
  4676. // set up initially, especially when we're confident the connection will work
  4677. // and can start sending media before we get a STUN response.
  4678. //
  4679. // With various optimizations enabled, here are the network delays we expect to
  4680. // be on the critical path:
  4681. // 1. 2 signaling trips: Signaling offer and offerer's TURN candidate, then
  4682. // signaling answer (with DTLS fingerprint).
  4683. // 2. 9 media hops: Rest of the DTLS handshake. 3 hops in each direction when
  4684. // using TURN<->TURN pair, and DTLS exchange is 4 packets,
  4685. // the first of which should have arrived before the answer.
  4686. TEST_P(PeerConnectionIntegrationTest, EndToEndConnectionTimeWithTurnTurnPair) {
  4687. rtc::ScopedFakeClock fake_clock;
  4688. // Some things use a time of "0" as a special value, so we need to start out
  4689. // the fake clock at a nonzero time.
  4690. // TODO(deadbeef): Fix this.
  4691. fake_clock.AdvanceTime(webrtc::TimeDelta::seconds(1));
  4692. static constexpr int media_hop_delay_ms = 50;
  4693. static constexpr int signaling_trip_delay_ms = 500;
  4694. // For explanation of these values, see comment above.
  4695. static constexpr int required_media_hops = 9;
  4696. static constexpr int required_signaling_trips = 2;
  4697. // For internal delays (such as posting an event asychronously).
  4698. static constexpr int allowed_internal_delay_ms = 20;
  4699. static constexpr int total_connection_time_ms =
  4700. media_hop_delay_ms * required_media_hops +
  4701. signaling_trip_delay_ms * required_signaling_trips +
  4702. allowed_internal_delay_ms;
  4703. static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
  4704. 3478};
  4705. static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
  4706. 0};
  4707. static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
  4708. 3478};
  4709. static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
  4710. 0};
  4711. cricket::TestTurnServer* turn_server_1 = CreateTurnServer(
  4712. turn_server_1_internal_address, turn_server_1_external_address);
  4713. cricket::TestTurnServer* turn_server_2 = CreateTurnServer(
  4714. turn_server_2_internal_address, turn_server_2_external_address);
  4715. // Bypass permission check on received packets so media can be sent before
  4716. // the candidate is signaled.
  4717. network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_1] {
  4718. turn_server_1->set_enable_permission_checks(false);
  4719. });
  4720. network_thread()->Invoke<void>(RTC_FROM_HERE, [turn_server_2] {
  4721. turn_server_2->set_enable_permission_checks(false);
  4722. });
  4723. PeerConnectionInterface::RTCConfiguration client_1_config;
  4724. webrtc::PeerConnectionInterface::IceServer ice_server_1;
  4725. ice_server_1.urls.push_back("turn:88.88.88.0:3478");
  4726. ice_server_1.username = "test";
  4727. ice_server_1.password = "test";
  4728. client_1_config.servers.push_back(ice_server_1);
  4729. client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
  4730. client_1_config.presume_writable_when_fully_relayed = true;
  4731. PeerConnectionInterface::RTCConfiguration client_2_config;
  4732. webrtc::PeerConnectionInterface::IceServer ice_server_2;
  4733. ice_server_2.urls.push_back("turn:99.99.99.0:3478");
  4734. ice_server_2.username = "test";
  4735. ice_server_2.password = "test";
  4736. client_2_config.servers.push_back(ice_server_2);
  4737. client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
  4738. client_2_config.presume_writable_when_fully_relayed = true;
  4739. ASSERT_TRUE(
  4740. CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
  4741. // Set up the simulated delays.
  4742. SetSignalingDelayMs(signaling_trip_delay_ms);
  4743. ConnectFakeSignaling();
  4744. virtual_socket_server()->set_delay_mean(media_hop_delay_ms);
  4745. virtual_socket_server()->UpdateDelayDistribution();
  4746. // Set "offer to receive audio/video" without adding any tracks, so we just
  4747. // set up ICE/DTLS with no media.
  4748. PeerConnectionInterface::RTCOfferAnswerOptions options;
  4749. options.offer_to_receive_audio = 1;
  4750. options.offer_to_receive_video = 1;
  4751. caller()->SetOfferAnswerOptions(options);
  4752. caller()->CreateAndSetAndSignalOffer();
  4753. EXPECT_TRUE_SIMULATED_WAIT(DtlsConnected(), total_connection_time_ms,
  4754. fake_clock);
  4755. // Closing the PeerConnections destroys the ports before the ScopedFakeClock.
  4756. // If this is not done a DCHECK can be hit in ports.cc, because a large
  4757. // negative number is calculated for the rtt due to the global clock changing.
  4758. ClosePeerConnections();
  4759. }
  4760. // Verify that a TurnCustomizer passed in through RTCConfiguration
  4761. // is actually used by the underlying TURN candidate pair.
  4762. // Note that turnport_unittest.cc contains more detailed, lower-level tests.
  4763. TEST_P(PeerConnectionIntegrationTest, TurnCustomizerUsedForTurnConnections) {
  4764. static const rtc::SocketAddress turn_server_1_internal_address{"88.88.88.0",
  4765. 3478};
  4766. static const rtc::SocketAddress turn_server_1_external_address{"88.88.88.1",
  4767. 0};
  4768. static const rtc::SocketAddress turn_server_2_internal_address{"99.99.99.0",
  4769. 3478};
  4770. static const rtc::SocketAddress turn_server_2_external_address{"99.99.99.1",
  4771. 0};
  4772. CreateTurnServer(turn_server_1_internal_address,
  4773. turn_server_1_external_address);
  4774. CreateTurnServer(turn_server_2_internal_address,
  4775. turn_server_2_external_address);
  4776. PeerConnectionInterface::RTCConfiguration client_1_config;
  4777. webrtc::PeerConnectionInterface::IceServer ice_server_1;
  4778. ice_server_1.urls.push_back("turn:88.88.88.0:3478");
  4779. ice_server_1.username = "test";
  4780. ice_server_1.password = "test";
  4781. client_1_config.servers.push_back(ice_server_1);
  4782. client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
  4783. auto* customizer1 = CreateTurnCustomizer();
  4784. client_1_config.turn_customizer = customizer1;
  4785. PeerConnectionInterface::RTCConfiguration client_2_config;
  4786. webrtc::PeerConnectionInterface::IceServer ice_server_2;
  4787. ice_server_2.urls.push_back("turn:99.99.99.0:3478");
  4788. ice_server_2.username = "test";
  4789. ice_server_2.password = "test";
  4790. client_2_config.servers.push_back(ice_server_2);
  4791. client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
  4792. auto* customizer2 = CreateTurnCustomizer();
  4793. client_2_config.turn_customizer = customizer2;
  4794. ASSERT_TRUE(
  4795. CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
  4796. ConnectFakeSignaling();
  4797. // Set "offer to receive audio/video" without adding any tracks, so we just
  4798. // set up ICE/DTLS with no media.
  4799. PeerConnectionInterface::RTCOfferAnswerOptions options;
  4800. options.offer_to_receive_audio = 1;
  4801. options.offer_to_receive_video = 1;
  4802. caller()->SetOfferAnswerOptions(options);
  4803. caller()->CreateAndSetAndSignalOffer();
  4804. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  4805. ExpectTurnCustomizerCountersIncremented(customizer1);
  4806. ExpectTurnCustomizerCountersIncremented(customizer2);
  4807. }
  4808. // Verifies that you can use TCP instead of UDP to connect to a TURN server and
  4809. // send media between the caller and the callee.
  4810. TEST_P(PeerConnectionIntegrationTest, TCPUsedForTurnConnections) {
  4811. static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
  4812. 3478};
  4813. static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
  4814. // Enable TCP for the fake turn server.
  4815. CreateTurnServer(turn_server_internal_address, turn_server_external_address,
  4816. cricket::PROTO_TCP);
  4817. webrtc::PeerConnectionInterface::IceServer ice_server;
  4818. ice_server.urls.push_back("turn:88.88.88.0:3478?transport=tcp");
  4819. ice_server.username = "test";
  4820. ice_server.password = "test";
  4821. PeerConnectionInterface::RTCConfiguration client_1_config;
  4822. client_1_config.servers.push_back(ice_server);
  4823. client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
  4824. PeerConnectionInterface::RTCConfiguration client_2_config;
  4825. client_2_config.servers.push_back(ice_server);
  4826. client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
  4827. ASSERT_TRUE(
  4828. CreatePeerConnectionWrappersWithConfig(client_1_config, client_2_config));
  4829. // Do normal offer/answer and wait for ICE to complete.
  4830. ConnectFakeSignaling();
  4831. caller()->AddAudioVideoTracks();
  4832. callee()->AddAudioVideoTracks();
  4833. caller()->CreateAndSetAndSignalOffer();
  4834. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4835. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  4836. callee()->ice_connection_state(), kMaxWaitForFramesMs);
  4837. MediaExpectations media_expectations;
  4838. media_expectations.ExpectBidirectionalAudioAndVideo();
  4839. EXPECT_TRUE(ExpectNewFrames(media_expectations));
  4840. }
  4841. // Verify that a SSLCertificateVerifier passed in through
  4842. // PeerConnectionDependencies is actually used by the underlying SSL
  4843. // implementation to determine whether a certificate presented by the TURN
  4844. // server is accepted by the client. Note that openssladapter_unittest.cc
  4845. // contains more detailed, lower-level tests.
  4846. TEST_P(PeerConnectionIntegrationTest,
  4847. SSLCertificateVerifierUsedForTurnConnections) {
  4848. static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
  4849. 3478};
  4850. static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
  4851. // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
  4852. // that host name verification passes on the fake certificate.
  4853. CreateTurnServer(turn_server_internal_address, turn_server_external_address,
  4854. cricket::PROTO_TLS, "88.88.88.0");
  4855. webrtc::PeerConnectionInterface::IceServer ice_server;
  4856. ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
  4857. ice_server.username = "test";
  4858. ice_server.password = "test";
  4859. PeerConnectionInterface::RTCConfiguration client_1_config;
  4860. client_1_config.servers.push_back(ice_server);
  4861. client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
  4862. PeerConnectionInterface::RTCConfiguration client_2_config;
  4863. client_2_config.servers.push_back(ice_server);
  4864. // Setting the type to kRelay forces the connection to go through a TURN
  4865. // server.
  4866. client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
  4867. // Get a copy to the pointer so we can verify calls later.
  4868. rtc::TestCertificateVerifier* client_1_cert_verifier =
  4869. new rtc::TestCertificateVerifier();
  4870. client_1_cert_verifier->verify_certificate_ = true;
  4871. rtc::TestCertificateVerifier* client_2_cert_verifier =
  4872. new rtc::TestCertificateVerifier();
  4873. client_2_cert_verifier->verify_certificate_ = true;
  4874. // Create the dependencies with the test certificate verifier.
  4875. webrtc::PeerConnectionDependencies client_1_deps(nullptr);
  4876. client_1_deps.tls_cert_verifier =
  4877. std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
  4878. webrtc::PeerConnectionDependencies client_2_deps(nullptr);
  4879. client_2_deps.tls_cert_verifier =
  4880. std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
  4881. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
  4882. client_1_config, std::move(client_1_deps), client_2_config,
  4883. std::move(client_2_deps)));
  4884. ConnectFakeSignaling();
  4885. // Set "offer to receive audio/video" without adding any tracks, so we just
  4886. // set up ICE/DTLS with no media.
  4887. PeerConnectionInterface::RTCOfferAnswerOptions options;
  4888. options.offer_to_receive_audio = 1;
  4889. options.offer_to_receive_video = 1;
  4890. caller()->SetOfferAnswerOptions(options);
  4891. caller()->CreateAndSetAndSignalOffer();
  4892. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  4893. EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
  4894. EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
  4895. }
  4896. TEST_P(PeerConnectionIntegrationTest,
  4897. SSLCertificateVerifierFailureUsedForTurnConnectionsFailsConnection) {
  4898. static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
  4899. 3478};
  4900. static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
  4901. // Enable TCP-TLS for the fake turn server. We need to pass in 88.88.88.0 so
  4902. // that host name verification passes on the fake certificate.
  4903. CreateTurnServer(turn_server_internal_address, turn_server_external_address,
  4904. cricket::PROTO_TLS, "88.88.88.0");
  4905. webrtc::PeerConnectionInterface::IceServer ice_server;
  4906. ice_server.urls.push_back("turns:88.88.88.0:3478?transport=tcp");
  4907. ice_server.username = "test";
  4908. ice_server.password = "test";
  4909. PeerConnectionInterface::RTCConfiguration client_1_config;
  4910. client_1_config.servers.push_back(ice_server);
  4911. client_1_config.type = webrtc::PeerConnectionInterface::kRelay;
  4912. PeerConnectionInterface::RTCConfiguration client_2_config;
  4913. client_2_config.servers.push_back(ice_server);
  4914. // Setting the type to kRelay forces the connection to go through a TURN
  4915. // server.
  4916. client_2_config.type = webrtc::PeerConnectionInterface::kRelay;
  4917. // Get a copy to the pointer so we can verify calls later.
  4918. rtc::TestCertificateVerifier* client_1_cert_verifier =
  4919. new rtc::TestCertificateVerifier();
  4920. client_1_cert_verifier->verify_certificate_ = false;
  4921. rtc::TestCertificateVerifier* client_2_cert_verifier =
  4922. new rtc::TestCertificateVerifier();
  4923. client_2_cert_verifier->verify_certificate_ = false;
  4924. // Create the dependencies with the test certificate verifier.
  4925. webrtc::PeerConnectionDependencies client_1_deps(nullptr);
  4926. client_1_deps.tls_cert_verifier =
  4927. std::unique_ptr<rtc::TestCertificateVerifier>(client_1_cert_verifier);
  4928. webrtc::PeerConnectionDependencies client_2_deps(nullptr);
  4929. client_2_deps.tls_cert_verifier =
  4930. std::unique_ptr<rtc::TestCertificateVerifier>(client_2_cert_verifier);
  4931. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfigAndDeps(
  4932. client_1_config, std::move(client_1_deps), client_2_config,
  4933. std::move(client_2_deps)));
  4934. ConnectFakeSignaling();
  4935. // Set "offer to receive audio/video" without adding any tracks, so we just
  4936. // set up ICE/DTLS with no media.
  4937. PeerConnectionInterface::RTCOfferAnswerOptions options;
  4938. options.offer_to_receive_audio = 1;
  4939. options.offer_to_receive_video = 1;
  4940. caller()->SetOfferAnswerOptions(options);
  4941. caller()->CreateAndSetAndSignalOffer();
  4942. bool wait_res = true;
  4943. // TODO(bugs.webrtc.org/9219): When IceConnectionState is implemented
  4944. // properly, should be able to just wait for a state of "failed" instead of
  4945. // waiting a fixed 10 seconds.
  4946. WAIT_(DtlsConnected(), kDefaultTimeout, wait_res);
  4947. ASSERT_FALSE(wait_res);
  4948. EXPECT_GT(client_1_cert_verifier->call_count_, 0u);
  4949. EXPECT_GT(client_2_cert_verifier->call_count_, 0u);
  4950. }
  4951. // Test that audio and video flow end-to-end when codec names don't use the
  4952. // expected casing, given that they're supposed to be case insensitive. To test
  4953. // this, all but one codec is removed from each media description, and its
  4954. // casing is changed.
  4955. //
  4956. // In the past, this has regressed and caused crashes/black video, due to the
  4957. // fact that code at some layers was doing case-insensitive comparisons and
  4958. // code at other layers was not.
  4959. TEST_P(PeerConnectionIntegrationTest, CodecNamesAreCaseInsensitive) {
  4960. ASSERT_TRUE(CreatePeerConnectionWrappers());
  4961. ConnectFakeSignaling();
  4962. caller()->AddAudioVideoTracks();
  4963. callee()->AddAudioVideoTracks();
  4964. // Remove all but one audio/video codec (opus and VP8), and change the
  4965. // casing of the caller's generated offer.
  4966. caller()->SetGeneratedSdpMunger([](cricket::SessionDescription* description) {
  4967. cricket::AudioContentDescription* audio =
  4968. GetFirstAudioContentDescription(description);
  4969. ASSERT_NE(nullptr, audio);
  4970. auto audio_codecs = audio->codecs();
  4971. audio_codecs.erase(std::remove_if(audio_codecs.begin(), audio_codecs.end(),
  4972. [](const cricket::AudioCodec& codec) {
  4973. return codec.name != "opus";
  4974. }),
  4975. audio_codecs.end());
  4976. ASSERT_EQ(1u, audio_codecs.size());
  4977. audio_codecs[0].name = "OpUs";
  4978. audio->set_codecs(audio_codecs);
  4979. cricket::VideoContentDescription* video =
  4980. GetFirstVideoContentDescription(description);
  4981. ASSERT_NE(nullptr, video);
  4982. auto video_codecs = video->codecs();
  4983. video_codecs.erase(std::remove_if(video_codecs.begin(), video_codecs.end(),
  4984. [](const cricket::VideoCodec& codec) {
  4985. return codec.name != "VP8";
  4986. }),
  4987. video_codecs.end());
  4988. ASSERT_EQ(1u, video_codecs.size());
  4989. video_codecs[0].name = "vP8";
  4990. video->set_codecs(video_codecs);
  4991. });
  4992. caller()->CreateAndSetAndSignalOffer();
  4993. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  4994. // Verify frames are still received end-to-end.
  4995. MediaExpectations media_expectations;
  4996. media_expectations.ExpectBidirectionalAudioAndVideo();
  4997. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  4998. }
  4999. TEST_P(PeerConnectionIntegrationTest, GetSourcesAudio) {
  5000. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5001. ConnectFakeSignaling();
  5002. caller()->AddAudioTrack();
  5003. caller()->CreateAndSetAndSignalOffer();
  5004. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5005. // Wait for one audio frame to be received by the callee.
  5006. MediaExpectations media_expectations;
  5007. media_expectations.CalleeExpectsSomeAudio(1);
  5008. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5009. ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
  5010. auto receiver = callee()->pc()->GetReceivers()[0];
  5011. ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_AUDIO);
  5012. auto sources = receiver->GetSources();
  5013. ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
  5014. EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
  5015. sources[0].source_id());
  5016. EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
  5017. }
  5018. TEST_P(PeerConnectionIntegrationTest, GetSourcesVideo) {
  5019. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5020. ConnectFakeSignaling();
  5021. caller()->AddVideoTrack();
  5022. caller()->CreateAndSetAndSignalOffer();
  5023. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5024. // Wait for one video frame to be received by the callee.
  5025. MediaExpectations media_expectations;
  5026. media_expectations.CalleeExpectsSomeVideo(1);
  5027. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5028. ASSERT_EQ(callee()->pc()->GetReceivers().size(), 1u);
  5029. auto receiver = callee()->pc()->GetReceivers()[0];
  5030. ASSERT_EQ(receiver->media_type(), cricket::MEDIA_TYPE_VIDEO);
  5031. auto sources = receiver->GetSources();
  5032. ASSERT_GT(receiver->GetParameters().encodings.size(), 0u);
  5033. ASSERT_GT(sources.size(), 0u);
  5034. EXPECT_EQ(receiver->GetParameters().encodings[0].ssrc,
  5035. sources[0].source_id());
  5036. EXPECT_EQ(webrtc::RtpSourceType::SSRC, sources[0].source_type());
  5037. }
  5038. // Test that if a track is removed and added again with a different stream ID,
  5039. // the new stream ID is successfully communicated in SDP and media continues to
  5040. // flow end-to-end.
  5041. // TODO(webrtc.bugs.org/8734): This test does not work for Unified Plan because
  5042. // it will not reuse a transceiver that has already been sending. After creating
  5043. // a new transceiver it tries to create an offer with two senders of the same
  5044. // track ids and it fails.
  5045. TEST_F(PeerConnectionIntegrationTestPlanB, RemoveAndAddTrackWithNewStreamId) {
  5046. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5047. ConnectFakeSignaling();
  5048. // Add track using stream 1, do offer/answer.
  5049. rtc::scoped_refptr<webrtc::AudioTrackInterface> track =
  5050. caller()->CreateLocalAudioTrack();
  5051. rtc::scoped_refptr<webrtc::RtpSenderInterface> sender =
  5052. caller()->AddTrack(track, {"stream_1"});
  5053. caller()->CreateAndSetAndSignalOffer();
  5054. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5055. {
  5056. MediaExpectations media_expectations;
  5057. media_expectations.CalleeExpectsSomeAudio(1);
  5058. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5059. }
  5060. // Remove the sender, and create a new one with the new stream.
  5061. caller()->pc()->RemoveTrack(sender);
  5062. sender = caller()->AddTrack(track, {"stream_2"});
  5063. caller()->CreateAndSetAndSignalOffer();
  5064. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5065. // Wait for additional audio frames to be received by the callee.
  5066. {
  5067. MediaExpectations media_expectations;
  5068. media_expectations.CalleeExpectsSomeAudio();
  5069. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5070. }
  5071. }
  5072. TEST_P(PeerConnectionIntegrationTest, RtcEventLogOutputWriteCalled) {
  5073. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5074. ConnectFakeSignaling();
  5075. auto output = std::make_unique<testing::NiceMock<MockRtcEventLogOutput>>();
  5076. ON_CALL(*output, IsActive()).WillByDefault(::testing::Return(true));
  5077. ON_CALL(*output, Write(::testing::_)).WillByDefault(::testing::Return(true));
  5078. EXPECT_CALL(*output, Write(::testing::_)).Times(::testing::AtLeast(1));
  5079. EXPECT_TRUE(caller()->pc()->StartRtcEventLog(
  5080. std::move(output), webrtc::RtcEventLog::kImmediateOutput));
  5081. caller()->AddAudioVideoTracks();
  5082. caller()->CreateAndSetAndSignalOffer();
  5083. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5084. }
  5085. // Test that if candidates are only signaled by applying full session
  5086. // descriptions (instead of using AddIceCandidate), the peers can connect to
  5087. // each other and exchange media.
  5088. TEST_P(PeerConnectionIntegrationTest, MediaFlowsWhenCandidatesSetOnlyInSdp) {
  5089. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5090. // Each side will signal the session descriptions but not candidates.
  5091. ConnectFakeSignalingForSdpOnly();
  5092. // Add audio video track and exchange the initial offer/answer with media
  5093. // information only. This will start ICE gathering on each side.
  5094. caller()->AddAudioVideoTracks();
  5095. callee()->AddAudioVideoTracks();
  5096. caller()->CreateAndSetAndSignalOffer();
  5097. // Wait for all candidates to be gathered on both the caller and callee.
  5098. ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
  5099. caller()->ice_gathering_state(), kDefaultTimeout);
  5100. ASSERT_EQ_WAIT(PeerConnectionInterface::kIceGatheringComplete,
  5101. callee()->ice_gathering_state(), kDefaultTimeout);
  5102. // The candidates will now be included in the session description, so
  5103. // signaling them will start the ICE connection.
  5104. caller()->CreateAndSetAndSignalOffer();
  5105. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5106. // Ensure that media flows in both directions.
  5107. MediaExpectations media_expectations;
  5108. media_expectations.ExpectBidirectionalAudioAndVideo();
  5109. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5110. }
  5111. // Test that SetAudioPlayout can be used to disable audio playout from the
  5112. // start, then later enable it. This may be useful, for example, if the caller
  5113. // needs to play a local ringtone until some event occurs, after which it
  5114. // switches to playing the received audio.
  5115. TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioPlayout) {
  5116. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5117. ConnectFakeSignaling();
  5118. // Set up audio-only call where audio playout is disabled on caller's side.
  5119. caller()->pc()->SetAudioPlayout(false);
  5120. caller()->AddAudioTrack();
  5121. callee()->AddAudioTrack();
  5122. caller()->CreateAndSetAndSignalOffer();
  5123. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5124. // Pump messages for a second.
  5125. WAIT(false, 1000);
  5126. // Since audio playout is disabled, the caller shouldn't have received
  5127. // anything (at the playout level, at least).
  5128. EXPECT_EQ(0, caller()->audio_frames_received());
  5129. // As a sanity check, make sure the callee (for which playout isn't disabled)
  5130. // did still see frames on its audio level.
  5131. ASSERT_GT(callee()->audio_frames_received(), 0);
  5132. // Enable playout again, and ensure audio starts flowing.
  5133. caller()->pc()->SetAudioPlayout(true);
  5134. MediaExpectations media_expectations;
  5135. media_expectations.ExpectBidirectionalAudio();
  5136. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5137. }
  5138. double GetAudioEnergyStat(PeerConnectionWrapper* pc) {
  5139. auto report = pc->NewGetStats();
  5140. auto track_stats_list =
  5141. report->GetStatsOfType<webrtc::RTCMediaStreamTrackStats>();
  5142. const webrtc::RTCMediaStreamTrackStats* remote_track_stats = nullptr;
  5143. for (const auto* track_stats : track_stats_list) {
  5144. if (track_stats->remote_source.is_defined() &&
  5145. *track_stats->remote_source) {
  5146. remote_track_stats = track_stats;
  5147. break;
  5148. }
  5149. }
  5150. if (!remote_track_stats->total_audio_energy.is_defined()) {
  5151. return 0.0;
  5152. }
  5153. return *remote_track_stats->total_audio_energy;
  5154. }
  5155. // Test that if audio playout is disabled via the SetAudioPlayout() method, then
  5156. // incoming audio is still processed and statistics are generated.
  5157. TEST_P(PeerConnectionIntegrationTest,
  5158. DisableAudioPlayoutStillGeneratesAudioStats) {
  5159. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5160. ConnectFakeSignaling();
  5161. // Set up audio-only call where playout is disabled but audio-processing is
  5162. // still active.
  5163. caller()->AddAudioTrack();
  5164. callee()->AddAudioTrack();
  5165. caller()->pc()->SetAudioPlayout(false);
  5166. caller()->CreateAndSetAndSignalOffer();
  5167. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5168. // Wait for the callee to receive audio stats.
  5169. EXPECT_TRUE_WAIT(GetAudioEnergyStat(caller()) > 0, kMaxWaitForFramesMs);
  5170. }
  5171. // Test that SetAudioRecording can be used to disable audio recording from the
  5172. // start, then later enable it. This may be useful, for example, if the caller
  5173. // wants to ensure that no audio resources are active before a certain state
  5174. // is reached.
  5175. TEST_P(PeerConnectionIntegrationTest, DisableAndEnableAudioRecording) {
  5176. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5177. ConnectFakeSignaling();
  5178. // Set up audio-only call where audio recording is disabled on caller's side.
  5179. caller()->pc()->SetAudioRecording(false);
  5180. caller()->AddAudioTrack();
  5181. callee()->AddAudioTrack();
  5182. caller()->CreateAndSetAndSignalOffer();
  5183. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5184. // Pump messages for a second.
  5185. WAIT(false, 1000);
  5186. // Since caller has disabled audio recording, the callee shouldn't have
  5187. // received anything.
  5188. EXPECT_EQ(0, callee()->audio_frames_received());
  5189. // As a sanity check, make sure the caller did still see frames on its
  5190. // audio level since audio recording is enabled on the calle side.
  5191. ASSERT_GT(caller()->audio_frames_received(), 0);
  5192. // Enable audio recording again, and ensure audio starts flowing.
  5193. caller()->pc()->SetAudioRecording(true);
  5194. MediaExpectations media_expectations;
  5195. media_expectations.ExpectBidirectionalAudio();
  5196. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5197. }
  5198. // Test that after closing PeerConnections, they stop sending any packets (ICE,
  5199. // DTLS, RTP...).
  5200. TEST_P(PeerConnectionIntegrationTest, ClosingConnectionStopsPacketFlow) {
  5201. // Set up audio/video/data, wait for some frames to be received.
  5202. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5203. ConnectFakeSignaling();
  5204. caller()->AddAudioVideoTracks();
  5205. #ifdef HAVE_SCTP
  5206. caller()->CreateDataChannel();
  5207. #endif
  5208. caller()->CreateAndSetAndSignalOffer();
  5209. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5210. MediaExpectations media_expectations;
  5211. media_expectations.CalleeExpectsSomeAudioAndVideo();
  5212. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5213. // Close PeerConnections.
  5214. ClosePeerConnections();
  5215. // Pump messages for a second, and ensure no new packets end up sent.
  5216. uint32_t sent_packets_a = virtual_socket_server()->sent_packets();
  5217. WAIT(false, 1000);
  5218. uint32_t sent_packets_b = virtual_socket_server()->sent_packets();
  5219. EXPECT_EQ(sent_packets_a, sent_packets_b);
  5220. }
  5221. // Test that transport stats are generated by the RTCStatsCollector for a
  5222. // connection that only involves data channels. This is a regression test for
  5223. // crbug.com/826972.
  5224. #ifdef HAVE_SCTP
  5225. TEST_P(PeerConnectionIntegrationTest,
  5226. TransportStatsReportedForDataChannelOnlyConnection) {
  5227. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5228. ConnectFakeSignaling();
  5229. caller()->CreateDataChannel();
  5230. caller()->CreateAndSetAndSignalOffer();
  5231. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5232. ASSERT_TRUE_WAIT(callee()->data_channel(), kDefaultTimeout);
  5233. auto caller_report = caller()->NewGetStats();
  5234. EXPECT_EQ(1u, caller_report->GetStatsOfType<RTCTransportStats>().size());
  5235. auto callee_report = callee()->NewGetStats();
  5236. EXPECT_EQ(1u, callee_report->GetStatsOfType<RTCTransportStats>().size());
  5237. }
  5238. #endif // HAVE_SCTP
  5239. TEST_P(PeerConnectionIntegrationTest,
  5240. IceEventsGeneratedAndLoggedInRtcEventLog) {
  5241. ASSERT_TRUE(CreatePeerConnectionWrappersWithFakeRtcEventLog());
  5242. ConnectFakeSignaling();
  5243. PeerConnectionInterface::RTCOfferAnswerOptions options;
  5244. options.offer_to_receive_audio = 1;
  5245. caller()->SetOfferAnswerOptions(options);
  5246. caller()->CreateAndSetAndSignalOffer();
  5247. ASSERT_TRUE_WAIT(DtlsConnected(), kDefaultTimeout);
  5248. ASSERT_NE(nullptr, caller()->event_log_factory());
  5249. ASSERT_NE(nullptr, callee()->event_log_factory());
  5250. webrtc::FakeRtcEventLog* caller_event_log =
  5251. static_cast<webrtc::FakeRtcEventLog*>(
  5252. caller()->event_log_factory()->last_log_created());
  5253. webrtc::FakeRtcEventLog* callee_event_log =
  5254. static_cast<webrtc::FakeRtcEventLog*>(
  5255. callee()->event_log_factory()->last_log_created());
  5256. ASSERT_NE(nullptr, caller_event_log);
  5257. ASSERT_NE(nullptr, callee_event_log);
  5258. int caller_ice_config_count = caller_event_log->GetEventCount(
  5259. webrtc::RtcEvent::Type::IceCandidatePairConfig);
  5260. int caller_ice_event_count = caller_event_log->GetEventCount(
  5261. webrtc::RtcEvent::Type::IceCandidatePairEvent);
  5262. int callee_ice_config_count = callee_event_log->GetEventCount(
  5263. webrtc::RtcEvent::Type::IceCandidatePairConfig);
  5264. int callee_ice_event_count = callee_event_log->GetEventCount(
  5265. webrtc::RtcEvent::Type::IceCandidatePairEvent);
  5266. EXPECT_LT(0, caller_ice_config_count);
  5267. EXPECT_LT(0, caller_ice_event_count);
  5268. EXPECT_LT(0, callee_ice_config_count);
  5269. EXPECT_LT(0, callee_ice_event_count);
  5270. }
  5271. TEST_P(PeerConnectionIntegrationTest, RegatherAfterChangingIceTransportType) {
  5272. static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
  5273. 3478};
  5274. static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
  5275. CreateTurnServer(turn_server_internal_address, turn_server_external_address);
  5276. webrtc::PeerConnectionInterface::IceServer ice_server;
  5277. ice_server.urls.push_back("turn:88.88.88.0:3478");
  5278. ice_server.username = "test";
  5279. ice_server.password = "test";
  5280. PeerConnectionInterface::RTCConfiguration caller_config;
  5281. caller_config.servers.push_back(ice_server);
  5282. caller_config.type = webrtc::PeerConnectionInterface::kRelay;
  5283. caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
  5284. caller_config.surface_ice_candidates_on_ice_transport_type_changed = true;
  5285. PeerConnectionInterface::RTCConfiguration callee_config;
  5286. callee_config.servers.push_back(ice_server);
  5287. callee_config.type = webrtc::PeerConnectionInterface::kRelay;
  5288. callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
  5289. callee_config.surface_ice_candidates_on_ice_transport_type_changed = true;
  5290. ASSERT_TRUE(
  5291. CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
  5292. // Do normal offer/answer and wait for ICE to complete.
  5293. ConnectFakeSignaling();
  5294. caller()->AddAudioVideoTracks();
  5295. callee()->AddAudioVideoTracks();
  5296. caller()->CreateAndSetAndSignalOffer();
  5297. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5298. // Since we are doing continual gathering, the ICE transport does not reach
  5299. // kIceGatheringComplete (see
  5300. // P2PTransportChannel::OnCandidatesAllocationDone), and consequently not
  5301. // kIceConnectionComplete.
  5302. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  5303. caller()->ice_connection_state(), kDefaultTimeout);
  5304. EXPECT_EQ_WAIT(webrtc::PeerConnectionInterface::kIceConnectionConnected,
  5305. callee()->ice_connection_state(), kDefaultTimeout);
  5306. // Note that we cannot use the metric
  5307. // |WebRTC.PeerConnection.CandidatePairType_UDP| in this test since this
  5308. // metric is only populated when we reach kIceConnectionComplete in the
  5309. // current implementation.
  5310. EXPECT_EQ(cricket::RELAY_PORT_TYPE,
  5311. caller()->last_candidate_gathered().type());
  5312. EXPECT_EQ(cricket::RELAY_PORT_TYPE,
  5313. callee()->last_candidate_gathered().type());
  5314. // Loosen the caller's candidate filter.
  5315. caller_config = caller()->pc()->GetConfiguration();
  5316. caller_config.type = webrtc::PeerConnectionInterface::kAll;
  5317. caller()->pc()->SetConfiguration(caller_config);
  5318. // We should have gathered a new host candidate.
  5319. EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
  5320. caller()->last_candidate_gathered().type(), kDefaultTimeout);
  5321. // Loosen the callee's candidate filter.
  5322. callee_config = callee()->pc()->GetConfiguration();
  5323. callee_config.type = webrtc::PeerConnectionInterface::kAll;
  5324. callee()->pc()->SetConfiguration(callee_config);
  5325. EXPECT_EQ_WAIT(cricket::LOCAL_PORT_TYPE,
  5326. callee()->last_candidate_gathered().type(), kDefaultTimeout);
  5327. }
  5328. TEST_P(PeerConnectionIntegrationTest, OnIceCandidateError) {
  5329. static const rtc::SocketAddress turn_server_internal_address{"88.88.88.0",
  5330. 3478};
  5331. static const rtc::SocketAddress turn_server_external_address{"88.88.88.1", 0};
  5332. CreateTurnServer(turn_server_internal_address, turn_server_external_address);
  5333. webrtc::PeerConnectionInterface::IceServer ice_server;
  5334. ice_server.urls.push_back("turn:88.88.88.0:3478");
  5335. ice_server.username = "test";
  5336. ice_server.password = "123";
  5337. PeerConnectionInterface::RTCConfiguration caller_config;
  5338. caller_config.servers.push_back(ice_server);
  5339. caller_config.type = webrtc::PeerConnectionInterface::kRelay;
  5340. caller_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
  5341. PeerConnectionInterface::RTCConfiguration callee_config;
  5342. callee_config.servers.push_back(ice_server);
  5343. callee_config.type = webrtc::PeerConnectionInterface::kRelay;
  5344. callee_config.continual_gathering_policy = PeerConnection::GATHER_CONTINUALLY;
  5345. ASSERT_TRUE(
  5346. CreatePeerConnectionWrappersWithConfig(caller_config, callee_config));
  5347. // Do normal offer/answer and wait for ICE to complete.
  5348. ConnectFakeSignaling();
  5349. caller()->AddAudioVideoTracks();
  5350. callee()->AddAudioVideoTracks();
  5351. caller()->CreateAndSetAndSignalOffer();
  5352. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5353. EXPECT_EQ_WAIT(401, caller()->error_event().error_code, kDefaultTimeout);
  5354. EXPECT_EQ("Unauthorized", caller()->error_event().error_text);
  5355. EXPECT_EQ("turn:88.88.88.0:3478?transport=udp", caller()->error_event().url);
  5356. EXPECT_NE(std::string::npos,
  5357. caller()->error_event().host_candidate.find(":"));
  5358. }
  5359. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  5360. AudioKeepsFlowingAfterImplicitRollback) {
  5361. PeerConnectionInterface::RTCConfiguration config;
  5362. config.sdp_semantics = SdpSemantics::kUnifiedPlan;
  5363. config.enable_implicit_rollback = true;
  5364. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
  5365. ConnectFakeSignaling();
  5366. caller()->AddAudioTrack();
  5367. callee()->AddAudioTrack();
  5368. caller()->CreateAndSetAndSignalOffer();
  5369. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5370. MediaExpectations media_expectations;
  5371. media_expectations.ExpectBidirectionalAudio();
  5372. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5373. SetSignalIceCandidates(false); // Workaround candidate outrace sdp.
  5374. caller()->AddVideoTrack();
  5375. callee()->AddVideoTrack();
  5376. rtc::scoped_refptr<MockSetSessionDescriptionObserver> observer(
  5377. new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
  5378. callee()->pc()->SetLocalDescription(observer,
  5379. callee()->CreateOfferAndWait().release());
  5380. EXPECT_TRUE_WAIT(observer->called(), kDefaultTimeout);
  5381. caller()->CreateAndSetAndSignalOffer(); // Implicit rollback.
  5382. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5383. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5384. }
  5385. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  5386. ImplicitRollbackVisitsStableState) {
  5387. RTCConfiguration config;
  5388. config.sdp_semantics = SdpSemantics::kUnifiedPlan;
  5389. config.enable_implicit_rollback = true;
  5390. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
  5391. rtc::scoped_refptr<MockSetSessionDescriptionObserver> sld_observer(
  5392. new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
  5393. callee()->pc()->SetLocalDescription(sld_observer,
  5394. callee()->CreateOfferAndWait().release());
  5395. EXPECT_TRUE_WAIT(sld_observer->called(), kDefaultTimeout);
  5396. EXPECT_EQ(sld_observer->error(), "");
  5397. rtc::scoped_refptr<MockSetSessionDescriptionObserver> srd_observer(
  5398. new rtc::RefCountedObject<MockSetSessionDescriptionObserver>());
  5399. callee()->pc()->SetRemoteDescription(
  5400. srd_observer, caller()->CreateOfferAndWait().release());
  5401. EXPECT_TRUE_WAIT(srd_observer->called(), kDefaultTimeout);
  5402. EXPECT_EQ(srd_observer->error(), "");
  5403. EXPECT_THAT(callee()->peer_connection_signaling_state_history(),
  5404. ElementsAre(PeerConnectionInterface::kHaveLocalOffer,
  5405. PeerConnectionInterface::kStable,
  5406. PeerConnectionInterface::kHaveRemoteOffer));
  5407. }
  5408. INSTANTIATE_TEST_SUITE_P(PeerConnectionIntegrationTest,
  5409. PeerConnectionIntegrationTest,
  5410. Values(SdpSemantics::kPlanB,
  5411. SdpSemantics::kUnifiedPlan));
  5412. // Tests that verify interoperability between Plan B and Unified Plan
  5413. // PeerConnections.
  5414. class PeerConnectionIntegrationInteropTest
  5415. : public PeerConnectionIntegrationBaseTest,
  5416. public ::testing::WithParamInterface<
  5417. std::tuple<SdpSemantics, SdpSemantics>> {
  5418. protected:
  5419. // Setting the SdpSemantics for the base test to kDefault does not matter
  5420. // because we specify not to use the test semantics when creating
  5421. // PeerConnectionWrappers.
  5422. PeerConnectionIntegrationInteropTest()
  5423. : PeerConnectionIntegrationBaseTest(SdpSemantics::kPlanB),
  5424. caller_semantics_(std::get<0>(GetParam())),
  5425. callee_semantics_(std::get<1>(GetParam())) {}
  5426. bool CreatePeerConnectionWrappersWithSemantics() {
  5427. return CreatePeerConnectionWrappersWithSdpSemantics(caller_semantics_,
  5428. callee_semantics_);
  5429. }
  5430. const SdpSemantics caller_semantics_;
  5431. const SdpSemantics callee_semantics_;
  5432. };
  5433. TEST_P(PeerConnectionIntegrationInteropTest, NoMediaLocalToNoMediaRemote) {
  5434. ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
  5435. ConnectFakeSignaling();
  5436. caller()->CreateAndSetAndSignalOffer();
  5437. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5438. }
  5439. TEST_P(PeerConnectionIntegrationInteropTest, OneAudioLocalToNoMediaRemote) {
  5440. ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
  5441. ConnectFakeSignaling();
  5442. auto audio_sender = caller()->AddAudioTrack();
  5443. caller()->CreateAndSetAndSignalOffer();
  5444. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5445. // Verify that one audio receiver has been created on the remote and that it
  5446. // has the same track ID as the sending track.
  5447. auto receivers = callee()->pc()->GetReceivers();
  5448. ASSERT_EQ(1u, receivers.size());
  5449. EXPECT_EQ(cricket::MEDIA_TYPE_AUDIO, receivers[0]->media_type());
  5450. EXPECT_EQ(receivers[0]->track()->id(), audio_sender->track()->id());
  5451. MediaExpectations media_expectations;
  5452. media_expectations.CalleeExpectsSomeAudio();
  5453. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5454. }
  5455. TEST_P(PeerConnectionIntegrationInteropTest, OneAudioOneVideoToNoMediaRemote) {
  5456. ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
  5457. ConnectFakeSignaling();
  5458. auto video_sender = caller()->AddVideoTrack();
  5459. auto audio_sender = caller()->AddAudioTrack();
  5460. caller()->CreateAndSetAndSignalOffer();
  5461. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5462. // Verify that one audio and one video receiver have been created on the
  5463. // remote and that they have the same track IDs as the sending tracks.
  5464. auto audio_receivers =
  5465. callee()->GetReceiversOfType(cricket::MEDIA_TYPE_AUDIO);
  5466. ASSERT_EQ(1u, audio_receivers.size());
  5467. EXPECT_EQ(audio_receivers[0]->track()->id(), audio_sender->track()->id());
  5468. auto video_receivers =
  5469. callee()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO);
  5470. ASSERT_EQ(1u, video_receivers.size());
  5471. EXPECT_EQ(video_receivers[0]->track()->id(), video_sender->track()->id());
  5472. MediaExpectations media_expectations;
  5473. media_expectations.CalleeExpectsSomeAudioAndVideo();
  5474. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5475. }
  5476. TEST_P(PeerConnectionIntegrationInteropTest,
  5477. OneAudioOneVideoLocalToOneAudioOneVideoRemote) {
  5478. ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
  5479. ConnectFakeSignaling();
  5480. caller()->AddAudioVideoTracks();
  5481. callee()->AddAudioVideoTracks();
  5482. caller()->CreateAndSetAndSignalOffer();
  5483. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5484. MediaExpectations media_expectations;
  5485. media_expectations.ExpectBidirectionalAudioAndVideo();
  5486. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5487. }
  5488. TEST_P(PeerConnectionIntegrationInteropTest,
  5489. ReverseRolesOneAudioLocalToOneVideoRemote) {
  5490. ASSERT_TRUE(CreatePeerConnectionWrappersWithSemantics());
  5491. ConnectFakeSignaling();
  5492. caller()->AddAudioTrack();
  5493. callee()->AddVideoTrack();
  5494. caller()->CreateAndSetAndSignalOffer();
  5495. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5496. // Verify that only the audio track has been negotiated.
  5497. EXPECT_EQ(0u, caller()->GetReceiversOfType(cricket::MEDIA_TYPE_VIDEO).size());
  5498. // Might also check that the callee's NegotiationNeeded flag is set.
  5499. // Reverse roles.
  5500. callee()->CreateAndSetAndSignalOffer();
  5501. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5502. MediaExpectations media_expectations;
  5503. media_expectations.CallerExpectsSomeVideo();
  5504. media_expectations.CalleeExpectsSomeAudio();
  5505. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5506. }
  5507. INSTANTIATE_TEST_SUITE_P(
  5508. PeerConnectionIntegrationTest,
  5509. PeerConnectionIntegrationInteropTest,
  5510. Values(std::make_tuple(SdpSemantics::kPlanB, SdpSemantics::kUnifiedPlan),
  5511. std::make_tuple(SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB)));
  5512. // Test that if the Unified Plan side offers two video tracks then the Plan B
  5513. // side will only see the first one and ignore the second.
  5514. TEST_F(PeerConnectionIntegrationTestPlanB, TwoVideoUnifiedPlanToNoMediaPlanB) {
  5515. ASSERT_TRUE(CreatePeerConnectionWrappersWithSdpSemantics(
  5516. SdpSemantics::kUnifiedPlan, SdpSemantics::kPlanB));
  5517. ConnectFakeSignaling();
  5518. auto first_sender = caller()->AddVideoTrack();
  5519. caller()->AddVideoTrack();
  5520. caller()->CreateAndSetAndSignalOffer();
  5521. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5522. // Verify that there is only one receiver and it corresponds to the first
  5523. // added track.
  5524. auto receivers = callee()->pc()->GetReceivers();
  5525. ASSERT_EQ(1u, receivers.size());
  5526. EXPECT_TRUE(receivers[0]->track()->enabled());
  5527. EXPECT_EQ(first_sender->track()->id(), receivers[0]->track()->id());
  5528. MediaExpectations media_expectations;
  5529. media_expectations.CalleeExpectsSomeVideo();
  5530. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5531. }
  5532. // Test that if the initial offer tagged BUNDLE section is rejected due to its
  5533. // associated RtpTransceiver being stopped and another transceiver is added,
  5534. // then renegotiation causes the callee to receive the new video track without
  5535. // error.
  5536. // This is a regression test for bugs.webrtc.org/9954
  5537. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  5538. ReOfferWithStoppedBundleTaggedTransceiver) {
  5539. RTCConfiguration config;
  5540. config.bundle_policy = PeerConnectionInterface::kBundlePolicyMaxBundle;
  5541. ASSERT_TRUE(CreatePeerConnectionWrappersWithConfig(config, config));
  5542. ConnectFakeSignaling();
  5543. auto audio_transceiver_or_error =
  5544. caller()->pc()->AddTransceiver(caller()->CreateLocalAudioTrack());
  5545. ASSERT_TRUE(audio_transceiver_or_error.ok());
  5546. auto audio_transceiver = audio_transceiver_or_error.MoveValue();
  5547. caller()->CreateAndSetAndSignalOffer();
  5548. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5549. {
  5550. MediaExpectations media_expectations;
  5551. media_expectations.CalleeExpectsSomeAudio();
  5552. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5553. }
  5554. audio_transceiver->Stop();
  5555. caller()->pc()->AddTransceiver(caller()->CreateLocalVideoTrack());
  5556. caller()->CreateAndSetAndSignalOffer();
  5557. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5558. {
  5559. MediaExpectations media_expectations;
  5560. media_expectations.CalleeExpectsSomeVideo();
  5561. ASSERT_TRUE(ExpectNewFrames(media_expectations));
  5562. }
  5563. }
  5564. #ifdef HAVE_SCTP
  5565. TEST_F(PeerConnectionIntegrationTestUnifiedPlan,
  5566. EndToEndCallWithBundledSctpDataChannel) {
  5567. ASSERT_TRUE(CreatePeerConnectionWrappers());
  5568. ConnectFakeSignaling();
  5569. caller()->CreateDataChannel();
  5570. caller()->AddAudioVideoTracks();
  5571. callee()->AddAudioVideoTracks();
  5572. caller()->SetGeneratedSdpMunger(MakeSpecCompliantSctpOffer);
  5573. caller()->CreateAndSetAndSignalOffer();
  5574. ASSERT_TRUE_WAIT(SignalingStateStable(), kDefaultTimeout);
  5575. // Ensure that media and data are multiplexed on the same DTLS transport.
  5576. // This only works on Unified Plan, because transports are not exposed in plan
  5577. // B.
  5578. auto sctp_info = caller()->pc()->GetSctpTransport()->Information();
  5579. EXPECT_EQ(sctp_info.dtls_transport(),
  5580. caller()->pc()->GetSenders()[0]->dtls_transport());
  5581. }
  5582. #endif // HAVE_SCTP
  5583. } // namespace
  5584. } // namespace webrtc
  5585. #endif // if !defined(THREAD_SANITIZER)