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.

7673 lines
298 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. #include "pc/peer_connection.h"
  11. #include <algorithm>
  12. #include <limits>
  13. #include <memory>
  14. #include <queue>
  15. #include <set>
  16. #include <utility>
  17. #include <vector>
  18. #include "absl/algorithm/container.h"
  19. #include "absl/strings/match.h"
  20. #include "api/jsep_ice_candidate.h"
  21. #include "api/jsep_session_description.h"
  22. #include "api/media_stream_proxy.h"
  23. #include "api/media_stream_track_proxy.h"
  24. #include "api/rtc_error.h"
  25. #include "api/rtc_event_log/rtc_event_log.h"
  26. #include "api/rtc_event_log_output_file.h"
  27. #include "api/rtp_parameters.h"
  28. #include "api/uma_metrics.h"
  29. #include "api/video/builtin_video_bitrate_allocator_factory.h"
  30. #include "call/call.h"
  31. #include "logging/rtc_event_log/ice_logger.h"
  32. #include "media/base/rid_description.h"
  33. #include "media/sctp/sctp_transport.h"
  34. #include "pc/audio_rtp_receiver.h"
  35. #include "pc/audio_track.h"
  36. #include "pc/channel.h"
  37. #include "pc/channel_manager.h"
  38. #include "pc/dtmf_sender.h"
  39. #include "pc/media_stream.h"
  40. #include "pc/media_stream_observer.h"
  41. #include "pc/remote_audio_source.h"
  42. #include "pc/rtp_media_utils.h"
  43. #include "pc/rtp_receiver.h"
  44. #include "pc/rtp_sender.h"
  45. #include "pc/sctp_transport.h"
  46. #include "pc/sctp_utils.h"
  47. #include "pc/sdp_utils.h"
  48. #include "pc/stream_collection.h"
  49. #include "pc/video_rtp_receiver.h"
  50. #include "pc/video_track.h"
  51. #include "rtc_base/bind.h"
  52. #include "rtc_base/checks.h"
  53. #include "rtc_base/logging.h"
  54. #include "rtc_base/string_encode.h"
  55. #include "rtc_base/strings/string_builder.h"
  56. #include "rtc_base/system/fallthrough.h"
  57. #include "rtc_base/trace_event.h"
  58. #include "system_wrappers/include/clock.h"
  59. #include "system_wrappers/include/field_trial.h"
  60. #include "system_wrappers/include/metrics.h"
  61. using cricket::ContentInfo;
  62. using cricket::ContentInfos;
  63. using cricket::MediaContentDescription;
  64. using cricket::MediaProtocolType;
  65. using cricket::RidDescription;
  66. using cricket::RidDirection;
  67. using cricket::SessionDescription;
  68. using cricket::SimulcastDescription;
  69. using cricket::SimulcastLayer;
  70. using cricket::SimulcastLayerList;
  71. using cricket::StreamParams;
  72. using cricket::TransportInfo;
  73. using cricket::LOCAL_PORT_TYPE;
  74. using cricket::PRFLX_PORT_TYPE;
  75. using cricket::RELAY_PORT_TYPE;
  76. using cricket::STUN_PORT_TYPE;
  77. namespace webrtc {
  78. // Error messages
  79. const char kBundleWithoutRtcpMux[] =
  80. "rtcp-mux must be enabled when BUNDLE "
  81. "is enabled.";
  82. const char kInvalidCandidates[] = "Description contains invalid candidates.";
  83. const char kInvalidSdp[] = "Invalid session description.";
  84. const char kMlineMismatchInAnswer[] =
  85. "The order of m-lines in answer doesn't match order in offer. Rejecting "
  86. "answer.";
  87. const char kMlineMismatchInSubsequentOffer[] =
  88. "The order of m-lines in subsequent offer doesn't match order from "
  89. "previous offer/answer.";
  90. const char kSdpWithoutDtlsFingerprint[] =
  91. "Called with SDP without DTLS fingerprint.";
  92. const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
  93. const char kSdpWithoutIceUfragPwd[] =
  94. "Called with SDP without ice-ufrag and ice-pwd.";
  95. const char kSessionError[] = "Session error code: ";
  96. const char kSessionErrorDesc[] = "Session error description: ";
  97. const char kDtlsSrtpSetupFailureRtp[] =
  98. "Couldn't set up DTLS-SRTP on RTP channel.";
  99. const char kDtlsSrtpSetupFailureRtcp[] =
  100. "Couldn't set up DTLS-SRTP on RTCP channel.";
  101. namespace {
  102. // Field trials.
  103. // Controls datagram transport support.
  104. const char kDatagramTransportFieldTrial[] = "WebRTC-DatagramTransport";
  105. // Controls datagram transport data channel support.
  106. const char kDatagramTransportDataChannelFieldTrial[] =
  107. "WebRTC-DatagramTransportDataChannels";
  108. // UMA metric names.
  109. const char kSimulcastVersionApplyLocalDescription[] =
  110. "WebRTC.PeerConnection.Simulcast.ApplyLocalDescription";
  111. const char kSimulcastVersionApplyRemoteDescription[] =
  112. "WebRTC.PeerConnection.Simulcast.ApplyRemoteDescription";
  113. const char kSimulcastNumberOfEncodings[] =
  114. "WebRTC.PeerConnection.Simulcast.NumberOfSendEncodings";
  115. const char kSimulcastDisabled[] = "WebRTC.PeerConnection.Simulcast.Disabled";
  116. static const char kDefaultStreamId[] = "default";
  117. static const char kDefaultAudioSenderId[] = "defaulta0";
  118. static const char kDefaultVideoSenderId[] = "defaultv0";
  119. // The length of RTCP CNAMEs.
  120. static const int kRtcpCnameLength = 16;
  121. enum {
  122. MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
  123. MSG_SET_SESSIONDESCRIPTION_FAILED,
  124. MSG_CREATE_SESSIONDESCRIPTION_FAILED,
  125. MSG_GETSTATS,
  126. MSG_FREE_DATACHANNELS,
  127. MSG_REPORT_USAGE_PATTERN,
  128. };
  129. static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
  130. struct SetSessionDescriptionMsg : public rtc::MessageData {
  131. explicit SetSessionDescriptionMsg(
  132. webrtc::SetSessionDescriptionObserver* observer)
  133. : observer(observer) {}
  134. rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
  135. RTCError error;
  136. };
  137. struct CreateSessionDescriptionMsg : public rtc::MessageData {
  138. explicit CreateSessionDescriptionMsg(
  139. webrtc::CreateSessionDescriptionObserver* observer)
  140. : observer(observer) {}
  141. rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
  142. RTCError error;
  143. };
  144. struct GetStatsMsg : public rtc::MessageData {
  145. GetStatsMsg(webrtc::StatsObserver* observer,
  146. webrtc::MediaStreamTrackInterface* track)
  147. : observer(observer), track(track) {}
  148. rtc::scoped_refptr<webrtc::StatsObserver> observer;
  149. rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
  150. };
  151. // Check if we can send |new_stream| on a PeerConnection.
  152. bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
  153. webrtc::MediaStreamInterface* new_stream) {
  154. if (!new_stream || !current_streams) {
  155. return false;
  156. }
  157. if (current_streams->find(new_stream->id()) != nullptr) {
  158. RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
  159. << " is already added.";
  160. return false;
  161. }
  162. return true;
  163. }
  164. // If the direction is "recvonly" or "inactive", treat the description
  165. // as containing no streams.
  166. // See: https://code.google.com/p/webrtc/issues/detail?id=5054
  167. std::vector<cricket::StreamParams> GetActiveStreams(
  168. const cricket::MediaContentDescription* desc) {
  169. return RtpTransceiverDirectionHasSend(desc->direction())
  170. ? desc->streams()
  171. : std::vector<cricket::StreamParams>();
  172. }
  173. bool IsValidOfferToReceiveMedia(int value) {
  174. typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
  175. return (value >= Options::kUndefined) &&
  176. (value <= Options::kMaxOfferToReceiveMedia);
  177. }
  178. // Add options to |[audio/video]_media_description_options| from |senders|.
  179. void AddPlanBRtpSenderOptions(
  180. const std::vector<rtc::scoped_refptr<
  181. RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
  182. cricket::MediaDescriptionOptions* audio_media_description_options,
  183. cricket::MediaDescriptionOptions* video_media_description_options,
  184. int num_sim_layers) {
  185. for (const auto& sender : senders) {
  186. if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
  187. if (audio_media_description_options) {
  188. audio_media_description_options->AddAudioSender(
  189. sender->id(), sender->internal()->stream_ids());
  190. }
  191. } else {
  192. RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
  193. if (video_media_description_options) {
  194. video_media_description_options->AddVideoSender(
  195. sender->id(), sender->internal()->stream_ids(), {},
  196. SimulcastLayerList(), num_sim_layers);
  197. }
  198. }
  199. }
  200. }
  201. // Add options to |session_options| from |rtp_data_channels|.
  202. void AddRtpDataChannelOptions(
  203. const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
  204. rtp_data_channels,
  205. cricket::MediaDescriptionOptions* data_media_description_options) {
  206. if (!data_media_description_options) {
  207. return;
  208. }
  209. // Check for data channels.
  210. for (const auto& kv : rtp_data_channels) {
  211. const DataChannel* channel = kv.second;
  212. if (channel->state() == DataChannel::kConnecting ||
  213. channel->state() == DataChannel::kOpen) {
  214. // Legacy RTP data channels are signaled with the track/stream ID set to
  215. // the data channel's label.
  216. data_media_description_options->AddRtpDataChannel(channel->label(),
  217. channel->label());
  218. }
  219. }
  220. }
  221. uint32_t ConvertIceTransportTypeToCandidateFilter(
  222. PeerConnectionInterface::IceTransportsType type) {
  223. switch (type) {
  224. case PeerConnectionInterface::kNone:
  225. return cricket::CF_NONE;
  226. case PeerConnectionInterface::kRelay:
  227. return cricket::CF_RELAY;
  228. case PeerConnectionInterface::kNoHost:
  229. return (cricket::CF_ALL & ~cricket::CF_HOST);
  230. case PeerConnectionInterface::kAll:
  231. return cricket::CF_ALL;
  232. default:
  233. RTC_NOTREACHED();
  234. }
  235. return cricket::CF_NONE;
  236. }
  237. std::string GetSignalingStateString(
  238. PeerConnectionInterface::SignalingState state) {
  239. switch (state) {
  240. case PeerConnectionInterface::kStable:
  241. return "kStable";
  242. case PeerConnectionInterface::kHaveLocalOffer:
  243. return "kHaveLocalOffer";
  244. case PeerConnectionInterface::kHaveLocalPrAnswer:
  245. return "kHavePrAnswer";
  246. case PeerConnectionInterface::kHaveRemoteOffer:
  247. return "kHaveRemoteOffer";
  248. case PeerConnectionInterface::kHaveRemotePrAnswer:
  249. return "kHaveRemotePrAnswer";
  250. case PeerConnectionInterface::kClosed:
  251. return "kClosed";
  252. }
  253. RTC_NOTREACHED();
  254. return "";
  255. }
  256. IceCandidatePairType GetIceCandidatePairCounter(
  257. const cricket::Candidate& local,
  258. const cricket::Candidate& remote) {
  259. const auto& l = local.type();
  260. const auto& r = remote.type();
  261. const auto& host = LOCAL_PORT_TYPE;
  262. const auto& srflx = STUN_PORT_TYPE;
  263. const auto& relay = RELAY_PORT_TYPE;
  264. const auto& prflx = PRFLX_PORT_TYPE;
  265. if (l == host && r == host) {
  266. bool local_hostname =
  267. !local.address().hostname().empty() && local.address().IsUnresolvedIP();
  268. bool remote_hostname = !remote.address().hostname().empty() &&
  269. remote.address().IsUnresolvedIP();
  270. bool local_private = IPIsPrivate(local.address().ipaddr());
  271. bool remote_private = IPIsPrivate(remote.address().ipaddr());
  272. if (local_hostname) {
  273. if (remote_hostname) {
  274. return kIceCandidatePairHostNameHostName;
  275. } else if (remote_private) {
  276. return kIceCandidatePairHostNameHostPrivate;
  277. } else {
  278. return kIceCandidatePairHostNameHostPublic;
  279. }
  280. } else if (local_private) {
  281. if (remote_hostname) {
  282. return kIceCandidatePairHostPrivateHostName;
  283. } else if (remote_private) {
  284. return kIceCandidatePairHostPrivateHostPrivate;
  285. } else {
  286. return kIceCandidatePairHostPrivateHostPublic;
  287. }
  288. } else {
  289. if (remote_hostname) {
  290. return kIceCandidatePairHostPublicHostName;
  291. } else if (remote_private) {
  292. return kIceCandidatePairHostPublicHostPrivate;
  293. } else {
  294. return kIceCandidatePairHostPublicHostPublic;
  295. }
  296. }
  297. }
  298. if (l == host && r == srflx)
  299. return kIceCandidatePairHostSrflx;
  300. if (l == host && r == relay)
  301. return kIceCandidatePairHostRelay;
  302. if (l == host && r == prflx)
  303. return kIceCandidatePairHostPrflx;
  304. if (l == srflx && r == host)
  305. return kIceCandidatePairSrflxHost;
  306. if (l == srflx && r == srflx)
  307. return kIceCandidatePairSrflxSrflx;
  308. if (l == srflx && r == relay)
  309. return kIceCandidatePairSrflxRelay;
  310. if (l == srflx && r == prflx)
  311. return kIceCandidatePairSrflxPrflx;
  312. if (l == relay && r == host)
  313. return kIceCandidatePairRelayHost;
  314. if (l == relay && r == srflx)
  315. return kIceCandidatePairRelaySrflx;
  316. if (l == relay && r == relay)
  317. return kIceCandidatePairRelayRelay;
  318. if (l == relay && r == prflx)
  319. return kIceCandidatePairRelayPrflx;
  320. if (l == prflx && r == host)
  321. return kIceCandidatePairPrflxHost;
  322. if (l == prflx && r == srflx)
  323. return kIceCandidatePairPrflxSrflx;
  324. if (l == prflx && r == relay)
  325. return kIceCandidatePairPrflxRelay;
  326. return kIceCandidatePairMax;
  327. }
  328. // Logic to decide if an m= section can be recycled. This means that the new
  329. // m= section is not rejected, but the old local or remote m= section is
  330. // rejected. |old_content_one| and |old_content_two| refer to the m= section
  331. // of the old remote and old local descriptions in no particular order.
  332. // We need to check both the old local and remote because either
  333. // could be the most current from the latest negotation.
  334. bool IsMediaSectionBeingRecycled(SdpType type,
  335. const ContentInfo& content,
  336. const ContentInfo* old_content_one,
  337. const ContentInfo* old_content_two) {
  338. return type == SdpType::kOffer && !content.rejected &&
  339. ((old_content_one && old_content_one->rejected) ||
  340. (old_content_two && old_content_two->rejected));
  341. }
  342. // Verify that the order of media sections in |new_desc| matches
  343. // |current_desc|. The number of m= sections in |new_desc| should be no
  344. // less than |current_desc|. In the case of checking an answer's
  345. // |new_desc|, the |current_desc| is the last offer that was set as the
  346. // local or remote. In the case of checking an offer's |new_desc| we
  347. // check against the local and remote descriptions stored from the last
  348. // negotiation, because either of these could be the most up to date for
  349. // possible rejected m sections. These are the |current_desc| and
  350. // |secondary_current_desc|.
  351. bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
  352. const SessionDescription* secondary_current_desc,
  353. const SessionDescription& new_desc,
  354. const SdpType type) {
  355. if (current_desc.contents().size() > new_desc.contents().size()) {
  356. return false;
  357. }
  358. for (size_t i = 0; i < current_desc.contents().size(); ++i) {
  359. const cricket::ContentInfo* secondary_content_info = nullptr;
  360. if (secondary_current_desc &&
  361. i < secondary_current_desc->contents().size()) {
  362. secondary_content_info = &secondary_current_desc->contents()[i];
  363. }
  364. if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
  365. &current_desc.contents()[i],
  366. secondary_content_info)) {
  367. // For new offer descriptions, if the media section can be recycled, it's
  368. // valid for the MID and media type to change.
  369. continue;
  370. }
  371. if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
  372. return false;
  373. }
  374. const MediaContentDescription* new_desc_mdesc =
  375. new_desc.contents()[i].media_description();
  376. const MediaContentDescription* current_desc_mdesc =
  377. current_desc.contents()[i].media_description();
  378. if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
  379. return false;
  380. }
  381. }
  382. return true;
  383. }
  384. bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
  385. const SessionDescription& desc2) {
  386. return desc1.contents().size() == desc2.contents().size();
  387. }
  388. void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
  389. cricket::MediaType media_type) {
  390. // Array of structs needed to map {KeyExchangeProtocolType,
  391. // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
  392. // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
  393. static constexpr struct {
  394. KeyExchangeProtocolType protocol_type;
  395. cricket::MediaType media_type;
  396. KeyExchangeProtocolMedia protocol_media;
  397. } kEnumCounterKeyProtocolMediaMap[] = {
  398. {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
  399. kEnumCounterKeyProtocolMediaTypeDtlsAudio},
  400. {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
  401. kEnumCounterKeyProtocolMediaTypeDtlsVideo},
  402. {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
  403. kEnumCounterKeyProtocolMediaTypeDtlsData},
  404. {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
  405. kEnumCounterKeyProtocolMediaTypeSdesAudio},
  406. {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
  407. kEnumCounterKeyProtocolMediaTypeSdesVideo},
  408. {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
  409. kEnumCounterKeyProtocolMediaTypeSdesData},
  410. };
  411. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
  412. kEnumCounterKeyProtocolMax);
  413. for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
  414. if (i.protocol_type == protocol_type && i.media_type == media_type) {
  415. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
  416. i.protocol_media,
  417. kEnumCounterKeyProtocolMediaTypeMax);
  418. }
  419. }
  420. }
  421. void NoteAddIceCandidateResult(int result) {
  422. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
  423. kAddIceCandidateMax);
  424. }
  425. // Checks that each non-rejected content has SDES crypto keys or a DTLS
  426. // fingerprint, unless it's in a BUNDLE group, in which case only the
  427. // BUNDLE-tag section (first media section/description in the BUNDLE group)
  428. // needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
  429. // to SDES keys, will be caught in JsepTransport negotiation, and backstopped
  430. // by Channel's |srtp_required| check.
  431. RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
  432. const cricket::ContentGroup* bundle =
  433. desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
  434. for (const cricket::ContentInfo& content_info : desc->contents()) {
  435. if (content_info.rejected) {
  436. continue;
  437. }
  438. // Note what media is used with each crypto protocol, for all sections.
  439. NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
  440. : webrtc::kEnumCounterKeyProtocolSdes,
  441. content_info.media_description()->type());
  442. const std::string& mid = content_info.name;
  443. if (bundle && bundle->HasContentName(mid) &&
  444. mid != *(bundle->FirstContentName())) {
  445. // This isn't the first media section in the BUNDLE group, so it's not
  446. // required to have crypto attributes, since only the crypto attributes
  447. // from the first section actually get used.
  448. continue;
  449. }
  450. // If the content isn't rejected or bundled into another m= section, crypto
  451. // must be present.
  452. const MediaContentDescription* media = content_info.media_description();
  453. const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
  454. if (!media || !tinfo) {
  455. // Something is not right.
  456. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
  457. }
  458. if (dtls_enabled) {
  459. if (!tinfo->description.identity_fingerprint) {
  460. RTC_LOG(LS_WARNING)
  461. << "Session description must have DTLS fingerprint if "
  462. "DTLS enabled.";
  463. return RTCError(RTCErrorType::INVALID_PARAMETER,
  464. kSdpWithoutDtlsFingerprint);
  465. }
  466. } else {
  467. if (media->cryptos().empty()) {
  468. RTC_LOG(LS_WARNING)
  469. << "Session description must have SDES when DTLS disabled.";
  470. return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
  471. }
  472. }
  473. }
  474. return RTCError::OK();
  475. }
  476. // Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
  477. // it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
  478. // media section/description in the BUNDLE group) needs a ufrag and pwd.
  479. bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
  480. const cricket::ContentGroup* bundle =
  481. desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
  482. for (const cricket::ContentInfo& content_info : desc->contents()) {
  483. if (content_info.rejected) {
  484. continue;
  485. }
  486. const std::string& mid = content_info.name;
  487. if (bundle && bundle->HasContentName(mid) &&
  488. mid != *(bundle->FirstContentName())) {
  489. // This isn't the first media section in the BUNDLE group, so it's not
  490. // required to have ufrag/password, since only the ufrag/password from
  491. // the first section actually get used.
  492. continue;
  493. }
  494. // If the content isn't rejected or bundled into another m= section,
  495. // ice-ufrag and ice-pwd must be present.
  496. const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
  497. if (!tinfo) {
  498. // Something is not right.
  499. RTC_LOG(LS_ERROR) << kInvalidSdp;
  500. return false;
  501. }
  502. if (tinfo->description.ice_ufrag.empty() ||
  503. tinfo->description.ice_pwd.empty()) {
  504. RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
  505. return false;
  506. }
  507. }
  508. return true;
  509. }
  510. // Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
  511. bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
  512. const SessionDescriptionInterface* new_desc,
  513. const std::string& content_name) {
  514. if (!old_desc) {
  515. return false;
  516. }
  517. const SessionDescription* new_sd = new_desc->description();
  518. const SessionDescription* old_sd = old_desc->description();
  519. const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
  520. if (!cinfo || cinfo->rejected) {
  521. return false;
  522. }
  523. // If the content isn't rejected, check if ufrag and password has changed.
  524. const cricket::TransportDescription* new_transport_desc =
  525. new_sd->GetTransportDescriptionByName(content_name);
  526. const cricket::TransportDescription* old_transport_desc =
  527. old_sd->GetTransportDescriptionByName(content_name);
  528. if (!new_transport_desc || !old_transport_desc) {
  529. // No transport description exists. This is not an ICE restart.
  530. return false;
  531. }
  532. if (cricket::IceCredentialsChanged(
  533. old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
  534. new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
  535. RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
  536. << ".";
  537. return true;
  538. }
  539. return false;
  540. }
  541. // Generates a string error message for SetLocalDescription/SetRemoteDescription
  542. // from an RTCError.
  543. std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
  544. SdpType type,
  545. const RTCError& error) {
  546. rtc::StringBuilder oss;
  547. oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
  548. << " " << SdpTypeToString(type) << " sdp: " << error.message();
  549. return oss.Release();
  550. }
  551. std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
  552. std::string output = "streams=[";
  553. const char* separator = "";
  554. for (const auto& stream_id : stream_ids) {
  555. output.append(separator).append(stream_id);
  556. separator = ", ";
  557. }
  558. output.append("]");
  559. return output;
  560. }
  561. absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
  562. int rtc_configuration_parameter) {
  563. if (rtc_configuration_parameter ==
  564. webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
  565. return absl::nullopt;
  566. }
  567. return rtc_configuration_parameter;
  568. }
  569. void ReportSimulcastApiVersion(const char* name,
  570. const SessionDescription& session) {
  571. bool has_legacy = false;
  572. bool has_spec_compliant = false;
  573. for (const ContentInfo& content : session.contents()) {
  574. if (!content.media_description()) {
  575. continue;
  576. }
  577. has_spec_compliant |= content.media_description()->HasSimulcast();
  578. for (const StreamParams& sp : content.media_description()->streams()) {
  579. has_legacy |= sp.has_ssrc_group(cricket::kSimSsrcGroupSemantics);
  580. }
  581. }
  582. if (has_legacy) {
  583. RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionLegacy,
  584. kSimulcastApiVersionMax);
  585. }
  586. if (has_spec_compliant) {
  587. RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionSpecCompliant,
  588. kSimulcastApiVersionMax);
  589. }
  590. if (!has_legacy && !has_spec_compliant) {
  591. RTC_HISTOGRAM_ENUMERATION(name, kSimulcastApiVersionNone,
  592. kSimulcastApiVersionMax);
  593. }
  594. }
  595. const ContentInfo* FindTransceiverMSection(
  596. RtpTransceiverProxyWithInternal<RtpTransceiver>* transceiver,
  597. const SessionDescriptionInterface* session_description) {
  598. return transceiver->mid()
  599. ? session_description->description()->GetContentByName(
  600. *transceiver->mid())
  601. : nullptr;
  602. }
  603. } // namespace
  604. class PeerConnection::LocalIceCredentialsToReplace {
  605. public:
  606. // Sets the ICE credentials that need restarting to the ICE credentials of
  607. // the current and pending descriptions.
  608. void SetIceCredentialsFromLocalDescriptions(
  609. const SessionDescriptionInterface* current_local_description,
  610. const SessionDescriptionInterface* pending_local_description) {
  611. ice_credentials_.clear();
  612. if (current_local_description) {
  613. AppendIceCredentialsFromSessionDescription(*current_local_description);
  614. }
  615. if (pending_local_description) {
  616. AppendIceCredentialsFromSessionDescription(*pending_local_description);
  617. }
  618. }
  619. void ClearIceCredentials() { ice_credentials_.clear(); }
  620. // Returns true if we have ICE credentials that need restarting.
  621. bool HasIceCredentials() const { return !ice_credentials_.empty(); }
  622. // Returns true if |local_description| shares no ICE credentials with the
  623. // ICE credentials that need restarting.
  624. bool SatisfiesIceRestart(
  625. const SessionDescriptionInterface& local_description) const {
  626. for (const auto& transport_info :
  627. local_description.description()->transport_infos()) {
  628. if (ice_credentials_.find(std::make_pair(
  629. transport_info.description.ice_ufrag,
  630. transport_info.description.ice_pwd)) != ice_credentials_.end()) {
  631. return false;
  632. }
  633. }
  634. return true;
  635. }
  636. private:
  637. void AppendIceCredentialsFromSessionDescription(
  638. const SessionDescriptionInterface& desc) {
  639. for (const auto& transport_info : desc.description()->transport_infos()) {
  640. ice_credentials_.insert(
  641. std::make_pair(transport_info.description.ice_ufrag,
  642. transport_info.description.ice_pwd));
  643. }
  644. }
  645. std::set<std::pair<std::string, std::string>> ice_credentials_;
  646. };
  647. // Upon completion, posts a task to execute the callback of the
  648. // SetSessionDescriptionObserver asynchronously on the same thread. At this
  649. // point, the state of the peer connection might no longer reflect the effects
  650. // of the SetRemoteDescription operation, as the peer connection could have been
  651. // modified during the post.
  652. // TODO(hbos): Remove this class once we remove the version of
  653. // PeerConnectionInterface::SetRemoteDescription() that takes a
  654. // SetSessionDescriptionObserver as an argument.
  655. class PeerConnection::SetRemoteDescriptionObserverAdapter
  656. : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
  657. public:
  658. SetRemoteDescriptionObserverAdapter(
  659. rtc::scoped_refptr<PeerConnection> pc,
  660. rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
  661. : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
  662. // SetRemoteDescriptionObserverInterface implementation.
  663. void OnSetRemoteDescriptionComplete(RTCError error) override {
  664. if (error.ok())
  665. pc_->PostSetSessionDescriptionSuccess(wrapper_);
  666. else
  667. pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
  668. }
  669. private:
  670. rtc::scoped_refptr<PeerConnection> pc_;
  671. rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
  672. };
  673. bool PeerConnectionInterface::RTCConfiguration::operator==(
  674. const PeerConnectionInterface::RTCConfiguration& o) const {
  675. // This static_assert prevents us from accidentally breaking operator==.
  676. // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
  677. struct stuff_being_tested_for_equality {
  678. IceServers servers;
  679. IceTransportsType type;
  680. BundlePolicy bundle_policy;
  681. RtcpMuxPolicy rtcp_mux_policy;
  682. std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
  683. int ice_candidate_pool_size;
  684. bool disable_ipv6;
  685. bool disable_ipv6_on_wifi;
  686. int max_ipv6_networks;
  687. bool disable_link_local_networks;
  688. bool enable_rtp_data_channel;
  689. absl::optional<int> screencast_min_bitrate;
  690. absl::optional<bool> combined_audio_video_bwe;
  691. absl::optional<bool> enable_dtls_srtp;
  692. TcpCandidatePolicy tcp_candidate_policy;
  693. CandidateNetworkPolicy candidate_network_policy;
  694. int audio_jitter_buffer_max_packets;
  695. bool audio_jitter_buffer_fast_accelerate;
  696. int audio_jitter_buffer_min_delay_ms;
  697. bool audio_jitter_buffer_enable_rtx_handling;
  698. int ice_connection_receiving_timeout;
  699. int ice_backup_candidate_pair_ping_interval;
  700. ContinualGatheringPolicy continual_gathering_policy;
  701. bool prioritize_most_likely_ice_candidate_pairs;
  702. struct cricket::MediaConfig media_config;
  703. bool prune_turn_ports;
  704. PortPrunePolicy turn_port_prune_policy;
  705. bool presume_writable_when_fully_relayed;
  706. bool enable_ice_renomination;
  707. bool redetermine_role_on_ice_restart;
  708. bool surface_ice_candidates_on_ice_transport_type_changed;
  709. absl::optional<int> ice_check_interval_strong_connectivity;
  710. absl::optional<int> ice_check_interval_weak_connectivity;
  711. absl::optional<int> ice_check_min_interval;
  712. absl::optional<int> ice_unwritable_timeout;
  713. absl::optional<int> ice_unwritable_min_checks;
  714. absl::optional<int> ice_inactive_timeout;
  715. absl::optional<int> stun_candidate_keepalive_interval;
  716. absl::optional<rtc::IntervalRange> ice_regather_interval_range;
  717. webrtc::TurnCustomizer* turn_customizer;
  718. SdpSemantics sdp_semantics;
  719. absl::optional<rtc::AdapterType> network_preference;
  720. bool active_reset_srtp_params;
  721. bool use_media_transport;
  722. bool use_media_transport_for_data_channels;
  723. absl::optional<bool> use_datagram_transport;
  724. absl::optional<bool> use_datagram_transport_for_data_channels;
  725. absl::optional<bool> use_datagram_transport_for_data_channels_receive_only;
  726. absl::optional<CryptoOptions> crypto_options;
  727. bool offer_extmap_allow_mixed;
  728. std::string turn_logging_id;
  729. bool enable_implicit_rollback;
  730. };
  731. static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
  732. "Did you add something to RTCConfiguration and forget to "
  733. "update operator==?");
  734. return type == o.type && servers == o.servers &&
  735. bundle_policy == o.bundle_policy &&
  736. rtcp_mux_policy == o.rtcp_mux_policy &&
  737. tcp_candidate_policy == o.tcp_candidate_policy &&
  738. candidate_network_policy == o.candidate_network_policy &&
  739. audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
  740. audio_jitter_buffer_fast_accelerate ==
  741. o.audio_jitter_buffer_fast_accelerate &&
  742. audio_jitter_buffer_min_delay_ms ==
  743. o.audio_jitter_buffer_min_delay_ms &&
  744. audio_jitter_buffer_enable_rtx_handling ==
  745. o.audio_jitter_buffer_enable_rtx_handling &&
  746. ice_connection_receiving_timeout ==
  747. o.ice_connection_receiving_timeout &&
  748. ice_backup_candidate_pair_ping_interval ==
  749. o.ice_backup_candidate_pair_ping_interval &&
  750. continual_gathering_policy == o.continual_gathering_policy &&
  751. certificates == o.certificates &&
  752. prioritize_most_likely_ice_candidate_pairs ==
  753. o.prioritize_most_likely_ice_candidate_pairs &&
  754. media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
  755. disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
  756. max_ipv6_networks == o.max_ipv6_networks &&
  757. disable_link_local_networks == o.disable_link_local_networks &&
  758. enable_rtp_data_channel == o.enable_rtp_data_channel &&
  759. screencast_min_bitrate == o.screencast_min_bitrate &&
  760. combined_audio_video_bwe == o.combined_audio_video_bwe &&
  761. enable_dtls_srtp == o.enable_dtls_srtp &&
  762. ice_candidate_pool_size == o.ice_candidate_pool_size &&
  763. prune_turn_ports == o.prune_turn_ports &&
  764. turn_port_prune_policy == o.turn_port_prune_policy &&
  765. presume_writable_when_fully_relayed ==
  766. o.presume_writable_when_fully_relayed &&
  767. enable_ice_renomination == o.enable_ice_renomination &&
  768. redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
  769. surface_ice_candidates_on_ice_transport_type_changed ==
  770. o.surface_ice_candidates_on_ice_transport_type_changed &&
  771. ice_check_interval_strong_connectivity ==
  772. o.ice_check_interval_strong_connectivity &&
  773. ice_check_interval_weak_connectivity ==
  774. o.ice_check_interval_weak_connectivity &&
  775. ice_check_min_interval == o.ice_check_min_interval &&
  776. ice_unwritable_timeout == o.ice_unwritable_timeout &&
  777. ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
  778. ice_inactive_timeout == o.ice_inactive_timeout &&
  779. stun_candidate_keepalive_interval ==
  780. o.stun_candidate_keepalive_interval &&
  781. ice_regather_interval_range == o.ice_regather_interval_range &&
  782. turn_customizer == o.turn_customizer &&
  783. sdp_semantics == o.sdp_semantics &&
  784. network_preference == o.network_preference &&
  785. active_reset_srtp_params == o.active_reset_srtp_params &&
  786. use_media_transport == o.use_media_transport &&
  787. use_media_transport_for_data_channels ==
  788. o.use_media_transport_for_data_channels &&
  789. use_datagram_transport == o.use_datagram_transport &&
  790. use_datagram_transport_for_data_channels ==
  791. o.use_datagram_transport_for_data_channels &&
  792. use_datagram_transport_for_data_channels_receive_only ==
  793. o.use_datagram_transport_for_data_channels_receive_only &&
  794. crypto_options == o.crypto_options &&
  795. offer_extmap_allow_mixed == o.offer_extmap_allow_mixed &&
  796. turn_logging_id == o.turn_logging_id &&
  797. enable_implicit_rollback == o.enable_implicit_rollback;
  798. }
  799. bool PeerConnectionInterface::RTCConfiguration::operator!=(
  800. const PeerConnectionInterface::RTCConfiguration& o) const {
  801. return !(*this == o);
  802. }
  803. // Generate a RTCP CNAME when a PeerConnection is created.
  804. std::string GenerateRtcpCname() {
  805. std::string cname;
  806. if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
  807. RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
  808. RTC_NOTREACHED();
  809. }
  810. return cname;
  811. }
  812. bool ValidateOfferAnswerOptions(
  813. const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
  814. return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
  815. IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
  816. }
  817. // From |rtc_options|, fill parts of |session_options| shared by all generated
  818. // m= sections (in other words, nothing that involves a map/array).
  819. void ExtractSharedMediaSessionOptions(
  820. const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
  821. cricket::MediaSessionOptions* session_options) {
  822. session_options->vad_enabled = rtc_options.voice_activity_detection;
  823. session_options->bundle_enabled = rtc_options.use_rtp_mux;
  824. session_options->raw_packetization_for_video =
  825. rtc_options.raw_packetization_for_video;
  826. }
  827. PeerConnection::PeerConnection(PeerConnectionFactory* factory,
  828. std::unique_ptr<RtcEventLog> event_log,
  829. std::unique_ptr<Call> call)
  830. : factory_(factory),
  831. event_log_(std::move(event_log)),
  832. event_log_ptr_(event_log_.get()),
  833. datagram_transport_config_(
  834. field_trial::FindFullName(kDatagramTransportFieldTrial)),
  835. datagram_transport_data_channel_config_(
  836. field_trial::FindFullName(kDatagramTransportDataChannelFieldTrial)),
  837. rtcp_cname_(GenerateRtcpCname()),
  838. local_streams_(StreamCollection::Create()),
  839. remote_streams_(StreamCollection::Create()),
  840. call_(std::move(call)),
  841. call_ptr_(call_.get()),
  842. data_channel_transport_(nullptr),
  843. local_ice_credentials_to_replace_(new LocalIceCredentialsToReplace()) {}
  844. PeerConnection::~PeerConnection() {
  845. TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
  846. RTC_DCHECK_RUN_ON(signaling_thread());
  847. // Need to stop transceivers before destroying the stats collector because
  848. // AudioRtpSender has a reference to the StatsCollector it will update when
  849. // stopping.
  850. for (const auto& transceiver : transceivers_) {
  851. transceiver->Stop();
  852. }
  853. stats_.reset(nullptr);
  854. if (stats_collector_) {
  855. stats_collector_->WaitForPendingRequest();
  856. stats_collector_ = nullptr;
  857. }
  858. // Don't destroy BaseChannels until after stats has been cleaned up so that
  859. // the last stats request can still read from the channels.
  860. DestroyAllChannels();
  861. RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
  862. webrtc_session_desc_factory_.reset();
  863. sctp_factory_.reset();
  864. data_channel_transport_invoker_.reset();
  865. transport_controller_.reset();
  866. // port_allocator_ lives on the network thread and should be destroyed there.
  867. network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
  868. RTC_DCHECK_RUN_ON(network_thread());
  869. port_allocator_.reset();
  870. });
  871. // call_ and event_log_ must be destroyed on the worker thread.
  872. worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
  873. RTC_DCHECK_RUN_ON(worker_thread());
  874. call_.reset();
  875. // The event log must outlive call (and any other object that uses it).
  876. event_log_.reset();
  877. });
  878. }
  879. void PeerConnection::DestroyAllChannels() {
  880. // Destroy video channels first since they may have a pointer to a voice
  881. // channel.
  882. for (const auto& transceiver : transceivers_) {
  883. if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
  884. DestroyTransceiverChannel(transceiver);
  885. }
  886. }
  887. for (const auto& transceiver : transceivers_) {
  888. if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
  889. DestroyTransceiverChannel(transceiver);
  890. }
  891. }
  892. DestroyDataChannel();
  893. }
  894. bool PeerConnection::Initialize(
  895. const PeerConnectionInterface::RTCConfiguration& configuration,
  896. PeerConnectionDependencies dependencies) {
  897. RTC_DCHECK_RUN_ON(signaling_thread());
  898. RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
  899. TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
  900. RTCError config_error = ValidateConfiguration(configuration);
  901. if (!config_error.ok()) {
  902. RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
  903. return false;
  904. }
  905. if (!dependencies.allocator) {
  906. RTC_LOG(LS_ERROR)
  907. << "PeerConnection initialized without a PortAllocator? "
  908. "This shouldn't happen if using PeerConnectionFactory.";
  909. return false;
  910. }
  911. if (!dependencies.observer) {
  912. // TODO(deadbeef): Why do we do this?
  913. RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
  914. "PeerConnectionObserver";
  915. return false;
  916. }
  917. observer_ = dependencies.observer;
  918. async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
  919. port_allocator_ = std::move(dependencies.allocator);
  920. tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
  921. cricket::ServerAddresses stun_servers;
  922. std::vector<cricket::RelayServerConfig> turn_servers;
  923. RTCErrorType parse_error =
  924. ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
  925. if (parse_error != RTCErrorType::NONE) {
  926. return false;
  927. }
  928. // Add the turn logging id to all turn servers
  929. for (cricket::RelayServerConfig& turn_server : turn_servers) {
  930. turn_server.turn_logging_id = configuration.turn_logging_id;
  931. }
  932. // The port allocator lives on the network thread and should be initialized
  933. // there.
  934. const auto pa_result =
  935. network_thread()->Invoke<InitializePortAllocatorResult>(
  936. RTC_FROM_HERE,
  937. rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
  938. stun_servers, turn_servers, configuration));
  939. // If initialization was successful, note if STUN or TURN servers
  940. // were supplied.
  941. if (!stun_servers.empty()) {
  942. NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
  943. }
  944. if (!turn_servers.empty()) {
  945. NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
  946. }
  947. // Send information about IPv4/IPv6 status.
  948. PeerConnectionAddressFamilyCounter address_family;
  949. if (pa_result.enable_ipv6) {
  950. address_family = kPeerConnection_IPv6;
  951. } else {
  952. address_family = kPeerConnection_IPv4;
  953. }
  954. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
  955. kPeerConnectionAddressFamilyCounter_Max);
  956. const PeerConnectionFactoryInterface::Options& options = factory_->options();
  957. // RFC 3264: The numeric value of the session id and version in the
  958. // o line MUST be representable with a "64 bit signed integer".
  959. // Due to this constraint session id |session_id_| is max limited to
  960. // LLONG_MAX.
  961. session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
  962. JsepTransportController::Config config;
  963. config.redetermine_role_on_ice_restart =
  964. configuration.redetermine_role_on_ice_restart;
  965. config.ssl_max_version = factory_->options().ssl_max_version;
  966. config.disable_encryption = options.disable_encryption;
  967. config.bundle_policy = configuration.bundle_policy;
  968. config.rtcp_mux_policy = configuration.rtcp_mux_policy;
  969. // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
  970. // stub.
  971. config.crypto_options = configuration.crypto_options.has_value()
  972. ? *configuration.crypto_options
  973. : options.crypto_options;
  974. config.transport_observer = this;
  975. // It's safe to pass |this| and using |rtcp_invoker_| and the |call_| pointer
  976. // since the JsepTransportController instance is owned by this PeerConnection
  977. // instance and is destroyed before both |rtcp_invoker_| and the |call_|
  978. // pointer.
  979. config.rtcp_handler = [this](const rtc::CopyOnWriteBuffer& packet,
  980. int64_t packet_time_us) {
  981. RTC_DCHECK_RUN_ON(network_thread());
  982. rtcp_invoker_.AsyncInvoke<void>(
  983. RTC_FROM_HERE, worker_thread(), [this, packet, packet_time_us] {
  984. RTC_DCHECK_RUN_ON(worker_thread());
  985. // |call_| is reset on the worker thread in the PeerConnection
  986. // destructor, so we check that it's still valid before propagating
  987. // the packet.
  988. if (call_) {
  989. call_->Receiver()->DeliverPacket(MediaType::ANY, packet,
  990. packet_time_us);
  991. }
  992. });
  993. };
  994. config.event_log = event_log_ptr_;
  995. #if defined(ENABLE_EXTERNAL_AUTH)
  996. config.enable_external_auth = true;
  997. #endif
  998. config.active_reset_srtp_params = configuration.active_reset_srtp_params;
  999. use_datagram_transport_ = datagram_transport_config_.enabled &&
  1000. configuration.use_datagram_transport.value_or(
  1001. datagram_transport_config_.default_value);
  1002. use_datagram_transport_for_data_channels_ =
  1003. datagram_transport_data_channel_config_.enabled &&
  1004. configuration.use_datagram_transport_for_data_channels.value_or(
  1005. datagram_transport_data_channel_config_.default_value);
  1006. use_datagram_transport_for_data_channels_receive_only_ =
  1007. configuration.use_datagram_transport_for_data_channels_receive_only
  1008. .value_or(datagram_transport_data_channel_config_.receive_only);
  1009. if (use_datagram_transport_ || use_datagram_transport_for_data_channels_ ||
  1010. configuration.use_media_transport ||
  1011. configuration.use_media_transport_for_data_channels) {
  1012. if (!factory_->media_transport_factory()) {
  1013. RTC_DCHECK(false)
  1014. << "PeerConnecton is initialized with use_media_transport = true or "
  1015. << "use_media_transport_for_data_channels = true "
  1016. << "but media transport factory is not set in PeerConnectionFactory";
  1017. return false;
  1018. }
  1019. if (configuration.use_media_transport ||
  1020. configuration.use_media_transport_for_data_channels) {
  1021. // TODO(bugs.webrtc.org/9719): This check will eventually go away, when
  1022. // RTP media transport is introduced. But until then, we require SDES to
  1023. // be enabled.
  1024. if (configuration.enable_dtls_srtp.has_value() &&
  1025. configuration.enable_dtls_srtp.value()) {
  1026. RTC_LOG(LS_WARNING)
  1027. << "When media transport is used, SDES must be enabled. Set "
  1028. "configuration.enable_dtls_srtp to false. use_media_transport="
  1029. << configuration.use_media_transport
  1030. << ", use_media_transport_for_data_channels="
  1031. << configuration.use_media_transport_for_data_channels;
  1032. return false;
  1033. }
  1034. }
  1035. config.use_media_transport_for_media = configuration.use_media_transport;
  1036. config.use_media_transport_for_data_channels =
  1037. configuration.use_media_transport_for_data_channels;
  1038. config.use_datagram_transport = use_datagram_transport_;
  1039. config.use_datagram_transport_for_data_channels =
  1040. use_datagram_transport_for_data_channels_;
  1041. config.use_datagram_transport_for_data_channels_receive_only =
  1042. use_datagram_transport_for_data_channels_receive_only_;
  1043. config.media_transport_factory = factory_->media_transport_factory();
  1044. }
  1045. // Obtain a certificate from RTCConfiguration if any were provided (optional).
  1046. rtc::scoped_refptr<rtc::RTCCertificate> certificate;
  1047. if (!configuration.certificates.empty()) {
  1048. // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
  1049. // just picking the first one. The decision should be made based on the DTLS
  1050. // handshake. The DTLS negotiations need to know about all certificates.
  1051. certificate = configuration.certificates[0];
  1052. }
  1053. if (options.disable_encryption) {
  1054. dtls_enabled_ = false;
  1055. } else {
  1056. // Enable DTLS by default if we have an identity store or a certificate.
  1057. dtls_enabled_ = (dependencies.cert_generator || certificate);
  1058. // |configuration| can override the default |dtls_enabled_| value.
  1059. if (configuration.enable_dtls_srtp) {
  1060. dtls_enabled_ = *(configuration.enable_dtls_srtp);
  1061. }
  1062. }
  1063. sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
  1064. if (use_datagram_transport_for_data_channels_) {
  1065. if (configuration.enable_rtp_data_channel) {
  1066. RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
  1067. "use_datagram_transport_for_data_channels are "
  1068. "incompatible and cannot both be set to true";
  1069. return false;
  1070. }
  1071. if (configuration.enable_dtls_srtp && !*configuration.enable_dtls_srtp) {
  1072. RTC_LOG(LS_INFO) << "Using data channel transport with no fallback";
  1073. data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT;
  1074. } else {
  1075. RTC_LOG(LS_INFO) << "Using data channel transport with fallback to SCTP";
  1076. data_channel_type_ = cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP;
  1077. config.sctp_factory = sctp_factory_.get();
  1078. }
  1079. } else if (configuration.use_media_transport_for_data_channels) {
  1080. if (configuration.enable_rtp_data_channel) {
  1081. RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
  1082. "use_media_transport_for_data_channels are "
  1083. "incompatible and cannot both be set to true";
  1084. return false;
  1085. }
  1086. data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
  1087. } else if (configuration.enable_rtp_data_channel) {
  1088. // Enable creation of RTP data channels if the kEnableRtpDataChannels is
  1089. // set. It takes precendence over the disable_sctp_data_channels
  1090. // PeerConnectionFactoryInterface::Options.
  1091. data_channel_type_ = cricket::DCT_RTP;
  1092. } else {
  1093. // DTLS has to be enabled to use SCTP.
  1094. if (!options.disable_sctp_data_channels && dtls_enabled_) {
  1095. data_channel_type_ = cricket::DCT_SCTP;
  1096. config.sctp_factory = sctp_factory_.get();
  1097. }
  1098. }
  1099. transport_controller_.reset(new JsepTransportController(
  1100. signaling_thread(), network_thread(), port_allocator_.get(),
  1101. async_resolver_factory_.get(), config));
  1102. transport_controller_->SignalIceConnectionState.connect(
  1103. this, &PeerConnection::OnTransportControllerConnectionState);
  1104. transport_controller_->SignalStandardizedIceConnectionState.connect(
  1105. this, &PeerConnection::SetStandardizedIceConnectionState);
  1106. transport_controller_->SignalConnectionState.connect(
  1107. this, &PeerConnection::SetConnectionState);
  1108. transport_controller_->SignalIceGatheringState.connect(
  1109. this, &PeerConnection::OnTransportControllerGatheringState);
  1110. transport_controller_->SignalIceCandidatesGathered.connect(
  1111. this, &PeerConnection::OnTransportControllerCandidatesGathered);
  1112. transport_controller_->SignalIceCandidateError.connect(
  1113. this, &PeerConnection::OnTransportControllerCandidateError);
  1114. transport_controller_->SignalIceCandidatesRemoved.connect(
  1115. this, &PeerConnection::OnTransportControllerCandidatesRemoved);
  1116. transport_controller_->SignalDtlsHandshakeError.connect(
  1117. this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
  1118. transport_controller_->SignalIceCandidatePairChanged.connect(
  1119. this, &PeerConnection::OnTransportControllerCandidateChanged);
  1120. stats_.reset(new StatsCollector(this));
  1121. stats_collector_ = RTCStatsCollector::Create(this);
  1122. configuration_ = configuration;
  1123. use_media_transport_ = configuration.use_media_transport;
  1124. transport_controller_->SetIceConfig(ParseIceConfig(configuration));
  1125. video_options_.screencast_min_bitrate_kbps =
  1126. configuration.screencast_min_bitrate;
  1127. audio_options_.combined_audio_video_bwe =
  1128. configuration.combined_audio_video_bwe;
  1129. audio_options_.audio_jitter_buffer_max_packets =
  1130. configuration.audio_jitter_buffer_max_packets;
  1131. audio_options_.audio_jitter_buffer_fast_accelerate =
  1132. configuration.audio_jitter_buffer_fast_accelerate;
  1133. audio_options_.audio_jitter_buffer_min_delay_ms =
  1134. configuration.audio_jitter_buffer_min_delay_ms;
  1135. audio_options_.audio_jitter_buffer_enable_rtx_handling =
  1136. configuration.audio_jitter_buffer_enable_rtx_handling;
  1137. // Whether the certificate generator/certificate is null or not determines
  1138. // what PeerConnectionDescriptionFactory will do, so make sure that we give it
  1139. // the right instructions by clearing the variables if needed.
  1140. if (!dtls_enabled_) {
  1141. dependencies.cert_generator.reset();
  1142. certificate = nullptr;
  1143. } else if (certificate) {
  1144. // Favor generated certificate over the certificate generator.
  1145. dependencies.cert_generator.reset();
  1146. }
  1147. webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
  1148. signaling_thread(), channel_manager(), this, session_id(),
  1149. std::move(dependencies.cert_generator), certificate, &ssrc_generator_));
  1150. webrtc_session_desc_factory_->SignalCertificateReady.connect(
  1151. this, &PeerConnection::OnCertificateReady);
  1152. if (options.disable_encryption) {
  1153. webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
  1154. }
  1155. webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
  1156. GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
  1157. webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
  1158. // Add default audio/video transceivers for Plan B SDP.
  1159. if (!IsUnifiedPlan()) {
  1160. transceivers_.push_back(
  1161. RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
  1162. signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
  1163. transceivers_.push_back(
  1164. RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
  1165. signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
  1166. }
  1167. int delay_ms =
  1168. return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
  1169. signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
  1170. MSG_REPORT_USAGE_PATTERN, nullptr);
  1171. if (dependencies.video_bitrate_allocator_factory) {
  1172. video_bitrate_allocator_factory_ =
  1173. std::move(dependencies.video_bitrate_allocator_factory);
  1174. } else {
  1175. video_bitrate_allocator_factory_ =
  1176. CreateBuiltinVideoBitrateAllocatorFactory();
  1177. }
  1178. return true;
  1179. }
  1180. RTCError PeerConnection::ValidateConfiguration(
  1181. const RTCConfiguration& config) const {
  1182. if (config.ice_regather_interval_range &&
  1183. config.continual_gathering_policy == GATHER_ONCE) {
  1184. return RTCError(RTCErrorType::INVALID_PARAMETER,
  1185. "ice_regather_interval_range specified but continual "
  1186. "gathering policy is GATHER_ONCE");
  1187. }
  1188. auto result =
  1189. cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
  1190. return result;
  1191. }
  1192. rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
  1193. RTC_DCHECK_RUN_ON(signaling_thread());
  1194. RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
  1195. "Plan SdpSemantics. Please use GetSenders "
  1196. "instead.";
  1197. return local_streams_;
  1198. }
  1199. rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
  1200. RTC_DCHECK_RUN_ON(signaling_thread());
  1201. RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
  1202. "Plan SdpSemantics. Please use GetReceivers "
  1203. "instead.";
  1204. return remote_streams_;
  1205. }
  1206. bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
  1207. RTC_DCHECK_RUN_ON(signaling_thread());
  1208. RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
  1209. "SdpSemantics. Please use AddTrack instead.";
  1210. TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
  1211. if (IsClosed()) {
  1212. return false;
  1213. }
  1214. if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
  1215. return false;
  1216. }
  1217. local_streams_->AddStream(local_stream);
  1218. MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
  1219. observer->SignalAudioTrackAdded.connect(this,
  1220. &PeerConnection::OnAudioTrackAdded);
  1221. observer->SignalAudioTrackRemoved.connect(
  1222. this, &PeerConnection::OnAudioTrackRemoved);
  1223. observer->SignalVideoTrackAdded.connect(this,
  1224. &PeerConnection::OnVideoTrackAdded);
  1225. observer->SignalVideoTrackRemoved.connect(
  1226. this, &PeerConnection::OnVideoTrackRemoved);
  1227. stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
  1228. for (const auto& track : local_stream->GetAudioTracks()) {
  1229. AddAudioTrack(track.get(), local_stream);
  1230. }
  1231. for (const auto& track : local_stream->GetVideoTracks()) {
  1232. AddVideoTrack(track.get(), local_stream);
  1233. }
  1234. stats_->AddStream(local_stream);
  1235. UpdateNegotiationNeeded();
  1236. return true;
  1237. }
  1238. void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
  1239. RTC_DCHECK_RUN_ON(signaling_thread());
  1240. RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
  1241. "Plan SdpSemantics. Please use RemoveTrack "
  1242. "instead.";
  1243. TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
  1244. if (!IsClosed()) {
  1245. for (const auto& track : local_stream->GetAudioTracks()) {
  1246. RemoveAudioTrack(track.get(), local_stream);
  1247. }
  1248. for (const auto& track : local_stream->GetVideoTracks()) {
  1249. RemoveVideoTrack(track.get(), local_stream);
  1250. }
  1251. }
  1252. local_streams_->RemoveStream(local_stream);
  1253. stream_observers_.erase(
  1254. std::remove_if(
  1255. stream_observers_.begin(), stream_observers_.end(),
  1256. [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
  1257. return observer->stream()->id().compare(local_stream->id()) == 0;
  1258. }),
  1259. stream_observers_.end());
  1260. if (IsClosed()) {
  1261. return;
  1262. }
  1263. UpdateNegotiationNeeded();
  1264. }
  1265. RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
  1266. rtc::scoped_refptr<MediaStreamTrackInterface> track,
  1267. const std::vector<std::string>& stream_ids) {
  1268. RTC_DCHECK_RUN_ON(signaling_thread());
  1269. TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
  1270. if (!track) {
  1271. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
  1272. }
  1273. if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
  1274. track->kind() == MediaStreamTrackInterface::kVideoKind)) {
  1275. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  1276. "Track has invalid kind: " + track->kind());
  1277. }
  1278. if (IsClosed()) {
  1279. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
  1280. "PeerConnection is closed.");
  1281. }
  1282. if (FindSenderForTrack(track)) {
  1283. LOG_AND_RETURN_ERROR(
  1284. RTCErrorType::INVALID_PARAMETER,
  1285. "Sender already exists for track " + track->id() + ".");
  1286. }
  1287. auto sender_or_error =
  1288. (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
  1289. : AddTrackPlanB(track, stream_ids));
  1290. if (sender_or_error.ok()) {
  1291. UpdateNegotiationNeeded();
  1292. stats_->AddTrack(track);
  1293. }
  1294. return sender_or_error;
  1295. }
  1296. RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
  1297. PeerConnection::AddTrackPlanB(
  1298. rtc::scoped_refptr<MediaStreamTrackInterface> track,
  1299. const std::vector<std::string>& stream_ids) {
  1300. if (stream_ids.size() > 1u) {
  1301. LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
  1302. "AddTrack with more than one stream is not "
  1303. "supported with Plan B semantics.");
  1304. }
  1305. std::vector<std::string> adjusted_stream_ids = stream_ids;
  1306. if (adjusted_stream_ids.empty()) {
  1307. adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
  1308. }
  1309. cricket::MediaType media_type =
  1310. (track->kind() == MediaStreamTrackInterface::kAudioKind
  1311. ? cricket::MEDIA_TYPE_AUDIO
  1312. : cricket::MEDIA_TYPE_VIDEO);
  1313. auto new_sender =
  1314. CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
  1315. if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
  1316. new_sender->internal()->SetMediaChannel(voice_media_channel());
  1317. GetAudioTransceiver()->internal()->AddSender(new_sender);
  1318. const RtpSenderInfo* sender_info =
  1319. FindSenderInfo(local_audio_sender_infos_,
  1320. new_sender->internal()->stream_ids()[0], track->id());
  1321. if (sender_info) {
  1322. new_sender->internal()->SetSsrc(sender_info->first_ssrc);
  1323. }
  1324. } else {
  1325. RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
  1326. new_sender->internal()->SetMediaChannel(video_media_channel());
  1327. GetVideoTransceiver()->internal()->AddSender(new_sender);
  1328. const RtpSenderInfo* sender_info =
  1329. FindSenderInfo(local_video_sender_infos_,
  1330. new_sender->internal()->stream_ids()[0], track->id());
  1331. if (sender_info) {
  1332. new_sender->internal()->SetSsrc(sender_info->first_ssrc);
  1333. }
  1334. }
  1335. return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
  1336. }
  1337. RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
  1338. PeerConnection::AddTrackUnifiedPlan(
  1339. rtc::scoped_refptr<MediaStreamTrackInterface> track,
  1340. const std::vector<std::string>& stream_ids) {
  1341. auto transceiver = FindFirstTransceiverForAddedTrack(track);
  1342. if (transceiver) {
  1343. RTC_LOG(LS_INFO) << "Reusing an existing "
  1344. << cricket::MediaTypeToString(transceiver->media_type())
  1345. << " transceiver for AddTrack.";
  1346. if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
  1347. transceiver->internal()->set_direction(
  1348. RtpTransceiverDirection::kSendRecv);
  1349. } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
  1350. transceiver->internal()->set_direction(
  1351. RtpTransceiverDirection::kSendOnly);
  1352. }
  1353. transceiver->sender()->SetTrack(track);
  1354. transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
  1355. } else {
  1356. cricket::MediaType media_type =
  1357. (track->kind() == MediaStreamTrackInterface::kAudioKind
  1358. ? cricket::MEDIA_TYPE_AUDIO
  1359. : cricket::MEDIA_TYPE_VIDEO);
  1360. RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
  1361. << " transceiver in response to a call to AddTrack.";
  1362. std::string sender_id = track->id();
  1363. // Avoid creating a sender with an existing ID by generating a random ID.
  1364. // This can happen if this is the second time AddTrack has created a sender
  1365. // for this track.
  1366. if (FindSenderById(sender_id)) {
  1367. sender_id = rtc::CreateRandomUuid();
  1368. }
  1369. auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
  1370. auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
  1371. transceiver = CreateAndAddTransceiver(sender, receiver);
  1372. transceiver->internal()->set_created_by_addtrack(true);
  1373. transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
  1374. }
  1375. return transceiver->sender();
  1376. }
  1377. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  1378. PeerConnection::FindFirstTransceiverForAddedTrack(
  1379. rtc::scoped_refptr<MediaStreamTrackInterface> track) {
  1380. RTC_DCHECK(track);
  1381. for (auto transceiver : transceivers_) {
  1382. if (!transceiver->sender()->track() &&
  1383. cricket::MediaTypeToString(transceiver->media_type()) ==
  1384. track->kind() &&
  1385. !transceiver->internal()->has_ever_been_used_to_send() &&
  1386. !transceiver->stopped()) {
  1387. return transceiver;
  1388. }
  1389. }
  1390. return nullptr;
  1391. }
  1392. bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
  1393. TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
  1394. return RemoveTrackNew(sender).ok();
  1395. }
  1396. RTCError PeerConnection::RemoveTrackNew(
  1397. rtc::scoped_refptr<RtpSenderInterface> sender) {
  1398. RTC_DCHECK_RUN_ON(signaling_thread());
  1399. if (!sender) {
  1400. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
  1401. }
  1402. if (IsClosed()) {
  1403. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
  1404. "PeerConnection is closed.");
  1405. }
  1406. if (IsUnifiedPlan()) {
  1407. auto transceiver = FindTransceiverBySender(sender);
  1408. if (!transceiver || !sender->track()) {
  1409. return RTCError::OK();
  1410. }
  1411. sender->SetTrack(nullptr);
  1412. if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
  1413. transceiver->internal()->set_direction(
  1414. RtpTransceiverDirection::kRecvOnly);
  1415. } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
  1416. transceiver->internal()->set_direction(
  1417. RtpTransceiverDirection::kInactive);
  1418. }
  1419. } else {
  1420. bool removed;
  1421. if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
  1422. removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
  1423. } else {
  1424. RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
  1425. removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
  1426. }
  1427. if (!removed) {
  1428. LOG_AND_RETURN_ERROR(
  1429. RTCErrorType::INVALID_PARAMETER,
  1430. "Couldn't find sender " + sender->id() + " to remove.");
  1431. }
  1432. }
  1433. UpdateNegotiationNeeded();
  1434. return RTCError::OK();
  1435. }
  1436. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  1437. PeerConnection::FindTransceiverBySender(
  1438. rtc::scoped_refptr<RtpSenderInterface> sender) {
  1439. for (auto transceiver : transceivers_) {
  1440. if (transceiver->sender() == sender) {
  1441. return transceiver;
  1442. }
  1443. }
  1444. return nullptr;
  1445. }
  1446. RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
  1447. PeerConnection::AddTransceiver(
  1448. rtc::scoped_refptr<MediaStreamTrackInterface> track) {
  1449. return AddTransceiver(track, RtpTransceiverInit());
  1450. }
  1451. RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
  1452. PeerConnection::AddTransceiver(
  1453. rtc::scoped_refptr<MediaStreamTrackInterface> track,
  1454. const RtpTransceiverInit& init) {
  1455. RTC_DCHECK_RUN_ON(signaling_thread());
  1456. RTC_CHECK(IsUnifiedPlan())
  1457. << "AddTransceiver is only available with Unified Plan SdpSemantics";
  1458. if (!track) {
  1459. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
  1460. }
  1461. cricket::MediaType media_type;
  1462. if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
  1463. media_type = cricket::MEDIA_TYPE_AUDIO;
  1464. } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
  1465. media_type = cricket::MEDIA_TYPE_VIDEO;
  1466. } else {
  1467. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  1468. "Track kind is not audio or video");
  1469. }
  1470. return AddTransceiver(media_type, track, init);
  1471. }
  1472. RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
  1473. PeerConnection::AddTransceiver(cricket::MediaType media_type) {
  1474. return AddTransceiver(media_type, RtpTransceiverInit());
  1475. }
  1476. RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
  1477. PeerConnection::AddTransceiver(cricket::MediaType media_type,
  1478. const RtpTransceiverInit& init) {
  1479. RTC_DCHECK_RUN_ON(signaling_thread());
  1480. RTC_CHECK(IsUnifiedPlan())
  1481. << "AddTransceiver is only available with Unified Plan SdpSemantics";
  1482. if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
  1483. media_type == cricket::MEDIA_TYPE_VIDEO)) {
  1484. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  1485. "media type is not audio or video");
  1486. }
  1487. return AddTransceiver(media_type, nullptr, init);
  1488. }
  1489. RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
  1490. PeerConnection::AddTransceiver(
  1491. cricket::MediaType media_type,
  1492. rtc::scoped_refptr<MediaStreamTrackInterface> track,
  1493. const RtpTransceiverInit& init,
  1494. bool update_negotiation_needed) {
  1495. RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
  1496. media_type == cricket::MEDIA_TYPE_VIDEO));
  1497. if (track) {
  1498. RTC_DCHECK_EQ(media_type,
  1499. (track->kind() == MediaStreamTrackInterface::kAudioKind
  1500. ? cricket::MEDIA_TYPE_AUDIO
  1501. : cricket::MEDIA_TYPE_VIDEO));
  1502. }
  1503. RTC_HISTOGRAM_COUNTS_LINEAR(kSimulcastNumberOfEncodings,
  1504. init.send_encodings.size(), 0, 7, 8);
  1505. size_t num_rids = absl::c_count_if(init.send_encodings,
  1506. [](const RtpEncodingParameters& encoding) {
  1507. return !encoding.rid.empty();
  1508. });
  1509. if (num_rids > 0 && num_rids != init.send_encodings.size()) {
  1510. LOG_AND_RETURN_ERROR(
  1511. RTCErrorType::INVALID_PARAMETER,
  1512. "RIDs must be provided for either all or none of the send encodings.");
  1513. }
  1514. if (num_rids > 0 && absl::c_any_of(init.send_encodings,
  1515. [](const RtpEncodingParameters& encoding) {
  1516. return !IsLegalRsidName(encoding.rid);
  1517. })) {
  1518. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  1519. "Invalid RID value provided.");
  1520. }
  1521. if (absl::c_any_of(init.send_encodings,
  1522. [](const RtpEncodingParameters& encoding) {
  1523. return encoding.ssrc.has_value();
  1524. })) {
  1525. LOG_AND_RETURN_ERROR(
  1526. RTCErrorType::UNSUPPORTED_PARAMETER,
  1527. "Attempted to set an unimplemented parameter of RtpParameters.");
  1528. }
  1529. RtpParameters parameters;
  1530. parameters.encodings = init.send_encodings;
  1531. // Encodings are dropped from the tail if too many are provided.
  1532. if (parameters.encodings.size() > kMaxSimulcastStreams) {
  1533. parameters.encodings.erase(
  1534. parameters.encodings.begin() + kMaxSimulcastStreams,
  1535. parameters.encodings.end());
  1536. }
  1537. // Single RID should be removed.
  1538. if (parameters.encodings.size() == 1 &&
  1539. !parameters.encodings[0].rid.empty()) {
  1540. RTC_LOG(LS_INFO) << "Removing RID: " << parameters.encodings[0].rid << ".";
  1541. parameters.encodings[0].rid.clear();
  1542. }
  1543. // If RIDs were not provided, they are generated for simulcast scenario.
  1544. if (parameters.encodings.size() > 1 && num_rids == 0) {
  1545. rtc::UniqueStringGenerator rid_generator;
  1546. for (RtpEncodingParameters& encoding : parameters.encodings) {
  1547. encoding.rid = rid_generator();
  1548. }
  1549. }
  1550. if (UnimplementedRtpParameterHasValue(parameters)) {
  1551. LOG_AND_RETURN_ERROR(
  1552. RTCErrorType::UNSUPPORTED_PARAMETER,
  1553. "Attempted to set an unimplemented parameter of RtpParameters.");
  1554. }
  1555. auto result = cricket::CheckRtpParametersValues(parameters);
  1556. if (!result.ok()) {
  1557. LOG_AND_RETURN_ERROR(result.type(), result.message());
  1558. }
  1559. RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
  1560. << " transceiver in response to a call to AddTransceiver.";
  1561. // Set the sender ID equal to the track ID if the track is specified unless
  1562. // that sender ID is already in use.
  1563. std::string sender_id =
  1564. (track && !FindSenderById(track->id()) ? track->id()
  1565. : rtc::CreateRandomUuid());
  1566. auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
  1567. parameters.encodings);
  1568. auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
  1569. auto transceiver = CreateAndAddTransceiver(sender, receiver);
  1570. transceiver->internal()->set_direction(init.direction);
  1571. if (update_negotiation_needed) {
  1572. UpdateNegotiationNeeded();
  1573. }
  1574. return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
  1575. }
  1576. rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
  1577. PeerConnection::CreateSender(
  1578. cricket::MediaType media_type,
  1579. const std::string& id,
  1580. rtc::scoped_refptr<MediaStreamTrackInterface> track,
  1581. const std::vector<std::string>& stream_ids,
  1582. const std::vector<RtpEncodingParameters>& send_encodings) {
  1583. RTC_DCHECK_RUN_ON(signaling_thread());
  1584. rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
  1585. if (media_type == cricket::MEDIA_TYPE_AUDIO) {
  1586. RTC_DCHECK(!track ||
  1587. (track->kind() == MediaStreamTrackInterface::kAudioKind));
  1588. sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
  1589. signaling_thread(),
  1590. AudioRtpSender::Create(worker_thread(), id, stats_.get(), this));
  1591. NoteUsageEvent(UsageEvent::AUDIO_ADDED);
  1592. } else {
  1593. RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
  1594. RTC_DCHECK(!track ||
  1595. (track->kind() == MediaStreamTrackInterface::kVideoKind));
  1596. sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
  1597. signaling_thread(), VideoRtpSender::Create(worker_thread(), id, this));
  1598. NoteUsageEvent(UsageEvent::VIDEO_ADDED);
  1599. }
  1600. bool set_track_succeeded = sender->SetTrack(track);
  1601. RTC_DCHECK(set_track_succeeded);
  1602. sender->internal()->set_stream_ids(stream_ids);
  1603. sender->internal()->set_init_send_encodings(send_encodings);
  1604. return sender;
  1605. }
  1606. rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
  1607. PeerConnection::CreateReceiver(cricket::MediaType media_type,
  1608. const std::string& receiver_id) {
  1609. rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
  1610. receiver;
  1611. if (media_type == cricket::MEDIA_TYPE_AUDIO) {
  1612. receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
  1613. signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
  1614. std::vector<std::string>({})));
  1615. NoteUsageEvent(UsageEvent::AUDIO_ADDED);
  1616. } else {
  1617. RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
  1618. receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
  1619. signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
  1620. std::vector<std::string>({})));
  1621. NoteUsageEvent(UsageEvent::VIDEO_ADDED);
  1622. }
  1623. return receiver;
  1624. }
  1625. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  1626. PeerConnection::CreateAndAddTransceiver(
  1627. rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
  1628. rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
  1629. receiver) {
  1630. // Ensure that the new sender does not have an ID that is already in use by
  1631. // another sender.
  1632. // Allow receiver IDs to conflict since those come from remote SDP (which
  1633. // could be invalid, but should not cause a crash).
  1634. RTC_DCHECK(!FindSenderById(sender->id()));
  1635. auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
  1636. signaling_thread(),
  1637. new RtpTransceiver(sender, receiver, channel_manager()));
  1638. transceivers_.push_back(transceiver);
  1639. transceiver->internal()->SignalNegotiationNeeded.connect(
  1640. this, &PeerConnection::OnNegotiationNeeded);
  1641. return transceiver;
  1642. }
  1643. void PeerConnection::OnNegotiationNeeded() {
  1644. RTC_DCHECK_RUN_ON(signaling_thread());
  1645. RTC_DCHECK(!IsClosed());
  1646. UpdateNegotiationNeeded();
  1647. }
  1648. rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
  1649. const std::string& kind,
  1650. const std::string& stream_id) {
  1651. RTC_DCHECK_RUN_ON(signaling_thread());
  1652. RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
  1653. "Plan SdpSemantics. Please use AddTransceiver "
  1654. "instead.";
  1655. TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
  1656. if (IsClosed()) {
  1657. return nullptr;
  1658. }
  1659. // Internally we need to have one stream with Plan B semantics, so we
  1660. // generate a random stream ID if not specified.
  1661. std::vector<std::string> stream_ids;
  1662. if (stream_id.empty()) {
  1663. stream_ids.push_back(rtc::CreateRandomUuid());
  1664. RTC_LOG(LS_INFO)
  1665. << "No stream_id specified for sender. Generated stream ID: "
  1666. << stream_ids[0];
  1667. } else {
  1668. stream_ids.push_back(stream_id);
  1669. }
  1670. // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
  1671. rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
  1672. if (kind == MediaStreamTrackInterface::kAudioKind) {
  1673. auto audio_sender = AudioRtpSender::Create(
  1674. worker_thread(), rtc::CreateRandomUuid(), stats_.get(), this);
  1675. audio_sender->SetMediaChannel(voice_media_channel());
  1676. new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
  1677. signaling_thread(), audio_sender);
  1678. GetAudioTransceiver()->internal()->AddSender(new_sender);
  1679. } else if (kind == MediaStreamTrackInterface::kVideoKind) {
  1680. auto video_sender =
  1681. VideoRtpSender::Create(worker_thread(), rtc::CreateRandomUuid(), this);
  1682. video_sender->SetMediaChannel(video_media_channel());
  1683. new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
  1684. signaling_thread(), video_sender);
  1685. GetVideoTransceiver()->internal()->AddSender(new_sender);
  1686. } else {
  1687. RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
  1688. return nullptr;
  1689. }
  1690. new_sender->internal()->set_stream_ids(stream_ids);
  1691. return new_sender;
  1692. }
  1693. std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
  1694. const {
  1695. RTC_DCHECK_RUN_ON(signaling_thread());
  1696. std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
  1697. for (const auto& sender : GetSendersInternal()) {
  1698. ret.push_back(sender);
  1699. }
  1700. return ret;
  1701. }
  1702. std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
  1703. PeerConnection::GetSendersInternal() const {
  1704. std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
  1705. all_senders;
  1706. for (const auto& transceiver : transceivers_) {
  1707. auto senders = transceiver->internal()->senders();
  1708. all_senders.insert(all_senders.end(), senders.begin(), senders.end());
  1709. }
  1710. return all_senders;
  1711. }
  1712. std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
  1713. PeerConnection::GetReceivers() const {
  1714. RTC_DCHECK_RUN_ON(signaling_thread());
  1715. std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
  1716. for (const auto& receiver : GetReceiversInternal()) {
  1717. ret.push_back(receiver);
  1718. }
  1719. return ret;
  1720. }
  1721. std::vector<
  1722. rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
  1723. PeerConnection::GetReceiversInternal() const {
  1724. std::vector<
  1725. rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
  1726. all_receivers;
  1727. for (const auto& transceiver : transceivers_) {
  1728. auto receivers = transceiver->internal()->receivers();
  1729. all_receivers.insert(all_receivers.end(), receivers.begin(),
  1730. receivers.end());
  1731. }
  1732. return all_receivers;
  1733. }
  1734. std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
  1735. PeerConnection::GetTransceivers() const {
  1736. RTC_DCHECK_RUN_ON(signaling_thread());
  1737. RTC_CHECK(IsUnifiedPlan())
  1738. << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
  1739. std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
  1740. for (const auto& transceiver : transceivers_) {
  1741. all_transceivers.push_back(transceiver);
  1742. }
  1743. return all_transceivers;
  1744. }
  1745. bool PeerConnection::GetStats(StatsObserver* observer,
  1746. MediaStreamTrackInterface* track,
  1747. StatsOutputLevel level) {
  1748. TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
  1749. RTC_DCHECK_RUN_ON(signaling_thread());
  1750. if (!observer) {
  1751. RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
  1752. return false;
  1753. }
  1754. stats_->UpdateStats(level);
  1755. // The StatsCollector is used to tell if a track is valid because it may
  1756. // remember tracks that the PeerConnection previously removed.
  1757. if (track && !stats_->IsValidTrack(track->id())) {
  1758. RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
  1759. << track->id();
  1760. return false;
  1761. }
  1762. signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
  1763. new GetStatsMsg(observer, track));
  1764. return true;
  1765. }
  1766. void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
  1767. TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
  1768. RTC_DCHECK_RUN_ON(signaling_thread());
  1769. RTC_DCHECK(stats_collector_);
  1770. RTC_DCHECK(callback);
  1771. stats_collector_->GetStatsReport(callback);
  1772. }
  1773. void PeerConnection::GetStats(
  1774. rtc::scoped_refptr<RtpSenderInterface> selector,
  1775. rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
  1776. TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
  1777. RTC_DCHECK_RUN_ON(signaling_thread());
  1778. RTC_DCHECK(callback);
  1779. RTC_DCHECK(stats_collector_);
  1780. rtc::scoped_refptr<RtpSenderInternal> internal_sender;
  1781. if (selector) {
  1782. for (const auto& proxy_transceiver : transceivers_) {
  1783. for (const auto& proxy_sender :
  1784. proxy_transceiver->internal()->senders()) {
  1785. if (proxy_sender == selector) {
  1786. internal_sender = proxy_sender->internal();
  1787. break;
  1788. }
  1789. }
  1790. if (internal_sender)
  1791. break;
  1792. }
  1793. }
  1794. // If there is no |internal_sender| then |selector| is either null or does not
  1795. // belong to the PeerConnection (in Plan B, senders can be removed from the
  1796. // PeerConnection). This means that "all the stats objects representing the
  1797. // selector" is an empty set. Invoking GetStatsReport() with a null selector
  1798. // produces an empty stats report.
  1799. stats_collector_->GetStatsReport(internal_sender, callback);
  1800. }
  1801. void PeerConnection::GetStats(
  1802. rtc::scoped_refptr<RtpReceiverInterface> selector,
  1803. rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
  1804. TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
  1805. RTC_DCHECK_RUN_ON(signaling_thread());
  1806. RTC_DCHECK(callback);
  1807. RTC_DCHECK(stats_collector_);
  1808. rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
  1809. if (selector) {
  1810. for (const auto& proxy_transceiver : transceivers_) {
  1811. for (const auto& proxy_receiver :
  1812. proxy_transceiver->internal()->receivers()) {
  1813. if (proxy_receiver == selector) {
  1814. internal_receiver = proxy_receiver->internal();
  1815. break;
  1816. }
  1817. }
  1818. if (internal_receiver)
  1819. break;
  1820. }
  1821. }
  1822. // If there is no |internal_receiver| then |selector| is either null or does
  1823. // not belong to the PeerConnection (in Plan B, receivers can be removed from
  1824. // the PeerConnection). This means that "all the stats objects representing
  1825. // the selector" is an empty set. Invoking GetStatsReport() with a null
  1826. // selector produces an empty stats report.
  1827. stats_collector_->GetStatsReport(internal_receiver, callback);
  1828. }
  1829. PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
  1830. RTC_DCHECK_RUN_ON(signaling_thread());
  1831. return signaling_state_;
  1832. }
  1833. PeerConnectionInterface::IceConnectionState
  1834. PeerConnection::ice_connection_state() {
  1835. RTC_DCHECK_RUN_ON(signaling_thread());
  1836. return ice_connection_state_;
  1837. }
  1838. PeerConnectionInterface::IceConnectionState
  1839. PeerConnection::standardized_ice_connection_state() {
  1840. RTC_DCHECK_RUN_ON(signaling_thread());
  1841. return standardized_ice_connection_state_;
  1842. }
  1843. PeerConnectionInterface::PeerConnectionState
  1844. PeerConnection::peer_connection_state() {
  1845. RTC_DCHECK_RUN_ON(signaling_thread());
  1846. return connection_state_;
  1847. }
  1848. PeerConnectionInterface::IceGatheringState
  1849. PeerConnection::ice_gathering_state() {
  1850. RTC_DCHECK_RUN_ON(signaling_thread());
  1851. return ice_gathering_state_;
  1852. }
  1853. rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
  1854. const std::string& label,
  1855. const DataChannelInit* config) {
  1856. RTC_DCHECK_RUN_ON(signaling_thread());
  1857. TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
  1858. bool first_datachannel = !HasDataChannels();
  1859. std::unique_ptr<InternalDataChannelInit> internal_config;
  1860. if (config) {
  1861. internal_config.reset(new InternalDataChannelInit(*config));
  1862. }
  1863. rtc::scoped_refptr<DataChannelInterface> channel(
  1864. InternalCreateDataChannel(label, internal_config.get()));
  1865. if (!channel.get()) {
  1866. return nullptr;
  1867. }
  1868. // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
  1869. // the first SCTP DataChannel.
  1870. if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
  1871. UpdateNegotiationNeeded();
  1872. }
  1873. NoteUsageEvent(UsageEvent::DATA_ADDED);
  1874. return DataChannelProxy::Create(signaling_thread(), channel.get());
  1875. }
  1876. void PeerConnection::RestartIce() {
  1877. RTC_DCHECK_RUN_ON(signaling_thread());
  1878. local_ice_credentials_to_replace_->SetIceCredentialsFromLocalDescriptions(
  1879. current_local_description_.get(), pending_local_description_.get());
  1880. UpdateNegotiationNeeded();
  1881. }
  1882. void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
  1883. const RTCOfferAnswerOptions& options) {
  1884. RTC_DCHECK_RUN_ON(signaling_thread());
  1885. TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
  1886. if (!observer) {
  1887. RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
  1888. return;
  1889. }
  1890. if (IsClosed()) {
  1891. std::string error = "CreateOffer called when PeerConnection is closed.";
  1892. RTC_LOG(LS_ERROR) << error;
  1893. PostCreateSessionDescriptionFailure(
  1894. observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
  1895. return;
  1896. }
  1897. // If a session error has occurred the PeerConnection is in a possibly
  1898. // inconsistent state so fail right away.
  1899. if (session_error() != SessionError::kNone) {
  1900. std::string error_message = GetSessionErrorMsg();
  1901. RTC_LOG(LS_ERROR) << "CreateOffer: " << error_message;
  1902. PostCreateSessionDescriptionFailure(
  1903. observer,
  1904. RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
  1905. return;
  1906. }
  1907. if (!ValidateOfferAnswerOptions(options)) {
  1908. std::string error = "CreateOffer called with invalid options.";
  1909. RTC_LOG(LS_ERROR) << error;
  1910. PostCreateSessionDescriptionFailure(
  1911. observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
  1912. return;
  1913. }
  1914. // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
  1915. // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
  1916. if (IsUnifiedPlan()) {
  1917. RTCError error = HandleLegacyOfferOptions(options);
  1918. if (!error.ok()) {
  1919. PostCreateSessionDescriptionFailure(observer, std::move(error));
  1920. return;
  1921. }
  1922. }
  1923. cricket::MediaSessionOptions session_options;
  1924. GetOptionsForOffer(options, &session_options);
  1925. webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
  1926. }
  1927. RTCError PeerConnection::HandleLegacyOfferOptions(
  1928. const RTCOfferAnswerOptions& options) {
  1929. RTC_DCHECK(IsUnifiedPlan());
  1930. if (options.offer_to_receive_audio == 0) {
  1931. RemoveRecvDirectionFromReceivingTransceiversOfType(
  1932. cricket::MEDIA_TYPE_AUDIO);
  1933. } else if (options.offer_to_receive_audio == 1) {
  1934. AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
  1935. } else if (options.offer_to_receive_audio > 1) {
  1936. LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
  1937. "offer_to_receive_audio > 1 is not supported.");
  1938. }
  1939. if (options.offer_to_receive_video == 0) {
  1940. RemoveRecvDirectionFromReceivingTransceiversOfType(
  1941. cricket::MEDIA_TYPE_VIDEO);
  1942. } else if (options.offer_to_receive_video == 1) {
  1943. AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
  1944. } else if (options.offer_to_receive_video > 1) {
  1945. LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
  1946. "offer_to_receive_video > 1 is not supported.");
  1947. }
  1948. return RTCError::OK();
  1949. }
  1950. void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
  1951. cricket::MediaType media_type) {
  1952. for (const auto& transceiver : GetReceivingTransceiversOfType(media_type)) {
  1953. RtpTransceiverDirection new_direction =
  1954. RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
  1955. if (new_direction != transceiver->direction()) {
  1956. RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
  1957. << " transceiver (MID="
  1958. << transceiver->mid().value_or("<not set>") << ") from "
  1959. << RtpTransceiverDirectionToString(
  1960. transceiver->direction())
  1961. << " to "
  1962. << RtpTransceiverDirectionToString(new_direction)
  1963. << " since CreateOffer specified offer_to_receive=0";
  1964. transceiver->internal()->set_direction(new_direction);
  1965. }
  1966. }
  1967. }
  1968. void PeerConnection::AddUpToOneReceivingTransceiverOfType(
  1969. cricket::MediaType media_type) {
  1970. RTC_DCHECK_RUN_ON(signaling_thread());
  1971. if (GetReceivingTransceiversOfType(media_type).empty()) {
  1972. RTC_LOG(LS_INFO)
  1973. << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
  1974. << " transceiver since CreateOffer specified offer_to_receive=1";
  1975. RtpTransceiverInit init;
  1976. init.direction = RtpTransceiverDirection::kRecvOnly;
  1977. AddTransceiver(media_type, nullptr, init,
  1978. /*update_negotiation_needed=*/false);
  1979. }
  1980. }
  1981. std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
  1982. PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
  1983. std::vector<
  1984. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
  1985. receiving_transceivers;
  1986. for (const auto& transceiver : transceivers_) {
  1987. if (!transceiver->stopped() && transceiver->media_type() == media_type &&
  1988. RtpTransceiverDirectionHasRecv(transceiver->direction())) {
  1989. receiving_transceivers.push_back(transceiver);
  1990. }
  1991. }
  1992. return receiving_transceivers;
  1993. }
  1994. void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
  1995. const RTCOfferAnswerOptions& options) {
  1996. RTC_DCHECK_RUN_ON(signaling_thread());
  1997. TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
  1998. if (!observer) {
  1999. RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
  2000. return;
  2001. }
  2002. // If a session error has occurred the PeerConnection is in a possibly
  2003. // inconsistent state so fail right away.
  2004. if (session_error() != SessionError::kNone) {
  2005. std::string error_message = GetSessionErrorMsg();
  2006. RTC_LOG(LS_ERROR) << "CreateAnswer: " << error_message;
  2007. PostCreateSessionDescriptionFailure(
  2008. observer,
  2009. RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
  2010. return;
  2011. }
  2012. if (!(signaling_state_ == kHaveRemoteOffer ||
  2013. signaling_state_ == kHaveLocalPrAnswer)) {
  2014. std::string error =
  2015. "PeerConnection cannot create an answer in a state other than "
  2016. "have-remote-offer or have-local-pranswer.";
  2017. RTC_LOG(LS_ERROR) << error;
  2018. PostCreateSessionDescriptionFailure(
  2019. observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
  2020. return;
  2021. }
  2022. // The remote description should be set if we're in the right state.
  2023. RTC_DCHECK(remote_description());
  2024. if (IsUnifiedPlan()) {
  2025. if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
  2026. RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
  2027. "supported with Unified Plan semantics. Use the "
  2028. "RtpTransceiver API instead.";
  2029. }
  2030. if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
  2031. RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
  2032. "supported with Unified Plan semantics. Use the "
  2033. "RtpTransceiver API instead.";
  2034. }
  2035. }
  2036. cricket::MediaSessionOptions session_options;
  2037. GetOptionsForAnswer(options, &session_options);
  2038. webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
  2039. }
  2040. void PeerConnection::SetLocalDescription(
  2041. SetSessionDescriptionObserver* observer,
  2042. SessionDescriptionInterface* desc_ptr) {
  2043. RTC_DCHECK_RUN_ON(signaling_thread());
  2044. TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
  2045. // The SetLocalDescription contract is that we take ownership of the session
  2046. // description regardless of the outcome, so wrap it in a unique_ptr right
  2047. // away. Ideally, SetLocalDescription's signature will be changed to take the
  2048. // description as a unique_ptr argument to formalize this agreement.
  2049. std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
  2050. if (!observer) {
  2051. RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
  2052. return;
  2053. }
  2054. if (!desc) {
  2055. PostSetSessionDescriptionFailure(
  2056. observer,
  2057. RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
  2058. return;
  2059. }
  2060. // If a session error has occurred the PeerConnection is in a possibly
  2061. // inconsistent state so fail right away.
  2062. if (session_error() != SessionError::kNone) {
  2063. std::string error_message = GetSessionErrorMsg();
  2064. RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
  2065. PostSetSessionDescriptionFailure(
  2066. observer,
  2067. RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
  2068. return;
  2069. }
  2070. // For SLD we support only explicit rollback.
  2071. if (desc->GetType() == SdpType::kRollback) {
  2072. if (IsUnifiedPlan()) {
  2073. RTCError error = Rollback(desc->GetType());
  2074. if (error.ok()) {
  2075. PostSetSessionDescriptionSuccess(observer);
  2076. } else {
  2077. PostSetSessionDescriptionFailure(observer, std::move(error));
  2078. }
  2079. } else {
  2080. PostSetSessionDescriptionFailure(
  2081. observer, RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
  2082. "Rollback not supported in Plan B"));
  2083. }
  2084. return;
  2085. }
  2086. RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
  2087. if (!error.ok()) {
  2088. std::string error_message = GetSetDescriptionErrorMessage(
  2089. cricket::CS_LOCAL, desc->GetType(), error);
  2090. RTC_LOG(LS_ERROR) << error_message;
  2091. PostSetSessionDescriptionFailure(
  2092. observer,
  2093. RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
  2094. return;
  2095. }
  2096. // Grab the description type before moving ownership to ApplyLocalDescription,
  2097. // which may destroy it before returning.
  2098. const SdpType type = desc->GetType();
  2099. error = ApplyLocalDescription(std::move(desc));
  2100. // |desc| may be destroyed at this point.
  2101. if (!error.ok()) {
  2102. // If ApplyLocalDescription fails, the PeerConnection could be in an
  2103. // inconsistent state, so act conservatively here and set the session error
  2104. // so that future calls to SetLocalDescription/SetRemoteDescription fail.
  2105. SetSessionError(SessionError::kContent, error.message());
  2106. std::string error_message =
  2107. GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
  2108. RTC_LOG(LS_ERROR) << error_message;
  2109. PostSetSessionDescriptionFailure(
  2110. observer,
  2111. RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
  2112. return;
  2113. }
  2114. RTC_DCHECK(local_description());
  2115. PostSetSessionDescriptionSuccess(observer);
  2116. // MaybeStartGathering needs to be called after posting
  2117. // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
  2118. // before signaling that SetLocalDescription completed.
  2119. transport_controller_->MaybeStartGathering();
  2120. if (local_description()->GetType() == SdpType::kAnswer) {
  2121. // TODO(deadbeef): We already had to hop to the network thread for
  2122. // MaybeStartGathering...
  2123. network_thread()->Invoke<void>(
  2124. RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
  2125. port_allocator_.get()));
  2126. // Make UMA notes about what was agreed to.
  2127. ReportNegotiatedSdpSemantics(*local_description());
  2128. }
  2129. if (IsUnifiedPlan()) {
  2130. bool was_negotiation_needed = is_negotiation_needed_;
  2131. UpdateNegotiationNeeded();
  2132. if (signaling_state() == kStable && was_negotiation_needed &&
  2133. is_negotiation_needed_) {
  2134. Observer()->OnRenegotiationNeeded();
  2135. }
  2136. }
  2137. NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED);
  2138. }
  2139. RTCError PeerConnection::ApplyLocalDescription(
  2140. std::unique_ptr<SessionDescriptionInterface> desc) {
  2141. RTC_DCHECK_RUN_ON(signaling_thread());
  2142. RTC_DCHECK(desc);
  2143. // Update stats here so that we have the most recent stats for tracks and
  2144. // streams that might be removed by updating the session description.
  2145. stats_->UpdateStats(kStatsOutputLevelStandard);
  2146. // Take a reference to the old local description since it's used below to
  2147. // compare against the new local description. When setting the new local
  2148. // description, grab ownership of the replaced session description in case it
  2149. // is the same as |old_local_description|, to keep it alive for the duration
  2150. // of the method.
  2151. const SessionDescriptionInterface* old_local_description =
  2152. local_description();
  2153. std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
  2154. SdpType type = desc->GetType();
  2155. if (type == SdpType::kAnswer) {
  2156. replaced_local_description = pending_local_description_
  2157. ? std::move(pending_local_description_)
  2158. : std::move(current_local_description_);
  2159. current_local_description_ = std::move(desc);
  2160. pending_local_description_ = nullptr;
  2161. current_remote_description_ = std::move(pending_remote_description_);
  2162. } else {
  2163. replaced_local_description = std::move(pending_local_description_);
  2164. pending_local_description_ = std::move(desc);
  2165. }
  2166. // The session description to apply now must be accessed by
  2167. // |local_description()|.
  2168. RTC_DCHECK(local_description());
  2169. // Report statistics about any use of simulcast.
  2170. ReportSimulcastApiVersion(kSimulcastVersionApplyLocalDescription,
  2171. *local_description()->description());
  2172. if (!is_caller_) {
  2173. if (remote_description()) {
  2174. // Remote description was applied first, so this PC is the callee.
  2175. is_caller_ = false;
  2176. } else {
  2177. // Local description is applied first, so this PC is the caller.
  2178. is_caller_ = true;
  2179. }
  2180. }
  2181. RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
  2182. if (!error.ok()) {
  2183. return error;
  2184. }
  2185. if (IsUnifiedPlan()) {
  2186. RTCError error = UpdateTransceiversAndDataChannels(
  2187. cricket::CS_LOCAL, *local_description(), old_local_description,
  2188. remote_description());
  2189. if (!error.ok()) {
  2190. return error;
  2191. }
  2192. std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
  2193. std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
  2194. for (const auto& transceiver : transceivers_) {
  2195. // 2.2.7.1.1.(6-9): Set sender and receiver's transport slots.
  2196. // Note that code paths that don't set MID won't be able to use
  2197. // information about DTLS transports.
  2198. if (transceiver->mid()) {
  2199. auto dtls_transport =
  2200. LookupDtlsTransportByMidInternal(*transceiver->mid());
  2201. transceiver->internal()->sender_internal()->set_transport(
  2202. dtls_transport);
  2203. transceiver->internal()->receiver_internal()->set_transport(
  2204. dtls_transport);
  2205. }
  2206. const ContentInfo* content =
  2207. FindMediaSectionForTransceiver(transceiver, local_description());
  2208. if (!content) {
  2209. continue;
  2210. }
  2211. const MediaContentDescription* media_desc = content->media_description();
  2212. // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
  2213. // the following steps:
  2214. if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
  2215. // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
  2216. // transceiver's [[FiredDirection]] slot is either "sendrecv" or
  2217. // "recvonly", process the removal of a remote track for the media
  2218. // description, given transceiver, removeList, and muteTracks.
  2219. if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
  2220. (transceiver->internal()->fired_direction() &&
  2221. RtpTransceiverDirectionHasRecv(
  2222. *transceiver->internal()->fired_direction()))) {
  2223. ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
  2224. &removed_streams);
  2225. }
  2226. // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
  2227. // [[FiredDirection]] slots to direction.
  2228. transceiver->internal()->set_current_direction(media_desc->direction());
  2229. transceiver->internal()->set_fired_direction(media_desc->direction());
  2230. }
  2231. }
  2232. auto observer = Observer();
  2233. for (const auto& transceiver : remove_list) {
  2234. observer->OnRemoveTrack(transceiver->receiver());
  2235. }
  2236. for (const auto& stream : removed_streams) {
  2237. observer->OnRemoveStream(stream);
  2238. }
  2239. } else {
  2240. // Media channels will be created only when offer is set. These may use new
  2241. // transports just created by PushdownTransportDescription.
  2242. if (type == SdpType::kOffer) {
  2243. // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
  2244. // description is applied. Restore back to old description.
  2245. RTCError error = CreateChannels(*local_description()->description());
  2246. if (!error.ok()) {
  2247. return error;
  2248. }
  2249. }
  2250. // Remove unused channels if MediaContentDescription is rejected.
  2251. RemoveUnusedChannels(local_description()->description());
  2252. }
  2253. error = UpdateSessionState(type, cricket::CS_LOCAL,
  2254. local_description()->description());
  2255. if (!error.ok()) {
  2256. return error;
  2257. }
  2258. if (remote_description()) {
  2259. // Now that we have a local description, we can push down remote candidates.
  2260. UseCandidatesInSessionDescription(remote_description());
  2261. }
  2262. pending_ice_restarts_.clear();
  2263. if (session_error() != SessionError::kNone) {
  2264. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
  2265. }
  2266. // If setting the description decided our SSL role, allocate any necessary
  2267. // SCTP sids.
  2268. rtc::SSLRole role;
  2269. if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
  2270. AllocateSctpSids(role);
  2271. }
  2272. if (IsUnifiedPlan()) {
  2273. for (const auto& transceiver : transceivers_) {
  2274. const ContentInfo* content =
  2275. FindMediaSectionForTransceiver(transceiver, local_description());
  2276. if (!content) {
  2277. continue;
  2278. }
  2279. cricket::ChannelInterface* channel = transceiver->internal()->channel();
  2280. if (content->rejected || !channel || channel->local_streams().empty()) {
  2281. // 0 is a special value meaning "this sender has no associated send
  2282. // stream". Need to call this so the sender won't attempt to configure
  2283. // a no longer existing stream and run into DCHECKs in the lower
  2284. // layers.
  2285. transceiver->internal()->sender_internal()->SetSsrc(0);
  2286. } else {
  2287. // Get the StreamParams from the channel which could generate SSRCs.
  2288. const std::vector<StreamParams>& streams = channel->local_streams();
  2289. transceiver->internal()->sender_internal()->set_stream_ids(
  2290. streams[0].stream_ids());
  2291. transceiver->internal()->sender_internal()->SetSsrc(
  2292. streams[0].first_ssrc());
  2293. }
  2294. }
  2295. } else {
  2296. // Plan B semantics.
  2297. // Update state and SSRC of local MediaStreams and DataChannels based on the
  2298. // local session description.
  2299. const cricket::ContentInfo* audio_content =
  2300. GetFirstAudioContent(local_description()->description());
  2301. if (audio_content) {
  2302. if (audio_content->rejected) {
  2303. RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
  2304. } else {
  2305. const cricket::AudioContentDescription* audio_desc =
  2306. audio_content->media_description()->as_audio();
  2307. UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
  2308. }
  2309. }
  2310. const cricket::ContentInfo* video_content =
  2311. GetFirstVideoContent(local_description()->description());
  2312. if (video_content) {
  2313. if (video_content->rejected) {
  2314. RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
  2315. } else {
  2316. const cricket::VideoContentDescription* video_desc =
  2317. video_content->media_description()->as_video();
  2318. UpdateLocalSenders(video_desc->streams(), video_desc->type());
  2319. }
  2320. }
  2321. }
  2322. const cricket::ContentInfo* data_content =
  2323. GetFirstDataContent(local_description()->description());
  2324. if (data_content) {
  2325. const cricket::RtpDataContentDescription* rtp_data_desc =
  2326. data_content->media_description()->as_rtp_data();
  2327. // rtp_data_desc will be null if this is an SCTP description.
  2328. if (rtp_data_desc) {
  2329. UpdateLocalRtpDataChannels(rtp_data_desc->streams());
  2330. }
  2331. }
  2332. if (type == SdpType::kAnswer &&
  2333. local_ice_credentials_to_replace_->SatisfiesIceRestart(
  2334. *current_local_description_)) {
  2335. local_ice_credentials_to_replace_->ClearIceCredentials();
  2336. }
  2337. return RTCError::OK();
  2338. }
  2339. // The SDP parser used to populate these values by default for the 'content
  2340. // name' if an a=mid line was absent.
  2341. static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
  2342. switch (media_type) {
  2343. case cricket::MEDIA_TYPE_AUDIO:
  2344. return cricket::CN_AUDIO;
  2345. case cricket::MEDIA_TYPE_VIDEO:
  2346. return cricket::CN_VIDEO;
  2347. case cricket::MEDIA_TYPE_DATA:
  2348. return cricket::CN_DATA;
  2349. }
  2350. RTC_NOTREACHED();
  2351. return "";
  2352. }
  2353. void PeerConnection::FillInMissingRemoteMids(
  2354. cricket::SessionDescription* new_remote_description) {
  2355. RTC_DCHECK(new_remote_description);
  2356. const cricket::ContentInfos no_infos;
  2357. const cricket::ContentInfos& local_contents =
  2358. (local_description() ? local_description()->description()->contents()
  2359. : no_infos);
  2360. const cricket::ContentInfos& remote_contents =
  2361. (remote_description() ? remote_description()->description()->contents()
  2362. : no_infos);
  2363. for (size_t i = 0; i < new_remote_description->contents().size(); ++i) {
  2364. cricket::ContentInfo& content = new_remote_description->contents()[i];
  2365. if (!content.name.empty()) {
  2366. continue;
  2367. }
  2368. std::string new_mid;
  2369. absl::string_view source_explanation;
  2370. if (IsUnifiedPlan()) {
  2371. if (i < local_contents.size()) {
  2372. new_mid = local_contents[i].name;
  2373. source_explanation = "from the matching local media section";
  2374. } else if (i < remote_contents.size()) {
  2375. new_mid = remote_contents[i].name;
  2376. source_explanation = "from the matching previous remote media section";
  2377. } else {
  2378. new_mid = mid_generator_();
  2379. source_explanation = "generated just now";
  2380. }
  2381. } else {
  2382. new_mid = std::string(
  2383. GetDefaultMidForPlanB(content.media_description()->type()));
  2384. source_explanation = "to match pre-existing behavior";
  2385. }
  2386. RTC_DCHECK(!new_mid.empty());
  2387. content.name = new_mid;
  2388. new_remote_description->transport_infos()[i].content_name = new_mid;
  2389. RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
  2390. << " is missing an a=mid line. Filling in the value '"
  2391. << new_mid << "' " << source_explanation << ".";
  2392. }
  2393. }
  2394. void PeerConnection::SetRemoteDescription(
  2395. SetSessionDescriptionObserver* observer,
  2396. SessionDescriptionInterface* desc) {
  2397. SetRemoteDescription(
  2398. std::unique_ptr<SessionDescriptionInterface>(desc),
  2399. rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
  2400. new SetRemoteDescriptionObserverAdapter(this, observer)));
  2401. }
  2402. void PeerConnection::SetRemoteDescription(
  2403. std::unique_ptr<SessionDescriptionInterface> desc,
  2404. rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
  2405. RTC_DCHECK_RUN_ON(signaling_thread());
  2406. TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
  2407. if (!observer) {
  2408. RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
  2409. return;
  2410. }
  2411. if (!desc) {
  2412. observer->OnSetRemoteDescriptionComplete(RTCError(
  2413. RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
  2414. return;
  2415. }
  2416. // If a session error has occurred the PeerConnection is in a possibly
  2417. // inconsistent state so fail right away.
  2418. if (session_error() != SessionError::kNone) {
  2419. std::string error_message = GetSessionErrorMsg();
  2420. RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
  2421. observer->OnSetRemoteDescriptionComplete(
  2422. RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
  2423. return;
  2424. }
  2425. if (IsUnifiedPlan()) {
  2426. if (configuration_.enable_implicit_rollback) {
  2427. if (desc->GetType() == SdpType::kOffer &&
  2428. signaling_state() == kHaveLocalOffer) {
  2429. Rollback(desc->GetType());
  2430. }
  2431. }
  2432. // Explicit rollback.
  2433. if (desc->GetType() == SdpType::kRollback) {
  2434. observer->OnSetRemoteDescriptionComplete(Rollback(desc->GetType()));
  2435. return;
  2436. }
  2437. } else if (desc->GetType() == SdpType::kRollback) {
  2438. observer->OnSetRemoteDescriptionComplete(
  2439. RTCError(RTCErrorType::UNSUPPORTED_OPERATION,
  2440. "Rollback not supported in Plan B"));
  2441. return;
  2442. }
  2443. if (desc->GetType() == SdpType::kOffer) {
  2444. // Report to UMA the format of the received offer.
  2445. ReportSdpFormatReceived(*desc);
  2446. }
  2447. // Handle remote descriptions missing a=mid lines for interop with legacy end
  2448. // points.
  2449. FillInMissingRemoteMids(desc->description());
  2450. RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
  2451. if (!error.ok()) {
  2452. std::string error_message = GetSetDescriptionErrorMessage(
  2453. cricket::CS_REMOTE, desc->GetType(), error);
  2454. RTC_LOG(LS_ERROR) << error_message;
  2455. observer->OnSetRemoteDescriptionComplete(
  2456. RTCError(error.type(), std::move(error_message)));
  2457. return;
  2458. }
  2459. // Grab the description type before moving ownership to
  2460. // ApplyRemoteDescription, which may destroy it before returning.
  2461. const SdpType type = desc->GetType();
  2462. error = ApplyRemoteDescription(std::move(desc));
  2463. // |desc| may be destroyed at this point.
  2464. if (!error.ok()) {
  2465. // If ApplyRemoteDescription fails, the PeerConnection could be in an
  2466. // inconsistent state, so act conservatively here and set the session error
  2467. // so that future calls to SetLocalDescription/SetRemoteDescription fail.
  2468. SetSessionError(SessionError::kContent, error.message());
  2469. std::string error_message =
  2470. GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
  2471. RTC_LOG(LS_ERROR) << error_message;
  2472. observer->OnSetRemoteDescriptionComplete(
  2473. RTCError(error.type(), std::move(error_message)));
  2474. return;
  2475. }
  2476. RTC_DCHECK(remote_description());
  2477. if (type == SdpType::kAnswer) {
  2478. // TODO(deadbeef): We already had to hop to the network thread for
  2479. // MaybeStartGathering...
  2480. network_thread()->Invoke<void>(
  2481. RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
  2482. port_allocator_.get()));
  2483. // Make UMA notes about what was agreed to.
  2484. ReportNegotiatedSdpSemantics(*remote_description());
  2485. }
  2486. if (IsUnifiedPlan()) {
  2487. bool was_negotiation_needed = is_negotiation_needed_;
  2488. UpdateNegotiationNeeded();
  2489. if (signaling_state() == kStable && was_negotiation_needed &&
  2490. is_negotiation_needed_) {
  2491. Observer()->OnRenegotiationNeeded();
  2492. }
  2493. }
  2494. observer->OnSetRemoteDescriptionComplete(RTCError::OK());
  2495. NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED);
  2496. }
  2497. RTCError PeerConnection::ApplyRemoteDescription(
  2498. std::unique_ptr<SessionDescriptionInterface> desc) {
  2499. RTC_DCHECK_RUN_ON(signaling_thread());
  2500. RTC_DCHECK(desc);
  2501. // Update stats here so that we have the most recent stats for tracks and
  2502. // streams that might be removed by updating the session description.
  2503. stats_->UpdateStats(kStatsOutputLevelStandard);
  2504. // Take a reference to the old remote description since it's used below to
  2505. // compare against the new remote description. When setting the new remote
  2506. // description, grab ownership of the replaced session description in case it
  2507. // is the same as |old_remote_description|, to keep it alive for the duration
  2508. // of the method.
  2509. const SessionDescriptionInterface* old_remote_description =
  2510. remote_description();
  2511. std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
  2512. SdpType type = desc->GetType();
  2513. if (type == SdpType::kAnswer) {
  2514. replaced_remote_description = pending_remote_description_
  2515. ? std::move(pending_remote_description_)
  2516. : std::move(current_remote_description_);
  2517. current_remote_description_ = std::move(desc);
  2518. pending_remote_description_ = nullptr;
  2519. current_local_description_ = std::move(pending_local_description_);
  2520. } else {
  2521. replaced_remote_description = std::move(pending_remote_description_);
  2522. pending_remote_description_ = std::move(desc);
  2523. }
  2524. // The session description to apply now must be accessed by
  2525. // |remote_description()|.
  2526. RTC_DCHECK(remote_description());
  2527. // Report statistics about any use of simulcast.
  2528. ReportSimulcastApiVersion(kSimulcastVersionApplyRemoteDescription,
  2529. *remote_description()->description());
  2530. RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
  2531. if (!error.ok()) {
  2532. return error;
  2533. }
  2534. // Transport and Media channels will be created only when offer is set.
  2535. if (IsUnifiedPlan()) {
  2536. RTCError error = UpdateTransceiversAndDataChannels(
  2537. cricket::CS_REMOTE, *remote_description(), local_description(),
  2538. old_remote_description);
  2539. if (!error.ok()) {
  2540. return error;
  2541. }
  2542. } else {
  2543. // Media channels will be created only when offer is set. These may use new
  2544. // transports just created by PushdownTransportDescription.
  2545. if (type == SdpType::kOffer) {
  2546. // TODO(mallinath) - Handle CreateChannel failure, as new local
  2547. // description is applied. Restore back to old description.
  2548. RTCError error = CreateChannels(*remote_description()->description());
  2549. if (!error.ok()) {
  2550. return error;
  2551. }
  2552. }
  2553. // Remove unused channels if MediaContentDescription is rejected.
  2554. RemoveUnusedChannels(remote_description()->description());
  2555. }
  2556. // NOTE: Candidates allocation will be initiated only when
  2557. // SetLocalDescription is called.
  2558. error = UpdateSessionState(type, cricket::CS_REMOTE,
  2559. remote_description()->description());
  2560. if (!error.ok()) {
  2561. return error;
  2562. }
  2563. if (local_description() &&
  2564. !UseCandidatesInSessionDescription(remote_description())) {
  2565. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
  2566. }
  2567. if (old_remote_description) {
  2568. for (const cricket::ContentInfo& content :
  2569. old_remote_description->description()->contents()) {
  2570. // Check if this new SessionDescription contains new ICE ufrag and
  2571. // password that indicates the remote peer requests an ICE restart.
  2572. // TODO(deadbeef): When we start storing both the current and pending
  2573. // remote description, this should reset pending_ice_restarts and compare
  2574. // against the current description.
  2575. if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
  2576. content.name)) {
  2577. if (type == SdpType::kOffer) {
  2578. pending_ice_restarts_.insert(content.name);
  2579. }
  2580. } else {
  2581. // We retain all received candidates only if ICE is not restarted.
  2582. // When ICE is restarted, all previous candidates belong to an old
  2583. // generation and should not be kept.
  2584. // TODO(deadbeef): This goes against the W3C spec which says the remote
  2585. // description should only contain candidates from the last set remote
  2586. // description plus any candidates added since then. We should remove
  2587. // this once we're sure it won't break anything.
  2588. WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
  2589. old_remote_description, content.name, mutable_remote_description());
  2590. }
  2591. }
  2592. }
  2593. if (session_error() != SessionError::kNone) {
  2594. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
  2595. }
  2596. // Set the the ICE connection state to connecting since the connection may
  2597. // become writable with peer reflexive candidates before any remote candidate
  2598. // is signaled.
  2599. // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
  2600. // is to have a new signal the indicates a change in checking state from the
  2601. // transport and expose a new checking() member from transport that can be
  2602. // read to determine the current checking state. The existing SignalConnecting
  2603. // actually means "gathering candidates", so cannot be be used here.
  2604. if (remote_description()->GetType() != SdpType::kOffer &&
  2605. remote_description()->number_of_mediasections() > 0u &&
  2606. ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
  2607. SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
  2608. }
  2609. // If setting the description decided our SSL role, allocate any necessary
  2610. // SCTP sids.
  2611. rtc::SSLRole role;
  2612. if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
  2613. AllocateSctpSids(role);
  2614. }
  2615. if (IsUnifiedPlan()) {
  2616. std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
  2617. now_receiving_transceivers;
  2618. std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
  2619. std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
  2620. std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
  2621. for (const auto& transceiver : transceivers_) {
  2622. const ContentInfo* content =
  2623. FindMediaSectionForTransceiver(transceiver, remote_description());
  2624. if (!content) {
  2625. continue;
  2626. }
  2627. const MediaContentDescription* media_desc = content->media_description();
  2628. RtpTransceiverDirection local_direction =
  2629. RtpTransceiverDirectionReversed(media_desc->direction());
  2630. // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
  2631. // RTCSessionDescription: Set the associated remote streams given
  2632. // transceiver.[[Receiver]], msids, addList, and removeList".
  2633. // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
  2634. if (RtpTransceiverDirectionHasRecv(local_direction)) {
  2635. std::vector<std::string> stream_ids;
  2636. if (!media_desc->streams().empty()) {
  2637. // The remote description has signaled the stream IDs.
  2638. stream_ids = media_desc->streams()[0].stream_ids();
  2639. }
  2640. RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
  2641. << " (" << GetStreamIdsString(stream_ids) << ").";
  2642. SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
  2643. stream_ids, &added_streams,
  2644. &removed_streams);
  2645. // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
  2646. // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
  2647. // and transceiver's current direction is neither sendrecv nor recvonly,
  2648. // process the addition of a remote track for the media description.
  2649. if (!transceiver->fired_direction() ||
  2650. !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
  2651. RTC_LOG(LS_INFO)
  2652. << "Processing the addition of a remote track for MID="
  2653. << content->name << ".";
  2654. now_receiving_transceivers.push_back(transceiver);
  2655. }
  2656. }
  2657. // 2.2.8.1.9: If direction is "sendonly" or "inactive", and transceiver's
  2658. // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
  2659. // removal of a remote track for the media description, given transceiver,
  2660. // removeList, and muteTracks.
  2661. if (!RtpTransceiverDirectionHasRecv(local_direction) &&
  2662. (transceiver->fired_direction() &&
  2663. RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
  2664. ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
  2665. &removed_streams);
  2666. }
  2667. // 2.2.8.1.10: Set transceiver's [[FiredDirection]] slot to direction.
  2668. transceiver->internal()->set_fired_direction(local_direction);
  2669. // 2.2.8.1.11: If description is of type "answer" or "pranswer", then run
  2670. // the following steps:
  2671. if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
  2672. // 2.2.8.1.11.1: Set transceiver's [[CurrentDirection]] slot to
  2673. // direction.
  2674. transceiver->internal()->set_current_direction(local_direction);
  2675. // 2.2.8.1.11.[3-6]: Set the transport internal slots.
  2676. if (transceiver->mid()) {
  2677. auto dtls_transport =
  2678. LookupDtlsTransportByMidInternal(*transceiver->mid());
  2679. transceiver->internal()->sender_internal()->set_transport(
  2680. dtls_transport);
  2681. transceiver->internal()->receiver_internal()->set_transport(
  2682. dtls_transport);
  2683. }
  2684. }
  2685. // 2.2.8.1.12: If the media description is rejected, and transceiver is
  2686. // not already stopped, stop the RTCRtpTransceiver transceiver.
  2687. if (content->rejected && !transceiver->stopped()) {
  2688. RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
  2689. << " since the media section was rejected.";
  2690. transceiver->Stop();
  2691. }
  2692. if (!content->rejected &&
  2693. RtpTransceiverDirectionHasRecv(local_direction)) {
  2694. if (!media_desc->streams().empty() &&
  2695. media_desc->streams()[0].has_ssrcs()) {
  2696. uint32_t ssrc = media_desc->streams()[0].first_ssrc();
  2697. transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
  2698. } else {
  2699. transceiver->internal()
  2700. ->receiver_internal()
  2701. ->SetupUnsignaledMediaChannel();
  2702. }
  2703. }
  2704. }
  2705. // Once all processing has finished, fire off callbacks.
  2706. auto observer = Observer();
  2707. for (const auto& transceiver : now_receiving_transceivers) {
  2708. stats_->AddTrack(transceiver->receiver()->track());
  2709. observer->OnTrack(transceiver);
  2710. observer->OnAddTrack(transceiver->receiver(),
  2711. transceiver->receiver()->streams());
  2712. }
  2713. for (const auto& stream : added_streams) {
  2714. observer->OnAddStream(stream);
  2715. }
  2716. for (const auto& transceiver : remove_list) {
  2717. observer->OnRemoveTrack(transceiver->receiver());
  2718. }
  2719. for (const auto& stream : removed_streams) {
  2720. observer->OnRemoveStream(stream);
  2721. }
  2722. }
  2723. const cricket::ContentInfo* audio_content =
  2724. GetFirstAudioContent(remote_description()->description());
  2725. const cricket::ContentInfo* video_content =
  2726. GetFirstVideoContent(remote_description()->description());
  2727. const cricket::AudioContentDescription* audio_desc =
  2728. GetFirstAudioContentDescription(remote_description()->description());
  2729. const cricket::VideoContentDescription* video_desc =
  2730. GetFirstVideoContentDescription(remote_description()->description());
  2731. const cricket::RtpDataContentDescription* rtp_data_desc =
  2732. GetFirstRtpDataContentDescription(remote_description()->description());
  2733. // Check if the descriptions include streams, just in case the peer supports
  2734. // MSID, but doesn't indicate so with "a=msid-semantic".
  2735. if (remote_description()->description()->msid_supported() ||
  2736. (audio_desc && !audio_desc->streams().empty()) ||
  2737. (video_desc && !video_desc->streams().empty())) {
  2738. remote_peer_supports_msid_ = true;
  2739. }
  2740. // We wait to signal new streams until we finish processing the description,
  2741. // since only at that point will new streams have all their tracks.
  2742. rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
  2743. if (!IsUnifiedPlan()) {
  2744. // TODO(steveanton): When removing RTP senders/receivers in response to a
  2745. // rejected media section, there is some cleanup logic that expects the
  2746. // voice/ video channel to still be set. But in this method the voice/video
  2747. // channel would have been destroyed by the SetRemoteDescription caller
  2748. // above so the cleanup that relies on them fails to run. The RemoveSenders
  2749. // calls should be moved to right before the DestroyChannel calls to fix
  2750. // this.
  2751. // Find all audio rtp streams and create corresponding remote AudioTracks
  2752. // and MediaStreams.
  2753. if (audio_content) {
  2754. if (audio_content->rejected) {
  2755. RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
  2756. } else {
  2757. bool default_audio_track_needed =
  2758. !remote_peer_supports_msid_ &&
  2759. RtpTransceiverDirectionHasSend(audio_desc->direction());
  2760. UpdateRemoteSendersList(GetActiveStreams(audio_desc),
  2761. default_audio_track_needed, audio_desc->type(),
  2762. new_streams);
  2763. }
  2764. }
  2765. // Find all video rtp streams and create corresponding remote VideoTracks
  2766. // and MediaStreams.
  2767. if (video_content) {
  2768. if (video_content->rejected) {
  2769. RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
  2770. } else {
  2771. bool default_video_track_needed =
  2772. !remote_peer_supports_msid_ &&
  2773. RtpTransceiverDirectionHasSend(video_desc->direction());
  2774. UpdateRemoteSendersList(GetActiveStreams(video_desc),
  2775. default_video_track_needed, video_desc->type(),
  2776. new_streams);
  2777. }
  2778. }
  2779. // If this is an RTP data transport, update the DataChannels with the
  2780. // information from the remote peer.
  2781. if (rtp_data_desc) {
  2782. UpdateRemoteRtpDataChannels(GetActiveStreams(rtp_data_desc));
  2783. }
  2784. // Iterate new_streams and notify the observer about new MediaStreams.
  2785. auto observer = Observer();
  2786. for (size_t i = 0; i < new_streams->count(); ++i) {
  2787. MediaStreamInterface* new_stream = new_streams->at(i);
  2788. stats_->AddStream(new_stream);
  2789. observer->OnAddStream(
  2790. rtc::scoped_refptr<MediaStreamInterface>(new_stream));
  2791. }
  2792. UpdateEndedRemoteMediaStreams();
  2793. }
  2794. if (type == SdpType::kAnswer &&
  2795. local_ice_credentials_to_replace_->SatisfiesIceRestart(
  2796. *current_local_description_)) {
  2797. local_ice_credentials_to_replace_->ClearIceCredentials();
  2798. }
  2799. return RTCError::OK();
  2800. }
  2801. void PeerConnection::SetAssociatedRemoteStreams(
  2802. rtc::scoped_refptr<RtpReceiverInternal> receiver,
  2803. const std::vector<std::string>& stream_ids,
  2804. std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
  2805. std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
  2806. std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
  2807. for (const std::string& stream_id : stream_ids) {
  2808. rtc::scoped_refptr<MediaStreamInterface> stream =
  2809. remote_streams_->find(stream_id);
  2810. if (!stream) {
  2811. stream = MediaStreamProxy::Create(rtc::Thread::Current(),
  2812. MediaStream::Create(stream_id));
  2813. remote_streams_->AddStream(stream);
  2814. added_streams->push_back(stream);
  2815. }
  2816. media_streams.push_back(stream);
  2817. }
  2818. // Special case: "a=msid" missing, use random stream ID.
  2819. if (media_streams.empty() &&
  2820. !(remote_description()->description()->msid_signaling() &
  2821. cricket::kMsidSignalingMediaSection)) {
  2822. if (!missing_msid_default_stream_) {
  2823. missing_msid_default_stream_ = MediaStreamProxy::Create(
  2824. rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
  2825. added_streams->push_back(missing_msid_default_stream_);
  2826. }
  2827. media_streams.push_back(missing_msid_default_stream_);
  2828. }
  2829. std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
  2830. receiver->streams();
  2831. // SetStreams() will add/remove the receiver's track to/from the streams. This
  2832. // differs from the spec - the spec uses an "addList" and "removeList" to
  2833. // update the stream-track relationships in a later step. We do this earlier,
  2834. // changing the order of things, but the end-result is the same.
  2835. // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
  2836. // instead. https://crbug.com/webrtc/9480
  2837. receiver->SetStreams(media_streams);
  2838. RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
  2839. }
  2840. void PeerConnection::ProcessRemovalOfRemoteTrack(
  2841. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  2842. transceiver,
  2843. std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
  2844. std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
  2845. RTC_DCHECK(transceiver->mid());
  2846. RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
  2847. << *transceiver->mid();
  2848. std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
  2849. transceiver->internal()->receiver_internal()->streams();
  2850. // This will remove the remote track from the streams.
  2851. transceiver->internal()->receiver_internal()->set_stream_ids({});
  2852. remove_list->push_back(transceiver);
  2853. RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
  2854. }
  2855. void PeerConnection::RemoveRemoteStreamsIfEmpty(
  2856. const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
  2857. std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
  2858. // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
  2859. // streams, see if the stream was removed by checking if this was the last
  2860. // receiver with that stream ID.
  2861. for (const auto& remote_stream : remote_streams) {
  2862. if (remote_stream->GetAudioTracks().empty() &&
  2863. remote_stream->GetVideoTracks().empty()) {
  2864. remote_streams_->RemoveStream(remote_stream);
  2865. removed_streams->push_back(remote_stream);
  2866. }
  2867. }
  2868. }
  2869. RTCError PeerConnection::UpdateTransceiversAndDataChannels(
  2870. cricket::ContentSource source,
  2871. const SessionDescriptionInterface& new_session,
  2872. const SessionDescriptionInterface* old_local_description,
  2873. const SessionDescriptionInterface* old_remote_description) {
  2874. RTC_DCHECK(IsUnifiedPlan());
  2875. const cricket::ContentGroup* bundle_group = nullptr;
  2876. if (new_session.GetType() == SdpType::kOffer) {
  2877. auto bundle_group_or_error =
  2878. GetEarlyBundleGroup(*new_session.description());
  2879. if (!bundle_group_or_error.ok()) {
  2880. return bundle_group_or_error.MoveError();
  2881. }
  2882. bundle_group = bundle_group_or_error.MoveValue();
  2883. }
  2884. const ContentInfos& new_contents = new_session.description()->contents();
  2885. for (size_t i = 0; i < new_contents.size(); ++i) {
  2886. const cricket::ContentInfo& new_content = new_contents[i];
  2887. cricket::MediaType media_type = new_content.media_description()->type();
  2888. mid_generator_.AddKnownId(new_content.name);
  2889. if (media_type == cricket::MEDIA_TYPE_AUDIO ||
  2890. media_type == cricket::MEDIA_TYPE_VIDEO) {
  2891. const cricket::ContentInfo* old_local_content = nullptr;
  2892. if (old_local_description &&
  2893. i < old_local_description->description()->contents().size()) {
  2894. old_local_content =
  2895. &old_local_description->description()->contents()[i];
  2896. }
  2897. const cricket::ContentInfo* old_remote_content = nullptr;
  2898. if (old_remote_description &&
  2899. i < old_remote_description->description()->contents().size()) {
  2900. old_remote_content =
  2901. &old_remote_description->description()->contents()[i];
  2902. }
  2903. auto transceiver_or_error =
  2904. AssociateTransceiver(source, new_session.GetType(), i, new_content,
  2905. old_local_content, old_remote_content);
  2906. if (!transceiver_or_error.ok()) {
  2907. return transceiver_or_error.MoveError();
  2908. }
  2909. auto transceiver = transceiver_or_error.MoveValue();
  2910. RTCError error =
  2911. UpdateTransceiverChannel(transceiver, new_content, bundle_group);
  2912. if (!error.ok()) {
  2913. return error;
  2914. }
  2915. } else if (media_type == cricket::MEDIA_TYPE_DATA) {
  2916. if (GetDataMid() && new_content.name != *GetDataMid()) {
  2917. // Ignore all but the first data section.
  2918. RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
  2919. << new_content.name;
  2920. continue;
  2921. }
  2922. RTCError error = UpdateDataChannel(source, new_content, bundle_group);
  2923. if (!error.ok()) {
  2924. return error;
  2925. }
  2926. } else {
  2927. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
  2928. "Unknown section type.");
  2929. }
  2930. }
  2931. return RTCError::OK();
  2932. }
  2933. RTCError PeerConnection::UpdateTransceiverChannel(
  2934. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  2935. transceiver,
  2936. const cricket::ContentInfo& content,
  2937. const cricket::ContentGroup* bundle_group) {
  2938. RTC_DCHECK(IsUnifiedPlan());
  2939. RTC_DCHECK(transceiver);
  2940. cricket::ChannelInterface* channel = transceiver->internal()->channel();
  2941. if (content.rejected) {
  2942. if (channel) {
  2943. transceiver->internal()->SetChannel(nullptr);
  2944. DestroyChannelInterface(channel);
  2945. }
  2946. } else {
  2947. if (!channel) {
  2948. if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
  2949. channel = CreateVoiceChannel(content.name);
  2950. } else {
  2951. RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
  2952. channel = CreateVideoChannel(content.name);
  2953. }
  2954. if (!channel) {
  2955. LOG_AND_RETURN_ERROR(
  2956. RTCErrorType::INTERNAL_ERROR,
  2957. "Failed to create channel for mid=" + content.name);
  2958. }
  2959. transceiver->internal()->SetChannel(channel);
  2960. }
  2961. }
  2962. return RTCError::OK();
  2963. }
  2964. RTCError PeerConnection::UpdateDataChannel(
  2965. cricket::ContentSource source,
  2966. const cricket::ContentInfo& content,
  2967. const cricket::ContentGroup* bundle_group) {
  2968. if (data_channel_type_ == cricket::DCT_NONE) {
  2969. // If data channels are disabled, ignore this media section. CreateAnswer
  2970. // will take care of rejecting it.
  2971. return RTCError::OK();
  2972. }
  2973. if (content.rejected) {
  2974. RTC_LOG(LS_INFO) << "Rejected data channel, mid=" << content.mid();
  2975. DestroyDataChannel();
  2976. } else {
  2977. if (!rtp_data_channel_ && !data_channel_transport_) {
  2978. RTC_LOG(LS_INFO) << "Creating data channel, mid=" << content.mid();
  2979. if (!CreateDataChannel(content.name)) {
  2980. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
  2981. "Failed to create data channel.");
  2982. }
  2983. }
  2984. if (source == cricket::CS_REMOTE) {
  2985. const MediaContentDescription* data_desc = content.media_description();
  2986. if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
  2987. UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
  2988. }
  2989. }
  2990. }
  2991. return RTCError::OK();
  2992. }
  2993. // This method will extract any send encodings that were sent by the remote
  2994. // connection. This is currently only relevant for Simulcast scenario (where
  2995. // the number of layers may be communicated by the server).
  2996. static std::vector<RtpEncodingParameters> GetSendEncodingsFromRemoteDescription(
  2997. const MediaContentDescription& desc) {
  2998. if (!desc.HasSimulcast()) {
  2999. return {};
  3000. }
  3001. std::vector<RtpEncodingParameters> result;
  3002. const SimulcastDescription& simulcast = desc.simulcast_description();
  3003. // This is a remote description, the parameters we are after should appear
  3004. // as receive streams.
  3005. for (const auto& alternatives : simulcast.receive_layers()) {
  3006. RTC_DCHECK(!alternatives.empty());
  3007. // There is currently no way to specify or choose from alternatives.
  3008. // We will always use the first alternative, which is the most preferred.
  3009. const SimulcastLayer& layer = alternatives[0];
  3010. RtpEncodingParameters parameters;
  3011. parameters.rid = layer.rid;
  3012. parameters.active = !layer.is_paused;
  3013. result.push_back(parameters);
  3014. }
  3015. return result;
  3016. }
  3017. static RTCError UpdateSimulcastLayerStatusInSender(
  3018. const std::vector<SimulcastLayer>& layers,
  3019. rtc::scoped_refptr<RtpSenderInternal> sender) {
  3020. RTC_DCHECK(sender);
  3021. RtpParameters parameters = sender->GetParametersInternal();
  3022. std::vector<std::string> disabled_layers;
  3023. // The simulcast envelope cannot be changed, only the status of the streams.
  3024. // So we will iterate over the send encodings rather than the layers.
  3025. for (RtpEncodingParameters& encoding : parameters.encodings) {
  3026. auto iter = std::find_if(layers.begin(), layers.end(),
  3027. [&encoding](const SimulcastLayer& layer) {
  3028. return layer.rid == encoding.rid;
  3029. });
  3030. // A layer that cannot be found may have been removed by the remote party.
  3031. if (iter == layers.end()) {
  3032. disabled_layers.push_back(encoding.rid);
  3033. continue;
  3034. }
  3035. encoding.active = !iter->is_paused;
  3036. }
  3037. RTCError result = sender->SetParametersInternal(parameters);
  3038. if (result.ok()) {
  3039. result = sender->DisableEncodingLayers(disabled_layers);
  3040. }
  3041. return result;
  3042. }
  3043. static bool SimulcastIsRejected(
  3044. const ContentInfo* local_content,
  3045. const MediaContentDescription& answer_media_desc) {
  3046. bool simulcast_offered = local_content &&
  3047. local_content->media_description() &&
  3048. local_content->media_description()->HasSimulcast();
  3049. bool simulcast_answered = answer_media_desc.HasSimulcast();
  3050. bool rids_supported = RtpExtension::FindHeaderExtensionByUri(
  3051. answer_media_desc.rtp_header_extensions(), RtpExtension::kRidUri);
  3052. return simulcast_offered && (!simulcast_answered || !rids_supported);
  3053. }
  3054. static RTCError DisableSimulcastInSender(
  3055. rtc::scoped_refptr<RtpSenderInternal> sender) {
  3056. RTC_DCHECK(sender);
  3057. RtpParameters parameters = sender->GetParametersInternal();
  3058. if (parameters.encodings.size() <= 1) {
  3059. return RTCError::OK();
  3060. }
  3061. std::vector<std::string> disabled_layers;
  3062. std::transform(
  3063. parameters.encodings.begin() + 1, parameters.encodings.end(),
  3064. std::back_inserter(disabled_layers),
  3065. [](const RtpEncodingParameters& encoding) { return encoding.rid; });
  3066. return sender->DisableEncodingLayers(disabled_layers);
  3067. }
  3068. RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
  3069. PeerConnection::AssociateTransceiver(cricket::ContentSource source,
  3070. SdpType type,
  3071. size_t mline_index,
  3072. const ContentInfo& content,
  3073. const ContentInfo* old_local_content,
  3074. const ContentInfo* old_remote_content) {
  3075. RTC_DCHECK(IsUnifiedPlan());
  3076. // If this is an offer then the m= section might be recycled. If the m=
  3077. // section is being recycled (defined as: rejected in the current local or
  3078. // remote description and not rejected in new description), dissociate the
  3079. // currently associated RtpTransceiver by setting its mid property to null,
  3080. // and discard the mapping between the transceiver and its m= section index.
  3081. if (IsMediaSectionBeingRecycled(type, content, old_local_content,
  3082. old_remote_content)) {
  3083. // We want to dissociate the transceiver that has the rejected mid.
  3084. const std::string& old_mid =
  3085. (old_local_content && old_local_content->rejected)
  3086. ? old_local_content->name
  3087. : old_remote_content->name;
  3088. auto old_transceiver = GetAssociatedTransceiver(old_mid);
  3089. if (old_transceiver) {
  3090. RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
  3091. << " since the media section is being recycled.";
  3092. old_transceiver->internal()->set_mid(absl::nullopt);
  3093. old_transceiver->internal()->set_mline_index(absl::nullopt);
  3094. }
  3095. }
  3096. const MediaContentDescription* media_desc = content.media_description();
  3097. auto transceiver = GetAssociatedTransceiver(content.name);
  3098. if (source == cricket::CS_LOCAL) {
  3099. // Find the RtpTransceiver that corresponds to this m= section, using the
  3100. // mapping between transceivers and m= section indices established when
  3101. // creating the offer.
  3102. if (!transceiver) {
  3103. transceiver = GetTransceiverByMLineIndex(mline_index);
  3104. }
  3105. if (!transceiver) {
  3106. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  3107. "Unknown transceiver");
  3108. }
  3109. } else {
  3110. RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
  3111. // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
  3112. // of the same type...
  3113. // When simulcast is requested, a transceiver cannot be associated because
  3114. // AddTrack cannot be called to initialize it.
  3115. if (!transceiver &&
  3116. RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
  3117. !media_desc->HasSimulcast()) {
  3118. transceiver = FindAvailableTransceiverToReceive(media_desc->type());
  3119. }
  3120. // If no RtpTransceiver was found in the previous step, create one with a
  3121. // recvonly direction.
  3122. if (!transceiver) {
  3123. RTC_LOG(LS_INFO) << "Adding "
  3124. << cricket::MediaTypeToString(media_desc->type())
  3125. << " transceiver for MID=" << content.name
  3126. << " at i=" << mline_index
  3127. << " in response to the remote description.";
  3128. std::string sender_id = rtc::CreateRandomUuid();
  3129. std::vector<RtpEncodingParameters> send_encodings =
  3130. GetSendEncodingsFromRemoteDescription(*media_desc);
  3131. auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {},
  3132. send_encodings);
  3133. std::string receiver_id;
  3134. if (!media_desc->streams().empty()) {
  3135. receiver_id = media_desc->streams()[0].id;
  3136. } else {
  3137. receiver_id = rtc::CreateRandomUuid();
  3138. }
  3139. auto receiver = CreateReceiver(media_desc->type(), receiver_id);
  3140. transceiver = CreateAndAddTransceiver(sender, receiver);
  3141. transceiver->internal()->set_direction(
  3142. RtpTransceiverDirection::kRecvOnly);
  3143. if (type == SdpType::kOffer) {
  3144. transceiver_stable_states_by_transceivers_[transceiver] =
  3145. TransceiverStableState(RtpTransceiverDirection::kRecvOnly,
  3146. absl::nullopt, absl::nullopt, true);
  3147. }
  3148. }
  3149. // Check if the offer indicated simulcast but the answer rejected it.
  3150. // This can happen when simulcast is not supported on the remote party.
  3151. if (SimulcastIsRejected(old_local_content, *media_desc)) {
  3152. RTC_HISTOGRAM_BOOLEAN(kSimulcastDisabled, true);
  3153. RTCError error =
  3154. DisableSimulcastInSender(transceiver->internal()->sender_internal());
  3155. if (!error.ok()) {
  3156. RTC_LOG(LS_ERROR) << "Failed to remove rejected simulcast.";
  3157. return std::move(error);
  3158. }
  3159. }
  3160. }
  3161. RTC_DCHECK(transceiver);
  3162. if (transceiver->media_type() != media_desc->type()) {
  3163. LOG_AND_RETURN_ERROR(
  3164. RTCErrorType::INVALID_PARAMETER,
  3165. "Transceiver type does not match media description type.");
  3166. }
  3167. if (media_desc->HasSimulcast()) {
  3168. std::vector<SimulcastLayer> layers =
  3169. source == cricket::CS_LOCAL
  3170. ? media_desc->simulcast_description().send_layers().GetAllLayers()
  3171. : media_desc->simulcast_description()
  3172. .receive_layers()
  3173. .GetAllLayers();
  3174. RTCError error = UpdateSimulcastLayerStatusInSender(
  3175. layers, transceiver->internal()->sender_internal());
  3176. if (!error.ok()) {
  3177. RTC_LOG(LS_ERROR) << "Failed updating status for simulcast layers.";
  3178. return std::move(error);
  3179. }
  3180. }
  3181. if (type == SdpType::kOffer) {
  3182. // Make sure we don't overwrite existing stable states and that the
  3183. // state is really going to change when adding new record to the map.
  3184. auto it = transceiver_stable_states_by_transceivers_.find(transceiver);
  3185. if (it == transceiver_stable_states_by_transceivers_.end() &&
  3186. (transceiver->internal()->mid() != content.name ||
  3187. transceiver->internal()->mline_index() != mline_index)) {
  3188. transceiver_stable_states_by_transceivers_[transceiver] =
  3189. TransceiverStableState(transceiver->internal()->direction(),
  3190. transceiver->internal()->mid(),
  3191. transceiver->internal()->mline_index(), false);
  3192. }
  3193. }
  3194. // Associate the found or created RtpTransceiver with the m= section by
  3195. // setting the value of the RtpTransceiver's mid property to the MID of the m=
  3196. // section, and establish a mapping between the transceiver and the index of
  3197. // the m= section.
  3198. transceiver->internal()->set_mid(content.name);
  3199. transceiver->internal()->set_mline_index(mline_index);
  3200. return std::move(transceiver);
  3201. }
  3202. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  3203. PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
  3204. RTC_DCHECK(IsUnifiedPlan());
  3205. for (auto transceiver : transceivers_) {
  3206. if (transceiver->mid() == mid) {
  3207. return transceiver;
  3208. }
  3209. }
  3210. return nullptr;
  3211. }
  3212. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  3213. PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
  3214. RTC_DCHECK(IsUnifiedPlan());
  3215. for (auto transceiver : transceivers_) {
  3216. if (transceiver->internal()->mline_index() == mline_index) {
  3217. return transceiver;
  3218. }
  3219. }
  3220. return nullptr;
  3221. }
  3222. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  3223. PeerConnection::FindAvailableTransceiverToReceive(
  3224. cricket::MediaType media_type) const {
  3225. RTC_DCHECK(IsUnifiedPlan());
  3226. // From JSEP section 5.10 (Applying a Remote Description):
  3227. // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
  3228. // the same type that were added to the PeerConnection by addTrack and are not
  3229. // associated with any m= section and are not stopped, find the first such
  3230. // RtpTransceiver.
  3231. for (auto transceiver : transceivers_) {
  3232. if (transceiver->media_type() == media_type &&
  3233. transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
  3234. !transceiver->stopped()) {
  3235. return transceiver;
  3236. }
  3237. }
  3238. return nullptr;
  3239. }
  3240. const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
  3241. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  3242. transceiver,
  3243. const SessionDescriptionInterface* sdesc) const {
  3244. RTC_DCHECK(transceiver);
  3245. RTC_DCHECK(sdesc);
  3246. if (IsUnifiedPlan()) {
  3247. if (!transceiver->internal()->mid()) {
  3248. // This transceiver is not associated with a media section yet.
  3249. return nullptr;
  3250. }
  3251. return sdesc->description()->GetContentByName(
  3252. *transceiver->internal()->mid());
  3253. } else {
  3254. // Plan B only allows at most one audio and one video section, so use the
  3255. // first media section of that type.
  3256. return cricket::GetFirstMediaContent(sdesc->description()->contents(),
  3257. transceiver->media_type());
  3258. }
  3259. }
  3260. PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
  3261. RTC_DCHECK_RUN_ON(signaling_thread());
  3262. return configuration_;
  3263. }
  3264. RTCError PeerConnection::SetConfiguration(
  3265. const RTCConfiguration& configuration) {
  3266. RTC_DCHECK_RUN_ON(signaling_thread());
  3267. RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
  3268. TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
  3269. if (IsClosed()) {
  3270. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
  3271. "SetConfiguration: PeerConnection is closed.");
  3272. }
  3273. // According to JSEP, after setLocalDescription, changing the candidate pool
  3274. // size is not allowed, and changing the set of ICE servers will not result
  3275. // in new candidates being gathered.
  3276. if (local_description() && configuration.ice_candidate_pool_size !=
  3277. configuration_.ice_candidate_pool_size) {
  3278. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3279. "Can't change candidate pool size after calling "
  3280. "SetLocalDescription.");
  3281. }
  3282. if (local_description() &&
  3283. configuration.use_media_transport != configuration_.use_media_transport) {
  3284. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3285. "Can't change media_transport after calling "
  3286. "SetLocalDescription.");
  3287. }
  3288. if (remote_description() &&
  3289. configuration.use_media_transport != configuration_.use_media_transport) {
  3290. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3291. "Can't change media_transport after calling "
  3292. "SetRemoteDescription.");
  3293. }
  3294. if (local_description() &&
  3295. configuration.use_media_transport_for_data_channels !=
  3296. configuration_.use_media_transport_for_data_channels) {
  3297. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3298. "Can't change media_transport_for_data_channels "
  3299. "after calling SetLocalDescription.");
  3300. }
  3301. if (remote_description() &&
  3302. configuration.use_media_transport_for_data_channels !=
  3303. configuration_.use_media_transport_for_data_channels) {
  3304. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3305. "Can't change media_transport_for_data_channels "
  3306. "after calling SetRemoteDescription.");
  3307. }
  3308. if (local_description() &&
  3309. configuration.crypto_options != configuration_.crypto_options) {
  3310. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3311. "Can't change crypto_options after calling "
  3312. "SetLocalDescription.");
  3313. }
  3314. if (local_description() && configuration.use_datagram_transport !=
  3315. configuration_.use_datagram_transport) {
  3316. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3317. "Can't change use_datagram_transport "
  3318. "after calling SetLocalDescription.");
  3319. }
  3320. if (remote_description() && configuration.use_datagram_transport !=
  3321. configuration_.use_datagram_transport) {
  3322. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3323. "Can't change use_datagram_transport "
  3324. "after calling SetRemoteDescription.");
  3325. }
  3326. if (local_description() &&
  3327. configuration.use_datagram_transport_for_data_channels !=
  3328. configuration_.use_datagram_transport_for_data_channels) {
  3329. LOG_AND_RETURN_ERROR(
  3330. RTCErrorType::INVALID_MODIFICATION,
  3331. "Can't change use_datagram_transport_for_data_channels "
  3332. "after calling SetLocalDescription.");
  3333. }
  3334. if (remote_description() &&
  3335. configuration.use_datagram_transport_for_data_channels !=
  3336. configuration_.use_datagram_transport_for_data_channels) {
  3337. LOG_AND_RETURN_ERROR(
  3338. RTCErrorType::INVALID_MODIFICATION,
  3339. "Can't change use_datagram_transport_for_data_channels "
  3340. "after calling SetRemoteDescription.");
  3341. }
  3342. if (local_description() &&
  3343. configuration.use_datagram_transport_for_data_channels_receive_only !=
  3344. configuration_
  3345. .use_datagram_transport_for_data_channels_receive_only) {
  3346. LOG_AND_RETURN_ERROR(
  3347. RTCErrorType::INVALID_MODIFICATION,
  3348. "Can't change use_datagram_transport_for_data_channels_receive_only "
  3349. "after calling SetLocalDescription.");
  3350. }
  3351. if (remote_description() &&
  3352. configuration.use_datagram_transport_for_data_channels_receive_only !=
  3353. configuration_
  3354. .use_datagram_transport_for_data_channels_receive_only) {
  3355. LOG_AND_RETURN_ERROR(
  3356. RTCErrorType::INVALID_MODIFICATION,
  3357. "Can't change use_datagram_transport_for_data_channels_receive_only "
  3358. "after calling SetRemoteDescription.");
  3359. }
  3360. if (configuration.use_media_transport_for_data_channels ||
  3361. configuration.use_media_transport ||
  3362. (configuration.use_datagram_transport &&
  3363. *configuration.use_datagram_transport) ||
  3364. (configuration.use_datagram_transport_for_data_channels &&
  3365. *configuration.use_datagram_transport_for_data_channels)) {
  3366. RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
  3367. << "Media transport requires MaxBundle policy.";
  3368. }
  3369. // The simplest (and most future-compatible) way to tell if the config was
  3370. // modified in an invalid way is to copy each property we do support
  3371. // modifying, then use operator==. There are far more properties we don't
  3372. // support modifying than those we do, and more could be added.
  3373. RTCConfiguration modified_config = configuration_;
  3374. modified_config.servers = configuration.servers;
  3375. modified_config.type = configuration.type;
  3376. modified_config.ice_candidate_pool_size =
  3377. configuration.ice_candidate_pool_size;
  3378. modified_config.prune_turn_ports = configuration.prune_turn_ports;
  3379. modified_config.turn_port_prune_policy = configuration.turn_port_prune_policy;
  3380. modified_config.surface_ice_candidates_on_ice_transport_type_changed =
  3381. configuration.surface_ice_candidates_on_ice_transport_type_changed;
  3382. modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
  3383. modified_config.ice_check_interval_strong_connectivity =
  3384. configuration.ice_check_interval_strong_connectivity;
  3385. modified_config.ice_check_interval_weak_connectivity =
  3386. configuration.ice_check_interval_weak_connectivity;
  3387. modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
  3388. modified_config.ice_unwritable_min_checks =
  3389. configuration.ice_unwritable_min_checks;
  3390. modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
  3391. modified_config.stun_candidate_keepalive_interval =
  3392. configuration.stun_candidate_keepalive_interval;
  3393. modified_config.turn_customizer = configuration.turn_customizer;
  3394. modified_config.network_preference = configuration.network_preference;
  3395. modified_config.active_reset_srtp_params =
  3396. configuration.active_reset_srtp_params;
  3397. modified_config.use_media_transport = configuration.use_media_transport;
  3398. modified_config.use_media_transport_for_data_channels =
  3399. configuration.use_media_transport_for_data_channels;
  3400. modified_config.use_datagram_transport = configuration.use_datagram_transport;
  3401. modified_config.use_datagram_transport_for_data_channels =
  3402. configuration.use_datagram_transport_for_data_channels;
  3403. modified_config.use_datagram_transport_for_data_channels_receive_only =
  3404. configuration.use_datagram_transport_for_data_channels_receive_only;
  3405. modified_config.turn_logging_id = configuration.turn_logging_id;
  3406. if (configuration != modified_config) {
  3407. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_MODIFICATION,
  3408. "Modifying the configuration in an unsupported way.");
  3409. }
  3410. // Validate the modified configuration.
  3411. RTCError validate_error = ValidateConfiguration(modified_config);
  3412. if (!validate_error.ok()) {
  3413. return validate_error;
  3414. }
  3415. // Note that this isn't possible through chromium, since it's an unsigned
  3416. // short in WebIDL.
  3417. if (configuration.ice_candidate_pool_size < 0 ||
  3418. configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
  3419. return RTCError(RTCErrorType::INVALID_RANGE);
  3420. }
  3421. // Parse ICE servers before hopping to network thread.
  3422. cricket::ServerAddresses stun_servers;
  3423. std::vector<cricket::RelayServerConfig> turn_servers;
  3424. RTCErrorType parse_error =
  3425. ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
  3426. if (parse_error != RTCErrorType::NONE) {
  3427. return RTCError(parse_error);
  3428. }
  3429. // Add the turn logging id to all turn servers
  3430. for (cricket::RelayServerConfig& turn_server : turn_servers) {
  3431. turn_server.turn_logging_id = configuration.turn_logging_id;
  3432. }
  3433. // Note if STUN or TURN servers were supplied.
  3434. if (!stun_servers.empty()) {
  3435. NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
  3436. }
  3437. if (!turn_servers.empty()) {
  3438. NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
  3439. }
  3440. // In theory this shouldn't fail.
  3441. if (!network_thread()->Invoke<bool>(
  3442. RTC_FROM_HERE,
  3443. rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
  3444. stun_servers, turn_servers, modified_config.type,
  3445. modified_config.ice_candidate_pool_size,
  3446. modified_config.GetTurnPortPrunePolicy(),
  3447. modified_config.turn_customizer,
  3448. modified_config.stun_candidate_keepalive_interval,
  3449. static_cast<bool>(local_description())))) {
  3450. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
  3451. "Failed to apply configuration to PortAllocator.");
  3452. }
  3453. // As described in JSEP, calling setConfiguration with new ICE servers or
  3454. // candidate policy must set a "needs-ice-restart" bit so that the next offer
  3455. // triggers an ICE restart which will pick up the changes.
  3456. if (modified_config.servers != configuration_.servers ||
  3457. modified_config.type != configuration_.type ||
  3458. modified_config.GetTurnPortPrunePolicy() !=
  3459. configuration_.GetTurnPortPrunePolicy()) {
  3460. transport_controller_->SetNeedsIceRestartFlag();
  3461. }
  3462. transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
  3463. use_datagram_transport_ = datagram_transport_config_.enabled &&
  3464. modified_config.use_datagram_transport.value_or(
  3465. datagram_transport_config_.default_value);
  3466. use_datagram_transport_for_data_channels_ =
  3467. datagram_transport_data_channel_config_.enabled &&
  3468. modified_config.use_datagram_transport_for_data_channels.value_or(
  3469. datagram_transport_data_channel_config_.default_value);
  3470. use_datagram_transport_for_data_channels_receive_only_ =
  3471. modified_config.use_datagram_transport_for_data_channels_receive_only
  3472. .value_or(datagram_transport_data_channel_config_.receive_only);
  3473. transport_controller_->SetMediaTransportSettings(
  3474. modified_config.use_media_transport,
  3475. modified_config.use_media_transport_for_data_channels,
  3476. use_datagram_transport_, use_datagram_transport_for_data_channels_,
  3477. use_datagram_transport_for_data_channels_receive_only_);
  3478. if (configuration_.active_reset_srtp_params !=
  3479. modified_config.active_reset_srtp_params) {
  3480. transport_controller_->SetActiveResetSrtpParams(
  3481. modified_config.active_reset_srtp_params);
  3482. }
  3483. configuration_ = modified_config;
  3484. use_media_transport_ = configuration.use_media_transport;
  3485. return RTCError::OK();
  3486. }
  3487. bool PeerConnection::AddIceCandidate(
  3488. const IceCandidateInterface* ice_candidate) {
  3489. RTC_DCHECK_RUN_ON(signaling_thread());
  3490. TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
  3491. if (IsClosed()) {
  3492. RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
  3493. NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
  3494. return false;
  3495. }
  3496. if (!remote_description()) {
  3497. RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
  3498. "without any remote session description.";
  3499. NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
  3500. return false;
  3501. }
  3502. if (!ice_candidate) {
  3503. RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
  3504. NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
  3505. return false;
  3506. }
  3507. bool valid = false;
  3508. bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
  3509. if (!valid) {
  3510. NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
  3511. return false;
  3512. }
  3513. // Add this candidate to the remote session description.
  3514. if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
  3515. RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
  3516. NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
  3517. return false;
  3518. }
  3519. if (ready) {
  3520. bool result = UseCandidate(ice_candidate);
  3521. if (result) {
  3522. NoteUsageEvent(UsageEvent::ADD_ICE_CANDIDATE_SUCCEEDED);
  3523. NoteAddIceCandidateResult(kAddIceCandidateSuccess);
  3524. } else {
  3525. NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
  3526. }
  3527. return result;
  3528. } else {
  3529. RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
  3530. NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
  3531. return true;
  3532. }
  3533. }
  3534. bool PeerConnection::RemoveIceCandidates(
  3535. const std::vector<cricket::Candidate>& candidates) {
  3536. TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
  3537. RTC_DCHECK_RUN_ON(signaling_thread());
  3538. if (IsClosed()) {
  3539. RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
  3540. return false;
  3541. }
  3542. if (!remote_description()) {
  3543. RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
  3544. "without any remote session description.";
  3545. return false;
  3546. }
  3547. if (candidates.empty()) {
  3548. RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
  3549. return false;
  3550. }
  3551. size_t number_removed =
  3552. mutable_remote_description()->RemoveCandidates(candidates);
  3553. if (number_removed != candidates.size()) {
  3554. RTC_LOG(LS_ERROR)
  3555. << "RemoveIceCandidates: Failed to remove candidates. Requested "
  3556. << candidates.size() << " but only " << number_removed
  3557. << " are removed.";
  3558. }
  3559. // Remove the candidates from the transport controller.
  3560. RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
  3561. if (!error.ok()) {
  3562. RTC_LOG(LS_ERROR)
  3563. << "RemoveIceCandidates: Error when removing remote candidates: "
  3564. << error.message();
  3565. }
  3566. return true;
  3567. }
  3568. RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
  3569. if (!worker_thread()->IsCurrent()) {
  3570. return worker_thread()->Invoke<RTCError>(
  3571. RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
  3572. }
  3573. RTC_DCHECK_RUN_ON(worker_thread());
  3574. const bool has_min = bitrate.min_bitrate_bps.has_value();
  3575. const bool has_start = bitrate.start_bitrate_bps.has_value();
  3576. const bool has_max = bitrate.max_bitrate_bps.has_value();
  3577. if (has_min && *bitrate.min_bitrate_bps < 0) {
  3578. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  3579. "min_bitrate_bps <= 0");
  3580. }
  3581. if (has_start) {
  3582. if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
  3583. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  3584. "start_bitrate_bps < min_bitrate_bps");
  3585. } else if (*bitrate.start_bitrate_bps < 0) {
  3586. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  3587. "curent_bitrate_bps < 0");
  3588. }
  3589. }
  3590. if (has_max) {
  3591. if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
  3592. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  3593. "max_bitrate_bps < start_bitrate_bps");
  3594. } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
  3595. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  3596. "max_bitrate_bps < min_bitrate_bps");
  3597. } else if (*bitrate.max_bitrate_bps < 0) {
  3598. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  3599. "max_bitrate_bps < 0");
  3600. }
  3601. }
  3602. RTC_DCHECK(call_.get());
  3603. call_->SetClientBitratePreferences(bitrate);
  3604. return RTCError::OK();
  3605. }
  3606. void PeerConnection::SetAudioPlayout(bool playout) {
  3607. if (!worker_thread()->IsCurrent()) {
  3608. worker_thread()->Invoke<void>(
  3609. RTC_FROM_HERE,
  3610. rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
  3611. return;
  3612. }
  3613. auto audio_state =
  3614. factory_->channel_manager()->media_engine()->voice().GetAudioState();
  3615. audio_state->SetPlayout(playout);
  3616. }
  3617. void PeerConnection::SetAudioRecording(bool recording) {
  3618. if (!worker_thread()->IsCurrent()) {
  3619. worker_thread()->Invoke<void>(
  3620. RTC_FROM_HERE,
  3621. rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
  3622. return;
  3623. }
  3624. auto audio_state =
  3625. factory_->channel_manager()->media_engine()->voice().GetAudioState();
  3626. audio_state->SetRecording(recording);
  3627. }
  3628. std::unique_ptr<rtc::SSLCertificate>
  3629. PeerConnection::GetRemoteAudioSSLCertificate() {
  3630. std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
  3631. if (!chain || !chain->GetSize()) {
  3632. return nullptr;
  3633. }
  3634. return chain->Get(0).Clone();
  3635. }
  3636. std::unique_ptr<rtc::SSLCertChain>
  3637. PeerConnection::GetRemoteAudioSSLCertChain() {
  3638. RTC_DCHECK_RUN_ON(signaling_thread());
  3639. auto audio_transceiver = GetFirstAudioTransceiver();
  3640. if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
  3641. return nullptr;
  3642. }
  3643. return transport_controller_->GetRemoteSSLCertChain(
  3644. audio_transceiver->internal()->channel()->transport_name());
  3645. }
  3646. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  3647. PeerConnection::GetFirstAudioTransceiver() const {
  3648. for (auto transceiver : transceivers_) {
  3649. if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
  3650. return transceiver;
  3651. }
  3652. }
  3653. return nullptr;
  3654. }
  3655. bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
  3656. int64_t output_period_ms) {
  3657. return worker_thread()->Invoke<bool>(
  3658. RTC_FROM_HERE,
  3659. [this, output = std::move(output), output_period_ms]() mutable {
  3660. return StartRtcEventLog_w(std::move(output), output_period_ms);
  3661. });
  3662. }
  3663. bool PeerConnection::StartRtcEventLog(
  3664. std::unique_ptr<RtcEventLogOutput> output) {
  3665. int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
  3666. if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
  3667. output_period_ms = 5000;
  3668. }
  3669. return StartRtcEventLog(std::move(output), output_period_ms);
  3670. }
  3671. void PeerConnection::StopRtcEventLog() {
  3672. worker_thread()->Invoke<void>(
  3673. RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
  3674. }
  3675. rtc::scoped_refptr<DtlsTransportInterface>
  3676. PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
  3677. RTC_DCHECK_RUN_ON(signaling_thread());
  3678. return transport_controller_->LookupDtlsTransportByMid(mid);
  3679. }
  3680. rtc::scoped_refptr<DtlsTransport>
  3681. PeerConnection::LookupDtlsTransportByMidInternal(const std::string& mid) {
  3682. RTC_DCHECK_RUN_ON(signaling_thread());
  3683. return transport_controller_->LookupDtlsTransportByMid(mid);
  3684. }
  3685. rtc::scoped_refptr<SctpTransportInterface> PeerConnection::GetSctpTransport()
  3686. const {
  3687. RTC_DCHECK_RUN_ON(signaling_thread());
  3688. if (!sctp_mid_) {
  3689. return nullptr;
  3690. }
  3691. return transport_controller_->GetSctpTransport(*sctp_mid_);
  3692. }
  3693. const SessionDescriptionInterface* PeerConnection::local_description() const {
  3694. RTC_DCHECK_RUN_ON(signaling_thread());
  3695. return pending_local_description_ ? pending_local_description_.get()
  3696. : current_local_description_.get();
  3697. }
  3698. const SessionDescriptionInterface* PeerConnection::remote_description() const {
  3699. RTC_DCHECK_RUN_ON(signaling_thread());
  3700. return pending_remote_description_ ? pending_remote_description_.get()
  3701. : current_remote_description_.get();
  3702. }
  3703. const SessionDescriptionInterface* PeerConnection::current_local_description()
  3704. const {
  3705. RTC_DCHECK_RUN_ON(signaling_thread());
  3706. return current_local_description_.get();
  3707. }
  3708. const SessionDescriptionInterface* PeerConnection::current_remote_description()
  3709. const {
  3710. RTC_DCHECK_RUN_ON(signaling_thread());
  3711. return current_remote_description_.get();
  3712. }
  3713. const SessionDescriptionInterface* PeerConnection::pending_local_description()
  3714. const {
  3715. RTC_DCHECK_RUN_ON(signaling_thread());
  3716. return pending_local_description_.get();
  3717. }
  3718. const SessionDescriptionInterface* PeerConnection::pending_remote_description()
  3719. const {
  3720. RTC_DCHECK_RUN_ON(signaling_thread());
  3721. return pending_remote_description_.get();
  3722. }
  3723. void PeerConnection::Close() {
  3724. RTC_DCHECK_RUN_ON(signaling_thread());
  3725. TRACE_EVENT0("webrtc", "PeerConnection::Close");
  3726. // Update stats here so that we have the most recent stats for tracks and
  3727. // streams before the channels are closed.
  3728. stats_->UpdateStats(kStatsOutputLevelStandard);
  3729. ChangeSignalingState(PeerConnectionInterface::kClosed);
  3730. NoteUsageEvent(UsageEvent::CLOSE_CALLED);
  3731. for (const auto& transceiver : transceivers_) {
  3732. transceiver->Stop();
  3733. }
  3734. // Ensure that all asynchronous stats requests are completed before destroying
  3735. // the transport controller below.
  3736. if (stats_collector_) {
  3737. stats_collector_->WaitForPendingRequest();
  3738. }
  3739. // Don't destroy BaseChannels until after stats has been cleaned up so that
  3740. // the last stats request can still read from the channels.
  3741. DestroyAllChannels();
  3742. // The event log is used in the transport controller, which must be outlived
  3743. // by the former. CreateOffer by the peer connection is implemented
  3744. // asynchronously and if the peer connection is closed without resetting the
  3745. // WebRTC session description factory, the session description factory would
  3746. // call the transport controller.
  3747. webrtc_session_desc_factory_.reset();
  3748. transport_controller_.reset();
  3749. network_thread()->Invoke<void>(
  3750. RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
  3751. port_allocator_.get()));
  3752. worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
  3753. RTC_DCHECK_RUN_ON(worker_thread());
  3754. call_.reset();
  3755. // The event log must outlive call (and any other object that uses it).
  3756. event_log_.reset();
  3757. });
  3758. ReportUsagePattern();
  3759. // The .h file says that observer can be discarded after close() returns.
  3760. // Make sure this is true.
  3761. observer_ = nullptr;
  3762. }
  3763. void PeerConnection::OnMessage(rtc::Message* msg) {
  3764. RTC_DCHECK_RUN_ON(signaling_thread());
  3765. switch (msg->message_id) {
  3766. case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
  3767. SetSessionDescriptionMsg* param =
  3768. static_cast<SetSessionDescriptionMsg*>(msg->pdata);
  3769. param->observer->OnSuccess();
  3770. delete param;
  3771. break;
  3772. }
  3773. case MSG_SET_SESSIONDESCRIPTION_FAILED: {
  3774. SetSessionDescriptionMsg* param =
  3775. static_cast<SetSessionDescriptionMsg*>(msg->pdata);
  3776. param->observer->OnFailure(std::move(param->error));
  3777. delete param;
  3778. break;
  3779. }
  3780. case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
  3781. CreateSessionDescriptionMsg* param =
  3782. static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
  3783. param->observer->OnFailure(std::move(param->error));
  3784. delete param;
  3785. break;
  3786. }
  3787. case MSG_GETSTATS: {
  3788. GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
  3789. StatsReports reports;
  3790. stats_->GetStats(param->track, &reports);
  3791. param->observer->OnComplete(reports);
  3792. delete param;
  3793. break;
  3794. }
  3795. case MSG_FREE_DATACHANNELS: {
  3796. sctp_data_channels_to_free_.clear();
  3797. break;
  3798. }
  3799. case MSG_REPORT_USAGE_PATTERN: {
  3800. ReportUsagePattern();
  3801. break;
  3802. }
  3803. default:
  3804. RTC_NOTREACHED() << "Not implemented";
  3805. break;
  3806. }
  3807. }
  3808. cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
  3809. RTC_DCHECK(!IsUnifiedPlan());
  3810. auto* voice_channel = static_cast<cricket::VoiceChannel*>(
  3811. GetAudioTransceiver()->internal()->channel());
  3812. if (voice_channel) {
  3813. return voice_channel->media_channel();
  3814. } else {
  3815. return nullptr;
  3816. }
  3817. }
  3818. cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
  3819. RTC_DCHECK(!IsUnifiedPlan());
  3820. auto* video_channel = static_cast<cricket::VideoChannel*>(
  3821. GetVideoTransceiver()->internal()->channel());
  3822. if (video_channel) {
  3823. return video_channel->media_channel();
  3824. } else {
  3825. return nullptr;
  3826. }
  3827. }
  3828. void PeerConnection::CreateAudioReceiver(
  3829. MediaStreamInterface* stream,
  3830. const RtpSenderInfo& remote_sender_info) {
  3831. std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
  3832. streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
  3833. // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
  3834. // the constructor taking stream IDs instead.
  3835. auto* audio_receiver = new AudioRtpReceiver(
  3836. worker_thread(), remote_sender_info.sender_id, streams);
  3837. audio_receiver->SetMediaChannel(voice_media_channel());
  3838. if (remote_sender_info.sender_id == kDefaultAudioSenderId) {
  3839. audio_receiver->SetupUnsignaledMediaChannel();
  3840. } else {
  3841. audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
  3842. }
  3843. auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
  3844. signaling_thread(), audio_receiver);
  3845. GetAudioTransceiver()->internal()->AddReceiver(receiver);
  3846. Observer()->OnAddTrack(receiver, streams);
  3847. NoteUsageEvent(UsageEvent::AUDIO_ADDED);
  3848. }
  3849. void PeerConnection::CreateVideoReceiver(
  3850. MediaStreamInterface* stream,
  3851. const RtpSenderInfo& remote_sender_info) {
  3852. std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
  3853. streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
  3854. // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
  3855. // the constructor taking stream IDs instead.
  3856. auto* video_receiver = new VideoRtpReceiver(
  3857. worker_thread(), remote_sender_info.sender_id, streams);
  3858. video_receiver->SetMediaChannel(video_media_channel());
  3859. if (remote_sender_info.sender_id == kDefaultVideoSenderId) {
  3860. video_receiver->SetupUnsignaledMediaChannel();
  3861. } else {
  3862. video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
  3863. }
  3864. auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
  3865. signaling_thread(), video_receiver);
  3866. GetVideoTransceiver()->internal()->AddReceiver(receiver);
  3867. Observer()->OnAddTrack(receiver, streams);
  3868. NoteUsageEvent(UsageEvent::VIDEO_ADDED);
  3869. }
  3870. // TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
  3871. // description.
  3872. rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
  3873. const RtpSenderInfo& remote_sender_info) {
  3874. auto receiver = FindReceiverById(remote_sender_info.sender_id);
  3875. if (!receiver) {
  3876. RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
  3877. << remote_sender_info.sender_id << " doesn't exist.";
  3878. return nullptr;
  3879. }
  3880. if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
  3881. GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
  3882. } else {
  3883. GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
  3884. }
  3885. return receiver;
  3886. }
  3887. void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
  3888. MediaStreamInterface* stream) {
  3889. RTC_DCHECK(!IsClosed());
  3890. RTC_DCHECK(track);
  3891. RTC_DCHECK(stream);
  3892. auto sender = FindSenderForTrack(track);
  3893. if (sender) {
  3894. // We already have a sender for this track, so just change the stream_id
  3895. // so that it's correct in the next call to CreateOffer.
  3896. sender->internal()->set_stream_ids({stream->id()});
  3897. return;
  3898. }
  3899. // Normal case; we've never seen this track before.
  3900. auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
  3901. {stream->id()}, {});
  3902. new_sender->internal()->SetMediaChannel(voice_media_channel());
  3903. GetAudioTransceiver()->internal()->AddSender(new_sender);
  3904. // If the sender has already been configured in SDP, we call SetSsrc,
  3905. // which will connect the sender to the underlying transport. This can
  3906. // occur if a local session description that contains the ID of the sender
  3907. // is set before AddStream is called. It can also occur if the local
  3908. // session description is not changed and RemoveStream is called, and
  3909. // later AddStream is called again with the same stream.
  3910. const RtpSenderInfo* sender_info =
  3911. FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
  3912. if (sender_info) {
  3913. new_sender->internal()->SetSsrc(sender_info->first_ssrc);
  3914. }
  3915. }
  3916. // TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
  3917. // indefinitely, when we have unified plan SDP.
  3918. void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
  3919. MediaStreamInterface* stream) {
  3920. RTC_DCHECK(!IsClosed());
  3921. auto sender = FindSenderForTrack(track);
  3922. if (!sender) {
  3923. RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
  3924. << " doesn't exist.";
  3925. return;
  3926. }
  3927. GetAudioTransceiver()->internal()->RemoveSender(sender);
  3928. }
  3929. void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
  3930. MediaStreamInterface* stream) {
  3931. RTC_DCHECK(!IsClosed());
  3932. RTC_DCHECK(track);
  3933. RTC_DCHECK(stream);
  3934. auto sender = FindSenderForTrack(track);
  3935. if (sender) {
  3936. // We already have a sender for this track, so just change the stream_id
  3937. // so that it's correct in the next call to CreateOffer.
  3938. sender->internal()->set_stream_ids({stream->id()});
  3939. return;
  3940. }
  3941. // Normal case; we've never seen this track before.
  3942. auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
  3943. {stream->id()}, {});
  3944. new_sender->internal()->SetMediaChannel(video_media_channel());
  3945. GetVideoTransceiver()->internal()->AddSender(new_sender);
  3946. const RtpSenderInfo* sender_info =
  3947. FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
  3948. if (sender_info) {
  3949. new_sender->internal()->SetSsrc(sender_info->first_ssrc);
  3950. }
  3951. }
  3952. void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
  3953. MediaStreamInterface* stream) {
  3954. RTC_DCHECK(!IsClosed());
  3955. auto sender = FindSenderForTrack(track);
  3956. if (!sender) {
  3957. RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
  3958. << " doesn't exist.";
  3959. return;
  3960. }
  3961. GetVideoTransceiver()->internal()->RemoveSender(sender);
  3962. }
  3963. void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
  3964. if (ice_connection_state_ == new_state) {
  3965. return;
  3966. }
  3967. // After transitioning to "closed", ignore any additional states from
  3968. // TransportController (such as "disconnected").
  3969. if (IsClosed()) {
  3970. return;
  3971. }
  3972. RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
  3973. << " => " << new_state;
  3974. RTC_DCHECK(ice_connection_state_ !=
  3975. PeerConnectionInterface::kIceConnectionClosed);
  3976. ice_connection_state_ = new_state;
  3977. Observer()->OnIceConnectionChange(ice_connection_state_);
  3978. }
  3979. void PeerConnection::SetStandardizedIceConnectionState(
  3980. PeerConnectionInterface::IceConnectionState new_state) {
  3981. if (standardized_ice_connection_state_ == new_state) {
  3982. return;
  3983. }
  3984. if (IsClosed()) {
  3985. return;
  3986. }
  3987. RTC_LOG(LS_INFO) << "Changing standardized IceConnectionState "
  3988. << standardized_ice_connection_state_ << " => " << new_state;
  3989. standardized_ice_connection_state_ = new_state;
  3990. Observer()->OnStandardizedIceConnectionChange(new_state);
  3991. }
  3992. void PeerConnection::SetConnectionState(
  3993. PeerConnectionInterface::PeerConnectionState new_state) {
  3994. if (connection_state_ == new_state)
  3995. return;
  3996. if (IsClosed())
  3997. return;
  3998. connection_state_ = new_state;
  3999. Observer()->OnConnectionChange(new_state);
  4000. }
  4001. void PeerConnection::OnIceGatheringChange(
  4002. PeerConnectionInterface::IceGatheringState new_state) {
  4003. if (IsClosed()) {
  4004. return;
  4005. }
  4006. ice_gathering_state_ = new_state;
  4007. Observer()->OnIceGatheringChange(ice_gathering_state_);
  4008. }
  4009. void PeerConnection::OnIceCandidate(
  4010. std::unique_ptr<IceCandidateInterface> candidate) {
  4011. if (IsClosed()) {
  4012. return;
  4013. }
  4014. ReportIceCandidateCollected(candidate->candidate());
  4015. Observer()->OnIceCandidate(candidate.get());
  4016. }
  4017. void PeerConnection::OnIceCandidateError(const std::string& host_candidate,
  4018. const std::string& url,
  4019. int error_code,
  4020. const std::string& error_text) {
  4021. if (IsClosed()) {
  4022. return;
  4023. }
  4024. Observer()->OnIceCandidateError(host_candidate, url, error_code, error_text);
  4025. }
  4026. void PeerConnection::OnIceCandidatesRemoved(
  4027. const std::vector<cricket::Candidate>& candidates) {
  4028. if (IsClosed()) {
  4029. return;
  4030. }
  4031. Observer()->OnIceCandidatesRemoved(candidates);
  4032. }
  4033. void PeerConnection::OnSelectedCandidatePairChanged(
  4034. const cricket::CandidatePairChangeEvent& event) {
  4035. if (IsClosed()) {
  4036. return;
  4037. }
  4038. if (event.selected_candidate_pair.local_candidate().type() ==
  4039. LOCAL_PORT_TYPE &&
  4040. event.selected_candidate_pair.remote_candidate().type() ==
  4041. LOCAL_PORT_TYPE) {
  4042. NoteUsageEvent(UsageEvent::DIRECT_CONNECTION_SELECTED);
  4043. }
  4044. Observer()->OnIceSelectedCandidatePairChanged(event);
  4045. }
  4046. void PeerConnection::ChangeSignalingState(
  4047. PeerConnectionInterface::SignalingState signaling_state) {
  4048. if (signaling_state_ == signaling_state) {
  4049. return;
  4050. }
  4051. RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
  4052. << GetSignalingStateString(signaling_state_)
  4053. << " New state: "
  4054. << GetSignalingStateString(signaling_state);
  4055. signaling_state_ = signaling_state;
  4056. if (signaling_state == kClosed) {
  4057. ice_connection_state_ = kIceConnectionClosed;
  4058. Observer()->OnIceConnectionChange(ice_connection_state_);
  4059. standardized_ice_connection_state_ =
  4060. PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
  4061. connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
  4062. Observer()->OnConnectionChange(connection_state_);
  4063. if (ice_gathering_state_ != kIceGatheringComplete) {
  4064. ice_gathering_state_ = kIceGatheringComplete;
  4065. Observer()->OnIceGatheringChange(ice_gathering_state_);
  4066. }
  4067. }
  4068. Observer()->OnSignalingChange(signaling_state_);
  4069. }
  4070. void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
  4071. MediaStreamInterface* stream) {
  4072. if (IsClosed()) {
  4073. return;
  4074. }
  4075. AddAudioTrack(track, stream);
  4076. UpdateNegotiationNeeded();
  4077. }
  4078. void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
  4079. MediaStreamInterface* stream) {
  4080. if (IsClosed()) {
  4081. return;
  4082. }
  4083. RemoveAudioTrack(track, stream);
  4084. UpdateNegotiationNeeded();
  4085. }
  4086. void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
  4087. MediaStreamInterface* stream) {
  4088. if (IsClosed()) {
  4089. return;
  4090. }
  4091. AddVideoTrack(track, stream);
  4092. UpdateNegotiationNeeded();
  4093. }
  4094. void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
  4095. MediaStreamInterface* stream) {
  4096. if (IsClosed()) {
  4097. return;
  4098. }
  4099. RemoveVideoTrack(track, stream);
  4100. UpdateNegotiationNeeded();
  4101. }
  4102. void PeerConnection::PostSetSessionDescriptionSuccess(
  4103. SetSessionDescriptionObserver* observer) {
  4104. SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
  4105. signaling_thread()->Post(RTC_FROM_HERE, this,
  4106. MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
  4107. }
  4108. void PeerConnection::PostSetSessionDescriptionFailure(
  4109. SetSessionDescriptionObserver* observer,
  4110. RTCError&& error) {
  4111. RTC_DCHECK(!error.ok());
  4112. SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
  4113. msg->error = std::move(error);
  4114. signaling_thread()->Post(RTC_FROM_HERE, this,
  4115. MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
  4116. }
  4117. void PeerConnection::PostCreateSessionDescriptionFailure(
  4118. CreateSessionDescriptionObserver* observer,
  4119. RTCError error) {
  4120. RTC_DCHECK(!error.ok());
  4121. CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
  4122. msg->error = std::move(error);
  4123. signaling_thread()->Post(RTC_FROM_HERE, this,
  4124. MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
  4125. }
  4126. void PeerConnection::GetOptionsForOffer(
  4127. const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
  4128. cricket::MediaSessionOptions* session_options) {
  4129. ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
  4130. if (IsUnifiedPlan()) {
  4131. GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
  4132. } else {
  4133. GetOptionsForPlanBOffer(offer_answer_options, session_options);
  4134. }
  4135. // Intentionally unset the data channel type for RTP data channel with the
  4136. // second condition. Otherwise the RTP data channels would be successfully
  4137. // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
  4138. // when building with chromium. We want to leave RTP data channels broken, so
  4139. // people won't try to use them.
  4140. if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
  4141. session_options->data_channel_type = data_channel_type();
  4142. }
  4143. // Apply ICE restart flag and renomination flag.
  4144. bool ice_restart = offer_answer_options.ice_restart ||
  4145. local_ice_credentials_to_replace_->HasIceCredentials();
  4146. for (auto& options : session_options->media_description_options) {
  4147. options.transport_options.ice_restart = ice_restart;
  4148. options.transport_options.enable_ice_renomination =
  4149. configuration_.enable_ice_renomination;
  4150. }
  4151. session_options->rtcp_cname = rtcp_cname_;
  4152. session_options->crypto_options = GetCryptoOptions();
  4153. session_options->pooled_ice_credentials =
  4154. network_thread()->Invoke<std::vector<cricket::IceParameters>>(
  4155. RTC_FROM_HERE,
  4156. rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
  4157. port_allocator_.get()));
  4158. session_options->offer_extmap_allow_mixed =
  4159. configuration_.offer_extmap_allow_mixed;
  4160. if (configuration_.use_media_transport ||
  4161. configuration_.use_media_transport_for_data_channels) {
  4162. session_options->media_transport_settings =
  4163. transport_controller_->GenerateOrGetLastMediaTransportOffer();
  4164. }
  4165. // If datagram transport is in use, add opaque transport parameters.
  4166. if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
  4167. for (auto& options : session_options->media_description_options) {
  4168. absl::optional<cricket::OpaqueTransportParameters> params =
  4169. transport_controller_->GetTransportParameters(options.mid);
  4170. if (!params) {
  4171. continue;
  4172. }
  4173. options.transport_options.opaque_parameters = params;
  4174. if ((use_datagram_transport_ &&
  4175. (options.type == cricket::MEDIA_TYPE_AUDIO ||
  4176. options.type == cricket::MEDIA_TYPE_VIDEO)) ||
  4177. (use_datagram_transport_for_data_channels_ &&
  4178. options.type == cricket::MEDIA_TYPE_DATA)) {
  4179. options.alt_protocol = params->protocol;
  4180. }
  4181. }
  4182. }
  4183. // Allow fallback for using obsolete SCTP syntax.
  4184. // Note that the default in |session_options| is true, while
  4185. // the default in |options| is false.
  4186. session_options->use_obsolete_sctp_sdp =
  4187. offer_answer_options.use_obsolete_sctp_sdp;
  4188. }
  4189. void PeerConnection::GetOptionsForPlanBOffer(
  4190. const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
  4191. cricket::MediaSessionOptions* session_options) {
  4192. // Figure out transceiver directional preferences.
  4193. bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
  4194. bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
  4195. // By default, generate sendrecv/recvonly m= sections.
  4196. bool recv_audio = true;
  4197. bool recv_video = true;
  4198. // By default, only offer a new m= section if we have media to send with it.
  4199. bool offer_new_audio_description = send_audio;
  4200. bool offer_new_video_description = send_video;
  4201. bool offer_new_data_description = HasDataChannels();
  4202. // The "offer_to_receive_X" options allow those defaults to be overridden.
  4203. if (offer_answer_options.offer_to_receive_audio !=
  4204. RTCOfferAnswerOptions::kUndefined) {
  4205. recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
  4206. offer_new_audio_description =
  4207. offer_new_audio_description ||
  4208. (offer_answer_options.offer_to_receive_audio > 0);
  4209. }
  4210. if (offer_answer_options.offer_to_receive_video !=
  4211. RTCOfferAnswerOptions::kUndefined) {
  4212. recv_video = (offer_answer_options.offer_to_receive_video > 0);
  4213. offer_new_video_description =
  4214. offer_new_video_description ||
  4215. (offer_answer_options.offer_to_receive_video > 0);
  4216. }
  4217. absl::optional<size_t> audio_index;
  4218. absl::optional<size_t> video_index;
  4219. absl::optional<size_t> data_index;
  4220. // If a current description exists, generate m= sections in the same order,
  4221. // using the first audio/video/data section that appears and rejecting
  4222. // extraneous ones.
  4223. if (local_description()) {
  4224. GenerateMediaDescriptionOptions(
  4225. local_description(),
  4226. RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
  4227. RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
  4228. &audio_index, &video_index, &data_index, session_options);
  4229. }
  4230. // Add audio/video/data m= sections to the end if needed.
  4231. if (!audio_index && offer_new_audio_description) {
  4232. session_options->media_description_options.push_back(
  4233. cricket::MediaDescriptionOptions(
  4234. cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
  4235. RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
  4236. false));
  4237. audio_index = session_options->media_description_options.size() - 1;
  4238. }
  4239. if (!video_index && offer_new_video_description) {
  4240. session_options->media_description_options.push_back(
  4241. cricket::MediaDescriptionOptions(
  4242. cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
  4243. RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
  4244. false));
  4245. video_index = session_options->media_description_options.size() - 1;
  4246. }
  4247. if (!data_index && offer_new_data_description) {
  4248. session_options->media_description_options.push_back(
  4249. GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
  4250. data_index = session_options->media_description_options.size() - 1;
  4251. }
  4252. cricket::MediaDescriptionOptions* audio_media_description_options =
  4253. !audio_index ? nullptr
  4254. : &session_options->media_description_options[*audio_index];
  4255. cricket::MediaDescriptionOptions* video_media_description_options =
  4256. !video_index ? nullptr
  4257. : &session_options->media_description_options[*video_index];
  4258. AddPlanBRtpSenderOptions(GetSendersInternal(),
  4259. audio_media_description_options,
  4260. video_media_description_options,
  4261. offer_answer_options.num_simulcast_layers);
  4262. }
  4263. static cricket::MediaDescriptionOptions
  4264. GetMediaDescriptionOptionsForTransceiver(
  4265. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  4266. transceiver,
  4267. const std::string& mid) {
  4268. cricket::MediaDescriptionOptions media_description_options(
  4269. transceiver->media_type(), mid, transceiver->direction(),
  4270. transceiver->stopped());
  4271. media_description_options.codec_preferences =
  4272. transceiver->codec_preferences();
  4273. // This behavior is specified in JSEP. The gist is that:
  4274. // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
  4275. // sendrecv.
  4276. // 2. If the MSID is included, then it must be included in any subsequent
  4277. // offer/answer exactly the same until the RtpTransceiver is stopped.
  4278. if (transceiver->stopped() ||
  4279. (!RtpTransceiverDirectionHasSend(transceiver->direction()) &&
  4280. !transceiver->internal()->has_ever_been_used_to_send())) {
  4281. return media_description_options;
  4282. }
  4283. cricket::SenderOptions sender_options;
  4284. sender_options.track_id = transceiver->sender()->id();
  4285. sender_options.stream_ids = transceiver->sender()->stream_ids();
  4286. // The following sets up RIDs and Simulcast.
  4287. // RIDs are included if Simulcast is requested or if any RID was specified.
  4288. RtpParameters send_parameters =
  4289. transceiver->internal()->sender_internal()->GetParametersInternal();
  4290. bool has_rids = std::any_of(send_parameters.encodings.begin(),
  4291. send_parameters.encodings.end(),
  4292. [](const RtpEncodingParameters& encoding) {
  4293. return !encoding.rid.empty();
  4294. });
  4295. std::vector<RidDescription> send_rids;
  4296. SimulcastLayerList send_layers;
  4297. for (const RtpEncodingParameters& encoding : send_parameters.encodings) {
  4298. if (encoding.rid.empty()) {
  4299. continue;
  4300. }
  4301. send_rids.push_back(RidDescription(encoding.rid, RidDirection::kSend));
  4302. send_layers.AddLayer(SimulcastLayer(encoding.rid, !encoding.active));
  4303. }
  4304. if (has_rids) {
  4305. sender_options.rids = send_rids;
  4306. }
  4307. sender_options.simulcast_layers = send_layers;
  4308. // When RIDs are configured, we must set num_sim_layers to 0 to.
  4309. // Otherwise, num_sim_layers must be 1 because either there is no
  4310. // simulcast, or simulcast is acheived by munging the SDP.
  4311. sender_options.num_sim_layers = has_rids ? 0 : 1;
  4312. media_description_options.sender_options.push_back(sender_options);
  4313. return media_description_options;
  4314. }
  4315. // Returns the ContentInfo at mline index |i|, or null if none exists.
  4316. static const ContentInfo* GetContentByIndex(
  4317. const SessionDescriptionInterface* sdesc,
  4318. size_t i) {
  4319. if (!sdesc) {
  4320. return nullptr;
  4321. }
  4322. const ContentInfos& contents = sdesc->description()->contents();
  4323. return (i < contents.size() ? &contents[i] : nullptr);
  4324. }
  4325. void PeerConnection::GetOptionsForUnifiedPlanOffer(
  4326. const RTCOfferAnswerOptions& offer_answer_options,
  4327. cricket::MediaSessionOptions* session_options) {
  4328. // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
  4329. // Offers) and 5.2.2 (Subsequent Offers).
  4330. RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
  4331. const ContentInfos no_infos;
  4332. const ContentInfos& local_contents =
  4333. (local_description() ? local_description()->description()->contents()
  4334. : no_infos);
  4335. const ContentInfos& remote_contents =
  4336. (remote_description() ? remote_description()->description()->contents()
  4337. : no_infos);
  4338. // The mline indices that can be recycled. New transceivers should reuse these
  4339. // slots first.
  4340. std::queue<size_t> recycleable_mline_indices;
  4341. // First, go through each media section that exists in either the local or
  4342. // remote description and generate a media section in this offer for the
  4343. // associated transceiver. If a media section can be recycled, generate a
  4344. // default, rejected media section here that can be later overwritten.
  4345. for (size_t i = 0;
  4346. i < std::max(local_contents.size(), remote_contents.size()); ++i) {
  4347. // Either |local_content| or |remote_content| is non-null.
  4348. const ContentInfo* local_content =
  4349. (i < local_contents.size() ? &local_contents[i] : nullptr);
  4350. const ContentInfo* current_local_content =
  4351. GetContentByIndex(current_local_description(), i);
  4352. const ContentInfo* remote_content =
  4353. (i < remote_contents.size() ? &remote_contents[i] : nullptr);
  4354. const ContentInfo* current_remote_content =
  4355. GetContentByIndex(current_remote_description(), i);
  4356. bool had_been_rejected =
  4357. (current_local_content && current_local_content->rejected) ||
  4358. (current_remote_content && current_remote_content->rejected);
  4359. const std::string& mid =
  4360. (local_content ? local_content->name : remote_content->name);
  4361. cricket::MediaType media_type =
  4362. (local_content ? local_content->media_description()->type()
  4363. : remote_content->media_description()->type());
  4364. if (media_type == cricket::MEDIA_TYPE_AUDIO ||
  4365. media_type == cricket::MEDIA_TYPE_VIDEO) {
  4366. auto transceiver = GetAssociatedTransceiver(mid);
  4367. RTC_CHECK(transceiver);
  4368. // A media section is considered eligible for recycling if it is marked as
  4369. // rejected in either the current local or current remote description.
  4370. if (had_been_rejected && transceiver->stopped()) {
  4371. session_options->media_description_options.push_back(
  4372. cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
  4373. RtpTransceiverDirection::kInactive,
  4374. /*stopped=*/true));
  4375. recycleable_mline_indices.push(i);
  4376. } else {
  4377. session_options->media_description_options.push_back(
  4378. GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
  4379. // CreateOffer shouldn't really cause any state changes in
  4380. // PeerConnection, but we need a way to match new transceivers to new
  4381. // media sections in SetLocalDescription and JSEP specifies this is done
  4382. // by recording the index of the media section generated for the
  4383. // transceiver in the offer.
  4384. transceiver->internal()->set_mline_index(i);
  4385. }
  4386. } else {
  4387. RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
  4388. RTC_CHECK(GetDataMid());
  4389. if (had_been_rejected || mid != *GetDataMid()) {
  4390. session_options->media_description_options.push_back(
  4391. GetMediaDescriptionOptionsForRejectedData(mid));
  4392. } else {
  4393. session_options->media_description_options.push_back(
  4394. GetMediaDescriptionOptionsForActiveData(mid));
  4395. }
  4396. }
  4397. }
  4398. // Next, look for transceivers that are newly added (that is, are not stopped
  4399. // and not associated). Reuse media sections marked as recyclable first,
  4400. // otherwise append to the end of the offer. New media sections should be
  4401. // added in the order they were added to the PeerConnection.
  4402. for (const auto& transceiver : transceivers_) {
  4403. if (transceiver->mid() || transceiver->stopped()) {
  4404. continue;
  4405. }
  4406. size_t mline_index;
  4407. if (!recycleable_mline_indices.empty()) {
  4408. mline_index = recycleable_mline_indices.front();
  4409. recycleable_mline_indices.pop();
  4410. session_options->media_description_options[mline_index] =
  4411. GetMediaDescriptionOptionsForTransceiver(transceiver,
  4412. mid_generator_());
  4413. } else {
  4414. mline_index = session_options->media_description_options.size();
  4415. session_options->media_description_options.push_back(
  4416. GetMediaDescriptionOptionsForTransceiver(transceiver,
  4417. mid_generator_()));
  4418. }
  4419. // See comment above for why CreateOffer changes the transceiver's state.
  4420. transceiver->internal()->set_mline_index(mline_index);
  4421. }
  4422. // Lastly, add a m-section if we have local data channels and an m section
  4423. // does not already exist.
  4424. if (!GetDataMid() && HasDataChannels()) {
  4425. session_options->media_description_options.push_back(
  4426. GetMediaDescriptionOptionsForActiveData(mid_generator_()));
  4427. }
  4428. }
  4429. void PeerConnection::GetOptionsForAnswer(
  4430. const RTCOfferAnswerOptions& offer_answer_options,
  4431. cricket::MediaSessionOptions* session_options) {
  4432. ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
  4433. if (IsUnifiedPlan()) {
  4434. GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
  4435. } else {
  4436. GetOptionsForPlanBAnswer(offer_answer_options, session_options);
  4437. }
  4438. // Intentionally unset the data channel type for RTP data channel. Otherwise
  4439. // the RTP data channels would be successfully negotiated by default and the
  4440. // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
  4441. // We want to leave RTP data channels broken, so people won't try to use them.
  4442. if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
  4443. session_options->data_channel_type = data_channel_type();
  4444. }
  4445. // Apply ICE renomination flag.
  4446. for (auto& options : session_options->media_description_options) {
  4447. options.transport_options.enable_ice_renomination =
  4448. configuration_.enable_ice_renomination;
  4449. }
  4450. session_options->rtcp_cname = rtcp_cname_;
  4451. session_options->crypto_options = GetCryptoOptions();
  4452. session_options->pooled_ice_credentials =
  4453. network_thread()->Invoke<std::vector<cricket::IceParameters>>(
  4454. RTC_FROM_HERE,
  4455. rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
  4456. port_allocator_.get()));
  4457. // If datagram transport is in use, add opaque transport parameters.
  4458. if (use_datagram_transport_ || use_datagram_transport_for_data_channels_) {
  4459. for (auto& options : session_options->media_description_options) {
  4460. absl::optional<cricket::OpaqueTransportParameters> params =
  4461. transport_controller_->GetTransportParameters(options.mid);
  4462. if (!params) {
  4463. continue;
  4464. }
  4465. options.transport_options.opaque_parameters = params;
  4466. if ((use_datagram_transport_ &&
  4467. (options.type == cricket::MEDIA_TYPE_AUDIO ||
  4468. options.type == cricket::MEDIA_TYPE_VIDEO)) ||
  4469. (use_datagram_transport_for_data_channels_ &&
  4470. options.type == cricket::MEDIA_TYPE_DATA)) {
  4471. options.alt_protocol = params->protocol;
  4472. }
  4473. }
  4474. }
  4475. }
  4476. void PeerConnection::GetOptionsForPlanBAnswer(
  4477. const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
  4478. cricket::MediaSessionOptions* session_options) {
  4479. // Figure out transceiver directional preferences.
  4480. bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
  4481. bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
  4482. // By default, generate sendrecv/recvonly m= sections. The direction is also
  4483. // restricted by the direction in the offer.
  4484. bool recv_audio = true;
  4485. bool recv_video = true;
  4486. // The "offer_to_receive_X" options allow those defaults to be overridden.
  4487. if (offer_answer_options.offer_to_receive_audio !=
  4488. RTCOfferAnswerOptions::kUndefined) {
  4489. recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
  4490. }
  4491. if (offer_answer_options.offer_to_receive_video !=
  4492. RTCOfferAnswerOptions::kUndefined) {
  4493. recv_video = (offer_answer_options.offer_to_receive_video > 0);
  4494. }
  4495. absl::optional<size_t> audio_index;
  4496. absl::optional<size_t> video_index;
  4497. absl::optional<size_t> data_index;
  4498. // Generate m= sections that match those in the offer.
  4499. // Note that mediasession.cc will handle intersection our preferred
  4500. // direction with the offered direction.
  4501. GenerateMediaDescriptionOptions(
  4502. remote_description(),
  4503. RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
  4504. RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
  4505. &video_index, &data_index, session_options);
  4506. cricket::MediaDescriptionOptions* audio_media_description_options =
  4507. !audio_index ? nullptr
  4508. : &session_options->media_description_options[*audio_index];
  4509. cricket::MediaDescriptionOptions* video_media_description_options =
  4510. !video_index ? nullptr
  4511. : &session_options->media_description_options[*video_index];
  4512. AddPlanBRtpSenderOptions(GetSendersInternal(),
  4513. audio_media_description_options,
  4514. video_media_description_options,
  4515. offer_answer_options.num_simulcast_layers);
  4516. }
  4517. void PeerConnection::GetOptionsForUnifiedPlanAnswer(
  4518. const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
  4519. cricket::MediaSessionOptions* session_options) {
  4520. // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
  4521. // Answers) and 5.3.2 (Subsequent Answers).
  4522. RTC_DCHECK(remote_description());
  4523. RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
  4524. for (const ContentInfo& content :
  4525. remote_description()->description()->contents()) {
  4526. cricket::MediaType media_type = content.media_description()->type();
  4527. if (media_type == cricket::MEDIA_TYPE_AUDIO ||
  4528. media_type == cricket::MEDIA_TYPE_VIDEO) {
  4529. auto transceiver = GetAssociatedTransceiver(content.name);
  4530. RTC_CHECK(transceiver);
  4531. session_options->media_description_options.push_back(
  4532. GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
  4533. } else {
  4534. RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
  4535. // Reject all data sections if data channels are disabled.
  4536. // Reject a data section if it has already been rejected.
  4537. // Reject all data sections except for the first one.
  4538. if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
  4539. content.name != *GetDataMid()) {
  4540. session_options->media_description_options.push_back(
  4541. GetMediaDescriptionOptionsForRejectedData(content.name));
  4542. } else {
  4543. session_options->media_description_options.push_back(
  4544. GetMediaDescriptionOptionsForActiveData(content.name));
  4545. }
  4546. }
  4547. }
  4548. }
  4549. void PeerConnection::GenerateMediaDescriptionOptions(
  4550. const SessionDescriptionInterface* session_desc,
  4551. RtpTransceiverDirection audio_direction,
  4552. RtpTransceiverDirection video_direction,
  4553. absl::optional<size_t>* audio_index,
  4554. absl::optional<size_t>* video_index,
  4555. absl::optional<size_t>* data_index,
  4556. cricket::MediaSessionOptions* session_options) {
  4557. for (const cricket::ContentInfo& content :
  4558. session_desc->description()->contents()) {
  4559. if (IsAudioContent(&content)) {
  4560. // If we already have an audio m= section, reject this extra one.
  4561. if (*audio_index) {
  4562. session_options->media_description_options.push_back(
  4563. cricket::MediaDescriptionOptions(
  4564. cricket::MEDIA_TYPE_AUDIO, content.name,
  4565. RtpTransceiverDirection::kInactive, /*stopped=*/true));
  4566. } else {
  4567. bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
  4568. session_options->media_description_options.push_back(
  4569. cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
  4570. content.name, audio_direction,
  4571. stopped));
  4572. *audio_index = session_options->media_description_options.size() - 1;
  4573. }
  4574. } else if (IsVideoContent(&content)) {
  4575. // If we already have an video m= section, reject this extra one.
  4576. if (*video_index) {
  4577. session_options->media_description_options.push_back(
  4578. cricket::MediaDescriptionOptions(
  4579. cricket::MEDIA_TYPE_VIDEO, content.name,
  4580. RtpTransceiverDirection::kInactive, /*stopped=*/true));
  4581. } else {
  4582. bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
  4583. session_options->media_description_options.push_back(
  4584. cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
  4585. content.name, video_direction,
  4586. stopped));
  4587. *video_index = session_options->media_description_options.size() - 1;
  4588. }
  4589. } else {
  4590. RTC_DCHECK(IsDataContent(&content));
  4591. // If we already have an data m= section, reject this extra one.
  4592. if (*data_index) {
  4593. session_options->media_description_options.push_back(
  4594. GetMediaDescriptionOptionsForRejectedData(content.name));
  4595. } else {
  4596. session_options->media_description_options.push_back(
  4597. GetMediaDescriptionOptionsForActiveData(content.name));
  4598. *data_index = session_options->media_description_options.size() - 1;
  4599. }
  4600. }
  4601. }
  4602. }
  4603. cricket::MediaDescriptionOptions
  4604. PeerConnection::GetMediaDescriptionOptionsForActiveData(
  4605. const std::string& mid) const {
  4606. // Direction for data sections is meaningless, but legacy endpoints might
  4607. // expect sendrecv.
  4608. cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
  4609. RtpTransceiverDirection::kSendRecv,
  4610. /*stopped=*/false);
  4611. AddRtpDataChannelOptions(rtp_data_channels_, &options);
  4612. return options;
  4613. }
  4614. cricket::MediaDescriptionOptions
  4615. PeerConnection::GetMediaDescriptionOptionsForRejectedData(
  4616. const std::string& mid) const {
  4617. cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
  4618. RtpTransceiverDirection::kInactive,
  4619. /*stopped=*/true);
  4620. AddRtpDataChannelOptions(rtp_data_channels_, &options);
  4621. return options;
  4622. }
  4623. absl::optional<std::string> PeerConnection::GetDataMid() const {
  4624. switch (data_channel_type_) {
  4625. case cricket::DCT_RTP:
  4626. if (!rtp_data_channel_) {
  4627. return absl::nullopt;
  4628. }
  4629. return rtp_data_channel_->content_name();
  4630. case cricket::DCT_SCTP:
  4631. case cricket::DCT_MEDIA_TRANSPORT:
  4632. case cricket::DCT_DATA_CHANNEL_TRANSPORT:
  4633. case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
  4634. return sctp_mid_;
  4635. default:
  4636. return absl::nullopt;
  4637. }
  4638. }
  4639. void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
  4640. UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
  4641. UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
  4642. media_type, nullptr);
  4643. }
  4644. void PeerConnection::UpdateRemoteSendersList(
  4645. const cricket::StreamParamsVec& streams,
  4646. bool default_sender_needed,
  4647. cricket::MediaType media_type,
  4648. StreamCollection* new_streams) {
  4649. RTC_DCHECK(!IsUnifiedPlan());
  4650. std::vector<RtpSenderInfo>* current_senders =
  4651. GetRemoteSenderInfos(media_type);
  4652. // Find removed senders. I.e., senders where the sender id or ssrc don't match
  4653. // the new StreamParam.
  4654. for (auto sender_it = current_senders->begin();
  4655. sender_it != current_senders->end();
  4656. /* incremented manually */) {
  4657. const RtpSenderInfo& info = *sender_it;
  4658. const cricket::StreamParams* params =
  4659. cricket::GetStreamBySsrc(streams, info.first_ssrc);
  4660. std::string params_stream_id;
  4661. if (params) {
  4662. params_stream_id =
  4663. (!params->first_stream_id().empty() ? params->first_stream_id()
  4664. : kDefaultStreamId);
  4665. }
  4666. bool sender_exists = params && params->id == info.sender_id &&
  4667. params_stream_id == info.stream_id;
  4668. // If this is a default track, and we still need it, don't remove it.
  4669. if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
  4670. sender_exists) {
  4671. ++sender_it;
  4672. } else {
  4673. OnRemoteSenderRemoved(info, media_type);
  4674. sender_it = current_senders->erase(sender_it);
  4675. }
  4676. }
  4677. // Find new and active senders.
  4678. for (const cricket::StreamParams& params : streams) {
  4679. if (!params.has_ssrcs()) {
  4680. // The remote endpoint has streams, but didn't signal ssrcs. For an active
  4681. // sender, this means it is coming from a Unified Plan endpoint,so we just
  4682. // create a default.
  4683. default_sender_needed = true;
  4684. break;
  4685. }
  4686. // |params.id| is the sender id and the stream id uses the first of
  4687. // |params.stream_ids|. The remote description could come from a Unified
  4688. // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
  4689. // not supported in Plan B, we just take the first here and create the
  4690. // default stream ID if none is specified.
  4691. const std::string& stream_id =
  4692. (!params.first_stream_id().empty() ? params.first_stream_id()
  4693. : kDefaultStreamId);
  4694. const std::string& sender_id = params.id;
  4695. uint32_t ssrc = params.first_ssrc();
  4696. rtc::scoped_refptr<MediaStreamInterface> stream =
  4697. remote_streams_->find(stream_id);
  4698. if (!stream) {
  4699. // This is a new MediaStream. Create a new remote MediaStream.
  4700. stream = MediaStreamProxy::Create(rtc::Thread::Current(),
  4701. MediaStream::Create(stream_id));
  4702. remote_streams_->AddStream(stream);
  4703. new_streams->AddStream(stream);
  4704. }
  4705. const RtpSenderInfo* sender_info =
  4706. FindSenderInfo(*current_senders, stream_id, sender_id);
  4707. if (!sender_info) {
  4708. current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
  4709. OnRemoteSenderAdded(current_senders->back(), media_type);
  4710. }
  4711. }
  4712. // Add default sender if necessary.
  4713. if (default_sender_needed) {
  4714. rtc::scoped_refptr<MediaStreamInterface> default_stream =
  4715. remote_streams_->find(kDefaultStreamId);
  4716. if (!default_stream) {
  4717. // Create the new default MediaStream.
  4718. default_stream = MediaStreamProxy::Create(
  4719. rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
  4720. remote_streams_->AddStream(default_stream);
  4721. new_streams->AddStream(default_stream);
  4722. }
  4723. std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
  4724. ? kDefaultAudioSenderId
  4725. : kDefaultVideoSenderId;
  4726. const RtpSenderInfo* default_sender_info =
  4727. FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
  4728. if (!default_sender_info) {
  4729. current_senders->push_back(
  4730. RtpSenderInfo(kDefaultStreamId, default_sender_id, /*ssrc=*/0));
  4731. OnRemoteSenderAdded(current_senders->back(), media_type);
  4732. }
  4733. }
  4734. }
  4735. void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
  4736. cricket::MediaType media_type) {
  4737. RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
  4738. << " receiver for track_id=" << sender_info.sender_id
  4739. << " and stream_id=" << sender_info.stream_id;
  4740. MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
  4741. if (media_type == cricket::MEDIA_TYPE_AUDIO) {
  4742. CreateAudioReceiver(stream, sender_info);
  4743. } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
  4744. CreateVideoReceiver(stream, sender_info);
  4745. } else {
  4746. RTC_NOTREACHED() << "Invalid media type";
  4747. }
  4748. }
  4749. void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
  4750. cricket::MediaType media_type) {
  4751. RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
  4752. << " receiver for track_id=" << sender_info.sender_id
  4753. << " and stream_id=" << sender_info.stream_id;
  4754. MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
  4755. rtc::scoped_refptr<RtpReceiverInterface> receiver;
  4756. if (media_type == cricket::MEDIA_TYPE_AUDIO) {
  4757. // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
  4758. // will be notified which will end the AudioRtpReceiver::track().
  4759. receiver = RemoveAndStopReceiver(sender_info);
  4760. rtc::scoped_refptr<AudioTrackInterface> audio_track =
  4761. stream->FindAudioTrack(sender_info.sender_id);
  4762. if (audio_track) {
  4763. stream->RemoveTrack(audio_track);
  4764. }
  4765. } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
  4766. // Stopping or destroying a VideoRtpReceiver will end the
  4767. // VideoRtpReceiver::track().
  4768. receiver = RemoveAndStopReceiver(sender_info);
  4769. rtc::scoped_refptr<VideoTrackInterface> video_track =
  4770. stream->FindVideoTrack(sender_info.sender_id);
  4771. if (video_track) {
  4772. // There's no guarantee the track is still available, e.g. the track may
  4773. // have been removed from the stream by an application.
  4774. stream->RemoveTrack(video_track);
  4775. }
  4776. } else {
  4777. RTC_NOTREACHED() << "Invalid media type";
  4778. }
  4779. if (receiver) {
  4780. Observer()->OnRemoveTrack(receiver);
  4781. }
  4782. }
  4783. void PeerConnection::UpdateEndedRemoteMediaStreams() {
  4784. std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
  4785. for (size_t i = 0; i < remote_streams_->count(); ++i) {
  4786. MediaStreamInterface* stream = remote_streams_->at(i);
  4787. if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
  4788. streams_to_remove.push_back(stream);
  4789. }
  4790. }
  4791. for (auto& stream : streams_to_remove) {
  4792. remote_streams_->RemoveStream(stream);
  4793. Observer()->OnRemoveStream(std::move(stream));
  4794. }
  4795. }
  4796. void PeerConnection::UpdateLocalSenders(
  4797. const std::vector<cricket::StreamParams>& streams,
  4798. cricket::MediaType media_type) {
  4799. std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
  4800. // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
  4801. // don't match the new StreamParam.
  4802. for (auto sender_it = current_senders->begin();
  4803. sender_it != current_senders->end();
  4804. /* incremented manually */) {
  4805. const RtpSenderInfo& info = *sender_it;
  4806. const cricket::StreamParams* params =
  4807. cricket::GetStreamBySsrc(streams, info.first_ssrc);
  4808. if (!params || params->id != info.sender_id ||
  4809. params->first_stream_id() != info.stream_id) {
  4810. OnLocalSenderRemoved(info, media_type);
  4811. sender_it = current_senders->erase(sender_it);
  4812. } else {
  4813. ++sender_it;
  4814. }
  4815. }
  4816. // Find new and active senders.
  4817. for (const cricket::StreamParams& params : streams) {
  4818. // The sync_label is the MediaStream label and the |stream.id| is the
  4819. // sender id.
  4820. const std::string& stream_id = params.first_stream_id();
  4821. const std::string& sender_id = params.id;
  4822. uint32_t ssrc = params.first_ssrc();
  4823. const RtpSenderInfo* sender_info =
  4824. FindSenderInfo(*current_senders, stream_id, sender_id);
  4825. if (!sender_info) {
  4826. current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
  4827. OnLocalSenderAdded(current_senders->back(), media_type);
  4828. }
  4829. }
  4830. }
  4831. void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
  4832. cricket::MediaType media_type) {
  4833. RTC_DCHECK(!IsUnifiedPlan());
  4834. auto sender = FindSenderById(sender_info.sender_id);
  4835. if (!sender) {
  4836. RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
  4837. << sender_info.sender_id
  4838. << " has been configured in the local description.";
  4839. return;
  4840. }
  4841. if (sender->media_type() != media_type) {
  4842. RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
  4843. " description with an unexpected media type.";
  4844. return;
  4845. }
  4846. sender->internal()->set_stream_ids({sender_info.stream_id});
  4847. sender->internal()->SetSsrc(sender_info.first_ssrc);
  4848. }
  4849. void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
  4850. cricket::MediaType media_type) {
  4851. auto sender = FindSenderById(sender_info.sender_id);
  4852. if (!sender) {
  4853. // This is the normal case. I.e., RemoveStream has been called and the
  4854. // SessionDescriptions has been renegotiated.
  4855. return;
  4856. }
  4857. // A sender has been removed from the SessionDescription but it's still
  4858. // associated with the PeerConnection. This only occurs if the SDP doesn't
  4859. // match with the calls to CreateSender, AddStream and RemoveStream.
  4860. if (sender->media_type() != media_type) {
  4861. RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
  4862. " description with an unexpected media type.";
  4863. return;
  4864. }
  4865. sender->internal()->SetSsrc(0);
  4866. }
  4867. void PeerConnection::UpdateLocalRtpDataChannels(
  4868. const cricket::StreamParamsVec& streams) {
  4869. std::vector<std::string> existing_channels;
  4870. // Find new and active data channels.
  4871. for (const cricket::StreamParams& params : streams) {
  4872. // |it->sync_label| is actually the data channel label. The reason is that
  4873. // we use the same naming of data channels as we do for
  4874. // MediaStreams and Tracks.
  4875. // For MediaStreams, the sync_label is the MediaStream label and the
  4876. // track label is the same as |streamid|.
  4877. const std::string& channel_label = params.first_stream_id();
  4878. auto data_channel_it = rtp_data_channels_.find(channel_label);
  4879. if (data_channel_it == rtp_data_channels_.end()) {
  4880. RTC_LOG(LS_ERROR) << "channel label not found";
  4881. continue;
  4882. }
  4883. // Set the SSRC the data channel should use for sending.
  4884. data_channel_it->second->SetSendSsrc(params.first_ssrc());
  4885. existing_channels.push_back(data_channel_it->first);
  4886. }
  4887. UpdateClosingRtpDataChannels(existing_channels, true);
  4888. }
  4889. void PeerConnection::UpdateRemoteRtpDataChannels(
  4890. const cricket::StreamParamsVec& streams) {
  4891. std::vector<std::string> existing_channels;
  4892. // Find new and active data channels.
  4893. for (const cricket::StreamParams& params : streams) {
  4894. // The data channel label is either the mslabel or the SSRC if the mslabel
  4895. // does not exist. Ex a=ssrc:444330170 mslabel:test1.
  4896. std::string label = params.first_stream_id().empty()
  4897. ? rtc::ToString(params.first_ssrc())
  4898. : params.first_stream_id();
  4899. auto data_channel_it = rtp_data_channels_.find(label);
  4900. if (data_channel_it == rtp_data_channels_.end()) {
  4901. // This is a new data channel.
  4902. CreateRemoteRtpDataChannel(label, params.first_ssrc());
  4903. } else {
  4904. data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
  4905. }
  4906. existing_channels.push_back(label);
  4907. }
  4908. UpdateClosingRtpDataChannels(existing_channels, false);
  4909. }
  4910. void PeerConnection::UpdateClosingRtpDataChannels(
  4911. const std::vector<std::string>& active_channels,
  4912. bool is_local_update) {
  4913. auto it = rtp_data_channels_.begin();
  4914. while (it != rtp_data_channels_.end()) {
  4915. DataChannel* data_channel = it->second;
  4916. if (absl::c_linear_search(active_channels, data_channel->label())) {
  4917. ++it;
  4918. continue;
  4919. }
  4920. if (is_local_update) {
  4921. data_channel->SetSendSsrc(0);
  4922. } else {
  4923. data_channel->RemotePeerRequestClose();
  4924. }
  4925. if (data_channel->state() == DataChannel::kClosed) {
  4926. rtp_data_channels_.erase(it);
  4927. it = rtp_data_channels_.begin();
  4928. } else {
  4929. ++it;
  4930. }
  4931. }
  4932. }
  4933. void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
  4934. uint32_t remote_ssrc) {
  4935. rtc::scoped_refptr<DataChannel> channel(
  4936. InternalCreateDataChannel(label, nullptr));
  4937. if (!channel.get()) {
  4938. RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
  4939. "CreateDataChannel failed.";
  4940. return;
  4941. }
  4942. channel->SetReceiveSsrc(remote_ssrc);
  4943. rtc::scoped_refptr<DataChannelInterface> proxy_channel =
  4944. DataChannelProxy::Create(signaling_thread(), channel);
  4945. Observer()->OnDataChannel(std::move(proxy_channel));
  4946. }
  4947. rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
  4948. const std::string& label,
  4949. const InternalDataChannelInit* config) {
  4950. if (IsClosed()) {
  4951. return nullptr;
  4952. }
  4953. if (data_channel_type() == cricket::DCT_NONE) {
  4954. RTC_LOG(LS_ERROR)
  4955. << "InternalCreateDataChannel: Data is not supported in this call.";
  4956. return nullptr;
  4957. }
  4958. InternalDataChannelInit new_config =
  4959. config ? (*config) : InternalDataChannelInit();
  4960. if (DataChannel::IsSctpLike(data_channel_type_)) {
  4961. if (new_config.id < 0) {
  4962. rtc::SSLRole role;
  4963. if ((GetSctpSslRole(&role)) &&
  4964. !sid_allocator_.AllocateSid(role, &new_config.id)) {
  4965. RTC_LOG(LS_ERROR)
  4966. << "No id can be allocated for the SCTP data channel.";
  4967. return nullptr;
  4968. }
  4969. } else if (!sid_allocator_.ReserveSid(new_config.id)) {
  4970. RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
  4971. "because the id is already in use or out of range.";
  4972. return nullptr;
  4973. }
  4974. }
  4975. rtc::scoped_refptr<DataChannel> channel(
  4976. DataChannel::Create(this, data_channel_type(), label, new_config));
  4977. if (!channel) {
  4978. sid_allocator_.ReleaseSid(new_config.id);
  4979. return nullptr;
  4980. }
  4981. if (channel->data_channel_type() == cricket::DCT_RTP) {
  4982. if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
  4983. RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
  4984. << " already exists.";
  4985. return nullptr;
  4986. }
  4987. rtp_data_channels_[channel->label()] = channel;
  4988. } else {
  4989. RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
  4990. sctp_data_channels_.push_back(channel);
  4991. channel->SignalClosed.connect(this,
  4992. &PeerConnection::OnSctpDataChannelClosed);
  4993. }
  4994. SignalDataChannelCreated_(channel.get());
  4995. return channel;
  4996. }
  4997. bool PeerConnection::HasDataChannels() const {
  4998. return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
  4999. }
  5000. void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
  5001. std::vector<rtc::scoped_refptr<DataChannel>> channels_to_close;
  5002. for (const auto& channel : sctp_data_channels_) {
  5003. if (channel->id() < 0) {
  5004. int sid;
  5005. if (!sid_allocator_.AllocateSid(role, &sid)) {
  5006. RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid, closing channel.";
  5007. channels_to_close.push_back(channel);
  5008. continue;
  5009. }
  5010. channel->SetSctpSid(sid);
  5011. }
  5012. }
  5013. // Since closing modifies the list of channels, we have to do the actual
  5014. // closing outside the loop.
  5015. for (const auto& channel : channels_to_close) {
  5016. channel->CloseAbruptly();
  5017. }
  5018. }
  5019. void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
  5020. RTC_DCHECK(signaling_thread()->IsCurrent());
  5021. for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
  5022. ++it) {
  5023. if (it->get() == channel) {
  5024. if (channel->id() >= 0) {
  5025. // After the closing procedure is done, it's safe to use this ID for
  5026. // another data channel.
  5027. sid_allocator_.ReleaseSid(channel->id());
  5028. }
  5029. // Since this method is triggered by a signal from the DataChannel,
  5030. // we can't free it directly here; we need to free it asynchronously.
  5031. sctp_data_channels_to_free_.push_back(*it);
  5032. sctp_data_channels_.erase(it);
  5033. signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
  5034. nullptr);
  5035. return;
  5036. }
  5037. }
  5038. }
  5039. void PeerConnection::OnDataChannelDestroyed() {
  5040. // Use a temporary copy of the RTP/SCTP DataChannel list because the
  5041. // DataChannel may callback to us and try to modify the list.
  5042. std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
  5043. temp_rtp_dcs.swap(rtp_data_channels_);
  5044. for (const auto& kv : temp_rtp_dcs) {
  5045. kv.second->OnTransportChannelDestroyed();
  5046. }
  5047. std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
  5048. temp_sctp_dcs.swap(sctp_data_channels_);
  5049. for (const auto& channel : temp_sctp_dcs) {
  5050. channel->OnTransportChannelDestroyed();
  5051. }
  5052. }
  5053. void PeerConnection::OnDataChannelOpenMessage(
  5054. const std::string& label,
  5055. const InternalDataChannelInit& config) {
  5056. rtc::scoped_refptr<DataChannel> channel(
  5057. InternalCreateDataChannel(label, &config));
  5058. if (!channel.get()) {
  5059. RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
  5060. return;
  5061. }
  5062. rtc::scoped_refptr<DataChannelInterface> proxy_channel =
  5063. DataChannelProxy::Create(signaling_thread(), channel);
  5064. Observer()->OnDataChannel(std::move(proxy_channel));
  5065. NoteUsageEvent(UsageEvent::DATA_ADDED);
  5066. }
  5067. bool PeerConnection::HandleOpenMessage_s(
  5068. const cricket::ReceiveDataParams& params,
  5069. const rtc::CopyOnWriteBuffer& buffer) {
  5070. if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
  5071. // Received OPEN message; parse and signal that a new data channel should
  5072. // be created.
  5073. std::string label;
  5074. InternalDataChannelInit config;
  5075. config.id = params.ssrc;
  5076. if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
  5077. RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
  5078. << params.ssrc;
  5079. return true;
  5080. }
  5081. config.open_handshake_role = InternalDataChannelInit::kAcker;
  5082. OnDataChannelOpenMessage(label, config);
  5083. return true;
  5084. }
  5085. return false;
  5086. }
  5087. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  5088. PeerConnection::GetAudioTransceiver() const {
  5089. // This method only works with Plan B SDP, where there is a single
  5090. // audio/video transceiver.
  5091. RTC_DCHECK(!IsUnifiedPlan());
  5092. for (auto transceiver : transceivers_) {
  5093. if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
  5094. return transceiver;
  5095. }
  5096. }
  5097. RTC_NOTREACHED();
  5098. return nullptr;
  5099. }
  5100. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  5101. PeerConnection::GetVideoTransceiver() const {
  5102. // This method only works with Plan B SDP, where there is a single
  5103. // audio/video transceiver.
  5104. RTC_DCHECK(!IsUnifiedPlan());
  5105. for (auto transceiver : transceivers_) {
  5106. if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
  5107. return transceiver;
  5108. }
  5109. }
  5110. RTC_NOTREACHED();
  5111. return nullptr;
  5112. }
  5113. // TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
  5114. // individual transceiver directions are supported.
  5115. bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
  5116. switch (type) {
  5117. case cricket::MEDIA_TYPE_AUDIO:
  5118. return !GetAudioTransceiver()->internal()->senders().empty();
  5119. case cricket::MEDIA_TYPE_VIDEO:
  5120. return !GetVideoTransceiver()->internal()->senders().empty();
  5121. case cricket::MEDIA_TYPE_DATA:
  5122. return false;
  5123. }
  5124. RTC_NOTREACHED();
  5125. return false;
  5126. }
  5127. rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
  5128. PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
  5129. for (const auto& transceiver : transceivers_) {
  5130. for (auto sender : transceiver->internal()->senders()) {
  5131. if (sender->track() == track) {
  5132. return sender;
  5133. }
  5134. }
  5135. }
  5136. return nullptr;
  5137. }
  5138. rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
  5139. PeerConnection::FindSenderById(const std::string& sender_id) const {
  5140. for (const auto& transceiver : transceivers_) {
  5141. for (auto sender : transceiver->internal()->senders()) {
  5142. if (sender->id() == sender_id) {
  5143. return sender;
  5144. }
  5145. }
  5146. }
  5147. return nullptr;
  5148. }
  5149. rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
  5150. PeerConnection::FindReceiverById(const std::string& receiver_id) const {
  5151. for (const auto& transceiver : transceivers_) {
  5152. for (auto receiver : transceiver->internal()->receivers()) {
  5153. if (receiver->id() == receiver_id) {
  5154. return receiver;
  5155. }
  5156. }
  5157. }
  5158. return nullptr;
  5159. }
  5160. std::vector<PeerConnection::RtpSenderInfo>*
  5161. PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
  5162. RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
  5163. media_type == cricket::MEDIA_TYPE_VIDEO);
  5164. return (media_type == cricket::MEDIA_TYPE_AUDIO)
  5165. ? &remote_audio_sender_infos_
  5166. : &remote_video_sender_infos_;
  5167. }
  5168. std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
  5169. cricket::MediaType media_type) {
  5170. RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
  5171. media_type == cricket::MEDIA_TYPE_VIDEO);
  5172. return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
  5173. : &local_video_sender_infos_;
  5174. }
  5175. const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
  5176. const std::vector<PeerConnection::RtpSenderInfo>& infos,
  5177. const std::string& stream_id,
  5178. const std::string sender_id) const {
  5179. for (const RtpSenderInfo& sender_info : infos) {
  5180. if (sender_info.stream_id == stream_id &&
  5181. sender_info.sender_id == sender_id) {
  5182. return &sender_info;
  5183. }
  5184. }
  5185. return nullptr;
  5186. }
  5187. DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
  5188. for (const auto& channel : sctp_data_channels_) {
  5189. if (channel->id() == sid) {
  5190. return channel;
  5191. }
  5192. }
  5193. return nullptr;
  5194. }
  5195. PeerConnection::InitializePortAllocatorResult
  5196. PeerConnection::InitializePortAllocator_n(
  5197. const cricket::ServerAddresses& stun_servers,
  5198. const std::vector<cricket::RelayServerConfig>& turn_servers,
  5199. const RTCConfiguration& configuration) {
  5200. RTC_DCHECK_RUN_ON(network_thread());
  5201. port_allocator_->Initialize();
  5202. // To handle both internal and externally created port allocator, we will
  5203. // enable BUNDLE here.
  5204. int port_allocator_flags = port_allocator_->flags();
  5205. port_allocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
  5206. cricket::PORTALLOCATOR_ENABLE_IPV6 |
  5207. cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
  5208. // If the disable-IPv6 flag was specified, we'll not override it
  5209. // by experiment.
  5210. if (configuration.disable_ipv6) {
  5211. port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
  5212. } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
  5213. .find("Disabled") == 0) {
  5214. port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
  5215. }
  5216. if (configuration.disable_ipv6_on_wifi) {
  5217. port_allocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
  5218. RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
  5219. }
  5220. if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
  5221. port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
  5222. RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
  5223. }
  5224. if (configuration.candidate_network_policy ==
  5225. kCandidateNetworkPolicyLowCost) {
  5226. port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
  5227. RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
  5228. }
  5229. if (configuration.disable_link_local_networks) {
  5230. port_allocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
  5231. RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
  5232. }
  5233. port_allocator_->set_flags(port_allocator_flags);
  5234. // No step delay is used while allocating ports.
  5235. port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
  5236. port_allocator_->SetCandidateFilter(
  5237. ConvertIceTransportTypeToCandidateFilter(configuration.type));
  5238. port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
  5239. auto turn_servers_copy = turn_servers;
  5240. for (auto& turn_server : turn_servers_copy) {
  5241. turn_server.tls_cert_verifier = tls_cert_verifier_.get();
  5242. }
  5243. // Call this last since it may create pooled allocator sessions using the
  5244. // properties set above.
  5245. port_allocator_->SetConfiguration(
  5246. stun_servers, std::move(turn_servers_copy),
  5247. configuration.ice_candidate_pool_size,
  5248. configuration.GetTurnPortPrunePolicy(), configuration.turn_customizer,
  5249. configuration.stun_candidate_keepalive_interval);
  5250. InitializePortAllocatorResult res;
  5251. res.enable_ipv6 = port_allocator_flags & cricket::PORTALLOCATOR_ENABLE_IPV6;
  5252. return res;
  5253. }
  5254. bool PeerConnection::ReconfigurePortAllocator_n(
  5255. const cricket::ServerAddresses& stun_servers,
  5256. const std::vector<cricket::RelayServerConfig>& turn_servers,
  5257. IceTransportsType type,
  5258. int candidate_pool_size,
  5259. PortPrunePolicy turn_port_prune_policy,
  5260. webrtc::TurnCustomizer* turn_customizer,
  5261. absl::optional<int> stun_candidate_keepalive_interval,
  5262. bool have_local_description) {
  5263. port_allocator_->SetCandidateFilter(
  5264. ConvertIceTransportTypeToCandidateFilter(type));
  5265. // According to JSEP, after setLocalDescription, changing the candidate pool
  5266. // size is not allowed, and changing the set of ICE servers will not result
  5267. // in new candidates being gathered.
  5268. if (have_local_description) {
  5269. port_allocator_->FreezeCandidatePool();
  5270. }
  5271. // Add the custom tls turn servers if they exist.
  5272. auto turn_servers_copy = turn_servers;
  5273. for (auto& turn_server : turn_servers_copy) {
  5274. turn_server.tls_cert_verifier = tls_cert_verifier_.get();
  5275. }
  5276. // Call this last since it may create pooled allocator sessions using the
  5277. // candidate filter set above.
  5278. return port_allocator_->SetConfiguration(
  5279. stun_servers, std::move(turn_servers_copy), candidate_pool_size,
  5280. turn_port_prune_policy, turn_customizer,
  5281. stun_candidate_keepalive_interval);
  5282. }
  5283. cricket::ChannelManager* PeerConnection::channel_manager() const {
  5284. return factory_->channel_manager();
  5285. }
  5286. bool PeerConnection::StartRtcEventLog_w(
  5287. std::unique_ptr<RtcEventLogOutput> output,
  5288. int64_t output_period_ms) {
  5289. RTC_DCHECK_RUN_ON(worker_thread());
  5290. if (!event_log_) {
  5291. return false;
  5292. }
  5293. return event_log_->StartLogging(std::move(output), output_period_ms);
  5294. }
  5295. void PeerConnection::StopRtcEventLog_w() {
  5296. RTC_DCHECK_RUN_ON(worker_thread());
  5297. if (event_log_) {
  5298. event_log_->StopLogging();
  5299. }
  5300. }
  5301. cricket::ChannelInterface* PeerConnection::GetChannel(
  5302. const std::string& content_name) {
  5303. for (const auto& transceiver : transceivers_) {
  5304. cricket::ChannelInterface* channel = transceiver->internal()->channel();
  5305. if (channel && channel->content_name() == content_name) {
  5306. return channel;
  5307. }
  5308. }
  5309. if (rtp_data_channel() &&
  5310. rtp_data_channel()->content_name() == content_name) {
  5311. return rtp_data_channel();
  5312. }
  5313. return nullptr;
  5314. }
  5315. bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
  5316. RTC_DCHECK_RUN_ON(signaling_thread());
  5317. if (!local_description() || !remote_description()) {
  5318. RTC_LOG(LS_INFO)
  5319. << "Local and Remote descriptions must be applied to get the "
  5320. "SSL Role of the SCTP transport.";
  5321. return false;
  5322. }
  5323. if (!data_channel_transport_) {
  5324. RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
  5325. "SSL Role of the SCTP transport.";
  5326. return false;
  5327. }
  5328. absl::optional<rtc::SSLRole> dtls_role;
  5329. if (sctp_mid_) {
  5330. dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
  5331. if (!dtls_role && is_caller_.has_value()) {
  5332. dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
  5333. }
  5334. *role = *dtls_role;
  5335. return true;
  5336. }
  5337. return false;
  5338. }
  5339. bool PeerConnection::GetSslRole(const std::string& content_name,
  5340. rtc::SSLRole* role) {
  5341. RTC_DCHECK_RUN_ON(signaling_thread());
  5342. if (!local_description() || !remote_description()) {
  5343. RTC_LOG(LS_INFO)
  5344. << "Local and Remote descriptions must be applied to get the "
  5345. "SSL Role of the session.";
  5346. return false;
  5347. }
  5348. auto dtls_role = transport_controller_->GetDtlsRole(content_name);
  5349. if (dtls_role) {
  5350. *role = *dtls_role;
  5351. return true;
  5352. }
  5353. return false;
  5354. }
  5355. void PeerConnection::SetSessionError(SessionError error,
  5356. const std::string& error_desc) {
  5357. RTC_DCHECK_RUN_ON(signaling_thread());
  5358. if (error != session_error_) {
  5359. session_error_ = error;
  5360. session_error_desc_ = error_desc;
  5361. }
  5362. }
  5363. RTCError PeerConnection::UpdateSessionState(
  5364. SdpType type,
  5365. cricket::ContentSource source,
  5366. const cricket::SessionDescription* description) {
  5367. RTC_DCHECK_RUN_ON(signaling_thread());
  5368. // If there's already a pending error then no state transition should happen.
  5369. // But all call-sites should be verifying this before calling us!
  5370. RTC_DCHECK(session_error() == SessionError::kNone);
  5371. // If this is answer-ish we're ready to let media flow.
  5372. if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
  5373. EnableSending();
  5374. }
  5375. // Update the signaling state according to the specified state machine (see
  5376. // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
  5377. if (type == SdpType::kOffer) {
  5378. ChangeSignalingState(source == cricket::CS_LOCAL
  5379. ? PeerConnectionInterface::kHaveLocalOffer
  5380. : PeerConnectionInterface::kHaveRemoteOffer);
  5381. } else if (type == SdpType::kPrAnswer) {
  5382. ChangeSignalingState(source == cricket::CS_LOCAL
  5383. ? PeerConnectionInterface::kHaveLocalPrAnswer
  5384. : PeerConnectionInterface::kHaveRemotePrAnswer);
  5385. } else {
  5386. RTC_DCHECK(type == SdpType::kAnswer);
  5387. ChangeSignalingState(PeerConnectionInterface::kStable);
  5388. transceiver_stable_states_by_transceivers_.clear();
  5389. }
  5390. // Update internal objects according to the session description's media
  5391. // descriptions.
  5392. RTCError error = PushdownMediaDescription(type, source);
  5393. if (!error.ok()) {
  5394. return error;
  5395. }
  5396. return RTCError::OK();
  5397. }
  5398. RTCError PeerConnection::PushdownMediaDescription(
  5399. SdpType type,
  5400. cricket::ContentSource source) {
  5401. const SessionDescriptionInterface* sdesc =
  5402. (source == cricket::CS_LOCAL ? local_description()
  5403. : remote_description());
  5404. RTC_DCHECK(sdesc);
  5405. // Push down the new SDP media section for each audio/video transceiver.
  5406. for (const auto& transceiver : transceivers_) {
  5407. const ContentInfo* content_info =
  5408. FindMediaSectionForTransceiver(transceiver, sdesc);
  5409. cricket::ChannelInterface* channel = transceiver->internal()->channel();
  5410. if (!channel || !content_info || content_info->rejected) {
  5411. continue;
  5412. }
  5413. const MediaContentDescription* content_desc =
  5414. content_info->media_description();
  5415. if (!content_desc) {
  5416. continue;
  5417. }
  5418. std::string error;
  5419. bool success = (source == cricket::CS_LOCAL)
  5420. ? channel->SetLocalContent(content_desc, type, &error)
  5421. : channel->SetRemoteContent(content_desc, type, &error);
  5422. if (!success) {
  5423. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
  5424. }
  5425. }
  5426. // If using the RtpDataChannel, push down the new SDP section for it too.
  5427. if (rtp_data_channel_) {
  5428. const ContentInfo* data_content =
  5429. cricket::GetFirstDataContent(sdesc->description());
  5430. if (data_content && !data_content->rejected) {
  5431. const MediaContentDescription* data_desc =
  5432. data_content->media_description();
  5433. if (data_desc) {
  5434. std::string error;
  5435. bool success =
  5436. (source == cricket::CS_LOCAL)
  5437. ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
  5438. : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
  5439. if (!success) {
  5440. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, error);
  5441. }
  5442. }
  5443. }
  5444. }
  5445. // Need complete offer/answer with an SCTP m= section before starting SCTP,
  5446. // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
  5447. if (sctp_mid_ && local_description() && remote_description()) {
  5448. rtc::scoped_refptr<SctpTransport> sctp_transport =
  5449. transport_controller_->GetSctpTransport(*sctp_mid_);
  5450. auto local_sctp_description = cricket::GetFirstSctpDataContentDescription(
  5451. local_description()->description());
  5452. auto remote_sctp_description = cricket::GetFirstSctpDataContentDescription(
  5453. remote_description()->description());
  5454. if (sctp_transport && local_sctp_description && remote_sctp_description) {
  5455. int max_message_size;
  5456. // A remote max message size of zero means "any size supported".
  5457. // We configure the connection with our own max message size.
  5458. if (remote_sctp_description->max_message_size() == 0) {
  5459. max_message_size = local_sctp_description->max_message_size();
  5460. } else {
  5461. max_message_size =
  5462. std::min(local_sctp_description->max_message_size(),
  5463. remote_sctp_description->max_message_size());
  5464. }
  5465. sctp_transport->Start(local_sctp_description->port(),
  5466. remote_sctp_description->port(), max_message_size);
  5467. }
  5468. }
  5469. return RTCError::OK();
  5470. }
  5471. RTCError PeerConnection::PushdownTransportDescription(
  5472. cricket::ContentSource source,
  5473. SdpType type) {
  5474. RTC_DCHECK_RUN_ON(signaling_thread());
  5475. if (source == cricket::CS_LOCAL) {
  5476. const SessionDescriptionInterface* sdesc = local_description();
  5477. RTC_DCHECK(sdesc);
  5478. return transport_controller_->SetLocalDescription(type,
  5479. sdesc->description());
  5480. } else {
  5481. const SessionDescriptionInterface* sdesc = remote_description();
  5482. RTC_DCHECK(sdesc);
  5483. return transport_controller_->SetRemoteDescription(type,
  5484. sdesc->description());
  5485. }
  5486. }
  5487. bool PeerConnection::GetTransportDescription(
  5488. const SessionDescription* description,
  5489. const std::string& content_name,
  5490. cricket::TransportDescription* tdesc) {
  5491. if (!description || !tdesc) {
  5492. return false;
  5493. }
  5494. const TransportInfo* transport_info =
  5495. description->GetTransportInfoByName(content_name);
  5496. if (!transport_info) {
  5497. return false;
  5498. }
  5499. *tdesc = transport_info->description;
  5500. return true;
  5501. }
  5502. cricket::IceConfig PeerConnection::ParseIceConfig(
  5503. const PeerConnectionInterface::RTCConfiguration& config) const {
  5504. cricket::ContinualGatheringPolicy gathering_policy;
  5505. switch (config.continual_gathering_policy) {
  5506. case PeerConnectionInterface::GATHER_ONCE:
  5507. gathering_policy = cricket::GATHER_ONCE;
  5508. break;
  5509. case PeerConnectionInterface::GATHER_CONTINUALLY:
  5510. gathering_policy = cricket::GATHER_CONTINUALLY;
  5511. break;
  5512. default:
  5513. RTC_NOTREACHED();
  5514. gathering_policy = cricket::GATHER_ONCE;
  5515. }
  5516. cricket::IceConfig ice_config;
  5517. ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
  5518. config.ice_connection_receiving_timeout);
  5519. ice_config.prioritize_most_likely_candidate_pairs =
  5520. config.prioritize_most_likely_ice_candidate_pairs;
  5521. ice_config.backup_connection_ping_interval =
  5522. RTCConfigurationToIceConfigOptionalInt(
  5523. config.ice_backup_candidate_pair_ping_interval);
  5524. ice_config.continual_gathering_policy = gathering_policy;
  5525. ice_config.presume_writable_when_fully_relayed =
  5526. config.presume_writable_when_fully_relayed;
  5527. ice_config.surface_ice_candidates_on_ice_transport_type_changed =
  5528. config.surface_ice_candidates_on_ice_transport_type_changed;
  5529. ice_config.ice_check_interval_strong_connectivity =
  5530. config.ice_check_interval_strong_connectivity;
  5531. ice_config.ice_check_interval_weak_connectivity =
  5532. config.ice_check_interval_weak_connectivity;
  5533. ice_config.ice_check_min_interval = config.ice_check_min_interval;
  5534. ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
  5535. ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
  5536. ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
  5537. ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
  5538. ice_config.regather_all_networks_interval_range =
  5539. config.ice_regather_interval_range;
  5540. ice_config.network_preference = config.network_preference;
  5541. return ice_config;
  5542. }
  5543. bool PeerConnection::SendData(const cricket::SendDataParams& params,
  5544. const rtc::CopyOnWriteBuffer& payload,
  5545. cricket::SendDataResult* result) {
  5546. RTC_DCHECK_RUN_ON(signaling_thread());
  5547. if (data_channel_transport_) {
  5548. SendDataParams send_params;
  5549. send_params.type = ToWebrtcDataMessageType(params.type);
  5550. send_params.ordered = params.ordered;
  5551. if (params.max_rtx_count >= 0) {
  5552. send_params.max_rtx_count = params.max_rtx_count;
  5553. } else if (params.max_rtx_ms >= 0) {
  5554. send_params.max_rtx_ms = params.max_rtx_ms;
  5555. }
  5556. RTCError error = network_thread()->Invoke<RTCError>(
  5557. RTC_FROM_HERE, [this, params, send_params, payload] {
  5558. return data_channel_transport_->SendData(params.sid, send_params,
  5559. payload);
  5560. });
  5561. if (error.ok()) {
  5562. *result = cricket::SendDataResult::SDR_SUCCESS;
  5563. return true;
  5564. } else if (error.type() == RTCErrorType::RESOURCE_EXHAUSTED) {
  5565. // SCTP transport uses RESOURCE_EXHAUSTED when it's blocked.
  5566. // TODO(mellem): Stop using RTCError here and get rid of the mapping.
  5567. *result = cricket::SendDataResult::SDR_BLOCK;
  5568. return false;
  5569. }
  5570. *result = cricket::SendDataResult::SDR_ERROR;
  5571. return false;
  5572. } else if (rtp_data_channel_) {
  5573. return rtp_data_channel_->SendData(params, payload, result);
  5574. }
  5575. RTC_LOG(LS_ERROR) << "SendData called before transport is ready";
  5576. return false;
  5577. }
  5578. bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
  5579. RTC_DCHECK_RUN_ON(signaling_thread());
  5580. if (!rtp_data_channel_ && !data_channel_transport_) {
  5581. // Don't log an error here, because DataChannels are expected to call
  5582. // ConnectDataChannel in this state. It's the only way to initially tell
  5583. // whether or not the underlying transport is ready.
  5584. return false;
  5585. }
  5586. if (data_channel_transport_) {
  5587. SignalDataChannelTransportWritable_s.connect(webrtc_data_channel,
  5588. &DataChannel::OnChannelReady);
  5589. SignalDataChannelTransportReceivedData_s.connect(
  5590. webrtc_data_channel, &DataChannel::OnDataReceived);
  5591. SignalDataChannelTransportChannelClosing_s.connect(
  5592. webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
  5593. SignalDataChannelTransportChannelClosed_s.connect(
  5594. webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
  5595. }
  5596. if (rtp_data_channel_) {
  5597. rtp_data_channel_->SignalReadyToSendData.connect(
  5598. webrtc_data_channel, &DataChannel::OnChannelReady);
  5599. rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
  5600. &DataChannel::OnDataReceived);
  5601. }
  5602. return true;
  5603. }
  5604. void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
  5605. RTC_DCHECK_RUN_ON(signaling_thread());
  5606. if (!rtp_data_channel_ && !data_channel_transport_) {
  5607. RTC_LOG(LS_ERROR)
  5608. << "DisconnectDataChannel called when rtp_data_channel_ and "
  5609. "sctp_transport_ are NULL.";
  5610. return;
  5611. }
  5612. if (data_channel_transport_) {
  5613. SignalDataChannelTransportWritable_s.disconnect(webrtc_data_channel);
  5614. SignalDataChannelTransportReceivedData_s.disconnect(webrtc_data_channel);
  5615. SignalDataChannelTransportChannelClosing_s.disconnect(webrtc_data_channel);
  5616. SignalDataChannelTransportChannelClosed_s.disconnect(webrtc_data_channel);
  5617. }
  5618. if (rtp_data_channel_) {
  5619. rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
  5620. rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
  5621. }
  5622. }
  5623. void PeerConnection::AddSctpDataStream(int sid) {
  5624. if (data_channel_transport_) {
  5625. network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
  5626. if (data_channel_transport_) {
  5627. data_channel_transport_->OpenChannel(sid);
  5628. }
  5629. });
  5630. }
  5631. }
  5632. void PeerConnection::RemoveSctpDataStream(int sid) {
  5633. if (data_channel_transport_) {
  5634. network_thread()->Invoke<void>(RTC_FROM_HERE, [this, sid] {
  5635. if (data_channel_transport_) {
  5636. data_channel_transport_->CloseChannel(sid);
  5637. }
  5638. });
  5639. }
  5640. }
  5641. bool PeerConnection::ReadyToSendData() const {
  5642. RTC_DCHECK_RUN_ON(signaling_thread());
  5643. return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
  5644. (data_channel_transport_ && data_channel_transport_ready_to_send_);
  5645. }
  5646. void PeerConnection::OnDataReceived(int channel_id,
  5647. DataMessageType type,
  5648. const rtc::CopyOnWriteBuffer& buffer) {
  5649. RTC_DCHECK_RUN_ON(network_thread());
  5650. cricket::ReceiveDataParams params;
  5651. params.sid = channel_id;
  5652. params.type = ToCricketDataMessageType(type);
  5653. data_channel_transport_invoker_->AsyncInvoke<void>(
  5654. RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
  5655. RTC_DCHECK_RUN_ON(signaling_thread());
  5656. if (!HandleOpenMessage_s(params, buffer)) {
  5657. SignalDataChannelTransportReceivedData_s(params, buffer);
  5658. }
  5659. });
  5660. }
  5661. void PeerConnection::OnChannelClosing(int channel_id) {
  5662. RTC_DCHECK_RUN_ON(network_thread());
  5663. data_channel_transport_invoker_->AsyncInvoke<void>(
  5664. RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
  5665. RTC_DCHECK_RUN_ON(signaling_thread());
  5666. SignalDataChannelTransportChannelClosing_s(channel_id);
  5667. });
  5668. }
  5669. void PeerConnection::OnChannelClosed(int channel_id) {
  5670. RTC_DCHECK_RUN_ON(network_thread());
  5671. data_channel_transport_invoker_->AsyncInvoke<void>(
  5672. RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
  5673. RTC_DCHECK_RUN_ON(signaling_thread());
  5674. SignalDataChannelTransportChannelClosed_s(channel_id);
  5675. });
  5676. }
  5677. void PeerConnection::OnReadyToSend() {
  5678. RTC_DCHECK_RUN_ON(network_thread());
  5679. data_channel_transport_invoker_->AsyncInvoke<void>(
  5680. RTC_FROM_HERE, signaling_thread(), [this] {
  5681. RTC_DCHECK_RUN_ON(signaling_thread());
  5682. data_channel_transport_ready_to_send_ = true;
  5683. SignalDataChannelTransportWritable_s(
  5684. data_channel_transport_ready_to_send_);
  5685. });
  5686. }
  5687. absl::optional<std::string> PeerConnection::sctp_transport_name() const {
  5688. RTC_DCHECK_RUN_ON(signaling_thread());
  5689. if (sctp_mid_ && transport_controller_) {
  5690. auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
  5691. if (dtls_transport) {
  5692. return dtls_transport->transport_name();
  5693. }
  5694. return absl::optional<std::string>();
  5695. }
  5696. return absl::optional<std::string>();
  5697. }
  5698. cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
  5699. cricket::CandidateStatsList candidate_states_list;
  5700. network_thread()->Invoke<void>(
  5701. RTC_FROM_HERE,
  5702. rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
  5703. port_allocator_.get(), &candidate_states_list));
  5704. return candidate_states_list;
  5705. }
  5706. std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
  5707. const {
  5708. RTC_DCHECK_RUN_ON(signaling_thread());
  5709. std::map<std::string, std::string> transport_names_by_mid;
  5710. for (const auto& transceiver : transceivers_) {
  5711. cricket::ChannelInterface* channel = transceiver->internal()->channel();
  5712. if (channel) {
  5713. transport_names_by_mid[channel->content_name()] =
  5714. channel->transport_name();
  5715. }
  5716. }
  5717. if (rtp_data_channel_) {
  5718. transport_names_by_mid[rtp_data_channel_->content_name()] =
  5719. rtp_data_channel_->transport_name();
  5720. }
  5721. if (data_channel_transport_) {
  5722. absl::optional<std::string> transport_name = sctp_transport_name();
  5723. RTC_DCHECK(transport_name);
  5724. transport_names_by_mid[*sctp_mid_] = *transport_name;
  5725. }
  5726. return transport_names_by_mid;
  5727. }
  5728. std::map<std::string, cricket::TransportStats>
  5729. PeerConnection::GetTransportStatsByNames(
  5730. const std::set<std::string>& transport_names) {
  5731. if (!network_thread()->IsCurrent()) {
  5732. return network_thread()
  5733. ->Invoke<std::map<std::string, cricket::TransportStats>>(
  5734. RTC_FROM_HERE,
  5735. [&] { return GetTransportStatsByNames(transport_names); });
  5736. }
  5737. RTC_DCHECK_RUN_ON(network_thread());
  5738. std::map<std::string, cricket::TransportStats> transport_stats_by_name;
  5739. for (const std::string& transport_name : transport_names) {
  5740. cricket::TransportStats transport_stats;
  5741. bool success =
  5742. transport_controller_->GetStats(transport_name, &transport_stats);
  5743. if (success) {
  5744. transport_stats_by_name[transport_name] = std::move(transport_stats);
  5745. } else {
  5746. RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
  5747. << transport_name;
  5748. }
  5749. }
  5750. return transport_stats_by_name;
  5751. }
  5752. bool PeerConnection::GetLocalCertificate(
  5753. const std::string& transport_name,
  5754. rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
  5755. if (!certificate) {
  5756. return false;
  5757. }
  5758. *certificate = transport_controller_->GetLocalCertificate(transport_name);
  5759. return *certificate != nullptr;
  5760. }
  5761. std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
  5762. const std::string& transport_name) {
  5763. return transport_controller_->GetRemoteSSLCertChain(transport_name);
  5764. }
  5765. cricket::DataChannelType PeerConnection::data_channel_type() const {
  5766. return data_channel_type_;
  5767. }
  5768. bool PeerConnection::IceRestartPending(const std::string& content_name) const {
  5769. RTC_DCHECK_RUN_ON(signaling_thread());
  5770. return pending_ice_restarts_.find(content_name) !=
  5771. pending_ice_restarts_.end();
  5772. }
  5773. bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
  5774. return transport_controller_->NeedsIceRestart(content_name);
  5775. }
  5776. void PeerConnection::OnCertificateReady(
  5777. const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
  5778. transport_controller_->SetLocalCertificate(certificate);
  5779. }
  5780. void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
  5781. SetSessionError(SessionError::kTransport,
  5782. rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
  5783. }
  5784. void PeerConnection::OnTransportControllerConnectionState(
  5785. cricket::IceConnectionState state) {
  5786. switch (state) {
  5787. case cricket::kIceConnectionConnecting:
  5788. // If the current state is Connected or Completed, then there were
  5789. // writable channels but now there are not, so the next state must
  5790. // be Disconnected.
  5791. // kIceConnectionConnecting is currently used as the default,
  5792. // un-connected state by the TransportController, so its only use is
  5793. // detecting disconnections.
  5794. if (ice_connection_state_ ==
  5795. PeerConnectionInterface::kIceConnectionConnected ||
  5796. ice_connection_state_ ==
  5797. PeerConnectionInterface::kIceConnectionCompleted) {
  5798. SetIceConnectionState(
  5799. PeerConnectionInterface::kIceConnectionDisconnected);
  5800. }
  5801. break;
  5802. case cricket::kIceConnectionFailed:
  5803. SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
  5804. break;
  5805. case cricket::kIceConnectionConnected:
  5806. RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
  5807. "all transports are writable.";
  5808. SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
  5809. NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
  5810. break;
  5811. case cricket::kIceConnectionCompleted:
  5812. RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
  5813. "all transports are complete.";
  5814. if (ice_connection_state_ !=
  5815. PeerConnectionInterface::kIceConnectionConnected) {
  5816. // If jumping directly from "checking" to "connected",
  5817. // signal "connected" first.
  5818. SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
  5819. }
  5820. SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
  5821. NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
  5822. ReportTransportStats();
  5823. break;
  5824. default:
  5825. RTC_NOTREACHED();
  5826. }
  5827. }
  5828. void PeerConnection::OnTransportControllerCandidatesGathered(
  5829. const std::string& transport_name,
  5830. const cricket::Candidates& candidates) {
  5831. int sdp_mline_index;
  5832. if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
  5833. RTC_LOG(LS_ERROR)
  5834. << "OnTransportControllerCandidatesGathered: content name "
  5835. << transport_name << " not found";
  5836. return;
  5837. }
  5838. for (cricket::Candidates::const_iterator citer = candidates.begin();
  5839. citer != candidates.end(); ++citer) {
  5840. // Use transport_name as the candidate media id.
  5841. std::unique_ptr<JsepIceCandidate> candidate(
  5842. new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
  5843. if (local_description()) {
  5844. mutable_local_description()->AddCandidate(candidate.get());
  5845. }
  5846. OnIceCandidate(std::move(candidate));
  5847. }
  5848. }
  5849. void PeerConnection::OnTransportControllerCandidateError(
  5850. const cricket::IceCandidateErrorEvent& event) {
  5851. OnIceCandidateError(event.host_candidate, event.url, event.error_code,
  5852. event.error_text);
  5853. }
  5854. void PeerConnection::OnTransportControllerCandidatesRemoved(
  5855. const std::vector<cricket::Candidate>& candidates) {
  5856. // Sanity check.
  5857. for (const cricket::Candidate& candidate : candidates) {
  5858. if (candidate.transport_name().empty()) {
  5859. RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
  5860. "empty content name in candidate "
  5861. << candidate.ToString();
  5862. return;
  5863. }
  5864. }
  5865. if (local_description()) {
  5866. mutable_local_description()->RemoveCandidates(candidates);
  5867. }
  5868. OnIceCandidatesRemoved(candidates);
  5869. }
  5870. void PeerConnection::OnTransportControllerCandidateChanged(
  5871. const cricket::CandidatePairChangeEvent& event) {
  5872. OnSelectedCandidatePairChanged(event);
  5873. }
  5874. void PeerConnection::OnTransportControllerDtlsHandshakeError(
  5875. rtc::SSLHandshakeError error) {
  5876. RTC_HISTOGRAM_ENUMERATION(
  5877. "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
  5878. static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
  5879. }
  5880. void PeerConnection::EnableSending() {
  5881. for (const auto& transceiver : transceivers_) {
  5882. cricket::ChannelInterface* channel = transceiver->internal()->channel();
  5883. if (channel && !channel->enabled()) {
  5884. channel->Enable(true);
  5885. }
  5886. }
  5887. if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
  5888. rtp_data_channel_->Enable(true);
  5889. }
  5890. }
  5891. // Returns the media index for a local ice candidate given the content name.
  5892. bool PeerConnection::GetLocalCandidateMediaIndex(
  5893. const std::string& content_name,
  5894. int* sdp_mline_index) {
  5895. if (!local_description() || !sdp_mline_index) {
  5896. return false;
  5897. }
  5898. bool content_found = false;
  5899. const ContentInfos& contents = local_description()->description()->contents();
  5900. for (size_t index = 0; index < contents.size(); ++index) {
  5901. if (contents[index].name == content_name) {
  5902. *sdp_mline_index = static_cast<int>(index);
  5903. content_found = true;
  5904. break;
  5905. }
  5906. }
  5907. return content_found;
  5908. }
  5909. bool PeerConnection::UseCandidatesInSessionDescription(
  5910. const SessionDescriptionInterface* remote_desc) {
  5911. if (!remote_desc) {
  5912. return true;
  5913. }
  5914. bool ret = true;
  5915. for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
  5916. const IceCandidateCollection* candidates = remote_desc->candidates(m);
  5917. for (size_t n = 0; n < candidates->count(); ++n) {
  5918. const IceCandidateInterface* candidate = candidates->at(n);
  5919. bool valid = false;
  5920. if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
  5921. if (valid) {
  5922. RTC_LOG(LS_INFO)
  5923. << "UseCandidatesInSessionDescription: Not ready to use "
  5924. "candidate.";
  5925. }
  5926. continue;
  5927. }
  5928. ret = UseCandidate(candidate);
  5929. if (!ret) {
  5930. break;
  5931. }
  5932. }
  5933. }
  5934. return ret;
  5935. }
  5936. bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
  5937. RTCErrorOr<const cricket::ContentInfo*> result =
  5938. FindContentInfo(remote_description(), candidate);
  5939. if (!result.ok()) {
  5940. RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate. "
  5941. << result.error().message();
  5942. return false;
  5943. }
  5944. std::vector<cricket::Candidate> candidates;
  5945. candidates.push_back(candidate->candidate());
  5946. // Invoking BaseSession method to handle remote candidates.
  5947. RTCError error = transport_controller_->AddRemoteCandidates(
  5948. result.value()->name, candidates);
  5949. if (error.ok()) {
  5950. ReportRemoteIceCandidateAdded(candidate->candidate());
  5951. // Candidates successfully submitted for checking.
  5952. if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
  5953. ice_connection_state_ ==
  5954. PeerConnectionInterface::kIceConnectionDisconnected) {
  5955. // If state is New, then the session has just gotten its first remote ICE
  5956. // candidates, so go to Checking.
  5957. // If state is Disconnected, the session is re-using old candidates or
  5958. // receiving additional ones, so go to Checking.
  5959. // If state is Connected, stay Connected.
  5960. // TODO(bemasc): If state is Connected, and the new candidates are for a
  5961. // newly added transport, then the state actually _should_ move to
  5962. // checking. Add a way to distinguish that case.
  5963. SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
  5964. }
  5965. // TODO(bemasc): If state is Completed, go back to Connected.
  5966. } else {
  5967. RTC_LOG(LS_WARNING) << error.message();
  5968. }
  5969. return true;
  5970. }
  5971. RTCErrorOr<const cricket::ContentInfo*> PeerConnection::FindContentInfo(
  5972. const SessionDescriptionInterface* description,
  5973. const IceCandidateInterface* candidate) {
  5974. if (candidate->sdp_mline_index() >= 0) {
  5975. size_t mediacontent_index =
  5976. static_cast<size_t>(candidate->sdp_mline_index());
  5977. size_t content_size = description->description()->contents().size();
  5978. if (mediacontent_index < content_size) {
  5979. return &description->description()->contents()[mediacontent_index];
  5980. } else {
  5981. return RTCError(RTCErrorType::INVALID_RANGE,
  5982. "Media line index (" +
  5983. rtc::ToString(candidate->sdp_mline_index()) +
  5984. ") out of range (number of mlines: " +
  5985. rtc::ToString(content_size) + ").");
  5986. }
  5987. } else if (!candidate->sdp_mid().empty()) {
  5988. auto& contents = description->description()->contents();
  5989. auto it = absl::c_find_if(
  5990. contents, [candidate](const cricket::ContentInfo& content_info) {
  5991. return content_info.mid() == candidate->sdp_mid();
  5992. });
  5993. if (it == contents.end()) {
  5994. return RTCError(
  5995. RTCErrorType::INVALID_PARAMETER,
  5996. "Mid " + candidate->sdp_mid() +
  5997. " specified but no media section with that mid found.");
  5998. } else {
  5999. return &*it;
  6000. }
  6001. }
  6002. return RTCError(RTCErrorType::INVALID_PARAMETER,
  6003. "Neither sdp_mline_index nor sdp_mid specified.");
  6004. }
  6005. void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
  6006. // Destroy video channel first since it may have a pointer to the
  6007. // voice channel.
  6008. const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
  6009. if (!video_info || video_info->rejected) {
  6010. DestroyTransceiverChannel(GetVideoTransceiver());
  6011. }
  6012. const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
  6013. if (!audio_info || audio_info->rejected) {
  6014. DestroyTransceiverChannel(GetAudioTransceiver());
  6015. }
  6016. const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
  6017. if (!data_info || data_info->rejected) {
  6018. DestroyDataChannel();
  6019. }
  6020. }
  6021. RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
  6022. const SessionDescription& desc) const {
  6023. const cricket::ContentGroup* bundle_group = nullptr;
  6024. if (configuration_.bundle_policy ==
  6025. PeerConnectionInterface::kBundlePolicyMaxBundle) {
  6026. bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
  6027. if (!bundle_group) {
  6028. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6029. "max-bundle configured but session description "
  6030. "has no BUNDLE group");
  6031. }
  6032. }
  6033. return bundle_group;
  6034. }
  6035. RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
  6036. // Creating the media channels. Transports should already have been created
  6037. // at this point.
  6038. const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
  6039. if (voice && !voice->rejected &&
  6040. !GetAudioTransceiver()->internal()->channel()) {
  6041. cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
  6042. if (!voice_channel) {
  6043. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
  6044. "Failed to create voice channel.");
  6045. }
  6046. GetAudioTransceiver()->internal()->SetChannel(voice_channel);
  6047. }
  6048. const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
  6049. if (video && !video->rejected &&
  6050. !GetVideoTransceiver()->internal()->channel()) {
  6051. cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
  6052. if (!video_channel) {
  6053. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
  6054. "Failed to create video channel.");
  6055. }
  6056. GetVideoTransceiver()->internal()->SetChannel(video_channel);
  6057. }
  6058. const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
  6059. if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
  6060. !rtp_data_channel_ && !data_channel_transport_) {
  6061. if (!CreateDataChannel(data->name)) {
  6062. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
  6063. "Failed to create data channel.");
  6064. }
  6065. }
  6066. return RTCError::OK();
  6067. }
  6068. // TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
  6069. cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
  6070. const std::string& mid) {
  6071. RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
  6072. MediaTransportConfig media_transport_config =
  6073. transport_controller_->GetMediaTransportConfig(mid);
  6074. cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
  6075. call_ptr_, configuration_.media_config, rtp_transport,
  6076. media_transport_config, signaling_thread(), mid, SrtpRequired(),
  6077. GetCryptoOptions(), &ssrc_generator_, audio_options_);
  6078. if (!voice_channel) {
  6079. return nullptr;
  6080. }
  6081. voice_channel->SignalDtlsSrtpSetupFailure.connect(
  6082. this, &PeerConnection::OnDtlsSrtpSetupFailure);
  6083. voice_channel->SignalSentPacket.connect(this,
  6084. &PeerConnection::OnSentPacket_w);
  6085. voice_channel->SetRtpTransport(rtp_transport);
  6086. return voice_channel;
  6087. }
  6088. // TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
  6089. cricket::VideoChannel* PeerConnection::CreateVideoChannel(
  6090. const std::string& mid) {
  6091. RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
  6092. MediaTransportConfig media_transport_config =
  6093. transport_controller_->GetMediaTransportConfig(mid);
  6094. cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
  6095. call_ptr_, configuration_.media_config, rtp_transport,
  6096. media_transport_config, signaling_thread(), mid, SrtpRequired(),
  6097. GetCryptoOptions(), &ssrc_generator_, video_options_,
  6098. video_bitrate_allocator_factory_.get());
  6099. if (!video_channel) {
  6100. return nullptr;
  6101. }
  6102. video_channel->SignalDtlsSrtpSetupFailure.connect(
  6103. this, &PeerConnection::OnDtlsSrtpSetupFailure);
  6104. video_channel->SignalSentPacket.connect(this,
  6105. &PeerConnection::OnSentPacket_w);
  6106. video_channel->SetRtpTransport(rtp_transport);
  6107. return video_channel;
  6108. }
  6109. bool PeerConnection::CreateDataChannel(const std::string& mid) {
  6110. switch (data_channel_type_) {
  6111. case cricket::DCT_SCTP:
  6112. case cricket::DCT_DATA_CHANNEL_TRANSPORT_SCTP:
  6113. case cricket::DCT_DATA_CHANNEL_TRANSPORT:
  6114. case cricket::DCT_MEDIA_TRANSPORT:
  6115. if (!network_thread()->Invoke<bool>(
  6116. RTC_FROM_HERE,
  6117. rtc::Bind(&PeerConnection::SetupDataChannelTransport_n, this,
  6118. mid))) {
  6119. return false;
  6120. }
  6121. // All non-RTP data channels must initialize |sctp_data_channels_|.
  6122. for (const auto& channel : sctp_data_channels_) {
  6123. channel->OnTransportChannelCreated();
  6124. }
  6125. return true;
  6126. case cricket::DCT_RTP:
  6127. default:
  6128. RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
  6129. rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
  6130. configuration_.media_config, rtp_transport, signaling_thread(), mid,
  6131. SrtpRequired(), GetCryptoOptions(), &ssrc_generator_);
  6132. if (!rtp_data_channel_) {
  6133. return false;
  6134. }
  6135. rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
  6136. this, &PeerConnection::OnDtlsSrtpSetupFailure);
  6137. rtp_data_channel_->SignalSentPacket.connect(
  6138. this, &PeerConnection::OnSentPacket_w);
  6139. rtp_data_channel_->SetRtpTransport(rtp_transport);
  6140. return true;
  6141. }
  6142. return false;
  6143. }
  6144. Call::Stats PeerConnection::GetCallStats() {
  6145. if (!worker_thread()->IsCurrent()) {
  6146. return worker_thread()->Invoke<Call::Stats>(
  6147. RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
  6148. }
  6149. RTC_DCHECK_RUN_ON(worker_thread());
  6150. if (call_) {
  6151. return call_->GetStats();
  6152. } else {
  6153. return Call::Stats();
  6154. }
  6155. }
  6156. bool PeerConnection::SetupDataChannelTransport_n(const std::string& mid) {
  6157. DataChannelTransportInterface* transport =
  6158. transport_controller_->GetDataChannelTransport(mid);
  6159. if (!transport) {
  6160. RTC_LOG(LS_ERROR)
  6161. << "Data channel transport is not available for data channels, mid="
  6162. << mid;
  6163. return false;
  6164. }
  6165. RTC_LOG(LS_INFO) << "Setting up data channel transport for mid=" << mid;
  6166. data_channel_transport_ = transport;
  6167. data_channel_transport_invoker_ = std::make_unique<rtc::AsyncInvoker>();
  6168. sctp_mid_ = mid;
  6169. // Note: setting the data sink and checking initial state must be done last,
  6170. // after setting up the data channel. Setting the data sink may trigger
  6171. // callbacks to PeerConnection which require the transport to be completely
  6172. // set up (eg. OnReadyToSend()).
  6173. transport->SetDataSink(this);
  6174. return true;
  6175. }
  6176. void PeerConnection::TeardownDataChannelTransport_n() {
  6177. if (!sctp_mid_ && !data_channel_transport_) {
  6178. return;
  6179. }
  6180. RTC_LOG(LS_INFO) << "Tearing down data channel transport for mid="
  6181. << *sctp_mid_;
  6182. // |sctp_mid_| may still be active through an SCTP transport. If not, unset
  6183. // it.
  6184. sctp_mid_.reset();
  6185. data_channel_transport_invoker_ = nullptr;
  6186. if (data_channel_transport_) {
  6187. data_channel_transport_->SetDataSink(nullptr);
  6188. }
  6189. data_channel_transport_ = nullptr;
  6190. }
  6191. // Returns false if bundle is enabled and rtcp_mux is disabled.
  6192. bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
  6193. bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
  6194. if (!bundle_enabled)
  6195. return true;
  6196. const cricket::ContentGroup* bundle_group =
  6197. desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
  6198. RTC_DCHECK(bundle_group != NULL);
  6199. const cricket::ContentInfos& contents = desc->contents();
  6200. for (cricket::ContentInfos::const_iterator citer = contents.begin();
  6201. citer != contents.end(); ++citer) {
  6202. const cricket::ContentInfo* content = (&*citer);
  6203. RTC_DCHECK(content != NULL);
  6204. if (bundle_group->HasContentName(content->name) && !content->rejected &&
  6205. content->type == MediaProtocolType::kRtp) {
  6206. if (!HasRtcpMuxEnabled(content))
  6207. return false;
  6208. }
  6209. }
  6210. // RTCP-MUX is enabled in all the contents.
  6211. return true;
  6212. }
  6213. bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
  6214. return content->media_description()->rtcp_mux();
  6215. }
  6216. static RTCError ValidateMids(const cricket::SessionDescription& description) {
  6217. std::set<std::string> mids;
  6218. for (const cricket::ContentInfo& content : description.contents()) {
  6219. if (content.name.empty()) {
  6220. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6221. "A media section is missing a MID attribute.");
  6222. }
  6223. if (!mids.insert(content.name).second) {
  6224. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6225. "Duplicate a=mid value '" + content.name + "'.");
  6226. }
  6227. }
  6228. return RTCError::OK();
  6229. }
  6230. RTCError PeerConnection::ValidateSessionDescription(
  6231. const SessionDescriptionInterface* sdesc,
  6232. cricket::ContentSource source) {
  6233. if (session_error() != SessionError::kNone) {
  6234. LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
  6235. }
  6236. if (!sdesc || !sdesc->description()) {
  6237. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
  6238. }
  6239. SdpType type = sdesc->GetType();
  6240. if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
  6241. (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
  6242. LOG_AND_RETURN_ERROR(
  6243. RTCErrorType::INVALID_STATE,
  6244. "Called in wrong state: " + GetSignalingStateString(signaling_state()));
  6245. }
  6246. RTCError error = ValidateMids(*sdesc->description());
  6247. if (!error.ok()) {
  6248. return error;
  6249. }
  6250. // Verify crypto settings.
  6251. std::string crypto_error;
  6252. if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
  6253. dtls_enabled_) {
  6254. RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
  6255. if (!crypto_error.ok()) {
  6256. return crypto_error;
  6257. }
  6258. }
  6259. // Verify ice-ufrag and ice-pwd.
  6260. if (!VerifyIceUfragPwdPresent(sdesc->description())) {
  6261. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6262. kSdpWithoutIceUfragPwd);
  6263. }
  6264. if (!ValidateBundleSettings(sdesc->description())) {
  6265. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6266. kBundleWithoutRtcpMux);
  6267. }
  6268. // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
  6269. // m-lines that do not rtcp-mux enabled.
  6270. // Verify m-lines in Answer when compared against Offer.
  6271. if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
  6272. // With an answer we want to compare the new answer session description with
  6273. // the offer's session description from the current negotiation.
  6274. const cricket::SessionDescription* offer_desc =
  6275. (source == cricket::CS_LOCAL) ? remote_description()->description()
  6276. : local_description()->description();
  6277. if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
  6278. !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
  6279. type)) {
  6280. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6281. kMlineMismatchInAnswer);
  6282. }
  6283. } else {
  6284. // The re-offers should respect the order of m= sections in current
  6285. // description. See RFC3264 Section 8 paragraph 4 for more details.
  6286. // With a re-offer, either the current local or current remote descriptions
  6287. // could be the most up to date, so we would like to check against both of
  6288. // them if they exist. It could be the case that one of them has a 0 port
  6289. // for a media section, but the other does not. This is important to check
  6290. // against in the case that we are recycling an m= section.
  6291. const cricket::SessionDescription* current_desc = nullptr;
  6292. const cricket::SessionDescription* secondary_current_desc = nullptr;
  6293. if (local_description()) {
  6294. current_desc = local_description()->description();
  6295. if (remote_description()) {
  6296. secondary_current_desc = remote_description()->description();
  6297. }
  6298. } else if (remote_description()) {
  6299. current_desc = remote_description()->description();
  6300. }
  6301. if (current_desc &&
  6302. !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
  6303. *sdesc->description(), type)) {
  6304. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6305. kMlineMismatchInSubsequentOffer);
  6306. }
  6307. }
  6308. if (IsUnifiedPlan()) {
  6309. // Ensure that each audio and video media section has at most one
  6310. // "StreamParams". This will return an error if receiving a session
  6311. // description from a "Plan B" endpoint which adds multiple tracks of the
  6312. // same type. With Unified Plan, there can only be at most one track per
  6313. // media section.
  6314. for (const ContentInfo& content : sdesc->description()->contents()) {
  6315. const MediaContentDescription& desc = *content.media_description();
  6316. if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
  6317. desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
  6318. desc.streams().size() > 1u) {
  6319. LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
  6320. "Media section has more than one track specified "
  6321. "with a=ssrc lines which is not supported with "
  6322. "Unified Plan.");
  6323. }
  6324. }
  6325. }
  6326. return RTCError::OK();
  6327. }
  6328. bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
  6329. PeerConnectionInterface::SignalingState state = signaling_state();
  6330. if (type == SdpType::kOffer) {
  6331. return (state == PeerConnectionInterface::kStable) ||
  6332. (state == PeerConnectionInterface::kHaveLocalOffer);
  6333. } else {
  6334. RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
  6335. return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
  6336. (state == PeerConnectionInterface::kHaveLocalPrAnswer);
  6337. }
  6338. }
  6339. bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
  6340. PeerConnectionInterface::SignalingState state = signaling_state();
  6341. if (type == SdpType::kOffer) {
  6342. return (state == PeerConnectionInterface::kStable) ||
  6343. (state == PeerConnectionInterface::kHaveRemoteOffer);
  6344. } else {
  6345. RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
  6346. return (state == PeerConnectionInterface::kHaveLocalOffer) ||
  6347. (state == PeerConnectionInterface::kHaveRemotePrAnswer);
  6348. }
  6349. }
  6350. const char* PeerConnection::SessionErrorToString(SessionError error) const {
  6351. switch (error) {
  6352. case SessionError::kNone:
  6353. return "ERROR_NONE";
  6354. case SessionError::kContent:
  6355. return "ERROR_CONTENT";
  6356. case SessionError::kTransport:
  6357. return "ERROR_TRANSPORT";
  6358. }
  6359. RTC_NOTREACHED();
  6360. return "";
  6361. }
  6362. std::string PeerConnection::GetSessionErrorMsg() {
  6363. rtc::StringBuilder desc;
  6364. desc << kSessionError << SessionErrorToString(session_error()) << ". ";
  6365. desc << kSessionErrorDesc << session_error_desc() << ".";
  6366. return desc.Release();
  6367. }
  6368. void PeerConnection::ReportSdpFormatReceived(
  6369. const SessionDescriptionInterface& remote_offer) {
  6370. int num_audio_mlines = 0;
  6371. int num_video_mlines = 0;
  6372. int num_audio_tracks = 0;
  6373. int num_video_tracks = 0;
  6374. for (const ContentInfo& content : remote_offer.description()->contents()) {
  6375. cricket::MediaType media_type = content.media_description()->type();
  6376. int num_tracks = std::max(
  6377. 1, static_cast<int>(content.media_description()->streams().size()));
  6378. if (media_type == cricket::MEDIA_TYPE_AUDIO) {
  6379. num_audio_mlines += 1;
  6380. num_audio_tracks += num_tracks;
  6381. } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
  6382. num_video_mlines += 1;
  6383. num_video_tracks += num_tracks;
  6384. }
  6385. }
  6386. SdpFormatReceived format = kSdpFormatReceivedNoTracks;
  6387. if (num_audio_mlines > 1 || num_video_mlines > 1) {
  6388. format = kSdpFormatReceivedComplexUnifiedPlan;
  6389. } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
  6390. format = kSdpFormatReceivedComplexPlanB;
  6391. } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
  6392. format = kSdpFormatReceivedSimple;
  6393. }
  6394. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
  6395. kSdpFormatReceivedMax);
  6396. }
  6397. void PeerConnection::ReportIceCandidateCollected(
  6398. const cricket::Candidate& candidate) {
  6399. NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
  6400. if (candidate.address().IsPrivateIP()) {
  6401. NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
  6402. }
  6403. if (candidate.address().IsUnresolvedIP()) {
  6404. NoteUsageEvent(UsageEvent::MDNS_CANDIDATE_COLLECTED);
  6405. }
  6406. if (candidate.address().family() == AF_INET6) {
  6407. NoteUsageEvent(UsageEvent::IPV6_CANDIDATE_COLLECTED);
  6408. }
  6409. }
  6410. void PeerConnection::ReportRemoteIceCandidateAdded(
  6411. const cricket::Candidate& candidate) {
  6412. NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
  6413. if (candidate.address().IsPrivateIP()) {
  6414. NoteUsageEvent(UsageEvent::REMOTE_PRIVATE_CANDIDATE_ADDED);
  6415. }
  6416. if (candidate.address().IsUnresolvedIP()) {
  6417. NoteUsageEvent(UsageEvent::REMOTE_MDNS_CANDIDATE_ADDED);
  6418. }
  6419. if (candidate.address().family() == AF_INET6) {
  6420. NoteUsageEvent(UsageEvent::REMOTE_IPV6_CANDIDATE_ADDED);
  6421. }
  6422. }
  6423. void PeerConnection::NoteUsageEvent(UsageEvent event) {
  6424. RTC_DCHECK_RUN_ON(signaling_thread());
  6425. usage_event_accumulator_ |= static_cast<int>(event);
  6426. }
  6427. void PeerConnection::ReportUsagePattern() const {
  6428. RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
  6429. RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
  6430. usage_event_accumulator_,
  6431. static_cast<int>(UsageEvent::MAX_VALUE));
  6432. const int bad_bits =
  6433. static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_SUCCEEDED) |
  6434. static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
  6435. const int good_bits =
  6436. static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_SUCCEEDED) |
  6437. static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
  6438. static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
  6439. if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
  6440. (usage_event_accumulator_ & good_bits) == 0) {
  6441. // If called after close(), we can't report, because observer may have
  6442. // been deallocated, and therefore pointer is null. Write to log instead.
  6443. if (observer_) {
  6444. Observer()->OnInterestingUsage(usage_event_accumulator_);
  6445. } else {
  6446. RTC_LOG(LS_INFO) << "Interesting usage signature "
  6447. << usage_event_accumulator_
  6448. << " observed after observer shutdown";
  6449. }
  6450. }
  6451. }
  6452. void PeerConnection::ReportNegotiatedSdpSemantics(
  6453. const SessionDescriptionInterface& answer) {
  6454. SdpSemanticNegotiated semantics_negotiated;
  6455. switch (answer.description()->msid_signaling()) {
  6456. case 0:
  6457. semantics_negotiated = kSdpSemanticNegotiatedNone;
  6458. break;
  6459. case cricket::kMsidSignalingMediaSection:
  6460. semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
  6461. break;
  6462. case cricket::kMsidSignalingSsrcAttribute:
  6463. semantics_negotiated = kSdpSemanticNegotiatedPlanB;
  6464. break;
  6465. case cricket::kMsidSignalingMediaSection |
  6466. cricket::kMsidSignalingSsrcAttribute:
  6467. semantics_negotiated = kSdpSemanticNegotiatedMixed;
  6468. break;
  6469. default:
  6470. RTC_NOTREACHED();
  6471. }
  6472. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
  6473. semantics_negotiated, kSdpSemanticNegotiatedMax);
  6474. }
  6475. // We need to check the local/remote description for the Transport instead of
  6476. // the session, because a new Transport added during renegotiation may have
  6477. // them unset while the session has them set from the previous negotiation.
  6478. // Not doing so may trigger the auto generation of transport description and
  6479. // mess up DTLS identity information, ICE credential, etc.
  6480. bool PeerConnection::ReadyToUseRemoteCandidate(
  6481. const IceCandidateInterface* candidate,
  6482. const SessionDescriptionInterface* remote_desc,
  6483. bool* valid) {
  6484. *valid = true;
  6485. const SessionDescriptionInterface* current_remote_desc =
  6486. remote_desc ? remote_desc : remote_description();
  6487. if (!current_remote_desc) {
  6488. return false;
  6489. }
  6490. RTCErrorOr<const cricket::ContentInfo*> result =
  6491. FindContentInfo(current_remote_desc, candidate);
  6492. if (!result.ok()) {
  6493. RTC_LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate. "
  6494. << result.error().message();
  6495. *valid = false;
  6496. return false;
  6497. }
  6498. std::string transport_name = GetTransportName(result.value()->name);
  6499. return !transport_name.empty();
  6500. }
  6501. bool PeerConnection::SrtpRequired() const {
  6502. return !use_datagram_transport_ &&
  6503. (dtls_enabled_ ||
  6504. webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED);
  6505. }
  6506. void PeerConnection::OnTransportControllerGatheringState(
  6507. cricket::IceGatheringState state) {
  6508. RTC_DCHECK(signaling_thread()->IsCurrent());
  6509. if (state == cricket::kIceGatheringGathering) {
  6510. OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
  6511. } else if (state == cricket::kIceGatheringComplete) {
  6512. OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
  6513. }
  6514. }
  6515. void PeerConnection::ReportTransportStats() {
  6516. std::map<std::string, std::set<cricket::MediaType>>
  6517. media_types_by_transport_name;
  6518. for (const auto& transceiver : transceivers_) {
  6519. if (transceiver->internal()->channel()) {
  6520. const std::string& transport_name =
  6521. transceiver->internal()->channel()->transport_name();
  6522. media_types_by_transport_name[transport_name].insert(
  6523. transceiver->media_type());
  6524. }
  6525. }
  6526. if (rtp_data_channel()) {
  6527. media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
  6528. cricket::MEDIA_TYPE_DATA);
  6529. }
  6530. absl::optional<std::string> transport_name = sctp_transport_name();
  6531. if (transport_name) {
  6532. media_types_by_transport_name[*transport_name].insert(
  6533. cricket::MEDIA_TYPE_DATA);
  6534. }
  6535. for (const auto& entry : media_types_by_transport_name) {
  6536. const std::string& transport_name = entry.first;
  6537. const std::set<cricket::MediaType> media_types = entry.second;
  6538. cricket::TransportStats stats;
  6539. if (transport_controller_->GetStats(transport_name, &stats)) {
  6540. ReportBestConnectionState(stats);
  6541. ReportNegotiatedCiphers(stats, media_types);
  6542. }
  6543. }
  6544. }
  6545. // Walk through the ConnectionInfos to gather best connection usage
  6546. // for IPv4 and IPv6.
  6547. void PeerConnection::ReportBestConnectionState(
  6548. const cricket::TransportStats& stats) {
  6549. for (const cricket::TransportChannelStats& channel_stats :
  6550. stats.channel_stats) {
  6551. for (const cricket::ConnectionInfo& connection_info :
  6552. channel_stats.ice_transport_stats.connection_infos) {
  6553. if (!connection_info.best_connection) {
  6554. continue;
  6555. }
  6556. const cricket::Candidate& local = connection_info.local_candidate;
  6557. const cricket::Candidate& remote = connection_info.remote_candidate;
  6558. // Increment the counter for IceCandidatePairType.
  6559. if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
  6560. (local.type() == RELAY_PORT_TYPE &&
  6561. local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
  6562. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
  6563. GetIceCandidatePairCounter(local, remote),
  6564. kIceCandidatePairMax);
  6565. } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
  6566. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
  6567. GetIceCandidatePairCounter(local, remote),
  6568. kIceCandidatePairMax);
  6569. } else {
  6570. RTC_CHECK(0);
  6571. }
  6572. // Increment the counter for IP type.
  6573. if (local.address().family() == AF_INET) {
  6574. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
  6575. kBestConnections_IPv4,
  6576. kPeerConnectionAddressFamilyCounter_Max);
  6577. } else if (local.address().family() == AF_INET6) {
  6578. RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
  6579. kBestConnections_IPv6,
  6580. kPeerConnectionAddressFamilyCounter_Max);
  6581. } else {
  6582. RTC_CHECK(!local.address().hostname().empty() &&
  6583. local.address().IsUnresolvedIP());
  6584. }
  6585. return;
  6586. }
  6587. }
  6588. }
  6589. void PeerConnection::ReportNegotiatedCiphers(
  6590. const cricket::TransportStats& stats,
  6591. const std::set<cricket::MediaType>& media_types) {
  6592. if (!dtls_enabled_ || stats.channel_stats.empty()) {
  6593. return;
  6594. }
  6595. int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
  6596. int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
  6597. if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
  6598. ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
  6599. return;
  6600. }
  6601. if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
  6602. for (cricket::MediaType media_type : media_types) {
  6603. switch (media_type) {
  6604. case cricket::MEDIA_TYPE_AUDIO:
  6605. RTC_HISTOGRAM_ENUMERATION_SPARSE(
  6606. "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
  6607. rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
  6608. break;
  6609. case cricket::MEDIA_TYPE_VIDEO:
  6610. RTC_HISTOGRAM_ENUMERATION_SPARSE(
  6611. "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
  6612. rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
  6613. break;
  6614. case cricket::MEDIA_TYPE_DATA:
  6615. RTC_HISTOGRAM_ENUMERATION_SPARSE(
  6616. "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
  6617. rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
  6618. break;
  6619. default:
  6620. RTC_NOTREACHED();
  6621. continue;
  6622. }
  6623. }
  6624. }
  6625. if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
  6626. for (cricket::MediaType media_type : media_types) {
  6627. switch (media_type) {
  6628. case cricket::MEDIA_TYPE_AUDIO:
  6629. RTC_HISTOGRAM_ENUMERATION_SPARSE(
  6630. "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
  6631. rtc::SSL_CIPHER_SUITE_MAX_VALUE);
  6632. break;
  6633. case cricket::MEDIA_TYPE_VIDEO:
  6634. RTC_HISTOGRAM_ENUMERATION_SPARSE(
  6635. "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
  6636. rtc::SSL_CIPHER_SUITE_MAX_VALUE);
  6637. break;
  6638. case cricket::MEDIA_TYPE_DATA:
  6639. RTC_HISTOGRAM_ENUMERATION_SPARSE(
  6640. "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
  6641. rtc::SSL_CIPHER_SUITE_MAX_VALUE);
  6642. break;
  6643. default:
  6644. RTC_NOTREACHED();
  6645. continue;
  6646. }
  6647. }
  6648. }
  6649. }
  6650. void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
  6651. RTC_DCHECK_RUN_ON(worker_thread());
  6652. RTC_DCHECK(call_);
  6653. call_->OnSentPacket(sent_packet);
  6654. }
  6655. const std::string PeerConnection::GetTransportName(
  6656. const std::string& content_name) {
  6657. cricket::ChannelInterface* channel = GetChannel(content_name);
  6658. if (channel) {
  6659. return channel->transport_name();
  6660. }
  6661. if (data_channel_transport_) {
  6662. RTC_DCHECK(sctp_mid_);
  6663. if (content_name == *sctp_mid_) {
  6664. return *sctp_transport_name();
  6665. }
  6666. }
  6667. // Return an empty string if failed to retrieve the transport name.
  6668. return "";
  6669. }
  6670. void PeerConnection::DestroyTransceiverChannel(
  6671. rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
  6672. transceiver) {
  6673. RTC_DCHECK(transceiver);
  6674. cricket::ChannelInterface* channel = transceiver->internal()->channel();
  6675. if (channel) {
  6676. transceiver->internal()->SetChannel(nullptr);
  6677. DestroyChannelInterface(channel);
  6678. }
  6679. }
  6680. void PeerConnection::DestroyDataChannel() {
  6681. if (rtp_data_channel_) {
  6682. OnDataChannelDestroyed();
  6683. DestroyChannelInterface(rtp_data_channel_);
  6684. rtp_data_channel_ = nullptr;
  6685. }
  6686. // Note: Cannot use rtc::Bind to create a functor to invoke because it will
  6687. // grab a reference to this PeerConnection. If this is called from the
  6688. // PeerConnection destructor, the RefCountedObject vtable will have already
  6689. // been destroyed (since it is a subclass of PeerConnection) and using
  6690. // rtc::Bind will cause "Pure virtual function called" error to appear.
  6691. if (sctp_mid_) {
  6692. OnDataChannelDestroyed();
  6693. network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
  6694. RTC_DCHECK_RUN_ON(network_thread());
  6695. TeardownDataChannelTransport_n();
  6696. });
  6697. }
  6698. }
  6699. void PeerConnection::DestroyChannelInterface(
  6700. cricket::ChannelInterface* channel) {
  6701. RTC_DCHECK(channel);
  6702. switch (channel->media_type()) {
  6703. case cricket::MEDIA_TYPE_AUDIO:
  6704. channel_manager()->DestroyVoiceChannel(
  6705. static_cast<cricket::VoiceChannel*>(channel));
  6706. break;
  6707. case cricket::MEDIA_TYPE_VIDEO:
  6708. channel_manager()->DestroyVideoChannel(
  6709. static_cast<cricket::VideoChannel*>(channel));
  6710. break;
  6711. case cricket::MEDIA_TYPE_DATA:
  6712. channel_manager()->DestroyRtpDataChannel(
  6713. static_cast<cricket::RtpDataChannel*>(channel));
  6714. break;
  6715. default:
  6716. RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
  6717. break;
  6718. }
  6719. }
  6720. bool PeerConnection::OnTransportChanged(
  6721. const std::string& mid,
  6722. RtpTransportInternal* rtp_transport,
  6723. rtc::scoped_refptr<DtlsTransport> dtls_transport,
  6724. MediaTransportInterface* media_transport,
  6725. DataChannelTransportInterface* data_channel_transport) {
  6726. RTC_DCHECK_RUN_ON(network_thread());
  6727. RTC_DCHECK_RUNS_SERIALIZED(&use_media_transport_race_checker_);
  6728. bool ret = true;
  6729. auto base_channel = GetChannel(mid);
  6730. if (base_channel) {
  6731. ret = base_channel->SetRtpTransport(rtp_transport);
  6732. }
  6733. if (use_media_transport_) {
  6734. RTC_LOG(LS_ERROR) << "Media transport isn't supported.";
  6735. }
  6736. if (data_channel_transport_ && mid == sctp_mid_ &&
  6737. data_channel_transport_ != data_channel_transport) {
  6738. // Changed which data channel transport is used for |sctp_mid_| (eg. now
  6739. // it's bundled).
  6740. data_channel_transport_->SetDataSink(nullptr);
  6741. data_channel_transport_ = data_channel_transport;
  6742. if (data_channel_transport) {
  6743. data_channel_transport->SetDataSink(this);
  6744. // There's a new data channel transport. This needs to be signaled to the
  6745. // |sctp_data_channels_| so that they can reopen and reconnect. This is
  6746. // necessary when bundling is applied.
  6747. data_channel_transport_invoker_->AsyncInvoke<void>(
  6748. RTC_FROM_HERE, signaling_thread(), [this] {
  6749. RTC_DCHECK_RUN_ON(signaling_thread());
  6750. for (auto channel : sctp_data_channels_) {
  6751. channel->OnTransportChannelCreated();
  6752. }
  6753. });
  6754. }
  6755. }
  6756. return ret;
  6757. }
  6758. void PeerConnection::OnSetStreams() {
  6759. RTC_DCHECK_RUN_ON(signaling_thread());
  6760. if (IsUnifiedPlan())
  6761. UpdateNegotiationNeeded();
  6762. }
  6763. PeerConnectionObserver* PeerConnection::Observer() const {
  6764. // In earlier production code, the pointer was not cleared on close,
  6765. // which might have led to undefined behavior if the observer was not
  6766. // deallocated, or strange crashes if it was.
  6767. // We use CHECK in order to catch such behavior if it exists.
  6768. // TODO(hta): Remove or replace with DCHECK if nothing is found.
  6769. RTC_CHECK(observer_);
  6770. return observer_;
  6771. }
  6772. CryptoOptions PeerConnection::GetCryptoOptions() {
  6773. // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
  6774. // after it has been removed.
  6775. return configuration_.crypto_options.has_value()
  6776. ? *configuration_.crypto_options
  6777. : factory_->options().crypto_options;
  6778. }
  6779. void PeerConnection::ClearStatsCache() {
  6780. RTC_DCHECK_RUN_ON(signaling_thread());
  6781. if (stats_collector_) {
  6782. stats_collector_->ClearCachedStatsReport();
  6783. }
  6784. }
  6785. void PeerConnection::RequestUsagePatternReportForTesting() {
  6786. signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
  6787. nullptr);
  6788. }
  6789. void PeerConnection::UpdateNegotiationNeeded() {
  6790. RTC_DCHECK_RUN_ON(signaling_thread());
  6791. if (!IsUnifiedPlan()) {
  6792. Observer()->OnRenegotiationNeeded();
  6793. return;
  6794. }
  6795. // If connection's [[IsClosed]] slot is true, abort these steps.
  6796. if (IsClosed())
  6797. return;
  6798. // If connection's signaling state is not "stable", abort these steps.
  6799. if (signaling_state() != kStable)
  6800. return;
  6801. // NOTE
  6802. // The negotiation-needed flag will be updated once the state transitions to
  6803. // "stable", as part of the steps for setting an RTCSessionDescription.
  6804. // If the result of checking if negotiation is needed is false, clear the
  6805. // negotiation-needed flag by setting connection's [[NegotiationNeeded]] slot
  6806. // to false, and abort these steps.
  6807. bool is_negotiation_needed = CheckIfNegotiationIsNeeded();
  6808. if (!is_negotiation_needed) {
  6809. is_negotiation_needed_ = false;
  6810. return;
  6811. }
  6812. // If connection's [[NegotiationNeeded]] slot is already true, abort these
  6813. // steps.
  6814. if (is_negotiation_needed_)
  6815. return;
  6816. // Set connection's [[NegotiationNeeded]] slot to true.
  6817. is_negotiation_needed_ = true;
  6818. // Queue a task that runs the following steps:
  6819. // If connection's [[IsClosed]] slot is true, abort these steps.
  6820. // If connection's [[NegotiationNeeded]] slot is false, abort these steps.
  6821. // Fire an event named negotiationneeded at connection.
  6822. Observer()->OnRenegotiationNeeded();
  6823. }
  6824. bool PeerConnection::CheckIfNegotiationIsNeeded() {
  6825. RTC_DCHECK_RUN_ON(signaling_thread());
  6826. // 1. If any implementation-specific negotiation is required, as described at
  6827. // the start of this section, return true.
  6828. // 2. If connection's [[RestartIce]] internal slot is true, return true.
  6829. if (local_ice_credentials_to_replace_->HasIceCredentials()) {
  6830. return true;
  6831. }
  6832. // 3. Let description be connection.[[CurrentLocalDescription]].
  6833. const SessionDescriptionInterface* description = current_local_description();
  6834. if (!description)
  6835. return true;
  6836. // 4. If connection has created any RTCDataChannels, and no m= section in
  6837. // description has been negotiated yet for data, return true.
  6838. if (!sctp_data_channels_.empty()) {
  6839. if (!cricket::GetFirstDataContent(description->description()->contents()))
  6840. return true;
  6841. }
  6842. // 5. For each transceiver in connection's set of transceivers, perform the
  6843. // following checks:
  6844. for (const auto& transceiver : transceivers_) {
  6845. const ContentInfo* current_local_msection =
  6846. FindTransceiverMSection(transceiver.get(), description);
  6847. const ContentInfo* current_remote_msection = FindTransceiverMSection(
  6848. transceiver.get(), current_remote_description());
  6849. // 5.3 If transceiver is stopped and is associated with an m= section,
  6850. // but the associated m= section is not yet rejected in
  6851. // connection.[[CurrentLocalDescription]] or
  6852. // connection.[[CurrentRemoteDescription]], return true.
  6853. if (transceiver->stopped()) {
  6854. if (current_local_msection && !current_local_msection->rejected &&
  6855. ((current_remote_msection && !current_remote_msection->rejected) ||
  6856. !current_remote_msection)) {
  6857. return true;
  6858. }
  6859. continue;
  6860. }
  6861. // 5.1 If transceiver isn't stopped and isn't yet associated with an m=
  6862. // section in description, return true.
  6863. if (!current_local_msection)
  6864. return true;
  6865. const MediaContentDescription* current_local_media_description =
  6866. current_local_msection->media_description();
  6867. // 5.2 If transceiver isn't stopped and is associated with an m= section
  6868. // in description then perform the following checks:
  6869. // 5.2.1 If transceiver.[[Direction]] is "sendrecv" or "sendonly", and the
  6870. // associated m= section in description either doesn't contain a single
  6871. // "a=msid" line, or the number of MSIDs from the "a=msid" lines in this
  6872. // m= section, or the MSID values themselves, differ from what is in
  6873. // transceiver.sender.[[AssociatedMediaStreamIds]], return true.
  6874. if (RtpTransceiverDirectionHasSend(transceiver->direction())) {
  6875. if (current_local_media_description->streams().size() == 0)
  6876. return true;
  6877. std::vector<std::string> msection_msids;
  6878. for (const auto& stream : current_local_media_description->streams()) {
  6879. for (const std::string& msid : stream.stream_ids())
  6880. msection_msids.push_back(msid);
  6881. }
  6882. std::vector<std::string> transceiver_msids =
  6883. transceiver->sender()->stream_ids();
  6884. if (msection_msids.size() != transceiver_msids.size())
  6885. return true;
  6886. absl::c_sort(transceiver_msids);
  6887. absl::c_sort(msection_msids);
  6888. if (transceiver_msids != msection_msids)
  6889. return true;
  6890. }
  6891. // 5.2.2 If description is of type "offer", and the direction of the
  6892. // associated m= section in neither connection.[[CurrentLocalDescription]]
  6893. // nor connection.[[CurrentRemoteDescription]] matches
  6894. // transceiver.[[Direction]], return true.
  6895. if (description->GetType() == SdpType::kOffer) {
  6896. if (!current_remote_description())
  6897. return true;
  6898. if (!current_remote_msection)
  6899. return true;
  6900. RtpTransceiverDirection current_local_direction =
  6901. current_local_media_description->direction();
  6902. RtpTransceiverDirection current_remote_direction =
  6903. current_remote_msection->media_description()->direction();
  6904. if (transceiver->direction() != current_local_direction &&
  6905. transceiver->direction() !=
  6906. RtpTransceiverDirectionReversed(current_remote_direction)) {
  6907. return true;
  6908. }
  6909. }
  6910. // 5.2.3 If description is of type "answer", and the direction of the
  6911. // associated m= section in the description does not match
  6912. // transceiver.[[Direction]] intersected with the offered direction (as
  6913. // described in [JSEP] (section 5.3.1.)), return true.
  6914. if (description->GetType() == SdpType::kAnswer) {
  6915. if (!remote_description())
  6916. return true;
  6917. const ContentInfo* offered_remote_msection =
  6918. FindTransceiverMSection(transceiver.get(), remote_description());
  6919. RtpTransceiverDirection offered_direction =
  6920. offered_remote_msection
  6921. ? offered_remote_msection->media_description()->direction()
  6922. : RtpTransceiverDirection::kInactive;
  6923. if (current_local_media_description->direction() !=
  6924. (RtpTransceiverDirectionIntersection(
  6925. transceiver->direction(),
  6926. RtpTransceiverDirectionReversed(offered_direction)))) {
  6927. return true;
  6928. }
  6929. }
  6930. }
  6931. // If all the preceding checks were performed and true was not returned,
  6932. // nothing remains to be negotiated; return false.
  6933. return false;
  6934. }
  6935. RTCError PeerConnection::Rollback(SdpType sdp_type) {
  6936. auto state = signaling_state();
  6937. if (state != PeerConnectionInterface::kHaveLocalOffer &&
  6938. state != PeerConnectionInterface::kHaveRemoteOffer) {
  6939. return RTCError(RTCErrorType::INVALID_STATE,
  6940. "Called in wrong signalingState: " +
  6941. GetSignalingStateString(signaling_state()));
  6942. }
  6943. RTC_DCHECK_RUN_ON(signaling_thread());
  6944. RTC_DCHECK(IsUnifiedPlan());
  6945. for (auto&& transceivers_stable_state_pair :
  6946. transceiver_stable_states_by_transceivers_) {
  6947. auto transceiver = transceivers_stable_state_pair.first;
  6948. auto state = transceivers_stable_state_pair.second;
  6949. RTC_DCHECK(transceiver->internal()->mid().has_value());
  6950. std::string mid = transceiver->internal()->mid().value();
  6951. transport_controller_->RollbackTransportForMid(mid);
  6952. DestroyTransceiverChannel(transceiver);
  6953. if (signaling_state() == PeerConnectionInterface::kHaveRemoteOffer &&
  6954. transceiver->receiver()) {
  6955. Observer()->OnRemoveTrack(transceiver->receiver());
  6956. }
  6957. if (state.newly_created()) {
  6958. // Remove added transceivers with no added track.
  6959. if (transceiver->internal()->sender()->track()) {
  6960. transceiver->internal()->set_created_by_addtrack(true);
  6961. } else {
  6962. int remaining_transceiver_count = 0;
  6963. for (auto&& t : transceivers_) {
  6964. if (t != transceiver) {
  6965. transceivers_[remaining_transceiver_count++] = t;
  6966. }
  6967. }
  6968. transceivers_.resize(remaining_transceiver_count);
  6969. }
  6970. }
  6971. transceiver->internal()->sender_internal()->set_transport(nullptr);
  6972. transceiver->internal()->receiver_internal()->set_transport(nullptr);
  6973. transceiver->internal()->set_direction(state.direction());
  6974. transceiver->internal()->set_mid(state.mid());
  6975. transceiver->internal()->set_mline_index(state.mline_index());
  6976. }
  6977. transceiver_stable_states_by_transceivers_.clear();
  6978. pending_local_description_.reset();
  6979. pending_remote_description_.reset();
  6980. ChangeSignalingState(PeerConnectionInterface::kStable);
  6981. // The assumption is that in case of implicit rollback UpdateNegotiationNeeded
  6982. // gets called in SetRemoteDescription.
  6983. if (sdp_type == SdpType::kRollback) {
  6984. UpdateNegotiationNeeded();
  6985. if (is_negotiation_needed_) {
  6986. Observer()->OnRenegotiationNeeded();
  6987. }
  6988. }
  6989. return RTCError::OK();
  6990. }
  6991. } // namespace webrtc