1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472
|
//go:build !js
// +build !js
package webrtc
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"io"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/pion/ice/v2"
"github.com/pion/interceptor"
"github.com/pion/logging"
"github.com/pion/rtcp"
"github.com/pion/sdp/v3"
"github.com/pion/srtp/v2"
"github.com/pion/webrtc/v3/internal/util"
"github.com/pion/webrtc/v3/pkg/rtcerr"
)
// PeerConnection represents a WebRTC connection that establishes a
// peer-to-peer communications with another PeerConnection instance in a
// browser, or to another endpoint implementing the required protocols.
type PeerConnection struct {
statsID string
mu sync.RWMutex
sdpOrigin sdp.Origin
// ops is an operations queue which will ensure the enqueued actions are
// executed in order. It is used for asynchronously, but serially processing
// remote and local descriptions
ops *operations
configuration Configuration
currentLocalDescription *SessionDescription
pendingLocalDescription *SessionDescription
currentRemoteDescription *SessionDescription
pendingRemoteDescription *SessionDescription
signalingState SignalingState
iceConnectionState atomic.Value // ICEConnectionState
connectionState atomic.Value // PeerConnectionState
idpLoginURL *string
isClosed *atomicBool
isNegotiationNeeded *atomicBool
negotiationNeededState negotiationNeededState
lastOffer string
lastAnswer string
// a value containing the last known greater mid value
// we internally generate mids as numbers. Needed since JSEP
// requires that when reusing a media section a new unique mid
// should be defined (see JSEP 3.4.1).
greaterMid int
rtpTransceivers []*RTPTransceiver
onSignalingStateChangeHandler func(SignalingState)
onICEConnectionStateChangeHandler atomic.Value // func(ICEConnectionState)
onConnectionStateChangeHandler atomic.Value // func(PeerConnectionState)
onTrackHandler func(*TrackRemote, *RTPReceiver)
onDataChannelHandler func(*DataChannel)
onNegotiationNeededHandler atomic.Value // func()
iceGatherer *ICEGatherer
iceTransport *ICETransport
dtlsTransport *DTLSTransport
sctpTransport *SCTPTransport
// A reference to the associated API state used by this connection
api *API
log logging.LeveledLogger
interceptorRTCPWriter interceptor.RTCPWriter
}
// NewPeerConnection creates a PeerConnection with the default codecs and
// interceptors. See RegisterDefaultCodecs and RegisterDefaultInterceptors.
//
// If you wish to customize the set of available codecs or the set of
// active interceptors, create a MediaEngine and call api.NewPeerConnection
// instead of this function.
func NewPeerConnection(configuration Configuration) (*PeerConnection, error) {
m := &MediaEngine{}
if err := m.RegisterDefaultCodecs(); err != nil {
return nil, err
}
i := &interceptor.Registry{}
if err := RegisterDefaultInterceptors(m, i); err != nil {
return nil, err
}
api := NewAPI(WithMediaEngine(m), WithInterceptorRegistry(i))
return api.NewPeerConnection(configuration)
}
// NewPeerConnection creates a new PeerConnection with the provided configuration against the received API object
func (api *API) NewPeerConnection(configuration Configuration) (*PeerConnection, error) {
// https://w3c.github.io/webrtc-pc/#constructor (Step #2)
// Some variables defined explicitly despite their implicit zero values to
// allow better readability to understand what is happening.
pc := &PeerConnection{
statsID: fmt.Sprintf("PeerConnection-%d", time.Now().UnixNano()),
configuration: Configuration{
ICEServers: []ICEServer{},
ICETransportPolicy: ICETransportPolicyAll,
BundlePolicy: BundlePolicyBalanced,
RTCPMuxPolicy: RTCPMuxPolicyRequire,
Certificates: []Certificate{},
ICECandidatePoolSize: 0,
},
ops: newOperations(),
isClosed: &atomicBool{},
isNegotiationNeeded: &atomicBool{},
negotiationNeededState: negotiationNeededStateEmpty,
lastOffer: "",
lastAnswer: "",
greaterMid: -1,
signalingState: SignalingStateStable,
api: api,
log: api.settingEngine.LoggerFactory.NewLogger("pc"),
}
pc.iceConnectionState.Store(ICEConnectionStateNew)
pc.connectionState.Store(PeerConnectionStateNew)
i, err := api.interceptorRegistry.Build("")
if err != nil {
return nil, err
}
pc.api = &API{
settingEngine: api.settingEngine,
interceptor: i,
}
if api.settingEngine.disableMediaEngineCopy {
pc.api.mediaEngine = api.mediaEngine
} else {
pc.api.mediaEngine = api.mediaEngine.copy()
}
if err = pc.initConfiguration(configuration); err != nil {
return nil, err
}
pc.iceGatherer, err = pc.createICEGatherer()
if err != nil {
return nil, err
}
// Create the ice transport
iceTransport := pc.createICETransport()
pc.iceTransport = iceTransport
// Create the DTLS transport
dtlsTransport, err := pc.api.NewDTLSTransport(pc.iceTransport, pc.configuration.Certificates)
if err != nil {
return nil, err
}
pc.dtlsTransport = dtlsTransport
// Create the SCTP transport
pc.sctpTransport = pc.api.NewSCTPTransport(pc.dtlsTransport)
// Wire up the on datachannel handler
pc.sctpTransport.OnDataChannel(func(d *DataChannel) {
pc.mu.RLock()
handler := pc.onDataChannelHandler
pc.mu.RUnlock()
if handler != nil {
handler(d)
}
})
pc.interceptorRTCPWriter = pc.api.interceptor.BindRTCPWriter(interceptor.RTCPWriterFunc(pc.writeRTCP))
return pc, nil
}
// initConfiguration defines validation of the specified Configuration and
// its assignment to the internal configuration variable. This function differs
// from its SetConfiguration counterpart because most of the checks do not
// include verification statements related to the existing state. Thus the
// function describes only minor verification of some the struct variables.
func (pc *PeerConnection) initConfiguration(configuration Configuration) error {
if configuration.PeerIdentity != "" {
pc.configuration.PeerIdentity = configuration.PeerIdentity
}
// https://www.w3.org/TR/webrtc/#constructor (step #3)
if len(configuration.Certificates) > 0 {
now := time.Now()
for _, x509Cert := range configuration.Certificates {
if !x509Cert.Expires().IsZero() && now.After(x509Cert.Expires()) {
return &rtcerr.InvalidAccessError{Err: ErrCertificateExpired}
}
pc.configuration.Certificates = append(pc.configuration.Certificates, x509Cert)
}
} else {
sk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return &rtcerr.UnknownError{Err: err}
}
certificate, err := GenerateCertificate(sk)
if err != nil {
return err
}
pc.configuration.Certificates = []Certificate{*certificate}
}
if configuration.BundlePolicy != BundlePolicy(Unknown) {
pc.configuration.BundlePolicy = configuration.BundlePolicy
}
if configuration.RTCPMuxPolicy != RTCPMuxPolicy(Unknown) {
pc.configuration.RTCPMuxPolicy = configuration.RTCPMuxPolicy
}
if configuration.ICECandidatePoolSize != 0 {
pc.configuration.ICECandidatePoolSize = configuration.ICECandidatePoolSize
}
if configuration.ICETransportPolicy != ICETransportPolicy(Unknown) {
pc.configuration.ICETransportPolicy = configuration.ICETransportPolicy
}
if configuration.SDPSemantics != SDPSemantics(Unknown) {
pc.configuration.SDPSemantics = configuration.SDPSemantics
}
sanitizedICEServers := configuration.getICEServers()
if len(sanitizedICEServers) > 0 {
for _, server := range sanitizedICEServers {
if err := server.validate(); err != nil {
return err
}
}
pc.configuration.ICEServers = sanitizedICEServers
}
return nil
}
// OnSignalingStateChange sets an event handler which is invoked when the
// peer connection's signaling state changes
func (pc *PeerConnection) OnSignalingStateChange(f func(SignalingState)) {
pc.mu.Lock()
defer pc.mu.Unlock()
pc.onSignalingStateChangeHandler = f
}
func (pc *PeerConnection) onSignalingStateChange(newState SignalingState) {
pc.mu.RLock()
handler := pc.onSignalingStateChangeHandler
pc.mu.RUnlock()
pc.log.Infof("signaling state changed to %s", newState)
if handler != nil {
go handler(newState)
}
}
// OnDataChannel sets an event handler which is invoked when a data
// channel message arrives from a remote peer.
func (pc *PeerConnection) OnDataChannel(f func(*DataChannel)) {
pc.mu.Lock()
defer pc.mu.Unlock()
pc.onDataChannelHandler = f
}
// OnNegotiationNeeded sets an event handler which is invoked when
// a change has occurred which requires session negotiation
func (pc *PeerConnection) OnNegotiationNeeded(f func()) {
pc.onNegotiationNeededHandler.Store(f)
}
// onNegotiationNeeded enqueues negotiationNeededOp if necessary
// caller of this method should hold `pc.mu` lock
func (pc *PeerConnection) onNegotiationNeeded() {
// https://w3c.github.io/webrtc-pc/#updating-the-negotiation-needed-flag
// non-canon step 1
if pc.negotiationNeededState == negotiationNeededStateRun {
pc.negotiationNeededState = negotiationNeededStateQueue
return
} else if pc.negotiationNeededState == negotiationNeededStateQueue {
return
}
pc.negotiationNeededState = negotiationNeededStateRun
pc.ops.Enqueue(pc.negotiationNeededOp)
}
func (pc *PeerConnection) negotiationNeededOp() {
// Don't run NegotiatedNeeded checks if OnNegotiationNeeded is not set
if handler, ok := pc.onNegotiationNeededHandler.Load().(func()); !ok || handler == nil {
return
}
// https://www.w3.org/TR/webrtc/#updating-the-negotiation-needed-flag
// Step 2.1
if pc.isClosed.get() {
return
}
// non-canon step 2.2
if !pc.ops.IsEmpty() {
pc.ops.Enqueue(pc.negotiationNeededOp)
return
}
// non-canon, run again if there was a request
defer func() {
pc.mu.Lock()
defer pc.mu.Unlock()
if pc.negotiationNeededState == negotiationNeededStateQueue {
defer pc.onNegotiationNeeded()
}
pc.negotiationNeededState = negotiationNeededStateEmpty
}()
// Step 2.3
if pc.SignalingState() != SignalingStateStable {
return
}
// Step 2.4
if !pc.checkNegotiationNeeded() {
pc.isNegotiationNeeded.set(false)
return
}
// Step 2.5
if pc.isNegotiationNeeded.get() {
return
}
// Step 2.6
pc.isNegotiationNeeded.set(true)
// Step 2.7
if handler, ok := pc.onNegotiationNeededHandler.Load().(func()); ok && handler != nil {
handler()
}
}
func (pc *PeerConnection) checkNegotiationNeeded() bool { //nolint:gocognit
// To check if negotiation is needed for connection, perform the following checks:
// Skip 1, 2 steps
// Step 3
pc.mu.Lock()
defer pc.mu.Unlock()
localDesc := pc.currentLocalDescription
remoteDesc := pc.currentRemoteDescription
if localDesc == nil {
return true
}
pc.sctpTransport.lock.Lock()
lenDataChannel := len(pc.sctpTransport.dataChannels)
pc.sctpTransport.lock.Unlock()
if lenDataChannel != 0 && haveDataChannel(localDesc) == nil {
return true
}
for _, t := range pc.rtpTransceivers {
// https://www.w3.org/TR/webrtc/#dfn-update-the-negotiation-needed-flag
// Step 5.1
// if t.stopping && !t.stopped {
// return true
// }
m := getByMid(t.Mid(), localDesc)
// Step 5.2
if !t.stopped && m == nil {
return true
}
if !t.stopped && m != nil {
// Step 5.3.1
if t.Direction() == RTPTransceiverDirectionSendrecv || t.Direction() == RTPTransceiverDirectionSendonly {
descMsid, okMsid := m.Attribute(sdp.AttrKeyMsid)
track := t.Sender().Track()
if !okMsid || descMsid != track.StreamID()+" "+track.ID() {
return true
}
}
switch localDesc.Type {
case SDPTypeOffer:
// Step 5.3.2
rm := getByMid(t.Mid(), remoteDesc)
if rm == nil {
return true
}
if getPeerDirection(m) != t.Direction() && getPeerDirection(rm) != t.Direction().Revers() {
return true
}
case SDPTypeAnswer:
// Step 5.3.3
if _, ok := m.Attribute(t.Direction().String()); !ok {
return true
}
default:
}
}
// Step 5.4
if t.stopped && t.Mid() != "" {
if getByMid(t.Mid(), localDesc) != nil || getByMid(t.Mid(), remoteDesc) != nil {
return true
}
}
}
// Step 6
return false
}
// OnICECandidate sets an event handler which is invoked when a new ICE
// candidate is found.
// ICE candidate gathering only begins when SetLocalDescription or
// SetRemoteDescription is called.
// Take note that the handler will be called with a nil pointer when
// gathering is finished.
func (pc *PeerConnection) OnICECandidate(f func(*ICECandidate)) {
pc.iceGatherer.OnLocalCandidate(f)
}
// OnICEGatheringStateChange sets an event handler which is invoked when the
// ICE candidate gathering state has changed.
func (pc *PeerConnection) OnICEGatheringStateChange(f func(ICEGathererState)) {
pc.iceGatherer.OnStateChange(f)
}
// OnTrack sets an event handler which is called when remote track
// arrives from a remote peer.
func (pc *PeerConnection) OnTrack(f func(*TrackRemote, *RTPReceiver)) {
pc.mu.Lock()
defer pc.mu.Unlock()
pc.onTrackHandler = f
}
func (pc *PeerConnection) onTrack(t *TrackRemote, r *RTPReceiver) {
pc.mu.RLock()
handler := pc.onTrackHandler
pc.mu.RUnlock()
pc.log.Debugf("got new track: %+v", t)
if t != nil {
if handler != nil {
go handler(t, r)
} else {
pc.log.Warnf("OnTrack unset, unable to handle incoming media streams")
}
}
}
// OnICEConnectionStateChange sets an event handler which is called
// when an ICE connection state is changed.
func (pc *PeerConnection) OnICEConnectionStateChange(f func(ICEConnectionState)) {
pc.onICEConnectionStateChangeHandler.Store(f)
}
func (pc *PeerConnection) onICEConnectionStateChange(cs ICEConnectionState) {
pc.iceConnectionState.Store(cs)
pc.log.Infof("ICE connection state changed: %s", cs)
if handler, ok := pc.onICEConnectionStateChangeHandler.Load().(func(ICEConnectionState)); ok && handler != nil {
handler(cs)
}
}
// OnConnectionStateChange sets an event handler which is called
// when the PeerConnectionState has changed
func (pc *PeerConnection) OnConnectionStateChange(f func(PeerConnectionState)) {
pc.onConnectionStateChangeHandler.Store(f)
}
func (pc *PeerConnection) onConnectionStateChange(cs PeerConnectionState) {
pc.connectionState.Store(cs)
pc.log.Infof("peer connection state changed: %s", cs)
if handler, ok := pc.onConnectionStateChangeHandler.Load().(func(PeerConnectionState)); ok && handler != nil {
go handler(cs)
}
}
// SetConfiguration updates the configuration of this PeerConnection object.
func (pc *PeerConnection) SetConfiguration(configuration Configuration) error { //nolint:gocognit
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-setconfiguration (step #2)
if pc.isClosed.get() {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #3)
if configuration.PeerIdentity != "" {
if configuration.PeerIdentity != pc.configuration.PeerIdentity {
return &rtcerr.InvalidModificationError{Err: ErrModifyingPeerIdentity}
}
pc.configuration.PeerIdentity = configuration.PeerIdentity
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #4)
if len(configuration.Certificates) > 0 {
if len(configuration.Certificates) != len(pc.configuration.Certificates) {
return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates}
}
for i, certificate := range configuration.Certificates {
if !pc.configuration.Certificates[i].Equals(certificate) {
return &rtcerr.InvalidModificationError{Err: ErrModifyingCertificates}
}
}
pc.configuration.Certificates = configuration.Certificates
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #5)
if configuration.BundlePolicy != BundlePolicy(Unknown) {
if configuration.BundlePolicy != pc.configuration.BundlePolicy {
return &rtcerr.InvalidModificationError{Err: ErrModifyingBundlePolicy}
}
pc.configuration.BundlePolicy = configuration.BundlePolicy
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #6)
if configuration.RTCPMuxPolicy != RTCPMuxPolicy(Unknown) {
if configuration.RTCPMuxPolicy != pc.configuration.RTCPMuxPolicy {
return &rtcerr.InvalidModificationError{Err: ErrModifyingRTCPMuxPolicy}
}
pc.configuration.RTCPMuxPolicy = configuration.RTCPMuxPolicy
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #7)
if configuration.ICECandidatePoolSize != 0 {
if pc.configuration.ICECandidatePoolSize != configuration.ICECandidatePoolSize &&
pc.LocalDescription() != nil {
return &rtcerr.InvalidModificationError{Err: ErrModifyingICECandidatePoolSize}
}
pc.configuration.ICECandidatePoolSize = configuration.ICECandidatePoolSize
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #8)
if configuration.ICETransportPolicy != ICETransportPolicy(Unknown) {
pc.configuration.ICETransportPolicy = configuration.ICETransportPolicy
}
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #11)
if len(configuration.ICEServers) > 0 {
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3)
for _, server := range configuration.ICEServers {
if err := server.validate(); err != nil {
return err
}
}
pc.configuration.ICEServers = configuration.ICEServers
}
return nil
}
// GetConfiguration returns a Configuration object representing the current
// configuration of this PeerConnection object. The returned object is a
// copy and direct mutation on it will not take affect until SetConfiguration
// has been called with Configuration passed as its only argument.
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-getconfiguration
func (pc *PeerConnection) GetConfiguration() Configuration {
return pc.configuration
}
func (pc *PeerConnection) getStatsID() string {
pc.mu.RLock()
defer pc.mu.RUnlock()
return pc.statsID
}
// hasLocalDescriptionChanged returns whether local media (rtpTransceivers) has changed
// caller of this method should hold `pc.mu` lock
func (pc *PeerConnection) hasLocalDescriptionChanged(desc *SessionDescription) bool {
for _, t := range pc.rtpTransceivers {
m := getByMid(t.Mid(), desc)
if m == nil {
return true
}
if getPeerDirection(m) != t.Direction() {
return true
}
}
return false
}
// CreateOffer starts the PeerConnection and generates the localDescription
// https://w3c.github.io/webrtc-pc/#dom-rtcpeerconnection-createoffer
func (pc *PeerConnection) CreateOffer(options *OfferOptions) (SessionDescription, error) { //nolint:gocognit
useIdentity := pc.idpLoginURL != nil
switch {
case useIdentity:
return SessionDescription{}, errIdentityProviderNotImplemented
case pc.isClosed.get():
return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
if options != nil && options.ICERestart {
if err := pc.iceTransport.restart(); err != nil {
return SessionDescription{}, err
}
}
var (
d *sdp.SessionDescription
offer SessionDescription
err error
)
// This may be necessary to recompute if, for example, createOffer was called when only an
// audio RTCRtpTransceiver was added to connection, but while performing the in-parallel
// steps to create an offer, a video RTCRtpTransceiver was added, requiring additional
// inspection of video system resources.
count := 0
pc.mu.Lock()
defer pc.mu.Unlock()
for {
// We cache current transceivers to ensure they aren't
// mutated during offer generation. We later check if they have
// been mutated and recompute the offer if necessary.
currentTransceivers := pc.rtpTransceivers
// in-parallel steps to create an offer
// https://w3c.github.io/webrtc-pc/#dfn-in-parallel-steps-to-create-an-offer
isPlanB := pc.configuration.SDPSemantics == SDPSemanticsPlanB
if pc.currentRemoteDescription != nil && isPlanB {
isPlanB = descriptionPossiblyPlanB(pc.currentRemoteDescription)
}
// include unmatched local transceivers
if !isPlanB {
// update the greater mid if the remote description provides a greater one
if pc.currentRemoteDescription != nil {
var numericMid int
for _, media := range pc.currentRemoteDescription.parsed.MediaDescriptions {
mid := getMidValue(media)
if mid == "" {
continue
}
numericMid, err = strconv.Atoi(mid)
if err != nil {
continue
}
if numericMid > pc.greaterMid {
pc.greaterMid = numericMid
}
}
}
for _, t := range currentTransceivers {
if mid := t.Mid(); mid != "" {
numericMid, errMid := strconv.Atoi(mid)
if errMid == nil {
if numericMid > pc.greaterMid {
pc.greaterMid = numericMid
}
}
continue
}
pc.greaterMid++
err = t.SetMid(strconv.Itoa(pc.greaterMid))
if err != nil {
return SessionDescription{}, err
}
}
}
if pc.currentRemoteDescription == nil {
d, err = pc.generateUnmatchedSDP(currentTransceivers, useIdentity)
} else {
d, err = pc.generateMatchedSDP(currentTransceivers, useIdentity, true /*includeUnmatched */, connectionRoleFromDtlsRole(defaultDtlsRoleOffer))
}
if err != nil {
return SessionDescription{}, err
}
updateSDPOrigin(&pc.sdpOrigin, d)
sdpBytes, err := d.Marshal()
if err != nil {
return SessionDescription{}, err
}
offer = SessionDescription{
Type: SDPTypeOffer,
SDP: string(sdpBytes),
parsed: d,
}
// Verify local media hasn't changed during offer
// generation. Recompute if necessary
if isPlanB || !pc.hasLocalDescriptionChanged(&offer) {
break
}
count++
if count >= 128 {
return SessionDescription{}, errExcessiveRetries
}
}
pc.lastOffer = offer.SDP
return offer, nil
}
func (pc *PeerConnection) createICEGatherer() (*ICEGatherer, error) {
g, err := pc.api.NewICEGatherer(ICEGatherOptions{
ICEServers: pc.configuration.getICEServers(),
ICEGatherPolicy: pc.configuration.ICETransportPolicy,
})
if err != nil {
return nil, err
}
return g, nil
}
// Update the PeerConnectionState given the state of relevant transports
// https://www.w3.org/TR/webrtc/#rtcpeerconnectionstate-enum
func (pc *PeerConnection) updateConnectionState(iceConnectionState ICEConnectionState, dtlsTransportState DTLSTransportState) {
connectionState := PeerConnectionStateNew
switch {
// The RTCPeerConnection object's [[IsClosed]] slot is true.
case pc.isClosed.get():
connectionState = PeerConnectionStateClosed
// Any of the RTCIceTransports or RTCDtlsTransports are in a "failed" state.
case iceConnectionState == ICEConnectionStateFailed || dtlsTransportState == DTLSTransportStateFailed:
connectionState = PeerConnectionStateFailed
// Any of the RTCIceTransports or RTCDtlsTransports are in the "disconnected"
// state and none of them are in the "failed" or "connecting" or "checking" state. */
case iceConnectionState == ICEConnectionStateDisconnected:
connectionState = PeerConnectionStateDisconnected
// All RTCIceTransports and RTCDtlsTransports are in the "connected", "completed" or "closed"
// state and at least one of them is in the "connected" or "completed" state.
case iceConnectionState == ICEConnectionStateConnected && dtlsTransportState == DTLSTransportStateConnected:
connectionState = PeerConnectionStateConnected
// Any of the RTCIceTransports or RTCDtlsTransports are in the "connecting" or
// "checking" state and none of them is in the "failed" state.
case iceConnectionState == ICEConnectionStateChecking && dtlsTransportState == DTLSTransportStateConnecting:
connectionState = PeerConnectionStateConnecting
}
if pc.connectionState.Load() == connectionState {
return
}
pc.onConnectionStateChange(connectionState)
}
func (pc *PeerConnection) createICETransport() *ICETransport {
t := pc.api.NewICETransport(pc.iceGatherer)
t.internalOnConnectionStateChangeHandler.Store(func(state ICETransportState) {
var cs ICEConnectionState
switch state {
case ICETransportStateNew:
cs = ICEConnectionStateNew
case ICETransportStateChecking:
cs = ICEConnectionStateChecking
case ICETransportStateConnected:
cs = ICEConnectionStateConnected
case ICETransportStateCompleted:
cs = ICEConnectionStateCompleted
case ICETransportStateFailed:
cs = ICEConnectionStateFailed
case ICETransportStateDisconnected:
cs = ICEConnectionStateDisconnected
case ICETransportStateClosed:
cs = ICEConnectionStateClosed
default:
pc.log.Warnf("OnConnectionStateChange: unhandled ICE state: %s", state)
return
}
pc.onICEConnectionStateChange(cs)
pc.updateConnectionState(cs, pc.dtlsTransport.State())
})
return t
}
// CreateAnswer starts the PeerConnection and generates the localDescription
func (pc *PeerConnection) CreateAnswer(options *AnswerOptions) (SessionDescription, error) {
useIdentity := pc.idpLoginURL != nil
remoteDesc := pc.RemoteDescription()
switch {
case remoteDesc == nil:
return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrNoRemoteDescription}
case useIdentity:
return SessionDescription{}, errIdentityProviderNotImplemented
case pc.isClosed.get():
return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
case pc.signalingState.Get() != SignalingStateHaveRemoteOffer && pc.signalingState.Get() != SignalingStateHaveLocalPranswer:
return SessionDescription{}, &rtcerr.InvalidStateError{Err: ErrIncorrectSignalingState}
}
connectionRole := connectionRoleFromDtlsRole(pc.api.settingEngine.answeringDTLSRole)
if connectionRole == sdp.ConnectionRole(0) {
connectionRole = connectionRoleFromDtlsRole(defaultDtlsRoleAnswer)
// If one of the agents is lite and the other one is not, the lite agent must be the controlling agent.
// If both or neither agents are lite the offering agent is controlling.
// RFC 8445 S6.1.1
if isIceLiteSet(remoteDesc.parsed) && !pc.api.settingEngine.candidates.ICELite {
connectionRole = connectionRoleFromDtlsRole(DTLSRoleServer)
}
}
pc.mu.Lock()
defer pc.mu.Unlock()
d, err := pc.generateMatchedSDP(pc.rtpTransceivers, useIdentity, false /*includeUnmatched */, connectionRole)
if err != nil {
return SessionDescription{}, err
}
updateSDPOrigin(&pc.sdpOrigin, d)
sdpBytes, err := d.Marshal()
if err != nil {
return SessionDescription{}, err
}
desc := SessionDescription{
Type: SDPTypeAnswer,
SDP: string(sdpBytes),
parsed: d,
}
pc.lastAnswer = desc.SDP
return desc, nil
}
// 4.4.1.6 Set the SessionDescription
func (pc *PeerConnection) setDescription(sd *SessionDescription, op stateChangeOp) error { //nolint:gocognit
switch {
case pc.isClosed.get():
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
case NewSDPType(sd.Type.String()) == SDPType(Unknown):
return &rtcerr.TypeError{Err: fmt.Errorf("%w: '%d' is not a valid enum value of type SDPType", errPeerConnSDPTypeInvalidValue, sd.Type)}
}
nextState, err := func() (SignalingState, error) {
pc.mu.Lock()
defer pc.mu.Unlock()
cur := pc.SignalingState()
setLocal := stateChangeOpSetLocal
setRemote := stateChangeOpSetRemote
newSDPDoesNotMatchOffer := &rtcerr.InvalidModificationError{Err: errSDPDoesNotMatchOffer}
newSDPDoesNotMatchAnswer := &rtcerr.InvalidModificationError{Err: errSDPDoesNotMatchAnswer}
var nextState SignalingState
var err error
switch op {
case setLocal:
switch sd.Type {
// stable->SetLocal(offer)->have-local-offer
case SDPTypeOffer:
if sd.SDP != pc.lastOffer {
return nextState, newSDPDoesNotMatchOffer
}
nextState, err = checkNextSignalingState(cur, SignalingStateHaveLocalOffer, setLocal, sd.Type)
if err == nil {
pc.pendingLocalDescription = sd
}
// have-remote-offer->SetLocal(answer)->stable
// have-local-pranswer->SetLocal(answer)->stable
case SDPTypeAnswer:
if sd.SDP != pc.lastAnswer {
return nextState, newSDPDoesNotMatchAnswer
}
nextState, err = checkNextSignalingState(cur, SignalingStateStable, setLocal, sd.Type)
if err == nil {
pc.currentLocalDescription = sd
pc.currentRemoteDescription = pc.pendingRemoteDescription
pc.pendingRemoteDescription = nil
pc.pendingLocalDescription = nil
}
case SDPTypeRollback:
nextState, err = checkNextSignalingState(cur, SignalingStateStable, setLocal, sd.Type)
if err == nil {
pc.pendingLocalDescription = nil
}
// have-remote-offer->SetLocal(pranswer)->have-local-pranswer
case SDPTypePranswer:
if sd.SDP != pc.lastAnswer {
return nextState, newSDPDoesNotMatchAnswer
}
nextState, err = checkNextSignalingState(cur, SignalingStateHaveLocalPranswer, setLocal, sd.Type)
if err == nil {
pc.pendingLocalDescription = sd
}
default:
return nextState, &rtcerr.OperationError{Err: fmt.Errorf("%w: %s(%s)", errPeerConnStateChangeInvalid, op, sd.Type)}
}
case setRemote:
switch sd.Type {
// stable->SetRemote(offer)->have-remote-offer
case SDPTypeOffer:
nextState, err = checkNextSignalingState(cur, SignalingStateHaveRemoteOffer, setRemote, sd.Type)
if err == nil {
pc.pendingRemoteDescription = sd
}
// have-local-offer->SetRemote(answer)->stable
// have-remote-pranswer->SetRemote(answer)->stable
case SDPTypeAnswer:
nextState, err = checkNextSignalingState(cur, SignalingStateStable, setRemote, sd.Type)
if err == nil {
pc.currentRemoteDescription = sd
pc.currentLocalDescription = pc.pendingLocalDescription
pc.pendingRemoteDescription = nil
pc.pendingLocalDescription = nil
}
case SDPTypeRollback:
nextState, err = checkNextSignalingState(cur, SignalingStateStable, setRemote, sd.Type)
if err == nil {
pc.pendingRemoteDescription = nil
}
// have-local-offer->SetRemote(pranswer)->have-remote-pranswer
case SDPTypePranswer:
nextState, err = checkNextSignalingState(cur, SignalingStateHaveRemotePranswer, setRemote, sd.Type)
if err == nil {
pc.pendingRemoteDescription = sd
}
default:
return nextState, &rtcerr.OperationError{Err: fmt.Errorf("%w: %s(%s)", errPeerConnStateChangeInvalid, op, sd.Type)}
}
default:
return nextState, &rtcerr.OperationError{Err: fmt.Errorf("%w: %q", errPeerConnStateChangeUnhandled, op)}
}
return nextState, err
}()
if err == nil {
pc.signalingState.Set(nextState)
if pc.signalingState.Get() == SignalingStateStable {
pc.isNegotiationNeeded.set(false)
pc.mu.Lock()
pc.onNegotiationNeeded()
pc.mu.Unlock()
}
pc.onSignalingStateChange(nextState)
}
return err
}
// SetLocalDescription sets the SessionDescription of the local peer
func (pc *PeerConnection) SetLocalDescription(desc SessionDescription) error {
if pc.isClosed.get() {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
haveLocalDescription := pc.currentLocalDescription != nil
// JSEP 5.4
if desc.SDP == "" {
switch desc.Type {
case SDPTypeAnswer, SDPTypePranswer:
desc.SDP = pc.lastAnswer
case SDPTypeOffer:
desc.SDP = pc.lastOffer
default:
return &rtcerr.InvalidModificationError{
Err: fmt.Errorf("%w: %s", errPeerConnSDPTypeInvalidValueSetLocalDescription, desc.Type),
}
}
}
desc.parsed = &sdp.SessionDescription{}
if err := desc.parsed.Unmarshal([]byte(desc.SDP)); err != nil {
return err
}
if err := pc.setDescription(&desc, stateChangeOpSetLocal); err != nil {
return err
}
currentTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...)
weAnswer := desc.Type == SDPTypeAnswer
remoteDesc := pc.RemoteDescription()
if weAnswer && remoteDesc != nil {
_ = setRTPTransceiverCurrentDirection(&desc, currentTransceivers, false)
if err := pc.startRTPSenders(currentTransceivers); err != nil {
return err
}
pc.configureRTPReceivers(haveLocalDescription, remoteDesc, currentTransceivers)
pc.ops.Enqueue(func() {
pc.startRTP(haveLocalDescription, remoteDesc, currentTransceivers)
})
}
if pc.iceGatherer.State() == ICEGathererStateNew {
return pc.iceGatherer.Gather()
}
return nil
}
// LocalDescription returns PendingLocalDescription if it is not null and
// otherwise it returns CurrentLocalDescription. This property is used to
// determine if SetLocalDescription has already been called.
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-localdescription
func (pc *PeerConnection) LocalDescription() *SessionDescription {
if pendingLocalDescription := pc.PendingLocalDescription(); pendingLocalDescription != nil {
return pendingLocalDescription
}
return pc.CurrentLocalDescription()
}
// SetRemoteDescription sets the SessionDescription of the remote peer
// nolint: gocyclo
func (pc *PeerConnection) SetRemoteDescription(desc SessionDescription) error { //nolint:gocognit
if pc.isClosed.get() {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
isRenegotation := pc.currentRemoteDescription != nil
if _, err := desc.Unmarshal(); err != nil {
return err
}
if err := pc.setDescription(&desc, stateChangeOpSetRemote); err != nil {
return err
}
if err := pc.api.mediaEngine.updateFromRemoteDescription(*desc.parsed); err != nil {
return err
}
var t *RTPTransceiver
localTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...)
detectedPlanB := descriptionIsPlanB(pc.RemoteDescription(), pc.log)
if pc.configuration.SDPSemantics != SDPSemanticsUnifiedPlan {
detectedPlanB = descriptionPossiblyPlanB(pc.RemoteDescription())
}
weOffer := desc.Type == SDPTypeAnswer
if !weOffer && !detectedPlanB {
for _, media := range pc.RemoteDescription().parsed.MediaDescriptions {
midValue := getMidValue(media)
if midValue == "" {
return errPeerConnRemoteDescriptionWithoutMidValue
}
if media.MediaName.Media == mediaSectionApplication {
continue
}
kind := NewRTPCodecType(media.MediaName.Media)
direction := getPeerDirection(media)
if kind == 0 || direction == RTPTransceiverDirection(Unknown) {
continue
}
t, localTransceivers = findByMid(midValue, localTransceivers)
if t == nil {
t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers)
} else if direction == RTPTransceiverDirectionInactive {
if err := t.Stop(); err != nil {
return err
}
}
switch {
case t == nil:
receiver, err := pc.api.NewRTPReceiver(kind, pc.dtlsTransport)
if err != nil {
return err
}
localDirection := RTPTransceiverDirectionRecvonly
if direction == RTPTransceiverDirectionRecvonly {
localDirection = RTPTransceiverDirectionSendonly
} else if direction == RTPTransceiverDirectionInactive {
localDirection = RTPTransceiverDirectionInactive
}
t = newRTPTransceiver(receiver, nil, localDirection, kind, pc.api)
pc.mu.Lock()
pc.addRTPTransceiver(t)
pc.mu.Unlock()
// if transceiver is create by remote sdp, set prefer codec same as remote peer
if codecs, err := codecsFromMediaDescription(media); err == nil {
filteredCodecs := []RTPCodecParameters{}
for _, codec := range codecs {
if c, matchType := codecParametersFuzzySearch(codec, pc.api.mediaEngine.getCodecsByKind(kind)); matchType == codecMatchExact {
// if codec match exact, use payloadtype register to mediaengine
codec.PayloadType = c.PayloadType
filteredCodecs = append(filteredCodecs, codec)
}
}
_ = t.SetCodecPreferences(filteredCodecs)
}
case direction == RTPTransceiverDirectionRecvonly:
if t.Direction() == RTPTransceiverDirectionSendrecv {
t.setDirection(RTPTransceiverDirectionSendonly)
}
case direction == RTPTransceiverDirectionSendrecv:
if t.Direction() == RTPTransceiverDirectionSendonly {
t.setDirection(RTPTransceiverDirectionSendrecv)
}
}
if t.Mid() == "" {
if err := t.SetMid(midValue); err != nil {
return err
}
}
}
}
remoteUfrag, remotePwd, candidates, err := extractICEDetails(desc.parsed, pc.log)
if err != nil {
return err
}
if isRenegotation && pc.iceTransport.haveRemoteCredentialsChange(remoteUfrag, remotePwd) {
// An ICE Restart only happens implicitly for a SetRemoteDescription of type offer
if !weOffer {
if err = pc.iceTransport.restart(); err != nil {
return err
}
}
if err = pc.iceTransport.setRemoteCredentials(remoteUfrag, remotePwd); err != nil {
return err
}
}
for i := range candidates {
if err = pc.iceTransport.AddRemoteCandidate(&candidates[i]); err != nil {
return err
}
}
currentTransceivers := append([]*RTPTransceiver{}, pc.GetTransceivers()...)
if isRenegotation {
if weOffer {
_ = setRTPTransceiverCurrentDirection(&desc, currentTransceivers, true)
if err = pc.startRTPSenders(currentTransceivers); err != nil {
return err
}
pc.configureRTPReceivers(true, &desc, currentTransceivers)
pc.ops.Enqueue(func() {
pc.startRTP(true, &desc, currentTransceivers)
})
}
return nil
}
remoteIsLite := isIceLiteSet(desc.parsed)
fingerprint, fingerprintHash, err := extractFingerprint(desc.parsed)
if err != nil {
return err
}
iceRole := ICERoleControlled
// If one of the agents is lite and the other one is not, the lite agent must be the controlling agent.
// If both or neither agents are lite the offering agent is controlling.
// RFC 8445 S6.1.1
if (weOffer && remoteIsLite == pc.api.settingEngine.candidates.ICELite) || (remoteIsLite && !pc.api.settingEngine.candidates.ICELite) {
iceRole = ICERoleControlling
}
// Start the networking in a new routine since it will block until
// the connection is actually established.
if weOffer {
_ = setRTPTransceiverCurrentDirection(&desc, currentTransceivers, true)
if err := pc.startRTPSenders(currentTransceivers); err != nil {
return err
}
pc.configureRTPReceivers(false, &desc, currentTransceivers)
}
pc.ops.Enqueue(func() {
pc.startTransports(iceRole, dtlsRoleFromRemoteSDP(desc.parsed), remoteUfrag, remotePwd, fingerprint, fingerprintHash)
if weOffer {
pc.startRTP(false, &desc, currentTransceivers)
}
})
return nil
}
func (pc *PeerConnection) configureReceiver(incoming trackDetails, receiver *RTPReceiver) {
receiver.configureReceive(trackDetailsToRTPReceiveParameters(&incoming))
// set track id and label early so they can be set as new track information
// is received from the SDP.
for i := range receiver.tracks {
receiver.tracks[i].track.mu.Lock()
receiver.tracks[i].track.id = incoming.id
receiver.tracks[i].track.streamID = incoming.streamID
receiver.tracks[i].track.mu.Unlock()
}
}
func (pc *PeerConnection) startReceiver(incoming trackDetails, receiver *RTPReceiver) {
if err := receiver.startReceive(trackDetailsToRTPReceiveParameters(&incoming)); err != nil {
pc.log.Warnf("RTPReceiver Receive failed %s", err)
return
}
for _, t := range receiver.Tracks() {
if t.SSRC() == 0 || t.RID() != "" {
return
}
go func(track *TrackRemote) {
b := make([]byte, pc.api.settingEngine.getReceiveMTU())
n, _, err := track.peek(b)
if err != nil {
pc.log.Warnf("Could not determine PayloadType for SSRC %d (%s)", track.SSRC(), err)
return
}
if err = track.checkAndUpdateTrack(b[:n]); err != nil {
pc.log.Warnf("Failed to set codec settings for track SSRC %d (%s)", track.SSRC(), err)
return
}
pc.onTrack(track, receiver)
}(t)
}
}
func setRTPTransceiverCurrentDirection(answer *SessionDescription, currentTransceivers []*RTPTransceiver, weOffer bool) error {
currentTransceivers = append([]*RTPTransceiver{}, currentTransceivers...)
for _, media := range answer.parsed.MediaDescriptions {
midValue := getMidValue(media)
if midValue == "" {
return errPeerConnRemoteDescriptionWithoutMidValue
}
if media.MediaName.Media == mediaSectionApplication {
continue
}
var t *RTPTransceiver
t, currentTransceivers = findByMid(midValue, currentTransceivers)
if t == nil {
return fmt.Errorf("%w: %q", errPeerConnTranscieverMidNil, midValue)
}
direction := getPeerDirection(media)
if direction == RTPTransceiverDirection(Unknown) {
continue
}
// reverse direction if it was a remote answer
if weOffer {
switch direction {
case RTPTransceiverDirectionSendonly:
direction = RTPTransceiverDirectionRecvonly
case RTPTransceiverDirectionRecvonly:
direction = RTPTransceiverDirectionSendonly
default:
}
}
// If a transceiver is created by applying a remote description that has recvonly transceiver,
// it will have no sender. In this case, the transceiver's current direction is set to inactive so
// that the transceiver can be reused by next AddTrack.
if direction == RTPTransceiverDirectionSendonly && t.Sender() == nil {
direction = RTPTransceiverDirectionInactive
}
t.setCurrentDirection(direction)
}
return nil
}
func runIfNewReceiver(
incomingTrack trackDetails,
transceivers []*RTPTransceiver,
f func(incomingTrack trackDetails, receiver *RTPReceiver),
) bool {
for _, t := range transceivers {
if t.Mid() != incomingTrack.mid {
continue
}
receiver := t.Receiver()
if (incomingTrack.kind != t.Kind()) ||
(t.Direction() != RTPTransceiverDirectionRecvonly && t.Direction() != RTPTransceiverDirectionSendrecv) ||
receiver == nil ||
(receiver.haveReceived()) {
continue
}
f(incomingTrack, receiver)
return true
}
return false
}
// configurepRTPReceivers opens knows inbound SRTP streams from the RemoteDescription
func (pc *PeerConnection) configureRTPReceivers(isRenegotiation bool, remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) { //nolint:gocognit
incomingTracks := trackDetailsFromSDP(pc.log, remoteDesc.parsed)
if isRenegotiation {
for _, t := range currentTransceivers {
receiver := t.Receiver()
if receiver == nil {
continue
}
tracks := t.Receiver().Tracks()
if len(tracks) == 0 {
continue
}
receiverNeedsStopped := false
func() {
for _, t := range tracks {
t.mu.Lock()
defer t.mu.Unlock()
if t.rid != "" {
if details := trackDetailsForRID(incomingTracks, t.rid); details != nil {
t.id = details.id
t.streamID = details.streamID
continue
}
} else if t.ssrc != 0 {
if details := trackDetailsForSSRC(incomingTracks, t.ssrc); details != nil {
t.id = details.id
t.streamID = details.streamID
continue
}
}
receiverNeedsStopped = true
}
}()
if !receiverNeedsStopped {
continue
}
if err := receiver.Stop(); err != nil {
pc.log.Warnf("Failed to stop RtpReceiver: %s", err)
continue
}
receiver, err := pc.api.NewRTPReceiver(receiver.kind, pc.dtlsTransport)
if err != nil {
pc.log.Warnf("Failed to create new RtpReceiver: %s", err)
continue
}
t.setReceiver(receiver)
}
}
localTransceivers := append([]*RTPTransceiver{}, currentTransceivers...)
// Ensure we haven't already started a transceiver for this ssrc
filteredTracks := append([]trackDetails{}, incomingTracks...)
for _, incomingTrack := range incomingTracks {
// If we already have a TrackRemote for a given SSRC don't handle it again
for _, t := range localTransceivers {
if receiver := t.Receiver(); receiver != nil {
for _, track := range receiver.Tracks() {
for _, ssrc := range incomingTrack.ssrcs {
if ssrc == track.SSRC() {
filteredTracks = filterTrackWithSSRC(filteredTracks, track.SSRC())
}
}
}
}
}
}
for _, incomingTrack := range filteredTracks {
_ = runIfNewReceiver(incomingTrack, localTransceivers, pc.configureReceiver)
}
}
// startRTPReceivers opens knows inbound SRTP streams from the RemoteDescription
func (pc *PeerConnection) startRTPReceivers(remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) {
incomingTracks := trackDetailsFromSDP(pc.log, remoteDesc.parsed)
if len(incomingTracks) == 0 {
return
}
localTransceivers := append([]*RTPTransceiver{}, currentTransceivers...)
unhandledTracks := incomingTracks[:0]
for _, incomingTrack := range incomingTracks {
trackHandled := runIfNewReceiver(incomingTrack, localTransceivers, pc.startReceiver)
if !trackHandled {
unhandledTracks = append(unhandledTracks, incomingTrack)
}
}
remoteIsPlanB := false
switch pc.configuration.SDPSemantics {
case SDPSemanticsPlanB:
remoteIsPlanB = true
case SDPSemanticsUnifiedPlanWithFallback:
remoteIsPlanB = descriptionPossiblyPlanB(pc.RemoteDescription())
default:
// none
}
if remoteIsPlanB {
for _, incomingTrack := range unhandledTracks {
t, err := pc.AddTransceiverFromKind(incomingTrack.kind, RTPTransceiverInit{
Direction: RTPTransceiverDirectionSendrecv,
})
if err != nil {
pc.log.Warnf("Could not add transceiver for remote SSRC %d: %s", incomingTrack.ssrcs[0], err)
continue
}
pc.configureReceiver(incomingTrack, t.Receiver())
pc.startReceiver(incomingTrack, t.Receiver())
}
}
}
// startRTPSenders starts all outbound RTP streams
func (pc *PeerConnection) startRTPSenders(currentTransceivers []*RTPTransceiver) error {
for _, transceiver := range currentTransceivers {
if sender := transceiver.Sender(); sender != nil && sender.isNegotiated() && !sender.hasSent() {
err := sender.Send(sender.GetParameters())
if err != nil {
return err
}
}
}
return nil
}
// Start SCTP subsystem
func (pc *PeerConnection) startSCTP() {
// Start sctp
if err := pc.sctpTransport.Start(SCTPCapabilities{
MaxMessageSize: 0,
}); err != nil {
pc.log.Warnf("Failed to start SCTP: %s", err)
if err = pc.sctpTransport.Stop(); err != nil {
pc.log.Warnf("Failed to stop SCTPTransport: %s", err)
}
return
}
}
func (pc *PeerConnection) handleUndeclaredSSRC(ssrc SSRC, remoteDescription *SessionDescription) (handled bool, err error) {
if len(remoteDescription.parsed.MediaDescriptions) != 1 {
return false, nil
}
onlyMediaSection := remoteDescription.parsed.MediaDescriptions[0]
streamID := ""
id := ""
for _, a := range onlyMediaSection.Attributes {
switch a.Key {
case sdp.AttrKeyMsid:
if split := strings.Split(a.Value, " "); len(split) == 2 {
streamID = split[0]
id = split[1]
}
case sdp.AttrKeySSRC:
return false, errPeerConnSingleMediaSectionHasExplicitSSRC
case sdpAttributeRid:
return false, nil
}
}
incoming := trackDetails{
ssrcs: []SSRC{ssrc},
kind: RTPCodecTypeVideo,
streamID: streamID,
id: id,
}
if onlyMediaSection.MediaName.Media == RTPCodecTypeAudio.String() {
incoming.kind = RTPCodecTypeAudio
}
t, err := pc.AddTransceiverFromKind(incoming.kind, RTPTransceiverInit{
Direction: RTPTransceiverDirectionSendrecv,
})
if err != nil {
return false, fmt.Errorf("%w: %d: %s", errPeerConnRemoteSSRCAddTransceiver, ssrc, err)
}
pc.configureReceiver(incoming, t.Receiver())
pc.startReceiver(incoming, t.Receiver())
return true, nil
}
func (pc *PeerConnection) handleIncomingSSRC(rtpStream io.Reader, ssrc SSRC) error { //nolint:gocognit
remoteDescription := pc.RemoteDescription()
if remoteDescription == nil {
return errPeerConnRemoteDescriptionNil
}
// If a SSRC already exists in the RemoteDescription don't perform heuristics upon it
for _, track := range trackDetailsFromSDP(pc.log, remoteDescription.parsed) {
if track.repairSsrc != nil && ssrc == *track.repairSsrc {
return nil
}
for _, trackSsrc := range track.ssrcs {
if ssrc == trackSsrc {
return nil
}
}
}
// If the remote SDP was only one media section the ssrc doesn't have to be explicitly declared
if handled, err := pc.handleUndeclaredSSRC(ssrc, remoteDescription); handled || err != nil {
return err
}
midExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdp.SDESMidURI})
if !audioSupported && !videoSupported {
return errPeerConnSimulcastMidRTPExtensionRequired
}
streamIDExtensionID, audioSupported, videoSupported := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdp.SDESRTPStreamIDURI})
if !audioSupported && !videoSupported {
return errPeerConnSimulcastStreamIDRTPExtensionRequired
}
repairStreamIDExtensionID, _, _ := pc.api.mediaEngine.getHeaderExtensionID(RTPHeaderExtensionCapability{sdesRepairRTPStreamIDURI})
b := make([]byte, pc.api.settingEngine.getReceiveMTU())
i, err := rtpStream.Read(b)
if err != nil {
return err
}
var mid, rid, rsid string
payloadType, err := handleUnknownRTPPacket(b[:i], uint8(midExtensionID), uint8(streamIDExtensionID), uint8(repairStreamIDExtensionID), &mid, &rid, &rsid)
if err != nil {
return err
}
params, err := pc.api.mediaEngine.getRTPParametersByPayloadType(payloadType)
if err != nil {
return err
}
streamInfo := createStreamInfo("", ssrc, params.Codecs[0].PayloadType, params.Codecs[0].RTPCodecCapability, params.HeaderExtensions)
readStream, interceptor, rtcpReadStream, rtcpInterceptor, err := pc.dtlsTransport.streamsForSSRC(ssrc, *streamInfo)
if err != nil {
return err
}
for readCount := 0; readCount <= simulcastProbeCount; readCount++ {
if mid == "" || (rid == "" && rsid == "") {
i, _, err := interceptor.Read(b, nil)
if err != nil {
return err
}
if _, err = handleUnknownRTPPacket(b[:i], uint8(midExtensionID), uint8(streamIDExtensionID), uint8(repairStreamIDExtensionID), &mid, &rid, &rsid); err != nil {
return err
}
continue
}
for _, t := range pc.GetTransceivers() {
receiver := t.Receiver()
if t.Mid() != mid || receiver == nil {
continue
}
if rsid != "" {
receiver.mu.Lock()
defer receiver.mu.Unlock()
return receiver.receiveForRtx(SSRC(0), rsid, streamInfo, readStream, interceptor, rtcpReadStream, rtcpInterceptor)
}
track, err := receiver.receiveForRid(rid, params, streamInfo, readStream, interceptor, rtcpReadStream, rtcpInterceptor)
if err != nil {
return err
}
pc.onTrack(track, receiver)
return nil
}
}
pc.api.interceptor.UnbindRemoteStream(streamInfo)
return errPeerConnSimulcastIncomingSSRCFailed
}
// undeclaredMediaProcessor handles RTP/RTCP packets that don't match any a:ssrc lines
func (pc *PeerConnection) undeclaredMediaProcessor() {
go pc.undeclaredRTPMediaProcessor()
go pc.undeclaredRTCPMediaProcessor()
}
func (pc *PeerConnection) undeclaredRTPMediaProcessor() {
var simulcastRoutineCount uint64
for {
srtpSession, err := pc.dtlsTransport.getSRTPSession()
if err != nil {
pc.log.Warnf("undeclaredMediaProcessor failed to open SrtpSession: %v", err)
return
}
stream, ssrc, err := srtpSession.AcceptStream()
if err != nil {
pc.log.Warnf("Failed to accept RTP %v", err)
return
}
if pc.isClosed.get() {
if err = stream.Close(); err != nil {
pc.log.Warnf("Failed to close RTP stream %v", err)
}
continue
}
if atomic.AddUint64(&simulcastRoutineCount, 1) >= simulcastMaxProbeRoutines {
atomic.AddUint64(&simulcastRoutineCount, ^uint64(0))
pc.log.Warn(ErrSimulcastProbeOverflow.Error())
pc.dtlsTransport.storeSimulcastStream(stream)
continue
}
go func(rtpStream io.Reader, ssrc SSRC) {
if err := pc.handleIncomingSSRC(rtpStream, ssrc); err != nil {
pc.log.Errorf(incomingUnhandledRTPSsrc, ssrc, err)
pc.dtlsTransport.storeSimulcastStream(stream)
}
atomic.AddUint64(&simulcastRoutineCount, ^uint64(0))
}(stream, SSRC(ssrc))
}
}
func (pc *PeerConnection) undeclaredRTCPMediaProcessor() {
var unhandledStreams []*srtp.ReadStreamSRTCP
defer func() {
for _, s := range unhandledStreams {
_ = s.Close()
}
}()
for {
srtcpSession, err := pc.dtlsTransport.getSRTCPSession()
if err != nil {
pc.log.Warnf("undeclaredMediaProcessor failed to open SrtcpSession: %v", err)
return
}
stream, ssrc, err := srtcpSession.AcceptStream()
if err != nil {
pc.log.Warnf("Failed to accept RTCP %v", err)
return
}
pc.log.Warnf("Incoming unhandled RTCP ssrc(%d), OnTrack will not be fired", ssrc)
unhandledStreams = append(unhandledStreams, stream)
}
}
// RemoteDescription returns pendingRemoteDescription if it is not null and
// otherwise it returns currentRemoteDescription. This property is used to
// determine if setRemoteDescription has already been called.
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-remotedescription
func (pc *PeerConnection) RemoteDescription() *SessionDescription {
pc.mu.RLock()
defer pc.mu.RUnlock()
if pc.pendingRemoteDescription != nil {
return pc.pendingRemoteDescription
}
return pc.currentRemoteDescription
}
// AddICECandidate accepts an ICE candidate string and adds it
// to the existing set of candidates.
func (pc *PeerConnection) AddICECandidate(candidate ICECandidateInit) error {
if pc.RemoteDescription() == nil {
return &rtcerr.InvalidStateError{Err: ErrNoRemoteDescription}
}
candidateValue := strings.TrimPrefix(candidate.Candidate, "candidate:")
var iceCandidate *ICECandidate
if candidateValue != "" {
candidate, err := ice.UnmarshalCandidate(candidateValue)
if err != nil {
if errors.Is(err, ice.ErrUnknownCandidateTyp) || errors.Is(err, ice.ErrDetermineNetworkType) {
pc.log.Warnf("Discarding remote candidate: %s", err)
return nil
}
return err
}
c, err := newICECandidateFromICE(candidate)
if err != nil {
return err
}
iceCandidate = &c
}
return pc.iceTransport.AddRemoteCandidate(iceCandidate)
}
// ICEConnectionState returns the ICE connection state of the
// PeerConnection instance.
func (pc *PeerConnection) ICEConnectionState() ICEConnectionState {
if state, ok := pc.iceConnectionState.Load().(ICEConnectionState); ok {
return state
}
return ICEConnectionState(0)
}
// GetSenders returns the RTPSender that are currently attached to this PeerConnection
func (pc *PeerConnection) GetSenders() (result []*RTPSender) {
pc.mu.Lock()
defer pc.mu.Unlock()
for _, transceiver := range pc.rtpTransceivers {
if sender := transceiver.Sender(); sender != nil {
result = append(result, sender)
}
}
return result
}
// GetReceivers returns the RTPReceivers that are currently attached to this PeerConnection
func (pc *PeerConnection) GetReceivers() (receivers []*RTPReceiver) {
pc.mu.Lock()
defer pc.mu.Unlock()
for _, transceiver := range pc.rtpTransceivers {
if receiver := transceiver.Receiver(); receiver != nil {
receivers = append(receivers, receiver)
}
}
return
}
// GetTransceivers returns the RtpTransceiver that are currently attached to this PeerConnection
func (pc *PeerConnection) GetTransceivers() []*RTPTransceiver {
pc.mu.Lock()
defer pc.mu.Unlock()
return pc.rtpTransceivers
}
// AddTrack adds a Track to the PeerConnection
func (pc *PeerConnection) AddTrack(track TrackLocal) (*RTPSender, error) {
if pc.isClosed.get() {
return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
pc.mu.Lock()
defer pc.mu.Unlock()
for _, t := range pc.rtpTransceivers {
currentDirection := t.getCurrentDirection()
// According to https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-addtrack, if the
// transceiver can be reused only if it's currentDirection never be sendrecv or sendonly.
// But that will cause sdp inflate. So we only check currentDirection's current value,
// that's worked for all browsers.
if !t.stopped && t.kind == track.Kind() && t.Sender() == nil &&
!(currentDirection == RTPTransceiverDirectionSendrecv || currentDirection == RTPTransceiverDirectionSendonly) {
sender, err := pc.api.NewRTPSender(track, pc.dtlsTransport)
if err == nil {
err = t.SetSender(sender, track)
if err != nil {
_ = sender.Stop()
t.setSender(nil)
}
}
if err != nil {
return nil, err
}
pc.onNegotiationNeeded()
return sender, nil
}
}
transceiver, err := pc.newTransceiverFromTrack(RTPTransceiverDirectionSendrecv, track)
if err != nil {
return nil, err
}
pc.addRTPTransceiver(transceiver)
return transceiver.Sender(), nil
}
// RemoveTrack removes a Track from the PeerConnection
func (pc *PeerConnection) RemoveTrack(sender *RTPSender) (err error) {
if pc.isClosed.get() {
return &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
var transceiver *RTPTransceiver
pc.mu.Lock()
defer pc.mu.Unlock()
for _, t := range pc.rtpTransceivers {
if t.Sender() == sender {
transceiver = t
break
}
}
if transceiver == nil {
return &rtcerr.InvalidAccessError{Err: ErrSenderNotCreatedByConnection}
} else if err = sender.Stop(); err == nil {
err = transceiver.setSendingTrack(nil)
if err == nil {
pc.onNegotiationNeeded()
}
}
return
}
func (pc *PeerConnection) newTransceiverFromTrack(direction RTPTransceiverDirection, track TrackLocal) (t *RTPTransceiver, err error) {
var (
r *RTPReceiver
s *RTPSender
)
switch direction {
case RTPTransceiverDirectionSendrecv:
r, err = pc.api.NewRTPReceiver(track.Kind(), pc.dtlsTransport)
if err != nil {
return
}
s, err = pc.api.NewRTPSender(track, pc.dtlsTransport)
case RTPTransceiverDirectionSendonly:
s, err = pc.api.NewRTPSender(track, pc.dtlsTransport)
default:
err = errPeerConnAddTransceiverFromTrackSupport
}
if err != nil {
return
}
return newRTPTransceiver(r, s, direction, track.Kind(), pc.api), nil
}
// AddTransceiverFromKind Create a new RtpTransceiver and adds it to the set of transceivers.
func (pc *PeerConnection) AddTransceiverFromKind(kind RTPCodecType, init ...RTPTransceiverInit) (t *RTPTransceiver, err error) {
if pc.isClosed.get() {
return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
direction := RTPTransceiverDirectionSendrecv
if len(init) > 1 {
return nil, errPeerConnAddTransceiverFromKindOnlyAcceptsOne
} else if len(init) == 1 {
direction = init[0].Direction
}
switch direction {
case RTPTransceiverDirectionSendonly, RTPTransceiverDirectionSendrecv:
codecs := pc.api.mediaEngine.getCodecsByKind(kind)
if len(codecs) == 0 {
return nil, ErrNoCodecsAvailable
}
track, err := NewTrackLocalStaticSample(codecs[0].RTPCodecCapability, util.MathRandAlpha(16), util.MathRandAlpha(16))
if err != nil {
return nil, err
}
t, err = pc.newTransceiverFromTrack(direction, track)
if err != nil {
return nil, err
}
case RTPTransceiverDirectionRecvonly:
receiver, err := pc.api.NewRTPReceiver(kind, pc.dtlsTransport)
if err != nil {
return nil, err
}
t = newRTPTransceiver(receiver, nil, RTPTransceiverDirectionRecvonly, kind, pc.api)
default:
return nil, errPeerConnAddTransceiverFromKindSupport
}
pc.mu.Lock()
pc.addRTPTransceiver(t)
pc.mu.Unlock()
return t, nil
}
// AddTransceiverFromTrack Create a new RtpTransceiver(SendRecv or SendOnly) and add it to the set of transceivers.
func (pc *PeerConnection) AddTransceiverFromTrack(track TrackLocal, init ...RTPTransceiverInit) (t *RTPTransceiver, err error) {
if pc.isClosed.get() {
return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
direction := RTPTransceiverDirectionSendrecv
if len(init) > 1 {
return nil, errPeerConnAddTransceiverFromTrackOnlyAcceptsOne
} else if len(init) == 1 {
direction = init[0].Direction
}
t, err = pc.newTransceiverFromTrack(direction, track)
if err == nil {
pc.mu.Lock()
pc.addRTPTransceiver(t)
pc.mu.Unlock()
}
return
}
// CreateDataChannel creates a new DataChannel object with the given label
// and optional DataChannelInit used to configure properties of the
// underlying channel such as data reliability.
func (pc *PeerConnection) CreateDataChannel(label string, options *DataChannelInit) (*DataChannel, error) {
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #2)
if pc.isClosed.get() {
return nil, &rtcerr.InvalidStateError{Err: ErrConnectionClosed}
}
params := &DataChannelParameters{
Label: label,
Ordered: true,
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #19)
if options != nil {
params.ID = options.ID
}
if options != nil {
// Ordered indicates if data is allowed to be delivered out of order. The
// default value of true, guarantees that data will be delivered in order.
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #9)
if options.Ordered != nil {
params.Ordered = *options.Ordered
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #7)
if options.MaxPacketLifeTime != nil {
params.MaxPacketLifeTime = options.MaxPacketLifeTime
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #8)
if options.MaxRetransmits != nil {
params.MaxRetransmits = options.MaxRetransmits
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #10)
if options.Protocol != nil {
params.Protocol = *options.Protocol
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #11)
if len(params.Protocol) > 65535 {
return nil, &rtcerr.TypeError{Err: ErrProtocolTooLarge}
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #12)
if options.Negotiated != nil {
params.Negotiated = *options.Negotiated
}
}
d, err := pc.api.newDataChannel(params, pc.log)
if err != nil {
return nil, err
}
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #16)
if d.maxPacketLifeTime != nil && d.maxRetransmits != nil {
return nil, &rtcerr.TypeError{Err: ErrRetransmitsOrPacketLifeTime}
}
pc.sctpTransport.lock.Lock()
pc.sctpTransport.dataChannels = append(pc.sctpTransport.dataChannels, d)
pc.sctpTransport.dataChannelsRequested++
pc.sctpTransport.lock.Unlock()
// If SCTP already connected open all the channels
if pc.sctpTransport.State() == SCTPTransportStateConnected {
if err = d.open(pc.sctpTransport); err != nil {
return nil, err
}
}
pc.mu.Lock()
pc.onNegotiationNeeded()
pc.mu.Unlock()
return d, nil
}
// SetIdentityProvider is used to configure an identity provider to generate identity assertions
func (pc *PeerConnection) SetIdentityProvider(provider string) error {
return errPeerConnSetIdentityProviderNotImplemented
}
// WriteRTCP sends a user provided RTCP packet to the connected peer. If no peer is connected the
// packet is discarded. It also runs any configured interceptors.
func (pc *PeerConnection) WriteRTCP(pkts []rtcp.Packet) error {
_, err := pc.interceptorRTCPWriter.Write(pkts, make(interceptor.Attributes))
return err
}
func (pc *PeerConnection) writeRTCP(pkts []rtcp.Packet, _ interceptor.Attributes) (int, error) {
return pc.dtlsTransport.WriteRTCP(pkts)
}
// Close ends the PeerConnection
func (pc *PeerConnection) Close() error {
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #1)
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #2)
if pc.isClosed.swap(true) {
return nil
}
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #3)
pc.signalingState.Set(SignalingStateClosed)
// Try closing everything and collect the errors
// Shutdown strategy:
// 1. All Conn close by closing their underlying Conn.
// 2. A Mux stops this chain. It won't close the underlying
// Conn if one of the endpoints is closed down. To
// continue the chain the Mux has to be closed.
closeErrs := make([]error, 4)
closeErrs = append(closeErrs, pc.api.interceptor.Close())
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #4)
pc.mu.Lock()
for _, t := range pc.rtpTransceivers {
if !t.stopped {
closeErrs = append(closeErrs, t.Stop())
}
}
pc.mu.Unlock()
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #5)
pc.sctpTransport.lock.Lock()
for _, d := range pc.sctpTransport.dataChannels {
d.setReadyState(DataChannelStateClosed)
}
pc.sctpTransport.lock.Unlock()
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #6)
if pc.sctpTransport != nil {
closeErrs = append(closeErrs, pc.sctpTransport.Stop())
}
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #7)
closeErrs = append(closeErrs, pc.dtlsTransport.Stop())
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #8, #9, #10)
if pc.iceTransport != nil {
closeErrs = append(closeErrs, pc.iceTransport.Stop())
}
// https://www.w3.org/TR/webrtc/#dom-rtcpeerconnection-close (step #11)
pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State())
return util.FlattenErrs(closeErrs)
}
// addRTPTransceiver appends t into rtpTransceivers
// and fires onNegotiationNeeded;
// caller of this method should hold `pc.mu` lock
func (pc *PeerConnection) addRTPTransceiver(t *RTPTransceiver) {
pc.rtpTransceivers = append(pc.rtpTransceivers, t)
pc.onNegotiationNeeded()
}
// CurrentLocalDescription represents the local description that was
// successfully negotiated the last time the PeerConnection transitioned
// into the stable state plus any local candidates that have been generated
// by the ICEAgent since the offer or answer was created.
func (pc *PeerConnection) CurrentLocalDescription() *SessionDescription {
pc.mu.Lock()
localDescription := pc.currentLocalDescription
iceGather := pc.iceGatherer
iceGatheringState := pc.ICEGatheringState()
pc.mu.Unlock()
return populateLocalCandidates(localDescription, iceGather, iceGatheringState)
}
// PendingLocalDescription represents a local description that is in the
// process of being negotiated plus any local candidates that have been
// generated by the ICEAgent since the offer or answer was created. If the
// PeerConnection is in the stable state, the value is null.
func (pc *PeerConnection) PendingLocalDescription() *SessionDescription {
pc.mu.Lock()
localDescription := pc.pendingLocalDescription
iceGather := pc.iceGatherer
iceGatheringState := pc.ICEGatheringState()
pc.mu.Unlock()
return populateLocalCandidates(localDescription, iceGather, iceGatheringState)
}
// CurrentRemoteDescription represents the last remote description that was
// successfully negotiated the last time the PeerConnection transitioned
// into the stable state plus any remote candidates that have been supplied
// via AddICECandidate() since the offer or answer was created.
func (pc *PeerConnection) CurrentRemoteDescription() *SessionDescription {
pc.mu.RLock()
defer pc.mu.RUnlock()
return pc.currentRemoteDescription
}
// PendingRemoteDescription represents a remote description that is in the
// process of being negotiated, complete with any remote candidates that
// have been supplied via AddICECandidate() since the offer or answer was
// created. If the PeerConnection is in the stable state, the value is
// null.
func (pc *PeerConnection) PendingRemoteDescription() *SessionDescription {
pc.mu.RLock()
defer pc.mu.RUnlock()
return pc.pendingRemoteDescription
}
// SignalingState attribute returns the signaling state of the
// PeerConnection instance.
func (pc *PeerConnection) SignalingState() SignalingState {
return pc.signalingState.Get()
}
// ICEGatheringState attribute returns the ICE gathering state of the
// PeerConnection instance.
func (pc *PeerConnection) ICEGatheringState() ICEGatheringState {
if pc.iceGatherer == nil {
return ICEGatheringStateNew
}
switch pc.iceGatherer.State() {
case ICEGathererStateNew:
return ICEGatheringStateNew
case ICEGathererStateGathering:
return ICEGatheringStateGathering
default:
return ICEGatheringStateComplete
}
}
// ConnectionState attribute returns the connection state of the
// PeerConnection instance.
func (pc *PeerConnection) ConnectionState() PeerConnectionState {
if state, ok := pc.connectionState.Load().(PeerConnectionState); ok {
return state
}
return PeerConnectionState(0)
}
// GetStats return data providing statistics about the overall connection
func (pc *PeerConnection) GetStats() StatsReport {
var (
dataChannelsAccepted uint32
dataChannelsClosed uint32
dataChannelsOpened uint32
dataChannelsRequested uint32
)
statsCollector := newStatsReportCollector()
statsCollector.Collecting()
pc.mu.Lock()
if pc.iceGatherer != nil {
pc.iceGatherer.collectStats(statsCollector)
}
if pc.iceTransport != nil {
pc.iceTransport.collectStats(statsCollector)
}
pc.sctpTransport.lock.Lock()
dataChannels := append([]*DataChannel{}, pc.sctpTransport.dataChannels...)
dataChannelsAccepted = pc.sctpTransport.dataChannelsAccepted
dataChannelsOpened = pc.sctpTransport.dataChannelsOpened
dataChannelsRequested = pc.sctpTransport.dataChannelsRequested
pc.sctpTransport.lock.Unlock()
for _, d := range dataChannels {
state := d.ReadyState()
if state != DataChannelStateConnecting && state != DataChannelStateOpen {
dataChannelsClosed++
}
d.collectStats(statsCollector)
}
pc.sctpTransport.collectStats(statsCollector)
stats := PeerConnectionStats{
Timestamp: statsTimestampNow(),
Type: StatsTypePeerConnection,
ID: pc.statsID,
DataChannelsAccepted: dataChannelsAccepted,
DataChannelsClosed: dataChannelsClosed,
DataChannelsOpened: dataChannelsOpened,
DataChannelsRequested: dataChannelsRequested,
}
statsCollector.Collect(stats.ID, stats)
certificates := pc.configuration.Certificates
for _, certificate := range certificates {
if err := certificate.collectStats(statsCollector); err != nil {
continue
}
}
pc.mu.Unlock()
pc.api.mediaEngine.collectStats(statsCollector)
return statsCollector.Ready()
}
// Start all transports. PeerConnection now has enough state
func (pc *PeerConnection) startTransports(iceRole ICERole, dtlsRole DTLSRole, remoteUfrag, remotePwd, fingerprint, fingerprintHash string) {
// Start the ice transport
err := pc.iceTransport.Start(
pc.iceGatherer,
ICEParameters{
UsernameFragment: remoteUfrag,
Password: remotePwd,
ICELite: false,
},
&iceRole,
)
if err != nil {
pc.log.Warnf("Failed to start manager: %s", err)
return
}
// Start the dtls transport
err = pc.dtlsTransport.Start(DTLSParameters{
Role: dtlsRole,
Fingerprints: []DTLSFingerprint{{Algorithm: fingerprintHash, Value: fingerprint}},
})
pc.updateConnectionState(pc.ICEConnectionState(), pc.dtlsTransport.State())
if err != nil {
pc.log.Warnf("Failed to start manager: %s", err)
return
}
}
// nolint: gocognit
func (pc *PeerConnection) startRTP(isRenegotiation bool, remoteDesc *SessionDescription, currentTransceivers []*RTPTransceiver) {
if !isRenegotiation {
pc.undeclaredMediaProcessor()
}
pc.startRTPReceivers(remoteDesc, currentTransceivers)
if haveApplicationMediaSection(remoteDesc.parsed) {
pc.startSCTP()
}
}
// generateUnmatchedSDP generates an SDP that doesn't take remote state into account
// This is used for the initial call for CreateOffer
func (pc *PeerConnection) generateUnmatchedSDP(transceivers []*RTPTransceiver, useIdentity bool) (*sdp.SessionDescription, error) {
d, err := sdp.NewJSEPSessionDescription(useIdentity)
if err != nil {
return nil, err
}
iceParams, err := pc.iceGatherer.GetLocalParameters()
if err != nil {
return nil, err
}
candidates, err := pc.iceGatherer.GetLocalCandidates()
if err != nil {
return nil, err
}
isPlanB := pc.configuration.SDPSemantics == SDPSemanticsPlanB
mediaSections := []mediaSection{}
// Needed for pc.sctpTransport.dataChannelsRequested
pc.sctpTransport.lock.Lock()
defer pc.sctpTransport.lock.Unlock()
if isPlanB {
video := make([]*RTPTransceiver, 0)
audio := make([]*RTPTransceiver, 0)
for _, t := range transceivers {
if t.kind == RTPCodecTypeVideo {
video = append(video, t)
} else if t.kind == RTPCodecTypeAudio {
audio = append(audio, t)
}
if sender := t.Sender(); sender != nil {
sender.setNegotiated()
}
}
if len(video) > 0 {
mediaSections = append(mediaSections, mediaSection{id: "video", transceivers: video})
}
if len(audio) > 0 {
mediaSections = append(mediaSections, mediaSection{id: "audio", transceivers: audio})
}
if pc.sctpTransport.dataChannelsRequested != 0 {
mediaSections = append(mediaSections, mediaSection{id: "data", data: true})
}
} else {
for _, t := range transceivers {
if sender := t.Sender(); sender != nil {
sender.setNegotiated()
}
mediaSections = append(mediaSections, mediaSection{id: t.Mid(), transceivers: []*RTPTransceiver{t}})
}
if pc.sctpTransport.dataChannelsRequested != 0 {
mediaSections = append(mediaSections, mediaSection{id: strconv.Itoa(len(mediaSections)), data: true})
}
}
dtlsFingerprints, err := pc.configuration.Certificates[0].GetFingerprints()
if err != nil {
return nil, err
}
return populateSDP(d, isPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, true, pc.api.mediaEngine, connectionRoleFromDtlsRole(defaultDtlsRoleOffer), candidates, iceParams, mediaSections, pc.ICEGatheringState())
}
// generateMatchedSDP generates a SDP and takes the remote state into account
// this is used everytime we have a RemoteDescription
// nolint: gocyclo
func (pc *PeerConnection) generateMatchedSDP(transceivers []*RTPTransceiver, useIdentity bool, includeUnmatched bool, connectionRole sdp.ConnectionRole) (*sdp.SessionDescription, error) { //nolint:gocognit
d, err := sdp.NewJSEPSessionDescription(useIdentity)
if err != nil {
return nil, err
}
iceParams, err := pc.iceGatherer.GetLocalParameters()
if err != nil {
return nil, err
}
candidates, err := pc.iceGatherer.GetLocalCandidates()
if err != nil {
return nil, err
}
var t *RTPTransceiver
remoteDescription := pc.currentRemoteDescription
if pc.pendingRemoteDescription != nil {
remoteDescription = pc.pendingRemoteDescription
}
isExtmapAllowMixed := isExtMapAllowMixedSet(remoteDescription.parsed)
localTransceivers := append([]*RTPTransceiver{}, transceivers...)
detectedPlanB := descriptionIsPlanB(remoteDescription, pc.log)
if pc.configuration.SDPSemantics != SDPSemanticsUnifiedPlan {
detectedPlanB = descriptionPossiblyPlanB(remoteDescription)
}
mediaSections := []mediaSection{}
alreadyHaveApplicationMediaSection := false
for _, media := range remoteDescription.parsed.MediaDescriptions {
midValue := getMidValue(media)
if midValue == "" {
return nil, errPeerConnRemoteDescriptionWithoutMidValue
}
if media.MediaName.Media == mediaSectionApplication {
mediaSections = append(mediaSections, mediaSection{id: midValue, data: true})
alreadyHaveApplicationMediaSection = true
continue
}
kind := NewRTPCodecType(media.MediaName.Media)
direction := getPeerDirection(media)
if kind == 0 || direction == RTPTransceiverDirection(Unknown) {
continue
}
sdpSemantics := pc.configuration.SDPSemantics
switch {
case sdpSemantics == SDPSemanticsPlanB || sdpSemantics == SDPSemanticsUnifiedPlanWithFallback && detectedPlanB:
if !detectedPlanB {
return nil, &rtcerr.TypeError{Err: fmt.Errorf("%w: Expected PlanB, but RemoteDescription is UnifiedPlan", ErrIncorrectSDPSemantics)}
}
// If we're responding to a plan-b offer, then we should try to fill up this
// media entry with all matching local transceivers
mediaTransceivers := []*RTPTransceiver{}
for {
// keep going until we can't get any more
t, localTransceivers = satisfyTypeAndDirection(kind, direction, localTransceivers)
if t == nil {
if len(mediaTransceivers) == 0 {
t = &RTPTransceiver{kind: kind, api: pc.api, codecs: pc.api.mediaEngine.getCodecsByKind(kind)}
t.setDirection(RTPTransceiverDirectionInactive)
mediaTransceivers = append(mediaTransceivers, t)
}
break
}
if sender := t.Sender(); sender != nil {
sender.setNegotiated()
}
mediaTransceivers = append(mediaTransceivers, t)
}
mediaSections = append(mediaSections, mediaSection{id: midValue, transceivers: mediaTransceivers})
case sdpSemantics == SDPSemanticsUnifiedPlan || sdpSemantics == SDPSemanticsUnifiedPlanWithFallback:
if detectedPlanB {
return nil, &rtcerr.TypeError{Err: fmt.Errorf("%w: Expected UnifiedPlan, but RemoteDescription is PlanB", ErrIncorrectSDPSemantics)}
}
t, localTransceivers = findByMid(midValue, localTransceivers)
if t == nil {
return nil, fmt.Errorf("%w: %q", errPeerConnTranscieverMidNil, midValue)
}
if sender := t.Sender(); sender != nil {
sender.setNegotiated()
}
mediaTransceivers := []*RTPTransceiver{t}
mediaSections = append(mediaSections, mediaSection{id: midValue, transceivers: mediaTransceivers, ridMap: getRids(media)})
}
}
// If we are offering also include unmatched local transceivers
if includeUnmatched {
if !detectedPlanB {
for _, t := range localTransceivers {
if sender := t.Sender(); sender != nil {
sender.setNegotiated()
}
mediaSections = append(mediaSections, mediaSection{id: t.Mid(), transceivers: []*RTPTransceiver{t}})
}
}
if pc.sctpTransport.dataChannelsRequested != 0 && !alreadyHaveApplicationMediaSection {
if detectedPlanB {
mediaSections = append(mediaSections, mediaSection{id: "data", data: true})
} else {
mediaSections = append(mediaSections, mediaSection{id: strconv.Itoa(len(mediaSections)), data: true})
}
}
}
if pc.configuration.SDPSemantics == SDPSemanticsUnifiedPlanWithFallback && detectedPlanB {
pc.log.Info("Plan-B Offer detected; responding with Plan-B Answer")
}
dtlsFingerprints, err := pc.configuration.Certificates[0].GetFingerprints()
if err != nil {
return nil, err
}
return populateSDP(d, detectedPlanB, dtlsFingerprints, pc.api.settingEngine.sdpMediaLevelFingerprints, pc.api.settingEngine.candidates.ICELite, isExtmapAllowMixed, pc.api.mediaEngine, connectionRole, candidates, iceParams, mediaSections, pc.ICEGatheringState())
}
func (pc *PeerConnection) setGatherCompleteHandler(handler func()) {
pc.iceGatherer.onGatheringCompleteHandler.Store(handler)
}
// SCTP returns the SCTPTransport for this PeerConnection
//
// The SCTP transport over which SCTP data is sent and received. If SCTP has not been negotiated, the value is nil.
// https://www.w3.org/TR/webrtc/#attributes-15
func (pc *PeerConnection) SCTP() *SCTPTransport {
return pc.sctpTransport
}
|