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
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
|
/**
* @file LLWebRTCVoiceClient.cpp
* @brief Implementation of LLWebRTCVoiceClient class which is the interface to the voice client process.
*
* $LicenseInfo:firstyear=2001&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2023, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include <algorithm>
#include "llvoicewebrtc.h"
#include "llsdutil.h"
// Linden library includes
#include "llavatarnamecache.h"
#include "llvoavatarself.h"
#include "llbufferstream.h"
#include "llfile.h"
#include "llmenugl.h"
#ifdef LL_USESYSTEMLIBS
# include "expat.h"
#else
# include "expat/expat.h"
#endif
#include "llcallbacklist.h"
#include "llviewernetwork.h" // for gGridChoice
#include "llbase64.h"
#include "llviewercontrol.h"
#include "llappviewer.h" // for gDisconnected, gDisableVoice
#include "llprocess.h"
// Viewer includes
#include "llmutelist.h" // to check for muted avatars
#include "llagent.h"
#include "llcachename.h"
#include "llimview.h" // for LLIMMgr
#include "llparcel.h"
#include "llviewerparcelmgr.h"
#include "llfirstuse.h"
#include "llspeakers.h"
#include "lltrans.h"
#include "llrand.h"
#include "llviewerwindow.h"
#include "llviewercamera.h"
#include "llversioninfo.h"
#include "llviewernetwork.h"
#include "llnotificationsutil.h"
#include "llcorehttputil.h"
#include "lleventfilter.h"
#include "stringize.h"
#include "llwebrtc.h"
// for base64 decoding
#include "apr_base64.h"
#include "json/reader.h"
#include "json/writer.h"
#define USE_SESSION_GROUPS 0
#define VX_NULL_POSITION -2147483648.0 /*The Silence*/
extern LLMenuBarGL* gMenuBarView;
extern void handle_voice_morphing_subscribe();
namespace {
const F32 VOLUME_SCALE_WEBRTC = 0.01f;
const F32 SPEAKING_TIMEOUT = 1.f;
const F32 SPEAKING_AUDIO_LEVEL = 0.05;
static const std::string VOICE_SERVER_TYPE = "WebRTC";
// Don't send positional updates more frequently than this:
const F32 UPDATE_THROTTLE_SECONDS = 0.1f;
// Timeout for connection to WebRTC
const F32 CONNECT_ATTEMPT_TIMEOUT = 300.0f;
const F32 CONNECT_DNS_TIMEOUT = 5.0f;
const F32 LOGOUT_ATTEMPT_TIMEOUT = 5.0f;
const S32 PROVISION_WAIT_TIMEOUT_SEC = 5;
// Cosine of a "trivially" small angle
const F32 FOUR_DEGREES = 4.0f * (F_PI / 180.0f);
const F32 MINUSCULE_ANGLE_COS = (F32) cos(0.5f * FOUR_DEGREES);
// Defines the maximum number of times(in a row) "stateJoiningSession" case for spatial channel is reached in stateMachine()
// which is treated as normal. The is the number of frames to wait for a channel join before giving up. This was changed
// from the original count of 50 for two reason. Modern PCs have higher frame rates and sometimes the SLVoice process
// backs up processing join requests. There is a log statement that records when channel joins take longer than 100 frames.
const int MAX_NORMAL_JOINING_SPATIAL_NUM = 1500;
// How often to check for expired voice fonts in seconds
const F32 VOICE_FONT_EXPIRY_INTERVAL = 10.f;
// Time of day at which WebRTC expires voice font subscriptions.
// Used to replace the time portion of received expiry timestamps.
static const std::string VOICE_FONT_EXPIRY_TIME = "T05:00:00Z";
// Maximum length of capture buffer recordings in seconds.
const F32 CAPTURE_BUFFER_MAX_TIME = 10.f;
}
static int scale_mic_volume(float volume)
{
// incoming volume has the range [0.0 ... 2.0], with 1.0 as the default.
// Map it to WebRTC levels as follows: 0.0 -> 30, 1.0 -> 50, 2.0 -> 70
return 30 + (int)(volume * 20.0f);
}
///////////////////////////////////////////////////////////////////////////////////////////////
void LLVoiceWebRTCStats::reset()
{
mStartTime = -1.0f;
mConnectCycles = 0;
mConnectTime = -1.0f;
mConnectAttempts = 0;
mProvisionTime = -1.0f;
mProvisionAttempts = 0;
mEstablishTime = -1.0f;
mEstablishAttempts = 0;
}
LLVoiceWebRTCStats::LLVoiceWebRTCStats()
{
reset();
}
LLVoiceWebRTCStats::~LLVoiceWebRTCStats()
{
}
void LLVoiceWebRTCStats::connectionAttemptStart()
{
if (!mConnectAttempts)
{
mStartTime = LLTimer::getTotalTime();
mConnectCycles++;
}
mConnectAttempts++;
}
void LLVoiceWebRTCStats::connectionAttemptEnd(bool success)
{
if ( success )
{
mConnectTime = (LLTimer::getTotalTime() - mStartTime) / USEC_PER_SEC;
}
}
void LLVoiceWebRTCStats::provisionAttemptStart()
{
if (!mProvisionAttempts)
{
mStartTime = LLTimer::getTotalTime();
}
mProvisionAttempts++;
}
void LLVoiceWebRTCStats::provisionAttemptEnd(bool success)
{
if ( success )
{
mProvisionTime = (LLTimer::getTotalTime() - mStartTime) / USEC_PER_SEC;
}
}
void LLVoiceWebRTCStats::establishAttemptStart()
{
if (!mEstablishAttempts)
{
mStartTime = LLTimer::getTotalTime();
}
mEstablishAttempts++;
}
void LLVoiceWebRTCStats::establishAttemptEnd(bool success)
{
if ( success )
{
mEstablishTime = (LLTimer::getTotalTime() - mStartTime) / USEC_PER_SEC;
}
}
LLSD LLVoiceWebRTCStats::read()
{
LLSD stats(LLSD::emptyMap());
stats["connect_cycles"] = LLSD::Integer(mConnectCycles);
stats["connect_attempts"] = LLSD::Integer(mConnectAttempts);
stats["connect_time"] = LLSD::Real(mConnectTime);
stats["provision_attempts"] = LLSD::Integer(mProvisionAttempts);
stats["provision_time"] = LLSD::Real(mProvisionTime);
stats["establish_attempts"] = LLSD::Integer(mEstablishAttempts);
stats["establish_time"] = LLSD::Real(mEstablishTime);
return stats;
}
///////////////////////////////////////////////////////////////////////////////////////////////
bool LLWebRTCVoiceClient::sShuttingDown = false;
bool LLWebRTCVoiceClient::sConnected = false;
LLPumpIO *LLWebRTCVoiceClient::sPump = nullptr;
LLWebRTCVoiceClient::LLWebRTCVoiceClient() :
mSessionTerminateRequested(false),
mRelogRequested(false),
mTerminateDaemon(false),
mSpatialJoiningNum(0),
mTuningMode(false),
mTuningEnergy(0.0f),
mTuningMicVolume(0),
mTuningMicVolumeDirty(true),
mTuningSpeakerVolume(50), // Set to 50 so the user can hear himself when he sets his mic volume
mTuningSpeakerVolumeDirty(true),
mDevicesListUpdated(false),
mAreaVoiceDisabled(false),
mAudioSession(), // TBD - should be NULL
mAudioSessionChanged(false),
mNextAudioSession(),
mCurrentParcelLocalID(0),
mConnectorEstablished(false),
mAccountLoggedIn(false),
mNumberOfAliases(0),
mCommandCookie(0),
mLoginRetryCount(0),
mBuddyListMapPopulated(false),
mBlockRulesListReceived(false),
mAutoAcceptRulesListReceived(false),
mSpatialCoordsDirty(false),
mIsInitialized(false),
mMuteMic(false),
mMuteMicDirty(false),
mFriendsListDirty(true),
mEarLocation(0),
mSpeakerVolumeDirty(true),
mSpeakerMuteDirty(true),
mMicVolume(0),
mMicVolumeDirty(true),
mVoiceEnabled(false),
mWriteInProgress(false),
mLipSyncEnabled(false),
mShutdownComplete(true),
mPlayRequestCount(0),
mAvatarNameCacheConnection(),
mIsInTuningMode(false),
mIsInChannel(false),
mIsJoiningSession(false),
mIsWaitingForFonts(false),
mIsLoggingIn(false),
mIsLoggedIn(false),
mIsProcessingChannels(false),
mIsCoroutineActive(false),
mWebRTCPump("WebRTCClientPump"),
mWebRTCDeviceInterface(nullptr),
mWebRTCPeerConnection(nullptr),
mWebRTCAudioInterface(nullptr)
{
sShuttingDown = false;
sConnected = false;
sPump = nullptr;
mSpeakerVolume = 0.0;
mVoiceVersion.serverVersion = "";
mVoiceVersion.serverType = VOICE_SERVER_TYPE;
// gMuteListp isn't set up at this point, so we defer this until later.
// gMuteListp->addObserver(&mutelist_listener);
#if LL_DARWIN || LL_LINUX
// HACK: THIS DOES NOT BELONG HERE
// When the WebRTC daemon dies, the next write attempt on our socket generates a SIGPIPE, which kills us.
// This should cause us to ignore SIGPIPE and handle the error through proper channels.
// This should really be set up elsewhere. Where should it go?
signal(SIGPIPE, SIG_IGN);
// Since we're now launching the gateway with fork/exec instead of system(), we need to deal with zombie processes.
// Ignoring SIGCHLD should prevent zombies from being created. Alternately, we could use wait(), but I'd rather not do that.
signal(SIGCHLD, SIG_IGN);
#endif
gIdleCallbacks.addFunction(idle, this);
}
//---------------------------------------------------
LLWebRTCVoiceClient::~LLWebRTCVoiceClient()
{
if (mAvatarNameCacheConnection.connected())
{
mAvatarNameCacheConnection.disconnect();
}
sShuttingDown = true;
}
//---------------------------------------------------
void LLWebRTCVoiceClient::init(LLPumpIO *pump)
{
// constructor will set up LLVoiceClient::getInstance()
sPump = pump;
// LLCoros::instance().launch("LLWebRTCVoiceClient::voiceControlCoro",
// boost::bind(&LLWebRTCVoiceClient::voiceControlCoro, LLWebRTCVoiceClient::getInstance()));
llwebrtc::init();
mWebRTCDeviceInterface = llwebrtc::getDeviceInterface();
mWebRTCDeviceInterface->setDevicesObserver(this);
mWebRTCPeerConnection = llwebrtc::newPeerConnection();
mWebRTCPeerConnection->setSignalingObserver(this);
}
void LLWebRTCVoiceClient::terminate()
{
if (sShuttingDown)
{
return;
}
mRelogRequested = false;
mVoiceEnabled = false;
llwebrtc::terminate();
sShuttingDown = true;
sPump = NULL;
}
//---------------------------------------------------
void LLWebRTCVoiceClient::cleanUp()
{
LL_DEBUGS("Voice") << LL_ENDL;
deleteAllSessions();
LL_DEBUGS("Voice") << "exiting" << LL_ENDL;
}
//---------------------------------------------------
const LLVoiceVersionInfo& LLWebRTCVoiceClient::getVersion()
{
return mVoiceVersion;
}
//---------------------------------------------------
void LLWebRTCVoiceClient::updateSettings()
{
setVoiceEnabled(voiceEnabled());
setEarLocation(gSavedSettings.getS32("VoiceEarLocation"));
std::string inputDevice = gSavedSettings.getString("VoiceInputAudioDevice");
setCaptureDevice(inputDevice);
std::string outputDevice = gSavedSettings.getString("VoiceOutputAudioDevice");
setRenderDevice(outputDevice);
F32 mic_level = gSavedSettings.getF32("AudioLevelMic");
setMicGain(mic_level);
setLipSyncEnabled(gSavedSettings.getBOOL("LipSyncEnabled"));
}
/////////////////////////////
// session control messages
void LLWebRTCVoiceClient::connectorCreate()
{
}
void LLWebRTCVoiceClient::connectorShutdown()
{
mShutdownComplete = true;
}
void LLWebRTCVoiceClient::userAuthorized(const std::string& user_id, const LLUUID &agentID)
{
mAccountDisplayName = user_id;
LL_INFOS("Voice") << "name \"" << mAccountDisplayName << "\" , ID " << agentID << LL_ENDL;
mAccountName = nameFromID(agentID);
}
void LLWebRTCVoiceClient::setLoginInfo(
const std::string& account_name,
const std::string& password,
const std::string& channel_sdp)
{
mRemoteChannelSDP = channel_sdp;
mWebRTCPeerConnection->AnswerAvailable(channel_sdp);
if(mAccountLoggedIn)
{
// Already logged in.
LL_WARNS("Voice") << "Called while already logged in." << LL_ENDL;
// Don't process another login.
return;
}
else if ( account_name != mAccountName )
{
LL_WARNS("Voice") << "Mismatched account name! " << account_name
<< " instead of " << mAccountName << LL_ENDL;
}
else
{
mAccountPassword = password;
}
}
void LLWebRTCVoiceClient::idle(void* user_data)
{
}
//=========================================================================
// the following are methods to support the coroutine implementation of the
// voice connection and processing. They should only be called in the context
// of a coroutine.
//
//
typedef enum e_voice_control_coro_state
{
VOICE_STATE_ERROR = -1,
VOICE_STATE_TP_WAIT = 0, // entry point
VOICE_STATE_START_DAEMON,
VOICE_STATE_PROVISION_ACCOUNT,
VOICE_STATE_SESSION_PROVISION_WAIT,
VOICE_STATE_START_SESSION,
VOICE_STATE_WAIT_FOR_SESSION_START,
VOICE_STATE_SESSION_RETRY,
VOICE_STATE_SESSION_ESTABLISHED,
VOICE_STATE_WAIT_FOR_CHANNEL,
VOICE_STATE_DISCONNECT,
VOICE_STATE_WAIT_FOR_EXIT,
} EVoiceControlCoroState;
void LLWebRTCVoiceClient::voiceControlCoro()
{
int state = 0;
try
{
// state is passed as a reference instead of being
// a member due to unresolved issues with coroutine
// surviving longer than LLWebRTCVoiceClient
voiceControlStateMachine();
}
catch (const LLCoros::Stop&)
{
LL_DEBUGS("LLWebRTCVoiceClient") << "Received a shutdown exception" << LL_ENDL;
}
catch (const LLContinueError&)
{
LOG_UNHANDLED_EXCEPTION("LLWebRTCVoiceClient");
}
catch (...)
{
// Ideally for Windows need to log SEH exception instead or to set SEH
// handlers but bugsplat shows local variables for windows, which should
// be enough
LL_WARNS("Voice") << "voiceControlStateMachine crashed in state " << state << LL_ENDL;
throw;
}
}
void LLWebRTCVoiceClient::voiceControlStateMachine()
{
if (sShuttingDown)
{
return;
}
LL_DEBUGS("Voice") << "starting" << LL_ENDL;
mIsCoroutineActive = true;
LLCoros::set_consuming(true);
U32 retry = 0;
U32 provisionWaitTimeout = 0;
setVoiceControlStateUnless(VOICE_STATE_TP_WAIT);
do
{
if (sShuttingDown)
{
// WebRTC singleton performed the exit, logged out,
// cleaned sockets, gateway and no longer cares
// about state of coroutine, so just stop
return;
}
processIceUpdates();
switch (getVoiceControlState())
{
case VOICE_STATE_TP_WAIT:
// starting point for voice
if (gAgent.getTeleportState() != LLAgent::TELEPORT_NONE)
{
LL_DEBUGS("Voice") << "Suspending voiceControlCoro() momentarily for teleport. Tuning: " << mTuningMode
<< ". Relog: " << mRelogRequested << LL_ENDL;
llcoro::suspendUntilTimeout(1.0);
}
else
{
LLMutexLock lock(&mVoiceStateMutex);
mTrickling = false;
mIceCompleted = false;
setVoiceControlStateUnless(VOICE_STATE_START_SESSION, VOICE_STATE_SESSION_RETRY);
}
break;
case VOICE_STATE_START_SESSION:
if (establishVoiceConnection() && getVoiceControlState() != VOICE_STATE_SESSION_RETRY)
{
setVoiceControlStateUnless(VOICE_STATE_WAIT_FOR_SESSION_START, VOICE_STATE_SESSION_RETRY);
}
else
{
setVoiceControlStateUnless(VOICE_STATE_SESSION_RETRY);
}
break;
case VOICE_STATE_WAIT_FOR_SESSION_START:
{
llcoro::suspendUntilTimeout(1.0);
std::string channel_sdp;
{
LLMutexLock lock(&mVoiceStateMutex);
if (mVoiceControlState == VOICE_STATE_SESSION_RETRY)
{
break;
}
if (!mChannelSDP.empty())
{
mVoiceControlState = VOICE_STATE_PROVISION_ACCOUNT;
}
}
break;
}
case VOICE_STATE_PROVISION_ACCOUNT:
if (!provisionVoiceAccount())
{
setVoiceControlStateUnless(VOICE_STATE_SESSION_RETRY);
}
else
{
provisionWaitTimeout = 0;
setVoiceControlStateUnless(VOICE_STATE_SESSION_PROVISION_WAIT, VOICE_STATE_SESSION_RETRY);
}
break;
case VOICE_STATE_SESSION_PROVISION_WAIT:
llcoro::suspendUntilTimeout(1.0);
if (provisionWaitTimeout++ > PROVISION_WAIT_TIMEOUT_SEC)
{
setVoiceControlStateUnless(VOICE_STATE_SESSION_RETRY);
}
break;
case VOICE_STATE_SESSION_RETRY:
giveUp(); // cleans sockets and session
if (mRelogRequested)
{
// We failed to connect, give it a bit time before retrying.
retry++;
F32 full_delay = llmin(2.f * (F32) retry, 10.f);
F32 current_delay = 0.f;
LL_INFOS("Voice") << "Voice failed to establish session after " << retry << " tries. Will attempt to reconnect in "
<< full_delay << " seconds" << LL_ENDL;
while (current_delay < full_delay && !sShuttingDown)
{
// Assuming that a second has passed is not accurate,
// but we don't need accurancy here, just to make sure
// that some time passed and not to outlive voice itself
current_delay++;
llcoro::suspendUntilTimeout(1.f);
}
}
setVoiceControlStateUnless(VOICE_STATE_DISCONNECT);
break;
case VOICE_STATE_SESSION_ESTABLISHED:
{
retry = 0;
if (mTuningMode)
{
performMicTuning();
}
sessionEstablished();
setVoiceControlStateUnless(VOICE_STATE_WAIT_FOR_CHANNEL, VOICE_STATE_SESSION_RETRY);
}
break;
case VOICE_STATE_WAIT_FOR_CHANNEL:
{
if ((!waitForChannel()) || !mVoiceEnabled) // todo: split into more states like login/fonts
{
setVoiceControlStateUnless(VOICE_STATE_DISCONNECT, VOICE_STATE_SESSION_RETRY);
}
// on true, it's a retry, so let the state stand.
}
break;
case VOICE_STATE_DISCONNECT:
LL_DEBUGS("Voice") << "lost channel RelogRequested=" << mRelogRequested << LL_ENDL;
breakVoiceConnection(true);
retry = 0; // Connected without issues
setVoiceControlStateUnless(VOICE_STATE_WAIT_FOR_EXIT);
break;
case VOICE_STATE_WAIT_FOR_EXIT:
if (mVoiceEnabled)
{
LL_INFOS("Voice") << "will attempt to reconnect to voice" << LL_ENDL;
setVoiceControlStateUnless(VOICE_STATE_TP_WAIT);
}
else
{
llcoro::suspendUntilTimeout(1.0);
}
break;
default:
{
LL_WARNS("Voice") << "Unknown voice control state " << getVoiceControlState() << LL_ENDL;
break;
}
}
} while (true);
}
bool LLWebRTCVoiceClient::callbackEndDaemon(const LLSD& data)
{
if (!sShuttingDown && mVoiceEnabled)
{
LL_WARNS("Voice") << "SLVoice terminated " << ll_stream_notation_sd(data) << LL_ENDL;
terminateAudioSession(false);
closeSocket();
cleanUp();
LLVoiceClient::getInstance()->setUserPTTState(false);
gAgent.setVoiceConnected(false);
mRelogRequested = true;
}
return false;
}
bool LLWebRTCVoiceClient::provisionVoiceAccount()
{
LL_INFOS("Voice") << "Provisioning voice account." << LL_ENDL;
while ((!gAgent.getRegion() || !gAgent.getRegion()->capabilitiesReceived()) && !sShuttingDown)
{
LL_DEBUGS("Voice") << "no capabilities for voice provisioning; waiting " << LL_ENDL;
// *TODO* Pump a message for wake up.
llcoro::suspend();
}
if (sShuttingDown)
{
return false;
}
std::string url = gAgent.getRegionCapability("ProvisionVoiceAccountRequest");
LL_DEBUGS("Voice") << "region ready for voice provisioning; url=" << url << LL_ENDL;
LLVoiceWebRTCStats::getInstance()->provisionAttemptStart();
LLSD body;
LLSD jsep;
jsep["type"] = "offer";
{
LLMutexLock lock(&mVoiceStateMutex);
jsep["sdp"] = mChannelSDP;
}
body["jsep"] = jsep;
LLCoreHttpUtil::HttpCoroutineAdapter::callbackHttpPost(
url,
LLCore::HttpRequest::DEFAULT_POLICY_ID,
body,
boost::bind(&LLWebRTCVoiceClient::OnVoiceAccountProvisioned, this, _1),
boost::bind(&LLWebRTCVoiceClient::OnVoiceAccountProvisionFailure, this, url, 3, body, _1));
return true;
}
void LLWebRTCVoiceClient::OnVoiceAccountProvisioned(const LLSD& result)
{
LLVoiceWebRTCStats::getInstance()->provisionAttemptEnd(true);
std::string channelSDP;
if (result.has("jsep") &&
result["jsep"].has("type") &&
result["jsep"]["type"] == "answer" &&
result["jsep"].has("sdp"))
{
channelSDP = result["jsep"]["sdp"].asString();
}
std::string voiceAccountServerUri;
std::string voiceUserName = gAgent.getID().asString();
std::string voicePassword = ""; // no password for now.
LL_DEBUGS("Voice") << "ProvisionVoiceAccountRequest response"
<< " user " << (voiceUserName.empty() ? "not set" : "set") << " password "
<< (voicePassword.empty() ? "not set" : "set") << " channel sdp " << channelSDP << LL_ENDL;
setLoginInfo(voiceUserName, voicePassword, channelSDP);
// switch to the default region channel.
switchChannel(gAgent.getRegion()->getRegionID().asString());
}
void LLWebRTCVoiceClient::OnVoiceAccountProvisionFailure(std::string url, int retries, LLSD body, const LLSD& result)
{
if (sShuttingDown)
{
return;
}
if (retries >= 0)
{
LLCoreHttpUtil::HttpCoroutineAdapter::callbackHttpPost(
url,
LLCore::HttpRequest::DEFAULT_POLICY_ID,
body,
boost::bind(&LLWebRTCVoiceClient::OnVoiceAccountProvisioned, this, _1),
boost::bind(&LLWebRTCVoiceClient::OnVoiceAccountProvisionFailure, this, url, retries - 1, body, _1));
}
else
{
LL_WARNS("Voice") << "Unable to complete ice trickling voice account, retrying." << LL_ENDL;
}
}
bool LLWebRTCVoiceClient::establishVoiceConnection()
{
LL_INFOS("Voice") << "Ice Gathering voice account." << LL_ENDL;
while ((!gAgent.getRegion() || !gAgent.getRegion()->capabilitiesReceived()) && !sShuttingDown)
{
LL_DEBUGS("Voice") << "no capabilities for voice provisioning; waiting " << LL_ENDL;
// *TODO* Pump a message for wake up.
llcoro::suspend();
return false;
}
if (!mVoiceEnabled && mIsInitialized)
{
LL_WARNS("Voice") << "cannot establish connection; enabled "<<mVoiceEnabled<<" initialized "<<mIsInitialized<<LL_ENDL;
return false;
}
if (sShuttingDown)
{
return false;
}
return mWebRTCPeerConnection->initializeConnection();
}
bool LLWebRTCVoiceClient::breakVoiceConnection(bool corowait)
{
LL_INFOS("Voice") << "Breaking voice account." << LL_ENDL;
while ((!gAgent.getRegion() || !gAgent.getRegion()->capabilitiesReceived()) && !sShuttingDown)
{
LL_DEBUGS("Voice") << "no capabilities for voice breaking; waiting " << LL_ENDL;
// *TODO* Pump a message for wake up.
llcoro::suspend();
}
if (sShuttingDown)
{
return false;
}
std::string url = gAgent.getRegionCapability("ProvisionVoiceAccountRequest");
LL_DEBUGS("Voice") << "region ready for voice break; url=" << url << LL_ENDL;
LL_DEBUGS("Voice") << "sending ProvisionVoiceAccountRequest (breaking) (" << mCurrentRegionName << ", " << mCurrentParcelLocalID << ")" << LL_ENDL;
LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("parcelVoiceInfoRequest", httpPolicy));
LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
LLVoiceWebRTCStats::getInstance()->provisionAttemptStart();
LLSD body;
body["logout"] = TRUE;
httpAdapter->postAndSuspend(httpRequest, url, body);
mWebRTCPeerConnection->shutdownConnection();
return true;
}
bool LLWebRTCVoiceClient::loginToWebRTC()
{
mRelogRequested = false;
mIsLoggedIn = true;
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_LOGGED_IN);
// Set the initial state of mic mute, local speaker volume, etc.
sendLocalAudioUpdates();
mIsLoggingIn = false;
return true;
}
void LLWebRTCVoiceClient::logoutOfWebRTC(bool wait)
{
if (mIsLoggedIn)
{
mAccountPassword.clear();
breakVoiceConnection(wait);
// Ensure that we'll re-request provisioning before logging in again
mIsLoggedIn = false;
}
}
bool LLWebRTCVoiceClient::requestParcelVoiceInfo()
{
//_INFOS("Voice") << "Requesting voice info for Parcel" << LL_ENDL;
LLViewerRegion * region = gAgent.getRegion();
if (region == NULL || !region->capabilitiesReceived())
{
LL_DEBUGS("Voice") << "ParcelVoiceInfoRequest capability not yet available, deferring" << LL_ENDL;
return false;
}
// grab the cap.
std::string url = gAgent.getRegion()->getCapability("ParcelVoiceInfoRequest");
if (url.empty())
{
// Region dosn't have the cap. Stop probing.
LL_DEBUGS("Voice") << "ParcelVoiceInfoRequest capability not available in this region" << LL_ENDL;
return false;
}
// update the parcel
checkParcelChanged(true);
LL_DEBUGS("Voice") << "sending ParcelVoiceInfoRequest (" << mCurrentRegionName << ", " << mCurrentParcelLocalID << ")" << LL_ENDL;
LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t
httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("parcelVoiceInfoRequest", httpPolicy));
LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
LLSD result = httpAdapter->postAndSuspend(httpRequest, url, LLSD());
if (sShuttingDown)
{
return false;
}
LLSD httpResults = result[LLCoreHttpUtil::HttpCoroutineAdapter::HTTP_RESULTS];
LLCore::HttpStatus status = LLCoreHttpUtil::HttpCoroutineAdapter::getStatusFromLLSD(httpResults);
if (mSessionTerminateRequested || (!mVoiceEnabled && mIsInitialized))
{
// if a terminate request has been received,
// bail and go to the stateSessionTerminated
// state. If the cap request is still pending,
// the responder will check to see if we've moved
// to a new session and won't change any state.
LL_DEBUGS("Voice") << "terminate requested " << mSessionTerminateRequested
<< " enabled " << mVoiceEnabled
<< " initialized " << mIsInitialized
<< LL_ENDL;
terminateAudioSession(true);
return false;
}
if ((!status) || (mSessionTerminateRequested || (!mVoiceEnabled && mIsInitialized)))
{
if (mSessionTerminateRequested || (!mVoiceEnabled && mIsInitialized))
{
LL_WARNS("Voice") << "Session terminated." << LL_ENDL;
}
LL_WARNS("Voice") << "No voice on parcel" << LL_ENDL;
sessionTerminate();
return false;
}
std::string uri;
std::string credentials;
LL_WARNS("Voice") << "Got voice credentials" << result << LL_ENDL;
if (result.has("voice_credentials"))
{
LLSD voice_credentials = result["voice_credentials"];
if (voice_credentials.has("channel_uri"))
{
LL_DEBUGS("Voice") << "got voice channel uri" << LL_ENDL;
uri = voice_credentials["channel_uri"].asString();
}
else
{
LL_WARNS("Voice") << "No voice channel uri" << LL_ENDL;
}
if (voice_credentials.has("channel_credentials"))
{
LL_DEBUGS("Voice") << "got voice channel credentials" << LL_ENDL;
credentials =
voice_credentials["channel_credentials"].asString();
}
else
{
LLVoiceChannel* channel = LLVoiceChannel::getCurrentVoiceChannel();
if (channel != NULL)
{
if (channel->getSessionName().empty() && channel->getSessionID().isNull())
{
if (LLViewerParcelMgr::getInstance()->allowAgentVoice())
{
LL_WARNS("Voice") << "No channel credentials for default channel" << LL_ENDL;
}
}
else
{
LL_WARNS("Voice") << "No voice channel credentials" << LL_ENDL;
}
}
}
}
else
{
if (LLViewerParcelMgr::getInstance()->allowAgentVoice())
{
LL_WARNS("Voice") << "No voice credentials" << LL_ENDL;
}
else
{
LL_DEBUGS("Voice") << "No voice credentials" << LL_ENDL;
}
}
// set the spatial channel. If no voice credentials or uri are
// available, then we simply drop out of voice spatially.
return !setSpatialChannel(uri, "");
}
bool LLWebRTCVoiceClient::addAndJoinSession(const sessionStatePtr_t &nextSession)
{
mIsJoiningSession = true;
sessionStatePtr_t oldSession = mAudioSession;
LL_INFOS("Voice") << "Adding or joining voice session " << nextSession->mHandle << LL_ENDL;
mAudioSession = nextSession;
mAudioSessionChanged = true;
if (!mAudioSession || !mAudioSession->mReconnect)
{
mNextAudioSession.reset();
}
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_JOINING);
llcoro::suspend();
if (sShuttingDown)
{
return false;
}
LLSD result;
if (mSpatialJoiningNum == MAX_NORMAL_JOINING_SPATIAL_NUM)
{
// Notify observers to let them know there is problem with voice
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_VOICE_DISABLED);
LL_WARNS() << "There seems to be problem with connection to voice server. Disabling voice chat abilities." << LL_ENDL;
}
// Increase mSpatialJoiningNum only for spatial sessions- it's normal to reach this case for
// example for p2p many times while waiting for response, so it can't be used to detect errors
if (mAudioSession && mAudioSession->mIsSpatial)
{
mSpatialJoiningNum++;
}
if (!mVoiceEnabled && mIsInitialized)
{
LL_DEBUGS("Voice") << "Voice no longer enabled. Exiting"
<< " enabled " << mVoiceEnabled
<< " initialized " << mIsInitialized
<< LL_ENDL;
mIsJoiningSession = false;
// User bailed out during connect -- jump straight to teardown.
terminateAudioSession(true);
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_VOICE_DISABLED);
return false;
}
else if (mSessionTerminateRequested)
{
LL_DEBUGS("Voice") << "Terminate requested" << LL_ENDL;
if (mAudioSession && !mAudioSession->mHandle.empty())
{
// Only allow direct exits from this state in p2p calls (for cancelling an invite).
// Terminating a half-connected session on other types of calls seems to break something in the WebRTC gateway.
if (mAudioSession->mIsP2P)
{
terminateAudioSession(true);
mIsJoiningSession = false;
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_LEFT_CHANNEL);
return false;
}
}
}
LLSD timeoutResult(LLSDMap("session", "timeout"));
// We are about to start a whole new session. Anything that MIGHT still be in our
// maildrop is going to be stale and cause us much wailing and gnashing of teeth.
// Just flush it all out and start new.
mWebRTCPump.discard();
// add 'self' participant.
addParticipantByID(gAgent.getID());
// tell peers that this participant has joined.
if (mWebRTCDataInterface)
{
Json::FastWriter writer;
Json::Value root = getPositionAndVolumeUpdateJson(true);
root["j"] = true;
std::string json_data = writer.write(root);
mWebRTCDataInterface->sendData(json_data, false);
}
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_JOINED);
return true;
}
bool LLWebRTCVoiceClient::terminateAudioSession(bool wait)
{
if (mAudioSession)
{
LL_INFOS("Voice") << "terminateAudioSession(" << wait << ") Terminating current voice session " << mAudioSession->mHandle << LL_ENDL;
if (mIsLoggedIn)
{
if (!mAudioSession->mHandle.empty())
{
if (wait)
{
LLSD result;
do
{
LLSD timeoutResult(LLSDMap("session", "timeout"));
result = llcoro::suspendUntilEventOnWithTimeout(mWebRTCPump, LOGOUT_ATTEMPT_TIMEOUT, timeoutResult);
if (sShuttingDown)
{
return false;
}
LL_DEBUGS("Voice") << "event=" << ll_stream_notation_sd(result) << LL_ENDL;
if (result.has("session"))
{
if (result.has("handle"))
{
if (result["handle"] != mAudioSession->mHandle)
{
LL_WARNS("Voice") << "Message for session handle \"" << result["handle"] << "\" while waiting for \"" << mAudioSession->mHandle << "\"." << LL_ENDL;
continue;
}
}
std::string message = result["session"].asString();
if (message == "removed" || message == "timeout")
break;
}
} while (true);
}
}
else
{
LL_WARNS("Voice") << "called with no session handle" << LL_ENDL;
}
}
else
{
LL_WARNS("Voice") << "Session " << mAudioSession->mHandle << " already terminated by logout." << LL_ENDL;
}
sessionStatePtr_t oldSession = mAudioSession;
mAudioSession.reset();
// We just notified status observers about this change. Don't do it again.
mAudioSessionChanged = false;
// The old session may now need to be deleted.
reapSession(oldSession);
}
else
{
LL_WARNS("Voice") << "terminateAudioSession(" << wait << ") with NULL mAudioSession" << LL_ENDL;
}
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_LEFT_CHANNEL);
// Always reset the terminate request flag when we get here.
// Some slower PCs have a race condition where they can switch to an incoming P2P call faster than the state machine leaves
// the region chat.
mSessionTerminateRequested = false;
bool status=((mVoiceEnabled || !mIsInitialized) && !mRelogRequested && !sShuttingDown);
LL_DEBUGS("Voice") << "exiting"
<< " VoiceEnabled " << mVoiceEnabled
<< " IsInitialized " << mIsInitialized
<< " RelogRequested " << mRelogRequested
<< " ShuttingDown " << (sShuttingDown ? "TRUE" : "FALSE")
<< " returning " << status
<< LL_ENDL;
return status;
}
typedef enum e_voice_wait_for_channel_state
{
VOICE_CHANNEL_STATE_LOGIN = 0, // entry point
VOICE_CHANNEL_STATE_START_CHANNEL_PROCESSING,
VOICE_CHANNEL_STATE_PROCESS_CHANNEL,
VOICE_CHANNEL_STATE_NEXT_CHANNEL_DELAY,
VOICE_CHANNEL_STATE_NEXT_CHANNEL_CHECK
} EVoiceWaitForChannelState;
bool LLWebRTCVoiceClient::waitForChannel()
{
LL_INFOS("Voice") << "Waiting for channel" << LL_ENDL;
EVoiceWaitForChannelState state = VOICE_CHANNEL_STATE_LOGIN;
do
{
if (sShuttingDown)
{
// terminate() forcefully disconects voice, no need for cleanup
return false;
}
if (getVoiceControlState() == VOICE_STATE_SESSION_RETRY)
{
mIsProcessingChannels = false;
return true;
}
processIceUpdates();
switch (state)
{
case VOICE_CHANNEL_STATE_LOGIN:
if (!loginToWebRTC())
{
return false;
}
state = VOICE_CHANNEL_STATE_START_CHANNEL_PROCESSING;
break;
case VOICE_CHANNEL_STATE_START_CHANNEL_PROCESSING:
mIsProcessingChannels = true;
llcoro::suspend();
state = VOICE_CHANNEL_STATE_PROCESS_CHANNEL;
break;
case VOICE_CHANNEL_STATE_PROCESS_CHANNEL:
if (mTuningMode)
{
performMicTuning();
}
else if (checkParcelChanged() || (mNextAudioSession == NULL))
{
// the parcel is changed, or we have no pending audio sessions,
// so try to request the parcel voice info
// if we have the cap, we move to the appropriate state
requestParcelVoiceInfo(); //suspends for http reply
}
else if (sessionNeedsRelog(mNextAudioSession))
{
LL_INFOS("Voice") << "Session requesting reprovision and login." << LL_ENDL;
requestRelog();
break;
}
else if (mNextAudioSession)
{
sessionStatePtr_t joinSession = mNextAudioSession;
mNextAudioSession.reset();
if (!runSession(joinSession)) //suspends
{
LL_DEBUGS("Voice") << "runSession returned false; leaving inner loop" << LL_ENDL;
break;
}
else
{
LL_DEBUGS("Voice")
<< "runSession returned true to inner loop"
<< " RelogRequested=" << mRelogRequested
<< " VoiceEnabled=" << mVoiceEnabled
<< LL_ENDL;
}
}
state = VOICE_CHANNEL_STATE_NEXT_CHANNEL_DELAY;
break;
case VOICE_CHANNEL_STATE_NEXT_CHANNEL_DELAY:
if (!mNextAudioSession)
{
llcoro::suspendUntilTimeout(1.0);
}
state = VOICE_CHANNEL_STATE_NEXT_CHANNEL_CHECK;
break;
case VOICE_CHANNEL_STATE_NEXT_CHANNEL_CHECK:
if (mVoiceEnabled && !mRelogRequested)
{
state = VOICE_CHANNEL_STATE_START_CHANNEL_PROCESSING;
break;
}
else
{
mIsProcessingChannels = false;
LL_DEBUGS("Voice")
<< "leaving inner waitForChannel loop"
<< " RelogRequested=" << mRelogRequested
<< " VoiceEnabled=" << mVoiceEnabled
<< LL_ENDL;
return !sShuttingDown;
}
}
} while (true);
}
bool LLWebRTCVoiceClient::runSession(const sessionStatePtr_t &session)
{
LL_INFOS("Voice") << "running new voice session " << session->mHandle << LL_ENDL;
bool joined_session = addAndJoinSession(session);
if (sShuttingDown)
{
return false;
}
if (!joined_session)
{
notifyStatusObservers(LLVoiceClientStatusObserver::ERROR_UNKNOWN);
if (mSessionTerminateRequested)
{
LL_DEBUGS("Voice") << "runSession terminate requested " << LL_ENDL;
terminateAudioSession(true);
}
// if a relog has been requested then addAndJoineSession
// failed in a spectacular way and we need to back out.
// If this is not the case then we were simply trying to
// make a call and the other party rejected it.
return !mRelogRequested;
}
notifyParticipantObservers();
LLSD timeoutEvent(LLSDMap("timeout", LLSD::Boolean(true)));
mIsInChannel = true;
mMuteMicDirty = true;
while (!sShuttingDown
&& mVoiceEnabled
&& !mSessionTerminateRequested
&& !mTuningMode)
{
if (sShuttingDown)
{
return false;
}
if (getVoiceControlState() == VOICE_STATE_SESSION_RETRY)
{
break;
}
if (mSessionTerminateRequested)
{
break;
}
if (mAudioSession && mAudioSession->mParticipantsChanged)
{
mAudioSession->mParticipantsChanged = false;
notifyParticipantObservers();
}
if (!inSpatialChannel())
{
// When in a non-spatial channel, never send positional updates.
mSpatialCoordsDirty = false;
}
else
{
updatePosition();
if (checkParcelChanged())
{
// *RIDER: I think I can just return here if the parcel has changed
// and grab the new voice channel from the outside loop.
//
// if the parcel has changed, attempted to request the
// cap for the parcel voice info. If we can't request it
// then we don't have the cap URL so we do nothing and will
// recheck next time around
if (requestParcelVoiceInfo()) // suspends
{ // The parcel voice URI has changed.. break out and reconnect.
break;
}
if (sShuttingDown)
{
return false;
}
}
// Do the calculation that enforces the listener<->speaker tether (and also updates the real camera position)
enforceTether();
}
sendPositionAndVolumeUpdate();
// send any requests to adjust mic and speaker settings if they have changed
sendLocalAudioUpdates();
mIsInitialized = true;
LLSD result = llcoro::suspendUntilEventOnWithTimeout(mWebRTCPump, UPDATE_THROTTLE_SECONDS, timeoutEvent);
if (sShuttingDown)
{
return false;
}
if (!result.has("timeout")) // logging the timeout event spams the log
{
LL_DEBUGS("Voice") << "event=" << ll_stream_notation_sd(result) << LL_ENDL;
}
if (result.has("session"))
{
if (result.has("handle"))
{
if (!mAudioSession)
{
LL_WARNS("Voice") << "Message for session handle \"" << result["handle"] << "\" while session is not initiated." << LL_ENDL;
continue;
}
if (result["handle"] != mAudioSession->mHandle)
{
LL_WARNS("Voice") << "Message for session handle \"" << result["handle"] << "\" while waiting for \"" << mAudioSession->mHandle << "\"." << LL_ENDL;
continue;
}
}
std::string message = result["session"];
if (message == "removed")
{
LL_DEBUGS("Voice") << "session removed" << LL_ENDL;
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_LEFT_CHANNEL);
break;
}
}
else if (result.has("login"))
{
std::string message = result["login"];
if (message == "account_logout")
{
LL_DEBUGS("Voice") << "logged out" << LL_ENDL;
mIsLoggedIn = false;
mRelogRequested = true;
break;
}
}
}
if (sShuttingDown)
{
return false;
}
mIsInChannel = false;
LL_DEBUGS("Voice") << "terminating at end of runSession" << LL_ENDL;
terminateAudioSession(true);
return true;
}
bool LLWebRTCVoiceClient::performMicTuning()
{
LL_INFOS("Voice") << "Entering voice tuning mode." << LL_ENDL;
mIsInTuningMode = false;
//---------------------------------------------------------------------
return true;
}
//=========================================================================
void LLWebRTCVoiceClient::closeSocket(void)
{
mSocket.reset();
sConnected = false;
mConnectorEstablished = false;
mAccountLoggedIn = false;
}
void LLWebRTCVoiceClient::logout()
{
// Ensure that we'll re-request provisioning before logging in again
mAccountPassword.clear();
mAccountLoggedIn = false;
}
void LLWebRTCVoiceClient::sessionTerminate()
{
mSessionTerminateRequested = true;
}
void LLWebRTCVoiceClient::requestRelog()
{
mSessionTerminateRequested = true;
mRelogRequested = true;
}
void LLWebRTCVoiceClient::leaveAudioSession()
{
if(mAudioSession)
{
LL_DEBUGS("Voice") << "leaving session: " << mAudioSession->mSIPURI << LL_ENDL;
if(mAudioSession->mHandle.empty())
{
LL_WARNS("Voice") << "called with no session handle" << LL_ENDL;
}
}
else
{
LL_WARNS("Voice") << "called with no active session" << LL_ENDL;
}
sessionTerminate();
}
void LLWebRTCVoiceClient::clearCaptureDevices()
{
LL_DEBUGS("Voice") << "called" << LL_ENDL;
mCaptureDevices.clear();
}
void LLWebRTCVoiceClient::addCaptureDevice(const LLVoiceDevice& device)
{
LL_DEBUGS("Voice") << "display: '" << device.display_name << "' device: '" << device.full_name << "'" << LL_ENDL;
mCaptureDevices.push_back(device);
}
LLVoiceDeviceList& LLWebRTCVoiceClient::getCaptureDevices()
{
return mCaptureDevices;
}
void LLWebRTCVoiceClient::setCaptureDevice(const std::string& name)
{
bool inTuningMode = mIsInTuningMode;
if (inTuningMode)
{
tuningStop();
}
mWebRTCDeviceInterface->setCaptureDevice(name);
if (inTuningMode)
{
tuningStart();
}
}
void LLWebRTCVoiceClient::setDevicesListUpdated(bool state)
{
mDevicesListUpdated = state;
}
void LLWebRTCVoiceClient::OnDevicesChanged(const llwebrtc::LLWebRTCVoiceDeviceList &render_devices,
const llwebrtc::LLWebRTCVoiceDeviceList &capture_devices)
{
clearRenderDevices();
for (auto &device : render_devices)
{
addRenderDevice(LLVoiceDevice(device.display_name, device.id));
}
clearCaptureDevices();
for (auto &device : capture_devices)
{
addCaptureDevice(LLVoiceDevice(device.display_name, device.id));
}
setDevicesListUpdated(true);
}
void LLWebRTCVoiceClient::clearRenderDevices()
{
LL_DEBUGS("Voice") << "called" << LL_ENDL;
mRenderDevices.clear();
}
void LLWebRTCVoiceClient::addRenderDevice(const LLVoiceDevice& device)
{
LL_DEBUGS("Voice") << "display: '" << device.display_name << "' device: '" << device.full_name << "'" << LL_ENDL;
mRenderDevices.push_back(device);
}
LLVoiceDeviceList& LLWebRTCVoiceClient::getRenderDevices()
{
return mRenderDevices;
}
void LLWebRTCVoiceClient::setRenderDevice(const std::string& name)
{
mWebRTCDeviceInterface->setRenderDevice(name);
}
void LLWebRTCVoiceClient::tuningStart()
{
if (!mIsInTuningMode)
{
mWebRTCDeviceInterface->setTuningMode(true);
mIsInTuningMode = true;
}
}
void LLWebRTCVoiceClient::tuningStop()
{
if (mIsInTuningMode)
{
mWebRTCDeviceInterface->setTuningMode(false);
mIsInTuningMode = false;
}
}
bool LLWebRTCVoiceClient::inTuningMode()
{
return mIsInTuningMode;
}
void LLWebRTCVoiceClient::tuningSetMicVolume(float volume)
{
int scaled_volume = scale_mic_volume(volume);
if(scaled_volume != mTuningMicVolume)
{
mTuningMicVolume = scaled_volume;
mTuningMicVolumeDirty = true;
}
}
void LLWebRTCVoiceClient::tuningSetSpeakerVolume(float volume)
{
if (volume != mTuningSpeakerVolume)
{
mTuningSpeakerVolume = volume;
mTuningSpeakerVolumeDirty = true;
}
}
float LLWebRTCVoiceClient::tuningGetEnergy(void)
{
return mWebRTCDeviceInterface->getTuningAudioLevel();
}
bool LLWebRTCVoiceClient::deviceSettingsAvailable()
{
bool result = true;
if(mRenderDevices.empty() || mCaptureDevices.empty())
result = false;
return result;
}
bool LLWebRTCVoiceClient::deviceSettingsUpdated()
{
bool updated = mDevicesListUpdated;
mDevicesListUpdated = false;
return updated;
}
void LLWebRTCVoiceClient::refreshDeviceLists(bool clearCurrentList)
{
if(clearCurrentList)
{
clearCaptureDevices();
clearRenderDevices();
}
mWebRTCDeviceInterface->refreshDevices();
}
void LLWebRTCVoiceClient::daemonDied()
{
// The daemon died, so the connection is gone. Reset everything and start over.
LL_WARNS("Voice") << "Connection to WebRTC daemon lost. Resetting state."<< LL_ENDL;
//TODO: Try to relaunch the daemon
}
void LLWebRTCVoiceClient::giveUp()
{
// All has failed. Clean up and stop trying.
LL_WARNS("Voice") << "Terminating Voice Service" << LL_ENDL;
closeSocket();
cleanUp();
}
void LLWebRTCVoiceClient::setHidden(bool hidden)
{
mHidden = hidden;
if (mHidden && inSpatialChannel())
{
// get out of the channel entirely
leaveAudioSession();
}
else
{
sendPositionAndVolumeUpdate();
}
}
Json::Value LLWebRTCVoiceClient::getPositionAndVolumeUpdateJson(bool force)
{
Json::Value root = Json::objectValue;
if ((mSpatialCoordsDirty || force) && inSpatialChannel())
{
LLVector3d earPosition;
LLQuaternion earRot;
switch (mEarLocation)
{
case earLocCamera:
default:
earPosition = mCameraPosition;
earRot = mCameraRot;
break;
case earLocAvatar:
earPosition = mAvatarPosition;
earRot = mAvatarRot;
break;
case earLocMixed:
earPosition = mAvatarPosition;
earRot = mCameraRot;
break;
}
root["sp"] = Json::objectValue;
root["sp"]["x"] = (int) (mAvatarPosition[0] * 100);
root["sp"]["y"] = (int) (mAvatarPosition[1] * 100);
root["sp"]["z"] = (int) (mAvatarPosition[2] * 100);
root["sh"] = Json::objectValue;
root["sh"]["x"] = (int) (mAvatarRot[0] * 100);
root["sh"]["y"] = (int) (mAvatarRot[1] * 100);
root["sh"]["z"] = (int) (mAvatarRot[2] * 100);
root["sh"]["w"] = (int) (mAvatarRot[3] * 100);
root["lp"] = Json::objectValue;
root["lp"]["x"] = (int) (earPosition[0] * 100);
root["lp"]["y"] = (int) (earPosition[1] * 100);
root["lp"]["z"] = (int) (earPosition[2] * 100);
root["lh"] = Json::objectValue;
root["lh"]["x"] = (int) (earRot[0] * 100);
root["lh"]["y"] = (int) (earRot[1] * 100);
root["lh"]["z"] = (int) (earRot[2] * 100);
root["lh"]["w"] = (int) (earRot[3] * 100);
mSpatialCoordsDirty = false;
}
F32 audio_level = 0.0;
if (!mMuteMic)
{
audio_level = (F32) mWebRTCDeviceInterface->getPeerAudioLevel();
}
uint32_t uint_audio_level = mMuteMic ? 0 : (uint32_t) (audio_level * 128);
if (force || (uint_audio_level != mAudioLevel))
{
root["p"] = uint_audio_level;
mAudioLevel = uint_audio_level;
participantStatePtr_t participant = findParticipantByID(gAgentID);
if (participant)
{
participant->mPower = audio_level;
participant->mIsSpeaking = participant->mPower > SPEAKING_AUDIO_LEVEL;
}
}
return root;
}
void LLWebRTCVoiceClient::sendPositionAndVolumeUpdate()
{
if (mWebRTCDataInterface && mWebRTCAudioInterface)
{
Json::Value root = getPositionAndVolumeUpdateJson(false);
if (root.size() > 0)
{
Json::FastWriter writer;
std::string json_data = writer.write(root);
mWebRTCDataInterface->sendData(json_data, false);
}
}
if(mAudioSession && (mAudioSession->mVolumeDirty || mAudioSession->mMuteDirty))
{
participantMap::iterator iter = mAudioSession->mParticipantsByURI.begin();
mAudioSession->mVolumeDirty = false;
mAudioSession->mMuteDirty = false;
for(; iter != mAudioSession->mParticipantsByURI.end(); iter++)
{
participantStatePtr_t p(iter->second);
if(p->mVolumeDirty)
{
// Can't set volume/mute for yourself
if(!p->mIsSelf)
{
// scale from the range 0.0-1.0 to WebRTC volume in the range 0-100
S32 volume = ll_round(p->mVolume / VOLUME_SCALE_WEBRTC);
bool mute = p->mOnMuteList;
if(mute)
{
// SetParticipantMuteForMe doesn't work in p2p sessions.
// If we want the user to be muted, set their volume to 0 as well.
// This isn't perfect, but it will at least reduce their volume to a minimum.
volume = 0;
// Mark the current volume level as set to prevent incoming events
// changing it to 0, so that we can return to it when unmuting.
p->mVolumeSet = true;
}
if(volume == 0)
{
mute = true;
}
LL_DEBUGS("Voice") << "Setting volume/mute for avatar " << p->mAvatarID << " to " << volume << (mute?"/true":"/false") << LL_ENDL;
}
p->mVolumeDirty = false;
}
}
}
}
void LLWebRTCVoiceClient::sendLocalAudioUpdates()
{
}
/////////////////////////////
// WebRTC Signaling Handlers
void LLWebRTCVoiceClient::OnIceGatheringState(llwebrtc::LLWebRTCSignalingObserver::IceGatheringState state)
{
LL_INFOS("Voice") << "Ice Gathering voice account. " << state << LL_ENDL;
switch (state)
{
case llwebrtc::LLWebRTCSignalingObserver::IceGatheringState::ICE_GATHERING_COMPLETE:
{
LLMutexLock lock(&mVoiceStateMutex);
mIceCompleted = true;
break;
}
case llwebrtc::LLWebRTCSignalingObserver::IceGatheringState::ICE_GATHERING_NEW:
{
LLMutexLock lock(&mVoiceStateMutex);
mIceCompleted = false;
}
default:
break;
}
}
void LLWebRTCVoiceClient::OnIceCandidate(const llwebrtc::LLWebRTCIceCandidate &candidate)
{
LLMutexLock lock(&mVoiceStateMutex);
mIceCandidates.push_back(candidate);
}
void LLWebRTCVoiceClient::processIceUpdates()
{
LL_INFOS("Voice") << "Ice Gathering voice account." << LL_ENDL;
while ((!gAgent.getRegion() || !gAgent.getRegion()->capabilitiesReceived()) && !sShuttingDown)
{
LL_DEBUGS("Voice") << "no capabilities for voice provisioning; waiting " << LL_ENDL;
// *TODO* Pump a message for wake up.
llcoro::suspend();
}
if (sShuttingDown)
{
return;
}
std::string url = gAgent.getRegionCapability("VoiceSignalingRequest");
LL_DEBUGS("Voice") << "region ready to complete voice signaling; url=" << url << LL_ENDL;
LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("voiceAccountProvision", httpPolicy));
LLCore::HttpRequest::ptr_t httpRequest(new LLCore::HttpRequest);
LLCore::HttpOptions::ptr_t httpOpts = LLCore::HttpOptions::ptr_t(new LLCore::HttpOptions);
bool iceCompleted = false;
LLSD body;
{
LLMutexLock lock(&mVoiceStateMutex);
if (!mTrickling)
{
if (mIceCandidates.size())
{
LLSD candidates = LLSD::emptyArray();
for (auto &ice_candidate : mIceCandidates)
{
LLSD body_candidate;
body_candidate["sdpMid"] = ice_candidate.sdp_mid;
body_candidate["sdpMLineIndex"] = ice_candidate.mline_index;
body_candidate["candidate"] = ice_candidate.candidate;
candidates.append(body_candidate);
}
body["candidates"] = candidates;
mIceCandidates.clear();
}
else if (mIceCompleted)
{
LLSD body_candidate;
body_candidate["completed"] = true;
body["candidate"] = body_candidate;
iceCompleted = mIceCompleted;
mIceCompleted = false;
}
else
{
return;
}
LLCoreHttpUtil::HttpCoroutineAdapter::callbackHttpPost(
url,
LLCore::HttpRequest::DEFAULT_POLICY_ID,
body,
boost::bind(&LLWebRTCVoiceClient::onIceUpdateComplete, this, iceCompleted, _1),
boost::bind(&LLWebRTCVoiceClient::onIceUpdateError, this, 3, url, body, iceCompleted, _1));
mTrickling = true;
}
}
}
void LLWebRTCVoiceClient::onIceUpdateComplete(bool ice_completed, const LLSD& result)
{ mTrickling = false; }
void LLWebRTCVoiceClient::onIceUpdateError(int retries, std::string url, LLSD body, bool ice_completed, const LLSD& result)
{
if (sShuttingDown)
{
return;
}
LLCore::HttpRequest::policy_t httpPolicy(LLCore::HttpRequest::DEFAULT_POLICY_ID);
LLCoreHttpUtil::HttpCoroutineAdapter::ptr_t httpAdapter(new LLCoreHttpUtil::HttpCoroutineAdapter("voiceAccountProvision", httpPolicy));
if (retries >= 0)
{
LL_WARNS("Voice") << "Unable to complete ice trickling voice account, retrying. " << result << LL_ENDL;
LLCoreHttpUtil::HttpCoroutineAdapter::callbackHttpPost(url,
LLCore::HttpRequest::DEFAULT_POLICY_ID,
body,
boost::bind(&LLWebRTCVoiceClient::onIceUpdateComplete, this, ice_completed, _1),
boost::bind(&LLWebRTCVoiceClient::onIceUpdateError, this, retries - 1, url, body, ice_completed, _1));
}
else
{
LL_WARNS("Voice") << "Unable to complete ice trickling voice account, restarting connection. " << result << LL_ENDL;
setVoiceControlStateUnless(VOICE_STATE_SESSION_RETRY);
mTrickling = false;
}
}
void LLWebRTCVoiceClient::OnOfferAvailable(const std::string &sdp)
{
LL_INFOS("Voice") << "On Offer Available." << LL_ENDL;
LLMutexLock lock(&mVoiceStateMutex);
mChannelSDP = sdp;
}
void LLWebRTCVoiceClient::OnAudioEstablished(llwebrtc::LLWebRTCAudioInterface * audio_interface)
{
LL_INFOS("Voice") << "On AudioEstablished." << LL_ENDL;
mWebRTCAudioInterface = audio_interface;
mWebRTCAudioInterface->setAudioObserver(this);
float speaker_volume = 0;
{
LLMutexLock lock(&mVoiceStateMutex);
speaker_volume = mSpeakerVolume;
}
mWebRTCDeviceInterface->setSpeakerVolume(mSpeakerVolume);
setVoiceControlStateUnless(VOICE_STATE_SESSION_ESTABLISHED, VOICE_STATE_SESSION_RETRY);
}
void LLWebRTCVoiceClient::OnDataReceived(const std::string& data, bool binary)
{
// incoming data will be a json structure (if it's not binary.) We may pack
// binary for size reasons. Most of the keys in the json objects are
// single or double characters for size reasons.
// The primary element is:
// An object where each key is an agent id. (in the future, we may allow
// integer indices into an agentid list, populated on join commands. For size.
// Each key will point to a json object with keys identifying what's updated.
// 'p' - audio source power (level/volume) (int8 as int)
// 'j' - join - object of join data (TBD) (true for now)
// 'l' - boolean, always true if exists.
if (binary)
{
LL_WARNS("Voice") << "Binary data received from data channel." << LL_ENDL;
return;
}
Json::Reader reader;
Json::Value voice_data;
if (reader.parse(data, voice_data, false)) // don't collect comments
{
if (!voice_data.isObject())
{
LL_WARNS("Voice") << "Expected object from data channel:" << data << LL_ENDL;
return;
}
bool new_participant = false;
for (auto &participant_id : voice_data.getMemberNames())
{
LLUUID agent_id(participant_id);
if (agent_id.isNull())
{
LL_WARNS("Voice") << "Bad participant ID from data channel (" << participant_id << "):" << data << LL_ENDL;
continue;
}
participantStatePtr_t participant = findParticipantByID(agent_id);
bool joined = voice_data[participant_id].get("j", Json::Value(false)).asBool();
new_participant |= joined;
if (!participant && joined)
{
participant = addParticipantByID(agent_id);
}
if (participant)
{
if(voice_data[participant_id].get("l", Json::Value(false)).asBool())
{
removeParticipantByID(agent_id);
}
F32 energyRMS = (F32) (voice_data[participant_id].get("p", Json::Value(participant->mPower)).asInt()) / 128;
// convert to decibles
participant->mPower = energyRMS;
/* WebRTC appears to have deprecated VAD, but it's still in the Audio Processing Module so maybe we
can use it at some point when we actually process frames. */
participant->mIsSpeaking = participant->mPower > SPEAKING_AUDIO_LEVEL;
}
}
}
}
void LLWebRTCVoiceClient::OnDataChannelReady(llwebrtc::LLWebRTCDataInterface *data_interface)
{
mWebRTCDataInterface = data_interface;
mWebRTCDataInterface->setDataObserver(this);
}
void LLWebRTCVoiceClient::OnRenegotiationNeeded()
{
LL_INFOS("Voice") << "On Renegotiation Needed." << LL_ENDL;
mRelogRequested = TRUE;
mIsProcessingChannels = FALSE;
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_LOGIN_RETRY);
setVoiceControlStateUnless(VOICE_STATE_SESSION_RETRY);
}
void LLWebRTCVoiceClient::joinedAudioSession(const sessionStatePtr_t &session)
{
LL_DEBUGS("Voice") << "Joined Audio Session" << LL_ENDL;
if(mAudioSession != session)
{
sessionStatePtr_t oldSession = mAudioSession;
mAudioSession = session;
mAudioSessionChanged = true;
// The old session may now need to be deleted.
reapSession(oldSession);
}
// This is the session we're joining.
if(mIsJoiningSession)
{
LLSD WebRTCevent(LLSDMap("handle", LLSD::String(session->mHandle))
("session", "joined"));
mWebRTCPump.post(WebRTCevent);
if(!session->mIsChannel)
{
// this is a p2p session. Make sure the other end is added as a participant.
participantStatePtr_t participant(session->addParticipant(LLUUID(session->mSIPURI)));
if(participant)
{
if(participant->mAvatarIDValid)
{
lookupName(participant->mAvatarID);
}
else if(!session->mName.empty())
{
participant->mDisplayName = session->mName;
avatarNameResolved(participant->mAvatarID, session->mName);
}
// TODO: Question: Do we need to set up mAvatarID/mAvatarIDValid here?
LL_INFOS("Voice") << "added caller as participant \"" << participant->mAccountName
<< "\" (" << participant->mAvatarID << ")"<< LL_ENDL;
}
}
}
}
void LLWebRTCVoiceClient::reapSession(const sessionStatePtr_t &session)
{
if(session)
{
if(session == mAudioSession)
{
LL_DEBUGS("Voice") << "NOT deleting session " << session->mSIPURI << " (it's the current session)" << LL_ENDL;
}
else if(session == mNextAudioSession)
{
LL_DEBUGS("Voice") << "NOT deleting session " << session->mSIPURI << " (it's the next session)" << LL_ENDL;
}
else
{
// We don't have a reason to keep tracking this session, so just delete it.
LL_DEBUGS("Voice") << "deleting session " << session->mSIPURI << LL_ENDL;
deleteSession(session);
}
}
else
{
// LL_DEBUGS("Voice") << "session is NULL" << LL_ENDL;
}
}
// Returns true if the session seems to indicate we've moved to a region on a different voice server
bool LLWebRTCVoiceClient::sessionNeedsRelog(const sessionStatePtr_t &session)
{
bool result = false;
if(session)
{
// Only make this check for spatial channels (so it won't happen for group or p2p calls)
if(session->mIsSpatial)
{
std::string::size_type atsign;
atsign = session->mSIPURI.find("@");
if(atsign != std::string::npos)
{
std::string urihost = session->mSIPURI.substr(atsign + 1);
}
}
}
return result;
}
void LLWebRTCVoiceClient::leftAudioSession(const sessionStatePtr_t &session)
{
if (mAudioSession == session)
{
LLSD WebRTCevent(LLSDMap("handle", LLSD::String(session->mHandle))
("session", "removed"));
mWebRTCPump.post(WebRTCevent);
}
}
void LLWebRTCVoiceClient::muteListChanged()
{
// The user's mute list has been updated. Go through the current participant list and sync it with the mute list.
if(mAudioSession)
{
participantMap::iterator iter = mAudioSession->mParticipantsByURI.begin();
for(; iter != mAudioSession->mParticipantsByURI.end(); iter++)
{
participantStatePtr_t p(iter->second);
// Check to see if this participant is on the mute list already
if(p->updateMuteState())
mAudioSession->mVolumeDirty = true;
}
}
}
/////////////////////////////
// Managing list of participants
LLWebRTCVoiceClient::participantState::participantState(const LLUUID& agent_id) :
mURI(agent_id.asString()),
mAvatarID(agent_id),
mPTT(false),
mIsSpeaking(false),
mIsModeratorMuted(false),
mLastSpokeTimestamp(0.f),
mPower(0.f),
mVolume(LLVoiceClient::VOLUME_DEFAULT),
mUserVolume(0),
mOnMuteList(false),
mVolumeSet(false),
mVolumeDirty(false),
mAvatarIDValid(false),
mIsSelf(false)
{
}
LLWebRTCVoiceClient::participantStatePtr_t LLWebRTCVoiceClient::sessionState::addParticipant(const LLUUID& agent_id)
{
participantStatePtr_t result;
participantUUIDMap::iterator iter = mParticipantsByUUID.find(agent_id);
if (iter != mParticipantsByUUID.end())
{
result = iter->second;
}
if(!result)
{
// participant isn't already in one list or the other.
result.reset(new participantState(agent_id));
mParticipantsByURI.insert(participantMap::value_type(agent_id.asString(), result));
mParticipantsChanged = true;
result->mAvatarIDValid = true;
result->mAvatarID = agent_id;
if(result->updateMuteState())
{
mMuteDirty = true;
}
mParticipantsByUUID.insert(participantUUIDMap::value_type(result->mAvatarID, result));
if (LLSpeakerVolumeStorage::getInstance()->getSpeakerVolume(result->mAvatarID, result->mVolume))
{
result->mVolumeDirty = true;
mVolumeDirty = true;
}
LL_DEBUGS("Voice") << "participant \"" << result->mURI << "\" added." << LL_ENDL;
}
return result;
}
bool LLWebRTCVoiceClient::participantState::updateMuteState()
{
bool result = false;
bool isMuted = LLMuteList::getInstance()->isMuted(mAvatarID, LLMute::flagVoiceChat);
if(mOnMuteList != isMuted)
{
mOnMuteList = isMuted;
mVolumeDirty = true;
result = true;
}
return result;
}
bool LLWebRTCVoiceClient::participantState::isAvatar()
{
return mAvatarIDValid;
}
void LLWebRTCVoiceClient::sessionState::removeParticipant(const LLWebRTCVoiceClient::participantStatePtr_t &participant)
{
if(participant)
{
participantMap::iterator iter = mParticipantsByURI.find(participant->mURI);
participantUUIDMap::iterator iter2 = mParticipantsByUUID.find(participant->mAvatarID);
LL_DEBUGS("Voice") << "participant \"" << participant->mURI << "\" (" << participant->mAvatarID << ") removed." << LL_ENDL;
if(iter == mParticipantsByURI.end())
{
LL_WARNS("Voice") << "Internal error: participant " << participant->mURI << " not in URI map" << LL_ENDL;
}
else if(iter2 == mParticipantsByUUID.end())
{
LL_WARNS("Voice") << "Internal error: participant ID " << participant->mAvatarID << " not in UUID map" << LL_ENDL;
}
else if(iter->second != iter2->second)
{
LL_WARNS("Voice") << "Internal error: participant mismatch!" << LL_ENDL;
}
else
{
mParticipantsByURI.erase(iter);
mParticipantsByUUID.erase(iter2);
mParticipantsChanged = true;
}
}
}
void LLWebRTCVoiceClient::sessionState::removeAllParticipants()
{
LL_DEBUGS("Voice") << "called" << LL_ENDL;
while(!mParticipantsByURI.empty())
{
removeParticipant(mParticipantsByURI.begin()->second);
}
if(!mParticipantsByUUID.empty())
{
LL_WARNS("Voice") << "Internal error: empty URI map, non-empty UUID map" << LL_ENDL;
}
}
/*static*/
void LLWebRTCVoiceClient::sessionState::VerifySessions()
{
std::set<wptr_t>::iterator it = mSession.begin();
while (it != mSession.end())
{
if ((*it).expired())
{
LL_WARNS("Voice") << "Expired session found! removing" << LL_ENDL;
it = mSession.erase(it);
}
else
++it;
}
}
void LLWebRTCVoiceClient::getParticipantList(std::set<LLUUID> &participants)
{
if(mAudioSession)
{
for(participantUUIDMap::iterator iter = mAudioSession->mParticipantsByUUID.begin();
iter != mAudioSession->mParticipantsByUUID.end();
iter++)
{
participants.insert(iter->first);
}
}
}
bool LLWebRTCVoiceClient::isParticipant(const LLUUID &speaker_id)
{
if(mAudioSession)
{
return (mAudioSession->mParticipantsByUUID.find(speaker_id) != mAudioSession->mParticipantsByUUID.end());
}
return false;
}
LLWebRTCVoiceClient::participantStatePtr_t LLWebRTCVoiceClient::sessionState::findParticipant(const std::string &uri)
{
participantStatePtr_t result;
participantMap::iterator iter = mParticipantsByURI.find(uri);
if(iter == mParticipantsByURI.end())
{
if(!mAlternateSIPURI.empty() && (uri == mAlternateSIPURI))
{
// This is a p2p session (probably with the SLIM client) with an alternate URI for the other participant.
// Look up the other URI
iter = mParticipantsByURI.find(mSIPURI);
}
}
if(iter != mParticipantsByURI.end())
{
result = iter->second;
}
return result;
}
LLWebRTCVoiceClient::participantStatePtr_t LLWebRTCVoiceClient::sessionState::findParticipantByID(const LLUUID& id)
{
participantStatePtr_t result;
participantUUIDMap::iterator iter = mParticipantsByUUID.find(id);
if(iter != mParticipantsByUUID.end())
{
result = iter->second;
}
return result;
}
LLWebRTCVoiceClient::participantStatePtr_t LLWebRTCVoiceClient::findParticipantByID(const LLUUID& id)
{
participantStatePtr_t result;
if(mAudioSession)
{
result = mAudioSession->findParticipantByID(id);
}
return result;
}
LLWebRTCVoiceClient::participantStatePtr_t LLWebRTCVoiceClient::addParticipantByID(const LLUUID &id)
{
participantStatePtr_t result;
if (mAudioSession)
{
result = mAudioSession->addParticipant(id);
}
return result;
}
void LLWebRTCVoiceClient::removeParticipantByID(const LLUUID &id)
{
participantStatePtr_t result;
if (mAudioSession)
{
participantStatePtr_t participant = mAudioSession->findParticipantByID(id);
if (participant)
{
mAudioSession->removeParticipant(participant);
}
}
}
// Check for parcel boundary crossing
bool LLWebRTCVoiceClient::checkParcelChanged(bool update)
{
LLViewerRegion *region = gAgent.getRegion();
LLParcel *parcel = LLViewerParcelMgr::getInstance()->getAgentParcel();
if(region && parcel)
{
S32 parcelLocalID = parcel->getLocalID();
std::string regionName = region->getName();
// LL_DEBUGS("Voice") << "Region name = \"" << regionName << "\", parcel local ID = " << parcelLocalID << ", cap URI = \"" << capURI << "\"" << LL_ENDL;
// The region name starts out empty and gets filled in later.
// Also, the cap gets filled in a short time after the region cross, but a little too late for our purposes.
// If either is empty, wait for the next time around.
if(!regionName.empty())
{
if((parcelLocalID != mCurrentParcelLocalID) || (regionName != mCurrentRegionName))
{
// We have changed parcels. Initiate a parcel channel lookup.
if (update)
{
mCurrentParcelLocalID = parcelLocalID;
mCurrentRegionName = regionName;
}
return true;
}
}
}
return false;
}
bool LLWebRTCVoiceClient::switchChannel(
std::string uri,
bool spatial,
bool no_reconnect,
bool is_p2p,
std::string hash)
{
bool needsSwitch = !mIsInChannel;
if (mIsInChannel)
{
if (mSessionTerminateRequested)
{
// If a terminate has been requested, we need to compare against where the URI we're already headed to.
if(mNextAudioSession)
{
if(mNextAudioSession->mSIPURI != uri)
needsSwitch = true;
}
else
{
// mNextAudioSession is null -- this probably means we're on our way back to spatial.
if(!uri.empty())
{
// We do want to process a switch in this case.
needsSwitch = true;
}
}
}
else
{
// Otherwise, compare against the URI we're in now.
if(mAudioSession)
{
if(mAudioSession->mSIPURI != uri)
{
needsSwitch = true;
}
}
else
{
if(!uri.empty())
{
// mAudioSession is null -- it's not clear what case would cause this.
// For now, log it as a warning and see if it ever crops up.
LL_WARNS("Voice") << "No current audio session... Forcing switch" << LL_ENDL;
needsSwitch = true;
}
}
}
}
if(needsSwitch)
{
if(uri.empty())
{
// Leave any channel we may be in
LL_DEBUGS("Voice") << "leaving channel" << LL_ENDL;
sessionStatePtr_t oldSession = mNextAudioSession;
mNextAudioSession.reset();
// The old session may now need to be deleted.
reapSession(oldSession);
// If voice was on, turn it off
if (LLVoiceClient::getInstance()->getUserPTTState())
{
LLVoiceClient::getInstance()->setUserPTTState(false);
}
notifyStatusObservers(LLVoiceClientStatusObserver::STATUS_VOICE_DISABLED);
}
else
{
LL_DEBUGS("Voice") << "switching to channel " << uri << LL_ENDL;
mNextAudioSession = addSession(uri);
mNextAudioSession->mIsSpatial = spatial;
mNextAudioSession->mReconnect = !no_reconnect;
mNextAudioSession->mIsP2P = is_p2p;
}
if (mIsInChannel)
{
// If we're already in a channel, or if we're joining one, terminate
// so we can rejoin with the new session data.
sessionTerminate();
}
}
return needsSwitch;
}
void LLWebRTCVoiceClient::joinSession(const sessionStatePtr_t &session)
{
mNextAudioSession = session;
if (mIsInChannel)
{
// If we're already in a channel, or if we're joining one, terminate
// so we can rejoin with the new session data.
sessionTerminate();
}
}
void LLWebRTCVoiceClient::setNonSpatialChannel(
const std::string &uri,
const std::string &credentials)
{
switchChannel(uri, false, false, false, credentials);
}
bool LLWebRTCVoiceClient::setSpatialChannel(
const std::string &uri, const std::string &credentials)
{
mSpatialSessionURI = uri;
mAreaVoiceDisabled = mSpatialSessionURI.empty();
LL_DEBUGS("Voice") << "got spatial channel uri: \"" << uri << "\"" << LL_ENDL;
if((mIsInChannel && mAudioSession && !(mAudioSession->mIsSpatial)) || (mNextAudioSession && !(mNextAudioSession->mIsSpatial)))
{
// User is in a non-spatial chat or joining a non-spatial chat. Don't switch channels.
LL_INFOS("Voice") << "in non-spatial chat, not switching channels" << LL_ENDL;
return false;
}
else
{
return switchChannel(mSpatialSessionURI, true, false, false);
}
}
void LLWebRTCVoiceClient::callUser(const LLUUID &uuid)
{
switchChannel(uuid.asString(), false, true, true);
}
void LLWebRTCVoiceClient::endUserIMSession(const LLUUID &uuid)
{
}
bool LLWebRTCVoiceClient::isValidChannel(std::string &sessionHandle)
{
return(findSession(sessionHandle) != NULL);
}
bool LLWebRTCVoiceClient::answerInvite(std::string &sessionHandle)
{
// this is only ever used to answer incoming p2p call invites.
sessionStatePtr_t session(findSession(sessionHandle));
if(session)
{
session->mIsSpatial = false;
session->mReconnect = false;
session->mIsP2P = true;
joinSession(session);
return true;
}
return false;
}
bool LLWebRTCVoiceClient::isVoiceWorking() const
{
//Added stateSessionTerminated state to avoid problems with call in parcels with disabled voice (EXT-4758)
// Condition with joining spatial num was added to take into account possible problems with connection to voice
// server(EXT-4313). See bug descriptions and comments for MAX_NORMAL_JOINING_SPATIAL_NUM for more info.
return (mSpatialJoiningNum < MAX_NORMAL_JOINING_SPATIAL_NUM) && mIsProcessingChannels;
// return (mSpatialJoiningNum < MAX_NORMAL_JOINING_SPATIAL_NUM) && (stateLoggedIn <= mState) && (mState <= stateSessionTerminated);
}
// Returns true if the indicated participant in the current audio session is really an SL avatar.
// Currently this will be false only for PSTN callers into group chats, and PSTN p2p calls.
BOOL LLWebRTCVoiceClient::isParticipantAvatar(const LLUUID &id)
{
BOOL result = TRUE;
sessionStatePtr_t session(findSession(id));
if(!session)
{
// Didn't find a matching session -- check the current audio session for a matching participant
if(mAudioSession)
{
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
result = participant->isAvatar();
}
}
}
return result;
}
// Returns true if calling back the session URI after the session has closed is possible.
// Currently this will be false only for PSTN P2P calls.
BOOL LLWebRTCVoiceClient::isSessionCallBackPossible(const LLUUID &session_id)
{
BOOL result = TRUE;
sessionStatePtr_t session(findSession(session_id));
if(session != NULL)
{
result = session->isCallBackPossible();
}
return result;
}
// Returns true if the session can accept text IM's.
// Currently this will be false only for PSTN P2P calls.
BOOL LLWebRTCVoiceClient::isSessionTextIMPossible(const LLUUID &session_id)
{
bool result = TRUE;
sessionStatePtr_t session(findSession(session_id));
if(session != NULL)
{
result = session->isTextIMPossible();
}
return result;
}
void LLWebRTCVoiceClient::declineInvite(std::string &sessionHandle)
{
}
void LLWebRTCVoiceClient::leaveNonSpatialChannel()
{
LL_DEBUGS("Voice") << "Request to leave spacial channel." << LL_ENDL;
// Make sure we don't rejoin the current session.
sessionStatePtr_t oldNextSession(mNextAudioSession);
mNextAudioSession.reset();
// Most likely this will still be the current session at this point, but check it anyway.
reapSession(oldNextSession);
verifySessionState();
sessionTerminate();
}
std::string LLWebRTCVoiceClient::getCurrentChannel()
{
std::string result;
if (mIsInChannel && !mSessionTerminateRequested)
{
result = getAudioSessionURI();
}
return result;
}
bool LLWebRTCVoiceClient::inProximalChannel()
{
bool result = false;
if (mIsInChannel && !mSessionTerminateRequested)
{
result = inSpatialChannel();
}
return result;
}
std::string LLWebRTCVoiceClient::nameFromAvatar(LLVOAvatar *avatar)
{
std::string result;
if(avatar)
{
result = nameFromID(avatar->getID());
}
return result;
}
std::string LLWebRTCVoiceClient::nameFromID(const LLUUID &uuid)
{
std::string result;
if (uuid.isNull()) {
//WebRTC, the uuid emtpy look for the mURIString and return that instead.
//result.assign(uuid.mURIStringName);
LLStringUtil::replaceChar(result, '_', ' ');
return result;
}
// Prepending this apparently prevents conflicts with reserved names inside the WebRTC code.
result = "x";
// Base64 encode and replace the pieces of base64 that are less compatible
// with e-mail local-parts.
// See RFC-4648 "Base 64 Encoding with URL and Filename Safe Alphabet"
result += LLBase64::encode(uuid.mData, UUID_BYTES);
LLStringUtil::replaceChar(result, '+', '-');
LLStringUtil::replaceChar(result, '/', '_');
// If you need to transform a GUID to this form on the Mac OS X command line, this will do so:
// echo -n x && (echo e669132a-6c43-4ee1-a78d-6c82fff59f32 |xxd -r -p |openssl base64|tr '/+' '_-')
// The reverse transform can be done with:
// echo 'x5mkTKmxDTuGnjWyC__WfMg==' |cut -b 2- -|tr '_-' '/+' |openssl base64 -d|xxd -p
return result;
}
bool LLWebRTCVoiceClient::IDFromName(const std::string inName, LLUUID &uuid)
{
bool result = false;
// SLIM SDK: The "name" may actually be a SIP URI such as: "sip:xFnPP04IpREWNkuw1cOXlhw==@bhr.WebRTC.com"
// If it is, convert to a bare name before doing the transform.
std::string name;
// Doesn't look like a SIP URI, assume it's an actual name.
if(name.empty())
name = inName;
// This will only work if the name is of the proper form.
// As an example, the account name for Monroe Linden (UUID 1673cfd3-8229-4445-8d92-ec3570e5e587) is:
// "xFnPP04IpREWNkuw1cOXlhw=="
if((name.size() == 25) && (name[0] == 'x') && (name[23] == '=') && (name[24] == '='))
{
// The name appears to have the right form.
// Reverse the transforms done by nameFromID
std::string temp = name;
LLStringUtil::replaceChar(temp, '-', '+');
LLStringUtil::replaceChar(temp, '_', '/');
U8 rawuuid[UUID_BYTES + 1];
int len = apr_base64_decode_binary(rawuuid, temp.c_str() + 1);
if(len == UUID_BYTES)
{
// The decode succeeded. Stuff the bits into the result's UUID
memcpy(uuid.mData, rawuuid, UUID_BYTES);
result = true;
}
}
if(!result)
{
// WebRTC: not a standard account name, just copy the URI name mURIString field
// and hope for the best. bpj
uuid.setNull(); // WebRTC, set the uuid field to nulls
}
return result;
}
std::string LLWebRTCVoiceClient::displayNameFromAvatar(LLVOAvatar *avatar)
{
return avatar->getFullname();
}
bool LLWebRTCVoiceClient::inSpatialChannel(void)
{
bool result = false;
if(mAudioSession)
{
result = mAudioSession->mIsSpatial;
}
return result;
}
std::string LLWebRTCVoiceClient::getAudioSessionURI()
{
std::string result;
if(mAudioSession)
result = mAudioSession->mSIPURI;
return result;
}
std::string LLWebRTCVoiceClient::getAudioSessionHandle()
{
std::string result;
if(mAudioSession)
result = mAudioSession->mHandle;
return result;
}
/////////////////////////////
// Sending updates of current state
void LLWebRTCVoiceClient::enforceTether(void)
{
LLVector3d tethered = mCameraRequestedPosition;
// constrain 'tethered' to within 50m of mAvatarPosition.
{
F32 max_dist = 50.0f;
LLVector3d camera_offset = mCameraRequestedPosition - mAvatarPosition;
F32 camera_distance = (F32)camera_offset.magVec();
if(camera_distance > max_dist)
{
tethered = mAvatarPosition +
(max_dist / camera_distance) * camera_offset;
}
}
if(dist_vec_squared(mCameraPosition, tethered) > 0.01)
{
mCameraPosition = tethered;
mSpatialCoordsDirty = true;
}
}
void LLWebRTCVoiceClient::updatePosition(void)
{
LLViewerRegion *region = gAgent.getRegion();
if(region && isAgentAvatarValid())
{
LLVector3d pos;
LLQuaternion qrot;
// TODO: If camera and avatar velocity are actually used by the voice system, we could compute them here...
// They're currently always set to zero.
// Send the current camera position to the voice code
pos = gAgent.getRegion()->getPosGlobalFromRegion(LLViewerCamera::getInstance()->getOrigin());
LLWebRTCVoiceClient::getInstance()->setCameraPosition(
pos, // position
LLVector3::zero, // velocity
LLViewerCamera::getInstance()->getQuaternion()); // rotation matrix
// Send the current avatar position to the voice code
qrot = gAgentAvatarp->getRootJoint()->getWorldRotation();
pos = gAgentAvatarp->getPositionGlobal();
// TODO: Can we get the head offset from outside the LLVOAvatar?
// pos += LLVector3d(mHeadOffset);
pos += LLVector3d(0.f, 0.f, 1.f);
LLWebRTCVoiceClient::getInstance()->setAvatarPosition(
pos, // position
LLVector3::zero, // velocity
qrot); // rotation matrix
}
}
void LLWebRTCVoiceClient::setCameraPosition(const LLVector3d &position, const LLVector3 &velocity, const LLQuaternion &rot)
{
mCameraRequestedPosition = position;
if(mCameraVelocity != velocity)
{
mCameraVelocity = velocity;
mSpatialCoordsDirty = true;
}
if(mCameraRot != rot)
{
mCameraRot = rot;
mSpatialCoordsDirty = true;
}
}
void LLWebRTCVoiceClient::setAvatarPosition(const LLVector3d &position, const LLVector3 &velocity, const LLQuaternion &rot)
{
if(dist_vec_squared(mAvatarPosition, position) > 0.01)
{
mAvatarPosition = position;
mSpatialCoordsDirty = true;
}
if(mAvatarVelocity != velocity)
{
mAvatarVelocity = velocity;
mSpatialCoordsDirty = true;
}
// If the two rotations are not exactly equal test their dot product
// to get the cos of the angle between them.
// If it is too small, don't update.
F32 rot_cos_diff = llabs(dot(mAvatarRot, rot));
if ((mAvatarRot != rot) && (rot_cos_diff < MINUSCULE_ANGLE_COS))
{
mAvatarRot = rot;
mSpatialCoordsDirty = true;
}
}
bool LLWebRTCVoiceClient::channelFromRegion(LLViewerRegion *region, std::string &name)
{
bool result = false;
if(region)
{
name = region->getName();
}
if(!name.empty())
result = true;
return result;
}
void LLWebRTCVoiceClient::leaveChannel(void)
{
if (mIsInChannel)
{
LL_DEBUGS("Voice") << "leaving channel for teleport/logout" << LL_ENDL;
mChannelName.clear();
sessionTerminate();
}
}
void LLWebRTCVoiceClient::setMuteMic(bool muted)
{
participantStatePtr_t participant = findParticipantByID(gAgentID);
if (participant)
{
participant->mPower = 0.0;
}
if (mWebRTCAudioInterface)
{
mWebRTCAudioInterface->setMute(muted);
}
mMuteMic = muted;
}
void LLWebRTCVoiceClient::setVoiceEnabled(bool enabled)
{
LL_DEBUGS("Voice")
<< "( " << (enabled ? "enabled" : "disabled") << " )"
<< " was "<< (mVoiceEnabled ? "enabled" : "disabled")
<< " coro "<< (mIsCoroutineActive ? "active" : "inactive")
<< LL_ENDL;
if (enabled != mVoiceEnabled)
{
// TODO: Refactor this so we don't call into LLVoiceChannel, but simply
// use the status observer
mVoiceEnabled = enabled;
LLVoiceClientStatusObserver::EStatusType status;
if (enabled)
{
LL_DEBUGS("Voice") << "enabling" << LL_ENDL;
LLVoiceChannel::getCurrentVoiceChannel()->activate();
status = LLVoiceClientStatusObserver::STATUS_VOICE_ENABLED;
if (!mIsCoroutineActive)
{
LLCoros::instance().launch("LLWebRTCVoiceClient::voiceControlCoro",
boost::bind(&LLWebRTCVoiceClient::voiceControlCoro, LLWebRTCVoiceClient::getInstance()));
}
else
{
LL_DEBUGS("Voice") << "coro should be active.. not launching" << LL_ENDL;
}
}
else
{
// Turning voice off looses your current channel -- this makes sure the UI isn't out of sync when you re-enable it.
LLVoiceChannel::getCurrentVoiceChannel()->deactivate();
gAgent.setVoiceConnected(false);
status = LLVoiceClientStatusObserver::STATUS_VOICE_DISABLED;
}
notifyStatusObservers(status);
}
else
{
LL_DEBUGS("Voice") << " no-op" << LL_ENDL;
}
}
bool LLWebRTCVoiceClient::voiceEnabled()
{
return gSavedSettings.getBOOL("EnableVoiceChat") &&
!gSavedSettings.getBOOL("CmdLineDisableVoice") &&
!gNonInteractive;
}
void LLWebRTCVoiceClient::setLipSyncEnabled(BOOL enabled)
{
mLipSyncEnabled = enabled;
}
BOOL LLWebRTCVoiceClient::lipSyncEnabled()
{
if ( mVoiceEnabled )
{
return mLipSyncEnabled;
}
else
{
return FALSE;
}
}
void LLWebRTCVoiceClient::setEarLocation(S32 loc)
{
if(mEarLocation != loc)
{
LL_DEBUGS("Voice") << "Setting mEarLocation to " << loc << LL_ENDL;
mEarLocation = loc;
mSpatialCoordsDirty = true;
}
}
void LLWebRTCVoiceClient::setVoiceVolume(F32 volume)
{
if (volume != mSpeakerVolume)
{
{
LLMutexLock lock(&mVoiceStateMutex);
int min_volume = 0.0;
if ((volume == min_volume) || (mSpeakerVolume == min_volume))
{
mSpeakerMuteDirty = true;
}
mSpeakerVolume = volume;
mSpeakerVolumeDirty = true;
}
if (mWebRTCAudioInterface)
{
mWebRTCDeviceInterface->setSpeakerVolume(volume);
}
}
}
void LLWebRTCVoiceClient::setMicGain(F32 volume)
{
int scaled_volume = scale_mic_volume(volume);
if(scaled_volume != mMicVolume)
{
mMicVolume = scaled_volume;
mMicVolumeDirty = true;
}
}
/////////////////////////////
// Accessors for data related to nearby speakers
BOOL LLWebRTCVoiceClient::getVoiceEnabled(const LLUUID& id)
{
BOOL result = FALSE;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
// I'm not sure what the semantics of this should be.
// For now, if we have any data about the user that came through the chat channel, assume they're voice-enabled.
result = TRUE;
}
return result;
}
std::string LLWebRTCVoiceClient::getDisplayName(const LLUUID& id)
{
std::string result;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
result = participant->mDisplayName;
}
return result;
}
BOOL LLWebRTCVoiceClient::getIsSpeaking(const LLUUID& id)
{
BOOL result = FALSE;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
result = participant->mIsSpeaking;
}
return result;
}
BOOL LLWebRTCVoiceClient::getIsModeratorMuted(const LLUUID& id)
{
BOOL result = FALSE;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
result = participant->mIsModeratorMuted;
}
return result;
}
F32 LLWebRTCVoiceClient::getCurrentPower(const LLUUID &id)
{
F32 result = 0;
participantStatePtr_t participant(findParticipantByID(id));
if (participant)
{
result = participant->mPower * 2.0;
}
return result;
}
BOOL LLWebRTCVoiceClient::getUsingPTT(const LLUUID& id)
{
BOOL result = FALSE;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
// I'm not sure what the semantics of this should be.
// Does "using PTT" mean they're configured with a push-to-talk button?
// For now, we know there's no PTT mechanism in place, so nobody is using it.
}
return result;
}
BOOL LLWebRTCVoiceClient::getOnMuteList(const LLUUID& id)
{
BOOL result = FALSE;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
result = participant->mOnMuteList;
}
return result;
}
// External accessors.
F32 LLWebRTCVoiceClient::getUserVolume(const LLUUID& id)
{
// Minimum volume will be returned for users with voice disabled
F32 result = LLVoiceClient::VOLUME_MIN;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
result = participant->mVolume;
// Enable this when debugging voice slider issues. It's way to spammy even for debug-level logging.
// LL_DEBUGS("Voice") << "mVolume = " << result << " for " << id << LL_ENDL;
}
return result;
}
void LLWebRTCVoiceClient::setUserVolume(const LLUUID& id, F32 volume)
{
if(mAudioSession)
{
participantStatePtr_t participant(findParticipantByID(id));
if (participant && !participant->mIsSelf)
{
if (!is_approx_equal(volume, LLVoiceClient::VOLUME_DEFAULT))
{
// Store this volume setting for future sessions if it has been
// changed from the default
LLSpeakerVolumeStorage::getInstance()->storeSpeakerVolume(id, volume);
}
else
{
// Remove stored volume setting if it is returned to the default
LLSpeakerVolumeStorage::getInstance()->removeSpeakerVolume(id);
}
participant->mVolume = llclamp(volume, LLVoiceClient::VOLUME_MIN, LLVoiceClient::VOLUME_MAX);
participant->mVolumeDirty = true;
mAudioSession->mVolumeDirty = true;
}
}
}
std::string LLWebRTCVoiceClient::getGroupID(const LLUUID& id)
{
std::string result;
participantStatePtr_t participant(findParticipantByID(id));
if(participant)
{
result = participant->mGroupID;
}
return result;
}
BOOL LLWebRTCVoiceClient::getAreaVoiceDisabled()
{
return mAreaVoiceDisabled;
}
//------------------------------------------------------------------------
std::set<LLWebRTCVoiceClient::sessionState::wptr_t> LLWebRTCVoiceClient::sessionState::mSession;
LLWebRTCVoiceClient::sessionState::sessionState() :
mErrorStatusCode(0),
mMediaStreamState(streamStateUnknown),
mIsChannel(false),
mIsSpatial(false),
mIsP2P(false),
mIncoming(false),
mVoiceActive(false),
mReconnect(false),
mVolumeDirty(false),
mMuteDirty(false),
mParticipantsChanged(false)
{
}
/*static*/
LLWebRTCVoiceClient::sessionState::ptr_t LLWebRTCVoiceClient::sessionState::createSession()
{
sessionState::ptr_t ptr(new sessionState());
std::pair<std::set<wptr_t>::iterator, bool> result = mSession.insert(ptr);
if (result.second)
ptr->mMyIterator = result.first;
return ptr;
}
LLWebRTCVoiceClient::sessionState::~sessionState()
{
LL_INFOS("Voice") << "Destroying session handle=" << mHandle << " SIP=" << mSIPURI << LL_ENDL;
if (mMyIterator != mSession.end())
mSession.erase(mMyIterator);
removeAllParticipants();
}
bool LLWebRTCVoiceClient::sessionState::isCallBackPossible()
{
// This may change to be explicitly specified by WebRTC in the future...
// Currently, only PSTN P2P calls cannot be returned.
// Conveniently, this is also the only case where we synthesize a caller UUID.
return false;
}
bool LLWebRTCVoiceClient::sessionState::isTextIMPossible()
{
// This may change to be explicitly specified by WebRTC in the future...
return false;
}
/*static*/
LLWebRTCVoiceClient::sessionState::ptr_t LLWebRTCVoiceClient::sessionState::matchSessionByHandle(const std::string &handle)
{
sessionStatePtr_t result;
// *TODO: My kingdom for a lambda!
std::set<wptr_t>::iterator it = std::find_if(mSession.begin(), mSession.end(), boost::bind(testByHandle, _1, handle));
if (it != mSession.end())
result = (*it).lock();
return result;
}
/*static*/
LLWebRTCVoiceClient::sessionState::ptr_t LLWebRTCVoiceClient::sessionState::matchSessionByURI(const std::string &uri)
{
sessionStatePtr_t result;
// *TODO: My kingdom for a lambda!
std::set<wptr_t>::iterator it = std::find_if(mSession.begin(), mSession.end(), boost::bind(testBySIPOrAlterateURI, _1, uri));
if (it != mSession.end())
result = (*it).lock();
return result;
}
/*static*/
LLWebRTCVoiceClient::sessionState::ptr_t LLWebRTCVoiceClient::sessionState::matchSessionByParticipant(const LLUUID &participant_id)
{
sessionStatePtr_t result;
// *TODO: My kingdom for a lambda!
std::set<wptr_t>::iterator it = std::find_if(mSession.begin(), mSession.end(), boost::bind(testByCallerId, _1, participant_id));
if (it != mSession.end())
result = (*it).lock();
return result;
}
void LLWebRTCVoiceClient::sessionState::for_each(sessionFunc_t func)
{
std::for_each(mSession.begin(), mSession.end(), boost::bind(for_eachPredicate, _1, func));
}
// simple test predicates.
// *TODO: These should be made into lambdas when we can pull the trigger on newer C++ features.
bool LLWebRTCVoiceClient::sessionState::testByHandle(const LLWebRTCVoiceClient::sessionState::wptr_t &a, std::string handle)
{
ptr_t aLock(a.lock());
return aLock ? aLock->mHandle == handle : false;
}
bool LLWebRTCVoiceClient::sessionState::testByCreatingURI(const LLWebRTCVoiceClient::sessionState::wptr_t &a, std::string uri)
{
ptr_t aLock(a.lock());
return aLock ? (aLock->mSIPURI == uri) : false;
}
bool LLWebRTCVoiceClient::sessionState::testBySIPOrAlterateURI(const LLWebRTCVoiceClient::sessionState::wptr_t &a, std::string uri)
{
ptr_t aLock(a.lock());
return aLock ? ((aLock->mSIPURI == uri) || (aLock->mAlternateSIPURI == uri)) : false;
}
bool LLWebRTCVoiceClient::sessionState::testByCallerId(const LLWebRTCVoiceClient::sessionState::wptr_t &a, LLUUID participantId)
{
ptr_t aLock(a.lock());
return aLock ? ((aLock->mCallerID == participantId) || (aLock->mIMSessionID == participantId)) : false;
}
/*static*/
void LLWebRTCVoiceClient::sessionState::for_eachPredicate(const LLWebRTCVoiceClient::sessionState::wptr_t &a, sessionFunc_t func)
{
ptr_t aLock(a.lock());
if (aLock)
func(aLock);
else
{
LL_WARNS("Voice") << "Stale handle in session map!" << LL_ENDL;
}
}
void LLWebRTCVoiceClient::sessionEstablished()
{
mWebRTCAudioInterface->setMute(mMuteMic);
addSession(gAgent.getRegion()->getRegionID().asString());
}
LLWebRTCVoiceClient::sessionStatePtr_t LLWebRTCVoiceClient::findSession(const std::string &handle)
{
sessionStatePtr_t result;
sessionMap::iterator iter = mSessionsByHandle.find(handle);
if(iter != mSessionsByHandle.end())
{
result = iter->second;
}
return result;
}
LLWebRTCVoiceClient::sessionStatePtr_t LLWebRTCVoiceClient::findSession(const LLUUID &participant_id)
{
sessionStatePtr_t result = sessionState::matchSessionByParticipant(participant_id);
return result;
}
LLWebRTCVoiceClient::sessionStatePtr_t LLWebRTCVoiceClient::addSession(const std::string &uri, const std::string &handle)
{
sessionStatePtr_t result;
if(handle.empty())
{
// No handle supplied.
// Check whether there's already a session with this URI
result = sessionState::matchSessionByURI(uri);
}
else // (!handle.empty())
{
// Check for an existing session with this handle
sessionMap::iterator iter = mSessionsByHandle.find(handle);
if(iter != mSessionsByHandle.end())
{
result = iter->second;
}
}
if(!result)
{
// No existing session found.
LL_DEBUGS("Voice") << "adding new session: handle \"" << handle << "\" URI " << uri << LL_ENDL;
result = sessionState::createSession();
result->mSIPURI = uri;
result->mHandle = handle;
if (LLVoiceClient::instance().getVoiceEffectEnabled())
{
result->mVoiceFontID = LLVoiceClient::instance().getVoiceEffectDefault();
}
if(!result->mHandle.empty())
{
// *TODO: Rider: This concerns me. There is a path (via switchChannel) where
// we do not track the session. In theory this means that we could end up with
// a mAuidoSession that does not match the session tracked in mSessionsByHandle
mSessionsByHandle.insert(sessionMap::value_type(result->mHandle, result));
}
}
else
{
// Found an existing session
if(uri != result->mSIPURI)
{
// TODO: Should this be an internal error?
LL_DEBUGS("Voice") << "changing uri from " << result->mSIPURI << " to " << uri << LL_ENDL;
setSessionURI(result, uri);
}
if(handle != result->mHandle)
{
if(handle.empty())
{
// There's at least one race condition where where addSession was clearing an existing session handle, which caused things to break.
LL_DEBUGS("Voice") << "NOT clearing handle " << result->mHandle << LL_ENDL;
}
else
{
// TODO: Should this be an internal error?
LL_DEBUGS("Voice") << "changing handle from " << result->mHandle << " to " << handle << LL_ENDL;
setSessionHandle(result, handle);
}
}
LL_DEBUGS("Voice") << "returning existing session: handle " << handle << " URI " << uri << LL_ENDL;
}
verifySessionState();
return result;
}
void LLWebRTCVoiceClient::clearSessionHandle(const sessionStatePtr_t &session)
{
if (session)
{
if (!session->mHandle.empty())
{
sessionMap::iterator iter = mSessionsByHandle.find(session->mHandle);
if (iter != mSessionsByHandle.end())
{
mSessionsByHandle.erase(iter);
}
}
else
{
LL_WARNS("Voice") << "Session has empty handle!" << LL_ENDL;
}
}
else
{
LL_WARNS("Voice") << "Attempt to clear NULL session!" << LL_ENDL;
}
}
void LLWebRTCVoiceClient::setSessionHandle(const sessionStatePtr_t &session, const std::string &handle)
{
// Have to remove the session from the handle-indexed map before changing the handle, or things will break badly.
if(!session->mHandle.empty())
{
// Remove session from the map if it should have been there.
sessionMap::iterator iter = mSessionsByHandle.find(session->mHandle);
if(iter != mSessionsByHandle.end())
{
if(iter->second != session)
{
LL_WARNS("Voice") << "Internal error: session mismatch! Session may have been duplicated. Removing version in map." << LL_ENDL;
}
mSessionsByHandle.erase(iter);
}
else
{
LL_WARNS("Voice") << "Attempt to remove session with handle " << session->mHandle << " not found in map!" << LL_ENDL;
}
}
session->mHandle = handle;
if(!handle.empty())
{
mSessionsByHandle.insert(sessionMap::value_type(session->mHandle, session));
}
verifySessionState();
}
void LLWebRTCVoiceClient::setSessionURI(const sessionStatePtr_t &session, const std::string &uri)
{
// There used to be a map of session URIs to sessions, which made this complex....
session->mSIPURI = uri;
verifySessionState();
}
void LLWebRTCVoiceClient::deleteSession(const sessionStatePtr_t &session)
{
// Remove the session from the handle map
if(!session->mHandle.empty())
{
sessionMap::iterator iter = mSessionsByHandle.find(session->mHandle);
if(iter != mSessionsByHandle.end())
{
if(iter->second != session)
{
LL_WARNS("Voice") << "Internal error: session mismatch, removing session in map." << LL_ENDL;
}
mSessionsByHandle.erase(iter);
}
}
// At this point, the session should be unhooked from all lists and all state should be consistent.
verifySessionState();
// If this is the current audio session, clean up the pointer which will soon be dangling.
if(mAudioSession == session)
{
mAudioSession.reset();
mAudioSessionChanged = true;
}
// ditto for the next audio session
if(mNextAudioSession == session)
{
mNextAudioSession.reset();
}
}
void LLWebRTCVoiceClient::deleteAllSessions()
{
LL_DEBUGS("Voice") << LL_ENDL;
while (!mSessionsByHandle.empty())
{
const sessionStatePtr_t session = mSessionsByHandle.begin()->second;
deleteSession(session);
}
}
void LLWebRTCVoiceClient::verifySessionState(void)
{
LL_DEBUGS("Voice") << "Sessions in handle map=" << mSessionsByHandle.size() << LL_ENDL;
sessionState::VerifySessions();
}
void LLWebRTCVoiceClient::addObserver(LLVoiceClientParticipantObserver* observer)
{
mParticipantObservers.insert(observer);
}
void LLWebRTCVoiceClient::removeObserver(LLVoiceClientParticipantObserver* observer)
{
mParticipantObservers.erase(observer);
}
void LLWebRTCVoiceClient::notifyParticipantObservers()
{
for (observer_set_t::iterator it = mParticipantObservers.begin();
it != mParticipantObservers.end();
)
{
LLVoiceClientParticipantObserver* observer = *it;
observer->onParticipantsChanged();
// In case onParticipantsChanged() deleted an entry.
it = mParticipantObservers.upper_bound(observer);
}
}
void LLWebRTCVoiceClient::addObserver(LLVoiceClientStatusObserver* observer)
{
mStatusObservers.insert(observer);
}
void LLWebRTCVoiceClient::removeObserver(LLVoiceClientStatusObserver* observer)
{
mStatusObservers.erase(observer);
}
void LLWebRTCVoiceClient::notifyStatusObservers(LLVoiceClientStatusObserver::EStatusType status)
{
LL_DEBUGS("Voice") << "( " << LLVoiceClientStatusObserver::status2string(status) << " )"
<< " mAudioSession=" << mAudioSession
<< LL_ENDL;
if(mAudioSession)
{
if(status == LLVoiceClientStatusObserver::ERROR_UNKNOWN)
{
switch(mAudioSession->mErrorStatusCode)
{
case 20713: status = LLVoiceClientStatusObserver::ERROR_CHANNEL_FULL; break;
case 20714: status = LLVoiceClientStatusObserver::ERROR_CHANNEL_LOCKED; break;
case 20715:
//invalid channel, we may be using a set of poorly cached
//info
status = LLVoiceClientStatusObserver::ERROR_NOT_AVAILABLE;
break;
case 1009:
//invalid username and password
status = LLVoiceClientStatusObserver::ERROR_NOT_AVAILABLE;
break;
}
// Reset the error code to make sure it won't be reused later by accident.
mAudioSession->mErrorStatusCode = 0;
}
else if(status == LLVoiceClientStatusObserver::STATUS_LEFT_CHANNEL)
{
switch(mAudioSession->mErrorStatusCode)
{
case HTTP_NOT_FOUND: // NOT_FOUND
// *TODO: Should this be 503?
case 480: // TEMPORARILY_UNAVAILABLE
case HTTP_REQUEST_TIME_OUT: // REQUEST_TIMEOUT
// call failed because other user was not available
// treat this as an error case
status = LLVoiceClientStatusObserver::ERROR_NOT_AVAILABLE;
// Reset the error code to make sure it won't be reused later by accident.
mAudioSession->mErrorStatusCode = 0;
break;
}
}
}
LL_DEBUGS("Voice")
<< " " << LLVoiceClientStatusObserver::status2string(status)
<< ", session URI " << getAudioSessionURI()
<< ", proximal is " << inSpatialChannel()
<< LL_ENDL;
for (status_observer_set_t::iterator it = mStatusObservers.begin();
it != mStatusObservers.end();
)
{
LLVoiceClientStatusObserver* observer = *it;
observer->onChange(status, getAudioSessionURI(), inSpatialChannel());
// In case onError() deleted an entry.
it = mStatusObservers.upper_bound(observer);
}
// skipped to avoid speak button blinking
if ( status != LLVoiceClientStatusObserver::STATUS_JOINING
&& status != LLVoiceClientStatusObserver::STATUS_LEFT_CHANNEL
&& status != LLVoiceClientStatusObserver::STATUS_VOICE_DISABLED)
{
bool voice_status = LLVoiceClient::getInstance()->voiceEnabled() && LLVoiceClient::getInstance()->isVoiceWorking();
gAgent.setVoiceConnected(voice_status);
if (voice_status)
{
LLFirstUse::speak(true);
}
}
}
void LLWebRTCVoiceClient::addObserver(LLFriendObserver* observer)
{
mFriendObservers.insert(observer);
}
void LLWebRTCVoiceClient::removeObserver(LLFriendObserver* observer)
{
mFriendObservers.erase(observer);
}
void LLWebRTCVoiceClient::notifyFriendObservers()
{
for (friend_observer_set_t::iterator it = mFriendObservers.begin();
it != mFriendObservers.end();
)
{
LLFriendObserver* observer = *it;
it++;
// The only friend-related thing we notify on is online/offline transitions.
observer->changed(LLFriendObserver::ONLINE);
}
}
void LLWebRTCVoiceClient::lookupName(const LLUUID &id)
{
if (mAvatarNameCacheConnection.connected())
{
mAvatarNameCacheConnection.disconnect();
}
mAvatarNameCacheConnection = LLAvatarNameCache::get(id, boost::bind(&LLWebRTCVoiceClient::onAvatarNameCache, this, _1, _2));
}
void LLWebRTCVoiceClient::onAvatarNameCache(const LLUUID& agent_id,
const LLAvatarName& av_name)
{
mAvatarNameCacheConnection.disconnect();
std::string display_name = av_name.getDisplayName();
avatarNameResolved(agent_id, display_name);
}
void LLWebRTCVoiceClient::predAvatarNameResolution(const LLWebRTCVoiceClient::sessionStatePtr_t &session, LLUUID id, std::string name)
{
participantStatePtr_t participant(session->findParticipantByID(id));
if (participant)
{
// Found -- fill in the name
participant->mAccountName = name;
// and post a "participants updated" message to listeners later.
session->mParticipantsChanged = true;
}
// Check whether this is a p2p session whose caller name just resolved
if (session->mCallerID == id)
{
// this session's "caller ID" just resolved. Fill in the name.
session->mName = name;
}
}
void LLWebRTCVoiceClient::avatarNameResolved(const LLUUID &id, const std::string &name)
{
sessionState::for_each(boost::bind(predAvatarNameResolution, _1, id, name));
}
std::string LLWebRTCVoiceClient::sipURIFromID(const LLUUID& id) { return id.asString(); }
LLWebRTCSecurity::LLWebRTCSecurity()
{
// This size is an arbitrary choice; WebRTC does not care
// Use a multiple of three so that there is no '=' padding in the base64 (purely an esthetic choice)
#define WebRTC_TOKEN_BYTES 9
U8 random_value[WebRTC_TOKEN_BYTES];
for (int b = 0; b < WebRTC_TOKEN_BYTES; b++)
{
random_value[b] = ll_rand() & 0xff;
}
mConnectorHandle = LLBase64::encode(random_value, WebRTC_TOKEN_BYTES);
for (int b = 0; b < WebRTC_TOKEN_BYTES; b++)
{
random_value[b] = ll_rand() & 0xff;
}
mAccountHandle = LLBase64::encode(random_value, WebRTC_TOKEN_BYTES);
}
LLWebRTCSecurity::~LLWebRTCSecurity()
{
}
|