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
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
|
/*
* Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <algorithm> // max
#include <memory>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/strings/match.h"
#include "api/sequence_checker.h"
#include "api/task_queue/default_task_queue_factory.h"
#include "api/task_queue/task_queue_base.h"
#include "api/test/metrics/global_metrics_logger_and_exporter.h"
#include "api/test/metrics/metric.h"
#include "api/test/simulated_network.h"
#include "api/units/time_delta.h"
#include "api/video/builtin_video_bitrate_allocator_factory.h"
#include "api/video/encoded_image.h"
#include "api/video/video_bitrate_allocation.h"
#include "api/video_codecs/video_encoder.h"
#include "call/call.h"
#include "call/fake_network_pipe.h"
#include "call/rtp_transport_controller_send.h"
#include "call/simulated_network.h"
#include "call/video_send_stream.h"
#include "media/engine/internal_encoder_factory.h"
#include "media/engine/simulcast_encoder_adapter.h"
#include "media/engine/webrtc_video_engine.h"
#include "modules/rtp_rtcp/include/rtp_header_extension_map.h"
#include "modules/rtp_rtcp/source/create_video_rtp_depacketizer.h"
#include "modules/rtp_rtcp/source/rtcp_sender.h"
#include "modules/rtp_rtcp/source/rtp_header_extensions.h"
#include "modules/rtp_rtcp/source/rtp_packet.h"
#include "modules/rtp_rtcp/source/rtp_rtcp_impl2.h"
#include "modules/rtp_rtcp/source/rtp_util.h"
#include "modules/rtp_rtcp/source/video_rtp_depacketizer_vp9.h"
#include "modules/video_coding/codecs/interface/common_constants.h"
#include "modules/video_coding/codecs/vp8/include/vp8.h"
#include "modules/video_coding/codecs/vp9/include/vp9.h"
#include "modules/video_coding/svc/create_scalability_structure.h"
#include "modules/video_coding/svc/scalability_mode_util.h"
#include "modules/video_coding/svc/scalable_video_controller.h"
#include "rtc_base/checks.h"
#include "rtc_base/event.h"
#include "rtc_base/experiments/alr_experiment.h"
#include "rtc_base/logging.h"
#include "rtc_base/platform_thread.h"
#include "rtc_base/rate_limiter.h"
#include "rtc_base/strings/string_builder.h"
#include "rtc_base/synchronization/mutex.h"
#include "rtc_base/task_queue_for_test.h"
#include "rtc_base/time_utils.h"
#include "rtc_base/unique_id_generator.h"
#include "system_wrappers/include/sleep.h"
#include "test/call_test.h"
#include "test/configurable_frame_size_encoder.h"
#include "test/fake_encoder.h"
#include "test/fake_texture_frame.h"
#include "test/frame_forwarder.h"
#include "test/frame_generator_capturer.h"
#include "test/frame_utils.h"
#include "test/gmock.h"
#include "test/gtest.h"
#include "test/null_transport.h"
#include "test/rtcp_packet_parser.h"
#include "test/rtp_rtcp_observer.h"
#include "test/video_encoder_proxy_factory.h"
#include "video/config/encoder_stream_factory.h"
#include "video/send_statistics_proxy.h"
#include "video/transport_adapter.h"
#include "video/video_send_stream.h"
namespace webrtc {
namespace test {
class VideoSendStreamPeer {
public:
explicit VideoSendStreamPeer(webrtc::VideoSendStream* base_class_stream)
: internal_stream_(
static_cast<internal::VideoSendStream*>(base_class_stream)) {}
absl::optional<float> GetPacingFactorOverride() const {
return internal_stream_->GetPacingFactorOverride();
}
private:
internal::VideoSendStream const* const internal_stream_;
};
} // namespace test
namespace {
enum : int { // The first valid value is 1.
kAbsSendTimeExtensionId = 1,
kTimestampOffsetExtensionId,
kTransportSequenceNumberExtensionId,
kVideoContentTypeExtensionId,
kVideoRotationExtensionId,
kVideoTimingExtensionId,
};
// Readability convenience enum for `WaitBitrateChanged()`.
enum class WaitUntil : bool { kZero = false, kNonZero = true };
constexpr int64_t kRtcpIntervalMs = 1000;
enum VideoFormat {
kGeneric,
kVP8,
};
struct Vp9TestParams {
std::string scalability_mode;
uint8_t num_spatial_layers;
uint8_t num_temporal_layers;
InterLayerPredMode inter_layer_pred;
};
using ParameterizationType = std::tuple<Vp9TestParams, bool>;
std::string ParamInfoToStr(
const testing::TestParamInfo<ParameterizationType>& info) {
rtc::StringBuilder sb;
sb << std::get<0>(info.param).scalability_mode << "_"
<< (std::get<1>(info.param) ? "WithIdentifier" : "WithoutIdentifier");
return sb.str();
}
} // namespace
class VideoSendStreamTest : public test::CallTest {
public:
VideoSendStreamTest() {
RegisterRtpExtension(RtpExtension(RtpExtension::kTransportSequenceNumberUri,
kTransportSequenceNumberExtensionId));
}
protected:
void TestNackRetransmission(uint32_t retransmit_ssrc,
uint8_t retransmit_payload_type);
void TestPacketFragmentationSize(VideoFormat format, bool with_fec);
void TestVp9NonFlexMode(const Vp9TestParams& params,
bool use_scalability_mode_identifier);
void TestRequestSourceRotateVideo(bool support_orientation_ext);
void TestTemporalLayers(VideoEncoderFactory* encoder_factory,
const std::string& payload_name,
const std::vector<int>& num_temporal_layers,
const std::vector<ScalabilityMode>& scalability_mode);
};
TEST_F(VideoSendStreamTest, CanStartStartedStream) {
SendTask(task_queue(), [this]() {
CreateSenderCall();
test::NullTransport transport;
CreateSendConfig(1, 0, 0, &transport);
CreateVideoStreams();
GetVideoSendStream()->Start();
GetVideoSendStream()->Start();
DestroyStreams();
DestroyCalls();
});
}
TEST_F(VideoSendStreamTest, CanStopStoppedStream) {
SendTask(task_queue(), [this]() {
CreateSenderCall();
test::NullTransport transport;
CreateSendConfig(1, 0, 0, &transport);
CreateVideoStreams();
GetVideoSendStream()->Stop();
GetVideoSendStream()->Stop();
DestroyStreams();
DestroyCalls();
});
}
TEST_F(VideoSendStreamTest, SupportsCName) {
static std::string kCName = "PjQatC14dGfbVwGPUOA9IH7RlsFDbWl4AhXEiDsBizo=";
class CNameObserver : public test::SendTest {
public:
CNameObserver() : SendTest(kDefaultTimeout) {}
private:
Action OnSendRtcp(const uint8_t* packet, size_t length) override {
test::RtcpPacketParser parser;
EXPECT_TRUE(parser.Parse(packet, length));
if (parser.sdes()->num_packets() > 0) {
EXPECT_EQ(1u, parser.sdes()->chunks().size());
EXPECT_EQ(kCName, parser.sdes()->chunks()[0].cname);
observation_complete_.Set();
}
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->rtp.c_name = kCName;
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for RTCP with CNAME.";
}
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsAbsoluteSendTime) {
class AbsoluteSendTimeObserver : public test::SendTest {
public:
AbsoluteSendTimeObserver() : SendTest(kDefaultTimeout) {
extensions_.Register<AbsoluteSendTime>(kAbsSendTimeExtensionId);
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
uint32_t abs_send_time = 0;
EXPECT_FALSE(rtp_packet.HasExtension<TransmissionOffset>());
EXPECT_TRUE(rtp_packet.GetExtension<AbsoluteSendTime>(&abs_send_time));
if (abs_send_time != 0) {
// Wait for at least one packet with a non-zero send time. The send time
// is a 16-bit value derived from the system clock, and it is valid
// for a packet to have a zero send time. To tell that from an
// unpopulated value we'll wait for a packet with non-zero send time.
observation_complete_.Set();
} else {
RTC_LOG(LS_WARNING)
<< "Got a packet with zero absoluteSendTime, waiting"
" for another packet...";
}
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->rtp.extensions.clear();
send_config->rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTimeUri, kAbsSendTimeExtensionId));
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for single RTP packet.";
}
private:
RtpHeaderExtensionMap extensions_;
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsTransmissionTimeOffset) {
static const int kEncodeDelayMs = 5;
class TransmissionTimeOffsetObserver : public test::SendTest {
public:
TransmissionTimeOffsetObserver()
: SendTest(kDefaultTimeout), encoder_factory_([]() {
return std::make_unique<test::DelayedEncoder>(
Clock::GetRealTimeClock(), kEncodeDelayMs);
}) {
extensions_.Register<TransmissionOffset>(kTimestampOffsetExtensionId);
}
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
int32_t toffset = 0;
EXPECT_TRUE(rtp_packet.GetExtension<TransmissionOffset>(&toffset));
EXPECT_FALSE(rtp_packet.HasExtension<AbsoluteSendTime>());
EXPECT_GT(toffset, 0);
observation_complete_.Set();
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
send_config->rtp.extensions.clear();
send_config->rtp.extensions.push_back(RtpExtension(
RtpExtension::kTimestampOffsetUri, kTimestampOffsetExtensionId));
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for a single RTP packet.";
}
test::FunctionVideoEncoderFactory encoder_factory_;
RtpHeaderExtensionMap extensions_;
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsTransportWideSequenceNumbers) {
static const uint8_t kExtensionId = kTransportSequenceNumberExtensionId;
class TransportWideSequenceNumberObserver : public test::SendTest {
public:
TransportWideSequenceNumberObserver()
: SendTest(kDefaultTimeout), encoder_factory_([]() {
return std::make_unique<test::FakeEncoder>(
Clock::GetRealTimeClock());
}) {
extensions_.Register<TransportSequenceNumber>(kExtensionId);
}
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
EXPECT_TRUE(rtp_packet.HasExtension<TransportSequenceNumber>());
EXPECT_FALSE(rtp_packet.HasExtension<TransmissionOffset>());
EXPECT_FALSE(rtp_packet.HasExtension<AbsoluteSendTime>());
observation_complete_.Set();
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for a single RTP packet.";
}
test::FunctionVideoEncoderFactory encoder_factory_;
RtpHeaderExtensionMap extensions_;
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsVideoRotation) {
class VideoRotationObserver : public test::SendTest {
public:
VideoRotationObserver() : SendTest(kDefaultTimeout) {
extensions_.Register<VideoOrientation>(kVideoRotationExtensionId);
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
// Only the last packet of the frame is required to have the extension.
if (!rtp_packet.Marker())
return SEND_PACKET;
EXPECT_EQ(rtp_packet.GetExtension<VideoOrientation>(), kVideoRotation_90);
observation_complete_.Set();
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->rtp.extensions.clear();
send_config->rtp.extensions.push_back(RtpExtension(
RtpExtension::kVideoRotationUri, kVideoRotationExtensionId));
}
void OnFrameGeneratorCapturerCreated(
test::FrameGeneratorCapturer* frame_generator_capturer) override {
frame_generator_capturer->SetFakeRotation(kVideoRotation_90);
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for single RTP packet.";
}
private:
RtpHeaderExtensionMap extensions_;
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsVideoContentType) {
class VideoContentTypeObserver : public test::SendTest {
public:
VideoContentTypeObserver()
: SendTest(kDefaultTimeout), first_frame_sent_(false) {
extensions_.Register<VideoContentTypeExtension>(
kVideoContentTypeExtensionId);
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
// Only the last packet of the key-frame must have extension.
if (!rtp_packet.Marker() || first_frame_sent_)
return SEND_PACKET;
// First marker bit seen means that the first frame is sent.
first_frame_sent_ = true;
VideoContentType type;
EXPECT_TRUE(rtp_packet.GetExtension<VideoContentTypeExtension>(&type));
EXPECT_TRUE(videocontenttypehelpers::IsScreenshare(type));
observation_complete_.Set();
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->rtp.extensions.clear();
send_config->rtp.extensions.push_back(RtpExtension(
RtpExtension::kVideoContentTypeUri, kVideoContentTypeExtensionId));
encoder_config->content_type = VideoEncoderConfig::ContentType::kScreen;
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for single RTP packet.";
}
private:
bool first_frame_sent_;
RtpHeaderExtensionMap extensions_;
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsVideoTimingFrames) {
class VideoTimingObserver : public test::SendTest {
public:
VideoTimingObserver()
: SendTest(kDefaultTimeout), first_frame_sent_(false) {
extensions_.Register<VideoTimingExtension>(kVideoTimingExtensionId);
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
// Only the last packet of the frame must have extension.
// Also don't check packets of the second frame if they happen to get
// through before the test terminates.
if (!rtp_packet.Marker() || first_frame_sent_)
return SEND_PACKET;
EXPECT_TRUE(rtp_packet.HasExtension<VideoTimingExtension>());
observation_complete_.Set();
first_frame_sent_ = true;
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->rtp.extensions.clear();
send_config->rtp.extensions.push_back(
RtpExtension(RtpExtension::kVideoTimingUri, kVideoTimingExtensionId));
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for timing frames.";
}
private:
RtpHeaderExtensionMap extensions_;
bool first_frame_sent_;
} test;
RunBaseTest(&test);
}
class FakeReceiveStatistics : public ReceiveStatisticsProvider {
public:
FakeReceiveStatistics(uint32_t send_ssrc,
uint32_t last_sequence_number,
uint32_t cumulative_lost,
uint8_t fraction_lost) {
stat_.SetMediaSsrc(send_ssrc);
stat_.SetExtHighestSeqNum(last_sequence_number);
stat_.SetCumulativeLost(cumulative_lost);
stat_.SetFractionLost(fraction_lost);
}
std::vector<rtcp::ReportBlock> RtcpReportBlocks(size_t max_blocks) override {
EXPECT_GE(max_blocks, 1u);
return {stat_};
}
private:
rtcp::ReportBlock stat_;
};
class UlpfecObserver : public test::EndToEndTest {
public:
// Some of the test cases are expected to time out.
// Use a shorter timeout window than the default one for those.
static constexpr TimeDelta kReducedTimeout = TimeDelta::Seconds(10);
UlpfecObserver(bool header_extensions_enabled,
bool use_nack,
bool expect_red,
bool expect_ulpfec,
const std::string& codec,
VideoEncoderFactory* encoder_factory)
: EndToEndTest(expect_ulpfec ? VideoSendStreamTest::kDefaultTimeout
: kReducedTimeout),
encoder_factory_(encoder_factory),
payload_name_(codec),
use_nack_(use_nack),
expect_red_(expect_red),
expect_ulpfec_(expect_ulpfec),
sent_media_(false),
sent_ulpfec_(false),
header_extensions_enabled_(header_extensions_enabled) {
extensions_.Register<AbsoluteSendTime>(kAbsSendTimeExtensionId);
extensions_.Register<TransportSequenceNumber>(
kTransportSequenceNumberExtensionId);
}
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
int encapsulated_payload_type = -1;
if (rtp_packet.PayloadType() == VideoSendStreamTest::kRedPayloadType) {
EXPECT_TRUE(expect_red_);
encapsulated_payload_type = rtp_packet.payload()[0];
if (encapsulated_payload_type !=
VideoSendStreamTest::kFakeVideoSendPayloadType) {
EXPECT_EQ(VideoSendStreamTest::kUlpfecPayloadType,
encapsulated_payload_type);
}
} else {
EXPECT_EQ(VideoSendStreamTest::kFakeVideoSendPayloadType,
rtp_packet.PayloadType());
if (rtp_packet.payload_size() > 0) {
// Not padding-only, media received outside of RED.
EXPECT_FALSE(expect_red_);
sent_media_ = true;
}
}
if (header_extensions_enabled_) {
uint32_t abs_send_time;
EXPECT_TRUE(rtp_packet.GetExtension<AbsoluteSendTime>(&abs_send_time));
uint16_t transport_seq_num;
EXPECT_TRUE(
rtp_packet.GetExtension<TransportSequenceNumber>(&transport_seq_num));
if (!first_packet_) {
uint32_t kHalf24BitsSpace = 0xFFFFFF / 2;
if (abs_send_time <= kHalf24BitsSpace &&
prev_abs_send_time_ > kHalf24BitsSpace) {
// 24 bits wrap.
EXPECT_GT(prev_abs_send_time_, abs_send_time);
} else {
EXPECT_GE(abs_send_time, prev_abs_send_time_);
}
uint16_t seq_num_diff = transport_seq_num - prev_transport_seq_num_;
EXPECT_EQ(1, seq_num_diff);
}
first_packet_ = false;
prev_abs_send_time_ = abs_send_time;
prev_transport_seq_num_ = transport_seq_num;
}
if (encapsulated_payload_type != -1) {
if (encapsulated_payload_type ==
VideoSendStreamTest::kUlpfecPayloadType) {
EXPECT_TRUE(expect_ulpfec_);
sent_ulpfec_ = true;
} else {
sent_media_ = true;
}
}
if (sent_media_ && sent_ulpfec_) {
observation_complete_.Set();
}
return SEND_PACKET;
}
BuiltInNetworkBehaviorConfig GetSendTransportConfig() const override {
// At low RTT (< kLowRttNackMs) -> NACK only, no FEC.
// Configure some network delay.
const int kNetworkDelayMs = 100;
BuiltInNetworkBehaviorConfig config;
config.loss_percent = 5;
config.queue_delay_ms = kNetworkDelayMs;
return config;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
if (use_nack_) {
send_config->rtp.nack.rtp_history_ms =
(*receive_configs)[0].rtp.nack.rtp_history_ms =
VideoSendStreamTest::kNackRtpHistoryMs;
}
send_config->encoder_settings.encoder_factory = encoder_factory_;
send_config->rtp.payload_name = payload_name_;
send_config->rtp.ulpfec.red_payload_type =
VideoSendStreamTest::kRedPayloadType;
send_config->rtp.ulpfec.ulpfec_payload_type =
VideoSendStreamTest::kUlpfecPayloadType;
if (!header_extensions_enabled_) {
send_config->rtp.extensions.clear();
} else {
send_config->rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTimeUri, kAbsSendTimeExtensionId));
}
(*receive_configs)[0].rtp.extensions = send_config->rtp.extensions;
encoder_config->codec_type = PayloadStringToCodecType(payload_name_);
(*receive_configs)[0].rtp.red_payload_type =
send_config->rtp.ulpfec.red_payload_type;
(*receive_configs)[0].rtp.ulpfec_payload_type =
send_config->rtp.ulpfec.ulpfec_payload_type;
}
void PerformTest() override {
EXPECT_EQ(expect_ulpfec_, Wait())
<< "Timed out waiting for ULPFEC and/or media packets.";
}
VideoEncoderFactory* encoder_factory_;
RtpHeaderExtensionMap extensions_;
const std::string payload_name_;
const bool use_nack_;
const bool expect_red_;
const bool expect_ulpfec_;
bool sent_media_;
bool sent_ulpfec_;
const bool header_extensions_enabled_;
bool first_packet_ = true;
uint32_t prev_abs_send_time_ = 0;
uint16_t prev_transport_seq_num_ = 0;
};
TEST_F(VideoSendStreamTest, SupportsUlpfecWithExtensions) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
UlpfecObserver test(true, false, true, true, "VP8", &encoder_factory);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsUlpfecWithoutExtensions) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
UlpfecObserver test(false, false, true, true, "VP8", &encoder_factory);
RunBaseTest(&test);
}
class VideoSendStreamWithoutUlpfecTest : public test::CallTest {
protected:
VideoSendStreamWithoutUlpfecTest()
: field_trial_(field_trials_, "WebRTC-DisableUlpFecExperiment/Enabled/") {
}
test::ScopedKeyValueConfig field_trial_;
};
TEST_F(VideoSendStreamWithoutUlpfecTest, NoUlpfecIfDisabledThroughFieldTrial) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
UlpfecObserver test(false, false, false, false, "VP8", &encoder_factory);
RunBaseTest(&test);
}
// The FEC scheme used is not efficient for H264, so we should not use RED/FEC
// since we'll still have to re-request FEC packets, effectively wasting
// bandwidth since the receiver has to wait for FEC retransmissions to determine
// that the received state is actually decodable.
TEST_F(VideoSendStreamTest, DoesNotUtilizeUlpfecForH264WithNackEnabled) {
test::FunctionVideoEncoderFactory encoder_factory([]() {
return std::make_unique<test::FakeH264Encoder>(Clock::GetRealTimeClock());
});
UlpfecObserver test(false, true, false, false, "H264", &encoder_factory);
RunBaseTest(&test);
}
// Without retransmissions FEC for H264 is fine.
TEST_F(VideoSendStreamTest, DoesUtilizeUlpfecForH264WithoutNackEnabled) {
test::FunctionVideoEncoderFactory encoder_factory([]() {
return std::make_unique<test::FakeH264Encoder>(Clock::GetRealTimeClock());
});
UlpfecObserver test(false, false, true, true, "H264", &encoder_factory);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, DoesUtilizeUlpfecForVp8WithNackEnabled) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
UlpfecObserver test(false, true, true, true, "VP8", &encoder_factory);
RunBaseTest(&test);
}
#if defined(RTC_ENABLE_VP9)
TEST_F(VideoSendStreamTest, DoesUtilizeUlpfecForVp9WithNackEnabled) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP9Encoder::Create(); });
UlpfecObserver test(false, true, true, true, "VP9", &encoder_factory);
RunBaseTest(&test);
}
#endif // defined(RTC_ENABLE_VP9)
TEST_F(VideoSendStreamTest, SupportsUlpfecWithMultithreadedH264) {
std::unique_ptr<TaskQueueFactory> task_queue_factory =
CreateDefaultTaskQueueFactory();
test::FunctionVideoEncoderFactory encoder_factory([&]() {
return std::make_unique<test::MultithreadedFakeH264Encoder>(
Clock::GetRealTimeClock(), task_queue_factory.get());
});
UlpfecObserver test(false, false, true, true, "H264", &encoder_factory);
RunBaseTest(&test);
}
// TODO(brandtr): Move these FlexFEC tests when we have created
// FlexfecSendStream.
class FlexfecObserver : public test::EndToEndTest {
public:
FlexfecObserver(bool header_extensions_enabled,
bool use_nack,
const std::string& codec,
VideoEncoderFactory* encoder_factory,
size_t num_video_streams)
: EndToEndTest(VideoSendStreamTest::kDefaultTimeout),
encoder_factory_(encoder_factory),
payload_name_(codec),
use_nack_(use_nack),
sent_media_(false),
sent_flexfec_(false),
header_extensions_enabled_(header_extensions_enabled),
num_video_streams_(num_video_streams) {
extensions_.Register<AbsoluteSendTime>(kAbsSendTimeExtensionId);
extensions_.Register<TransmissionOffset>(kTimestampOffsetExtensionId);
extensions_.Register<TransportSequenceNumber>(
kTransportSequenceNumberExtensionId);
}
size_t GetNumFlexfecStreams() const override { return 1; }
size_t GetNumVideoStreams() const override { return num_video_streams_; }
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet(&extensions_);
EXPECT_TRUE(rtp_packet.Parse(packet, length));
if (rtp_packet.PayloadType() == VideoSendStreamTest::kFlexfecPayloadType) {
EXPECT_EQ(VideoSendStreamTest::kFlexfecSendSsrc, rtp_packet.Ssrc());
sent_flexfec_ = true;
} else {
EXPECT_EQ(VideoSendStreamTest::kFakeVideoSendPayloadType,
rtp_packet.PayloadType());
EXPECT_THAT(::testing::make_tuple(VideoSendStreamTest::kVideoSendSsrcs,
num_video_streams_),
::testing::Contains(rtp_packet.Ssrc()));
sent_media_ = true;
}
if (header_extensions_enabled_) {
EXPECT_TRUE(rtp_packet.HasExtension<AbsoluteSendTime>());
EXPECT_TRUE(rtp_packet.HasExtension<TransmissionOffset>());
EXPECT_TRUE(rtp_packet.HasExtension<TransportSequenceNumber>());
}
if (sent_media_ && sent_flexfec_) {
observation_complete_.Set();
}
return SEND_PACKET;
}
BuiltInNetworkBehaviorConfig GetSendTransportConfig() const {
// At low RTT (< kLowRttNackMs) -> NACK only, no FEC.
// Therefore we need some network delay.
const int kNetworkDelayMs = 100;
BuiltInNetworkBehaviorConfig config;
config.loss_percent = 5;
config.queue_delay_ms = kNetworkDelayMs;
return config;
}
BuiltInNetworkBehaviorConfig GetReceiveTransportConfig() const {
// We need the RTT to be >200 ms to send FEC and the network delay for the
// send transport is 100 ms, so add 100 ms (but no loss) on the return link.
BuiltInNetworkBehaviorConfig config;
config.loss_percent = 0;
config.queue_delay_ms = 100;
return config;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
if (use_nack_) {
send_config->rtp.nack.rtp_history_ms =
(*receive_configs)[0].rtp.nack.rtp_history_ms =
VideoSendStreamTest::kNackRtpHistoryMs;
}
send_config->encoder_settings.encoder_factory = encoder_factory_;
send_config->rtp.payload_name = payload_name_;
if (header_extensions_enabled_) {
send_config->rtp.extensions.push_back(
RtpExtension(RtpExtension::kAbsSendTimeUri, kAbsSendTimeExtensionId));
send_config->rtp.extensions.push_back(RtpExtension(
RtpExtension::kTimestampOffsetUri, kTimestampOffsetExtensionId));
} else {
send_config->rtp.extensions.clear();
}
(*receive_configs)[0].rtp.extensions = send_config->rtp.extensions;
encoder_config->codec_type = PayloadStringToCodecType(payload_name_);
}
void PerformTest() override {
EXPECT_TRUE(Wait())
<< "Timed out waiting for FlexFEC and/or media packets.";
}
VideoEncoderFactory* encoder_factory_;
RtpHeaderExtensionMap extensions_;
const std::string payload_name_;
const bool use_nack_;
bool sent_media_;
bool sent_flexfec_;
const bool header_extensions_enabled_;
const size_t num_video_streams_;
};
TEST_F(VideoSendStreamTest, SupportsFlexfecVp8) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
FlexfecObserver test(false, false, "VP8", &encoder_factory, 1);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsFlexfecSimulcastVp8) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
FlexfecObserver test(false, false, "VP8", &encoder_factory, 2);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsFlexfecWithNackVp8) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
FlexfecObserver test(false, true, "VP8", &encoder_factory, 1);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsFlexfecWithRtpExtensionsVp8) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
FlexfecObserver test(true, false, "VP8", &encoder_factory, 1);
RunBaseTest(&test);
}
#if defined(RTC_ENABLE_VP9)
TEST_F(VideoSendStreamTest, SupportsFlexfecVp9) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP9Encoder::Create(); });
FlexfecObserver test(false, false, "VP9", &encoder_factory, 1);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsFlexfecWithNackVp9) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP9Encoder::Create(); });
FlexfecObserver test(false, true, "VP9", &encoder_factory, 1);
RunBaseTest(&test);
}
#endif // defined(RTC_ENABLE_VP9)
TEST_F(VideoSendStreamTest, SupportsFlexfecH264) {
test::FunctionVideoEncoderFactory encoder_factory([]() {
return std::make_unique<test::FakeH264Encoder>(Clock::GetRealTimeClock());
});
FlexfecObserver test(false, false, "H264", &encoder_factory, 1);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsFlexfecWithNackH264) {
test::FunctionVideoEncoderFactory encoder_factory([]() {
return std::make_unique<test::FakeH264Encoder>(Clock::GetRealTimeClock());
});
FlexfecObserver test(false, true, "H264", &encoder_factory, 1);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, SupportsFlexfecWithMultithreadedH264) {
std::unique_ptr<TaskQueueFactory> task_queue_factory =
CreateDefaultTaskQueueFactory();
test::FunctionVideoEncoderFactory encoder_factory([&]() {
return std::make_unique<test::MultithreadedFakeH264Encoder>(
Clock::GetRealTimeClock(), task_queue_factory.get());
});
FlexfecObserver test(false, false, "H264", &encoder_factory, 1);
RunBaseTest(&test);
}
void VideoSendStreamTest::TestNackRetransmission(
uint32_t retransmit_ssrc,
uint8_t retransmit_payload_type) {
class NackObserver : public test::SendTest {
public:
explicit NackObserver(uint32_t retransmit_ssrc,
uint8_t retransmit_payload_type)
: SendTest(kDefaultTimeout),
send_count_(0),
retransmit_count_(0),
retransmit_ssrc_(retransmit_ssrc),
retransmit_payload_type_(retransmit_payload_type) {}
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet;
EXPECT_TRUE(rtp_packet.Parse(packet, length));
// NACK packets two times at some arbitrary points.
const int kNackedPacketsAtOnceCount = 3;
const int kRetransmitTarget = kNackedPacketsAtOnceCount * 2;
// Skip padding packets because they will never be retransmitted.
if (rtp_packet.payload_size() == 0) {
return SEND_PACKET;
}
++send_count_;
// NACK packets at arbitrary points.
if (send_count_ % 25 == 0) {
RTCPSender::Configuration config;
config.clock = Clock::GetRealTimeClock();
config.outgoing_transport = transport_adapter_.get();
config.rtcp_report_interval = TimeDelta::Millis(kRtcpIntervalMs);
config.local_media_ssrc = kReceiverLocalVideoSsrc;
RTCPSender rtcp_sender(config);
rtcp_sender.SetRTCPStatus(RtcpMode::kReducedSize);
rtcp_sender.SetRemoteSSRC(kVideoSendSsrcs[0]);
RTCPSender::FeedbackState feedback_state;
uint16_t nack_sequence_numbers[kNackedPacketsAtOnceCount];
int nack_count = 0;
for (uint16_t sequence_number :
sequence_numbers_pending_retransmission_) {
if (nack_count < kNackedPacketsAtOnceCount) {
nack_sequence_numbers[nack_count++] = sequence_number;
} else {
break;
}
}
EXPECT_EQ(0, rtcp_sender.SendRTCP(feedback_state, kRtcpNack, nack_count,
nack_sequence_numbers));
}
uint16_t sequence_number = rtp_packet.SequenceNumber();
if (rtp_packet.Ssrc() == retransmit_ssrc_ &&
retransmit_ssrc_ != kVideoSendSsrcs[0]) {
// Not kVideoSendSsrcs[0], assume correct RTX packet. Extract sequence
// number.
const uint8_t* rtx_header = rtp_packet.payload().data();
sequence_number = (rtx_header[0] << 8) + rtx_header[1];
}
auto it = sequence_numbers_pending_retransmission_.find(sequence_number);
if (it == sequence_numbers_pending_retransmission_.end()) {
// Not currently pending retransmission. Add it to retransmission queue
// if media and limit not reached.
if (rtp_packet.Ssrc() == kVideoSendSsrcs[0] &&
rtp_packet.payload_size() > 0 &&
retransmit_count_ +
sequence_numbers_pending_retransmission_.size() <
kRetransmitTarget) {
sequence_numbers_pending_retransmission_.insert(sequence_number);
return DROP_PACKET;
}
} else {
// Packet is a retransmission, remove it from queue and check if done.
sequence_numbers_pending_retransmission_.erase(it);
if (++retransmit_count_ == kRetransmitTarget) {
EXPECT_EQ(retransmit_ssrc_, rtp_packet.Ssrc());
EXPECT_EQ(retransmit_payload_type_, rtp_packet.PayloadType());
observation_complete_.Set();
}
}
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
transport_adapter_.reset(
new internal::TransportAdapter(send_config->send_transport));
transport_adapter_->Enable();
send_config->rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
send_config->rtp.rtx.payload_type = retransmit_payload_type_;
if (retransmit_ssrc_ != kVideoSendSsrcs[0])
send_config->rtp.rtx.ssrcs.push_back(retransmit_ssrc_);
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for NACK retransmission.";
}
std::unique_ptr<internal::TransportAdapter> transport_adapter_;
int send_count_;
int retransmit_count_;
const uint32_t retransmit_ssrc_;
const uint8_t retransmit_payload_type_;
std::set<uint16_t> sequence_numbers_pending_retransmission_;
} test(retransmit_ssrc, retransmit_payload_type);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, RetransmitsNack) {
// Normal NACKs should use the send SSRC.
TestNackRetransmission(kVideoSendSsrcs[0], kFakeVideoSendPayloadType);
}
TEST_F(VideoSendStreamTest, RetransmitsNackOverRtx) {
// NACKs over RTX should use a separate SSRC.
TestNackRetransmission(kSendRtxSsrcs[0], kSendRtxPayloadType);
}
void VideoSendStreamTest::TestPacketFragmentationSize(VideoFormat format,
bool with_fec) {
// Use a fake encoder to output a frame of every size in the range [90, 290],
// for each size making sure that the exact number of payload bytes received
// is correct and that packets are fragmented to respect max packet size.
static const size_t kMaxPacketSize = 128;
static const size_t start = 90;
static const size_t stop = 290;
// Observer that verifies that the expected number of packets and bytes
// arrive for each frame size, from start_size to stop_size.
class FrameFragmentationTest : public test::SendTest {
public:
FrameFragmentationTest(size_t max_packet_size,
size_t start_size,
size_t stop_size,
bool test_generic_packetization,
bool use_fec)
: SendTest(kLongTimeout),
encoder_(stop),
encoder_factory_(&encoder_),
max_packet_size_(max_packet_size),
stop_size_(stop_size),
test_generic_packetization_(test_generic_packetization),
use_fec_(use_fec),
packet_count_(0),
packets_lost_(0),
last_packet_count_(0),
last_packets_lost_(0),
accumulated_size_(0),
accumulated_payload_(0),
fec_packet_received_(false),
current_size_rtp_(start_size),
current_size_frame_(static_cast<int>(start_size)) {
// Fragmentation required, this test doesn't make sense without it.
encoder_.SetFrameSize(start_size);
RTC_DCHECK_GT(stop_size, max_packet_size);
if (!test_generic_packetization_)
encoder_.SetCodecType(kVideoCodecVP8);
}
private:
Action OnSendRtp(const uint8_t* packet, size_t size) override {
size_t length = size;
RtpPacket rtp_packet;
EXPECT_TRUE(rtp_packet.Parse(packet, length));
EXPECT_LE(length, max_packet_size_);
if (use_fec_ && rtp_packet.payload_size() > 0) {
uint8_t payload_type = rtp_packet.payload()[0];
bool is_fec = rtp_packet.PayloadType() == kRedPayloadType &&
payload_type == kUlpfecPayloadType;
if (is_fec) {
fec_packet_received_ = true;
return SEND_PACKET;
}
}
accumulated_size_ += length;
if (use_fec_)
TriggerLossReport(rtp_packet);
if (test_generic_packetization_) {
size_t overhead = rtp_packet.headers_size() + rtp_packet.padding_size();
// Only remove payload header and RED header if the packet actually
// contains payload.
if (length > overhead) {
overhead += (1 /* Generic header */);
if (use_fec_)
overhead += 1; // RED for FEC header.
}
EXPECT_GE(length, overhead);
accumulated_payload_ += length - overhead;
}
// Marker bit set indicates last packet of a frame.
if (rtp_packet.Marker()) {
if (use_fec_ && accumulated_payload_ == current_size_rtp_ - 1) {
// With FEC enabled, frame size is incremented asynchronously, so
// "old" frames one byte too small may arrive. Accept, but don't
// increase expected frame size.
accumulated_size_ = 0;
accumulated_payload_ = 0;
return SEND_PACKET;
}
EXPECT_GE(accumulated_size_, current_size_rtp_);
if (test_generic_packetization_) {
EXPECT_EQ(current_size_rtp_, accumulated_payload_);
}
// Last packet of frame; reset counters.
accumulated_size_ = 0;
accumulated_payload_ = 0;
if (current_size_rtp_ == stop_size_) {
// Done! (Don't increase size again, might arrive more @ stop_size).
observation_complete_.Set();
} else {
// Increase next expected frame size. If testing with FEC, make sure
// a FEC packet has been received for this frame size before
// proceeding, to make sure that redundancy packets don't exceed
// size limit.
if (!use_fec_) {
++current_size_rtp_;
} else if (fec_packet_received_) {
fec_packet_received_ = false;
++current_size_rtp_;
MutexLock lock(&mutex_);
++current_size_frame_;
}
}
}
return SEND_PACKET;
}
void TriggerLossReport(const RtpPacket& rtp_packet) {
// Send lossy receive reports to trigger FEC enabling.
const int kLossPercent = 5;
if (++packet_count_ % (100 / kLossPercent) == 0) {
packets_lost_++;
int loss_delta = packets_lost_ - last_packets_lost_;
int packets_delta = packet_count_ - last_packet_count_;
last_packet_count_ = packet_count_;
last_packets_lost_ = packets_lost_;
uint8_t loss_ratio =
static_cast<uint8_t>(loss_delta * 255 / packets_delta);
FakeReceiveStatistics lossy_receive_stats(
kVideoSendSsrcs[0], rtp_packet.SequenceNumber(),
packets_lost_, // Cumulative lost.
loss_ratio); // Loss percent.
RTCPSender::Configuration config;
config.clock = Clock::GetRealTimeClock();
config.receive_statistics = &lossy_receive_stats;
config.outgoing_transport = transport_adapter_.get();
config.rtcp_report_interval = TimeDelta::Millis(kRtcpIntervalMs);
config.local_media_ssrc = kVideoSendSsrcs[0];
RTCPSender rtcp_sender(config);
rtcp_sender.SetRTCPStatus(RtcpMode::kReducedSize);
rtcp_sender.SetRemoteSSRC(kVideoSendSsrcs[0]);
RTCPSender::FeedbackState feedback_state;
EXPECT_EQ(0, rtcp_sender.SendRTCP(feedback_state, kRtcpRr));
}
}
void UpdateConfiguration() {
MutexLock lock(&mutex_);
// Increase frame size for next encoded frame, in the context of the
// encoder thread.
if (!use_fec_ && current_size_frame_ < static_cast<int32_t>(stop_size_)) {
++current_size_frame_;
}
encoder_.SetFrameSize(static_cast<size_t>(current_size_frame_));
}
void ModifySenderBitrateConfig(
BitrateConstraints* bitrate_config) override {
const int kMinBitrateBps = 300000;
bitrate_config->min_bitrate_bps = kMinBitrateBps;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
transport_adapter_.reset(
new internal::TransportAdapter(send_config->send_transport));
transport_adapter_->Enable();
if (use_fec_) {
send_config->rtp.ulpfec.red_payload_type = kRedPayloadType;
send_config->rtp.ulpfec.ulpfec_payload_type = kUlpfecPayloadType;
}
if (!test_generic_packetization_)
send_config->rtp.payload_name = "VP8";
send_config->encoder_settings.encoder_factory = &encoder_factory_;
send_config->rtp.max_packet_size = kMaxPacketSize;
encoder_.RegisterPostEncodeCallback([this]() { UpdateConfiguration(); });
// Make sure there is at least one extension header, to make the RTP
// header larger than the base length of 12 bytes.
EXPECT_FALSE(send_config->rtp.extensions.empty());
// Setup screen content disables frame dropping which makes this easier.
EXPECT_EQ(1u, encoder_config->simulcast_layers.size());
encoder_config->simulcast_layers[0].num_temporal_layers = 2;
encoder_config->content_type = VideoEncoderConfig::ContentType::kScreen;
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while observing incoming RTP packets.";
}
std::unique_ptr<internal::TransportAdapter> transport_adapter_;
test::ConfigurableFrameSizeEncoder encoder_;
test::VideoEncoderProxyFactory encoder_factory_;
const size_t max_packet_size_;
const size_t stop_size_;
const bool test_generic_packetization_;
const bool use_fec_;
uint32_t packet_count_;
uint32_t packets_lost_;
uint32_t last_packet_count_;
uint32_t last_packets_lost_;
size_t accumulated_size_;
size_t accumulated_payload_;
bool fec_packet_received_;
size_t current_size_rtp_;
Mutex mutex_;
int current_size_frame_ RTC_GUARDED_BY(mutex_);
};
// Don't auto increment if FEC is used; continue sending frame size until
// a FEC packet has been received.
FrameFragmentationTest test(kMaxPacketSize, start, stop, format == kGeneric,
with_fec);
RunBaseTest(&test);
}
// TODO(sprang): Is there any way of speeding up these tests?
TEST_F(VideoSendStreamTest, FragmentsGenericAccordingToMaxPacketSize) {
TestPacketFragmentationSize(kGeneric, false);
}
TEST_F(VideoSendStreamTest, FragmentsGenericAccordingToMaxPacketSizeWithFec) {
TestPacketFragmentationSize(kGeneric, true);
}
TEST_F(VideoSendStreamTest, FragmentsVp8AccordingToMaxPacketSize) {
TestPacketFragmentationSize(kVP8, false);
}
TEST_F(VideoSendStreamTest, FragmentsVp8AccordingToMaxPacketSizeWithFec) {
TestPacketFragmentationSize(kVP8, true);
}
// This test that padding stops being send after a while if the Camera stops
// producing video frames and that padding resumes if the camera restarts.
TEST_F(VideoSendStreamTest, NoPaddingWhenVideoIsMuted) {
class NoPaddingWhenVideoIsMuted : public test::SendTest {
public:
NoPaddingWhenVideoIsMuted()
: SendTest(kDefaultTimeout),
clock_(Clock::GetRealTimeClock()),
capturer_(nullptr) {}
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
MutexLock lock(&mutex_);
last_packet_time_ms_ = clock_->TimeInMilliseconds();
RtpPacket rtp_packet;
rtp_packet.Parse(packet, length);
const bool only_padding = rtp_packet.payload_size() == 0;
if (test_state_ == kBeforeStopCapture) {
// Packets are flowing, stop camera.
capturer_->Stop();
test_state_ = kWaitingForPadding;
} else if (test_state_ == kWaitingForPadding && only_padding) {
// We're still getting padding, after stopping camera.
test_state_ = kWaitingForNoPackets;
} else if (test_state_ == kWaitingForMediaAfterCameraRestart &&
!only_padding) {
// Media packets are flowing again, stop camera a second time.
capturer_->Stop();
test_state_ = kWaitingForPaddingAfterCameraStopsAgain;
} else if (test_state_ == kWaitingForPaddingAfterCameraStopsAgain &&
only_padding) {
// Padding is still flowing, test ok.
observation_complete_.Set();
}
return SEND_PACKET;
}
Action OnSendRtcp(const uint8_t* packet, size_t length) override {
MutexLock lock(&mutex_);
const int kNoPacketsThresholdMs = 2000;
if (test_state_ == kWaitingForNoPackets &&
(last_packet_time_ms_ &&
clock_->TimeInMilliseconds() - last_packet_time_ms_.value() >
kNoPacketsThresholdMs)) {
// No packets seen for `kNoPacketsThresholdMs`, restart camera.
capturer_->Start();
test_state_ = kWaitingForMediaAfterCameraRestart;
}
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
// Make sure padding is sent if encoder is not producing media.
encoder_config->min_transmit_bitrate_bps = 50000;
}
void OnFrameGeneratorCapturerCreated(
test::FrameGeneratorCapturer* frame_generator_capturer) override {
MutexLock lock(&mutex_);
capturer_ = frame_generator_capturer;
}
void PerformTest() override {
EXPECT_TRUE(Wait())
<< "Timed out while waiting for RTP packets to stop being sent.";
}
enum TestState {
kBeforeStopCapture,
kWaitingForPadding,
kWaitingForNoPackets,
kWaitingForMediaAfterCameraRestart,
kWaitingForPaddingAfterCameraStopsAgain
};
TestState test_state_ = kBeforeStopCapture;
Clock* const clock_;
Mutex mutex_;
absl::optional<int64_t> last_packet_time_ms_ RTC_GUARDED_BY(mutex_);
test::FrameGeneratorCapturer* capturer_ RTC_GUARDED_BY(mutex_);
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, PaddingIsPrimarilyRetransmissions) {
const int kCapacityKbps = 10000; // 10 Mbps
class PaddingIsPrimarilyRetransmissions : public test::EndToEndTest {
public:
PaddingIsPrimarilyRetransmissions()
: EndToEndTest(kDefaultTimeout),
clock_(Clock::GetRealTimeClock()),
padding_length_(0),
total_length_(0),
call_(nullptr) {}
private:
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
call_ = sender_call;
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
MutexLock lock(&mutex_);
RtpPacket rtp_packet;
rtp_packet.Parse(packet, length);
padding_length_ += rtp_packet.padding_size();
total_length_ += length;
return SEND_PACKET;
}
BuiltInNetworkBehaviorConfig GetSendTransportConfig() const override {
const int kNetworkDelayMs = 50;
BuiltInNetworkBehaviorConfig config;
config.loss_percent = 10;
config.link_capacity_kbps = kCapacityKbps;
config.queue_delay_ms = kNetworkDelayMs;
return config;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
// Turn on RTX.
send_config->rtp.rtx.payload_type = kFakeVideoSendPayloadType;
send_config->rtp.rtx.ssrcs.push_back(kSendRtxSsrcs[0]);
}
void PerformTest() override {
// TODO(isheriff): Some platforms do not ramp up as expected to full
// capacity due to packet scheduling delays. Fix that before getting
// rid of this.
SleepMs(5000);
{
MutexLock lock(&mutex_);
// Expect padding to be a small percentage of total bytes sent.
EXPECT_LT(padding_length_, .1 * total_length_);
}
}
Mutex mutex_;
Clock* const clock_;
size_t padding_length_ RTC_GUARDED_BY(mutex_);
size_t total_length_ RTC_GUARDED_BY(mutex_);
Call* call_;
} test;
RunBaseTest(&test);
}
// This test first observes "high" bitrate use at which point it sends a REMB to
// indicate that it should be lowered significantly. The test then observes that
// the bitrate observed is sinking well below the min-transmit-bitrate threshold
// to verify that the min-transmit bitrate respects incoming REMB.
//
// Note that the test starts at "high" bitrate and does not ramp up to "higher"
// bitrate since no receiver block or remb is sent in the initial phase.
TEST_F(VideoSendStreamTest, MinTransmitBitrateRespectsRemb) {
static const int kMinTransmitBitrateBps = 400000;
static const int kHighBitrateBps = 150000;
static const int kRembBitrateBps = 80000;
static const int kRembRespectedBitrateBps = 100000;
class BitrateObserver : public test::SendTest {
public:
explicit BitrateObserver(TaskQueueBase* task_queue)
: SendTest(kDefaultTimeout),
task_queue_(task_queue),
retranmission_rate_limiter_(Clock::GetRealTimeClock(), 1000),
stream_(nullptr),
bitrate_capped_(false),
task_safety_flag_(PendingTaskSafetyFlag::CreateDetached()) {}
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
if (IsRtcpPacket(rtc::MakeArrayView(packet, length)))
return DROP_PACKET;
RtpPacket rtp_packet;
RTC_CHECK(rtp_packet.Parse(packet, length));
const uint32_t ssrc = rtp_packet.Ssrc();
RTC_DCHECK(stream_);
task_queue_->PostTask(SafeTask(task_safety_flag_, [this, ssrc]() {
VideoSendStream::Stats stats = stream_->GetStats();
if (!stats.substreams.empty()) {
EXPECT_EQ(1u, stats.substreams.size());
int total_bitrate_bps =
stats.substreams.begin()->second.total_bitrate_bps;
test::GetGlobalMetricsLogger()->LogSingleValueMetric(
"bitrate_stats_min_transmit_bitrate_low_remb", "bitrate_bps",
static_cast<size_t>(total_bitrate_bps) / 1000.0,
test::Unit::kKilobitsPerSecond,
test::ImprovementDirection::kNeitherIsBetter);
if (total_bitrate_bps > kHighBitrateBps) {
rtp_rtcp_->SetRemb(kRembBitrateBps, {ssrc});
bitrate_capped_ = true;
} else if (bitrate_capped_ &&
total_bitrate_bps < kRembRespectedBitrateBps) {
observation_complete_.Set();
}
}
}));
// Packets don't have to be delivered since the test is the receiver.
return DROP_PACKET;
}
void OnVideoStreamsCreated(VideoSendStream* send_stream,
const std::vector<VideoReceiveStreamInterface*>&
receive_streams) override {
stream_ = send_stream;
RtpRtcpInterface::Configuration config;
config.clock = Clock::GetRealTimeClock();
config.outgoing_transport = feedback_transport_.get();
config.retransmission_rate_limiter = &retranmission_rate_limiter_;
rtp_rtcp_ = ModuleRtpRtcpImpl2::Create(config);
rtp_rtcp_->SetRTCPStatus(RtcpMode::kReducedSize);
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
feedback_transport_.reset(
new internal::TransportAdapter(send_config->send_transport));
feedback_transport_->Enable();
encoder_config->min_transmit_bitrate_bps = kMinTransmitBitrateBps;
}
void OnStreamsStopped() override {
task_safety_flag_->SetNotAlive();
rtp_rtcp_.reset();
}
void PerformTest() override {
EXPECT_TRUE(Wait())
<< "Timeout while waiting for low bitrate stats after REMB.";
}
TaskQueueBase* const task_queue_;
std::unique_ptr<ModuleRtpRtcpImpl2> rtp_rtcp_;
std::unique_ptr<internal::TransportAdapter> feedback_transport_;
RateLimiter retranmission_rate_limiter_;
VideoSendStream* stream_;
bool bitrate_capped_;
rtc::scoped_refptr<PendingTaskSafetyFlag> task_safety_flag_;
} test(task_queue());
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, ChangingNetworkRoute) {
static const int kStartBitrateBps = 300000;
static const int kNewMaxBitrateBps = 1234567;
static const uint8_t kExtensionId = kTransportSequenceNumberExtensionId;
class ChangingNetworkRouteTest : public test::EndToEndTest {
public:
explicit ChangingNetworkRouteTest(TaskQueueBase* task_queue)
: EndToEndTest(test::CallTest::kDefaultTimeout),
task_queue_(task_queue),
call_(nullptr) {
module_process_thread_.Detach();
task_queue_thread_.Detach();
extensions_.Register<TransportSequenceNumber>(kExtensionId);
}
~ChangingNetworkRouteTest() {
// Block until all already posted tasks run to avoid 'use after free'
// when such task accesses `this`.
SendTask(task_queue_, [] {});
}
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
RTC_DCHECK(!call_);
call_ = sender_call;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
send_config->rtp.extensions.clear();
send_config->rtp.extensions.push_back(RtpExtension(
RtpExtension::kTransportSequenceNumberUri, kExtensionId));
(*receive_configs)[0].rtp.extensions = send_config->rtp.extensions;
}
void ModifyAudioConfigs(AudioSendStream::Config* send_config,
std::vector<AudioReceiveStreamInterface::Config>*
receive_configs) override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
send_config->rtp.extensions.clear();
send_config->rtp.extensions.push_back(RtpExtension(
RtpExtension::kTransportSequenceNumberUri, kExtensionId));
(*receive_configs)[0].rtp.extensions.clear();
(*receive_configs)[0].rtp.extensions = send_config->rtp.extensions;
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RTC_DCHECK_RUN_ON(&module_process_thread_);
task_queue_->PostTask([this]() {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
if (!call_)
return;
Call::Stats stats = call_->GetStats();
if (stats.send_bandwidth_bps > kStartBitrateBps)
observation_complete_.Set();
});
return SEND_PACKET;
}
void OnStreamsStopped() override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
call_ = nullptr;
}
void PerformTest() override {
rtc::NetworkRoute new_route;
new_route.connected = true;
new_route.local = rtc::RouteEndpoint::CreateWithNetworkId(10);
new_route.remote = rtc::RouteEndpoint::CreateWithNetworkId(20);
BitrateConstraints bitrate_config;
SendTask(task_queue_,
[this, &new_route, &bitrate_config]() {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
call_->GetTransportControllerSend()->OnNetworkRouteChanged(
"transport", new_route);
bitrate_config.start_bitrate_bps = kStartBitrateBps;
call_->GetTransportControllerSend()->SetSdpBitrateParameters(
bitrate_config);
});
EXPECT_TRUE(Wait())
<< "Timed out while waiting for start bitrate to be exceeded.";
SendTask(
task_queue_, [this, &new_route, &bitrate_config]() {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
bitrate_config.start_bitrate_bps = -1;
bitrate_config.max_bitrate_bps = kNewMaxBitrateBps;
call_->GetTransportControllerSend()->SetSdpBitrateParameters(
bitrate_config);
// TODO(holmer): We should set the last sent packet id here and
// verify that we correctly ignore any packet loss reported prior to
// that id.
new_route.local = rtc::RouteEndpoint::CreateWithNetworkId(
new_route.local.network_id() + 1);
call_->GetTransportControllerSend()->OnNetworkRouteChanged(
"transport", new_route);
EXPECT_GE(call_->GetStats().send_bandwidth_bps, kStartBitrateBps);
});
}
private:
webrtc::SequenceChecker module_process_thread_;
webrtc::SequenceChecker task_queue_thread_;
TaskQueueBase* const task_queue_;
RtpHeaderExtensionMap extensions_;
Call* call_ RTC_GUARDED_BY(task_queue_thread_);
} test(task_queue());
RunBaseTest(&test);
}
// Test that if specified, relay cap is lifted on transition to direct
// connection.
// TODO(https://bugs.webrtc.org/13353): Test disabled due to flakiness.
TEST_F(VideoSendStreamTest, DISABLED_RelayToDirectRoute) {
static const int kStartBitrateBps = 300000;
static const int kRelayBandwidthCapBps = 800000;
static const int kMinPacketsToSend = 100;
webrtc::test::ScopedKeyValueConfig field_trials(
field_trials_, "WebRTC-Bwe-NetworkRouteConstraints/relay_cap:" +
std::to_string(kRelayBandwidthCapBps) + "bps/");
class RelayToDirectRouteTest : public test::EndToEndTest {
public:
explicit RelayToDirectRouteTest(TaskQueueBase* task_queue)
: EndToEndTest(test::CallTest::kDefaultTimeout),
task_queue_(task_queue),
call_(nullptr),
packets_sent_(0),
relayed_phase_(true) {
module_process_thread_.Detach();
task_queue_thread_.Detach();
}
~RelayToDirectRouteTest() {
// Block until all already posted tasks run to avoid 'use after free'
// when such task accesses `this`.
SendTask(task_queue_, [] {});
}
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
RTC_DCHECK(!call_);
call_ = sender_call;
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RTC_DCHECK_RUN_ON(&module_process_thread_);
task_queue_->PostTask([this]() {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
if (!call_)
return;
bool had_time_to_exceed_cap_in_relayed_phase =
relayed_phase_ && ++packets_sent_ > kMinPacketsToSend;
bool did_exceed_cap =
call_->GetStats().send_bandwidth_bps > kRelayBandwidthCapBps;
if (did_exceed_cap || had_time_to_exceed_cap_in_relayed_phase)
observation_complete_.Set();
});
return SEND_PACKET;
}
void OnStreamsStopped() override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
call_ = nullptr;
}
void PerformTest() override {
rtc::NetworkRoute route;
route.connected = true;
route.local = rtc::RouteEndpoint::CreateWithNetworkId(10);
route.remote = rtc::RouteEndpoint::CreateWithNetworkId(20);
SendTask(task_queue_, [this, &route]() {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
relayed_phase_ = true;
route.remote = route.remote.CreateWithTurn(true);
call_->GetTransportControllerSend()->OnNetworkRouteChanged("transport",
route);
BitrateConstraints bitrate_config;
bitrate_config.start_bitrate_bps = kStartBitrateBps;
call_->GetTransportControllerSend()->SetSdpBitrateParameters(
bitrate_config);
});
EXPECT_TRUE(Wait())
<< "Timeout waiting for sufficient packets sent count.";
SendTask(task_queue_, [this, &route]() {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
EXPECT_LE(call_->GetStats().send_bandwidth_bps, kRelayBandwidthCapBps);
route.remote = route.remote.CreateWithTurn(false);
call_->GetTransportControllerSend()->OnNetworkRouteChanged("transport",
route);
relayed_phase_ = false;
observation_complete_.Reset();
});
EXPECT_TRUE(Wait())
<< "Timeout while waiting for bandwidth to outgrow relay cap.";
}
private:
webrtc::SequenceChecker module_process_thread_;
webrtc::SequenceChecker task_queue_thread_;
TaskQueueBase* const task_queue_;
Call* call_ RTC_GUARDED_BY(task_queue_thread_);
int packets_sent_ RTC_GUARDED_BY(task_queue_thread_);
bool relayed_phase_ RTC_GUARDED_BY(task_queue_thread_);
} test(task_queue());
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, ChangingTransportOverhead) {
class ChangingTransportOverheadTest : public test::EndToEndTest {
public:
explicit ChangingTransportOverheadTest(TaskQueueBase* task_queue)
: EndToEndTest(test::CallTest::kDefaultTimeout),
task_queue_(task_queue),
call_(nullptr),
packets_sent_(0),
transport_overhead_(0) {}
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
call_ = sender_call;
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
EXPECT_LE(length, kMaxRtpPacketSize);
MutexLock lock(&lock_);
if (++packets_sent_ < 100)
return SEND_PACKET;
observation_complete_.Set();
return SEND_PACKET;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->rtp.max_packet_size = kMaxRtpPacketSize;
}
void PerformTest() override {
SendTask(task_queue_, [this]() {
transport_overhead_ = 100;
call_->GetTransportControllerSend()->OnTransportOverheadChanged(
transport_overhead_);
});
EXPECT_TRUE(Wait());
{
MutexLock lock(&lock_);
packets_sent_ = 0;
}
SendTask(task_queue_, [this]() {
transport_overhead_ = 500;
call_->GetTransportControllerSend()->OnTransportOverheadChanged(
transport_overhead_);
});
EXPECT_TRUE(Wait());
}
private:
TaskQueueBase* const task_queue_;
Call* call_;
Mutex lock_;
int packets_sent_ RTC_GUARDED_BY(lock_);
int transport_overhead_;
const size_t kMaxRtpPacketSize = 1000;
} test(task_queue());
RunBaseTest(&test);
}
// Test class takes takes as argument a switch selecting if type switch should
// occur and a function pointer to reset the send stream. This is necessary
// since you cannot change the content type of a VideoSendStream, you need to
// recreate it. Stopping and recreating the stream can only be done on the main
// thread and in the context of VideoSendStreamTest (not BaseTest).
template <typename T>
class MaxPaddingSetTest : public test::SendTest {
public:
static const uint32_t kMinTransmitBitrateBps = 400000;
static const uint32_t kActualEncodeBitrateBps = 40000;
static const uint32_t kMinPacketsToSend = 50;
MaxPaddingSetTest(bool test_switch_content_type,
T* stream_reset_fun,
TaskQueueBase* task_queue)
: SendTest(test::CallTest::kDefaultTimeout),
running_without_padding_(test_switch_content_type),
stream_resetter_(stream_reset_fun),
task_queue_(task_queue) {
RTC_DCHECK(stream_resetter_);
module_process_thread_.Detach();
task_queue_thread_.Detach();
}
~MaxPaddingSetTest() {
// Block until all already posted tasks run to avoid 'use after free'
// when such task accesses `this`.
SendTask(task_queue_, [] {});
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
RTC_DCHECK_EQ(1, encoder_config->number_of_streams);
if (running_without_padding_) {
encoder_config->min_transmit_bitrate_bps = 0;
encoder_config->content_type =
VideoEncoderConfig::ContentType::kRealtimeVideo;
} else {
encoder_config->min_transmit_bitrate_bps = kMinTransmitBitrateBps;
encoder_config->content_type = VideoEncoderConfig::ContentType::kScreen;
}
send_stream_config_ = send_config->Copy();
encoder_config_ = encoder_config->Copy();
}
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
RTC_DCHECK(task_queue_->IsCurrent());
RTC_DCHECK(!call_);
RTC_DCHECK(sender_call);
call_ = sender_call;
}
// Called on the pacer thread.
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RTC_DCHECK_RUN_ON(&module_process_thread_);
// Check the stats on the correct thread and signal the 'complete' flag
// once we detect that we're done.
task_queue_->PostTask([this]() {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
// In case we get a callback during teardown.
// When this happens, OnStreamsStopped() has been called already,
// `call_` is null and the streams are being torn down.
if (!call_)
return;
++packets_sent_;
Call::Stats stats = call_->GetStats();
if (running_without_padding_) {
EXPECT_EQ(0, stats.max_padding_bitrate_bps);
// Wait until at least kMinPacketsToSend frames have been encoded, so
// that we have reliable data.
if (packets_sent_ < kMinPacketsToSend)
return;
// We've sent kMinPacketsToSend packets with default configuration,
// switch to enabling screen content and setting min transmit bitrate.
// Note that we need to recreate the stream if changing content type.
packets_sent_ = 0;
encoder_config_.min_transmit_bitrate_bps = kMinTransmitBitrateBps;
encoder_config_.content_type = VideoEncoderConfig::ContentType::kScreen;
running_without_padding_ = false;
(*stream_resetter_)(send_stream_config_, encoder_config_);
} else {
// Make sure the pacer has been configured with a min transmit bitrate.
if (stats.max_padding_bitrate_bps > 0) {
observation_complete_.Set();
}
}
});
return SEND_PACKET;
}
// Called on `task_queue_`
void OnStreamsStopped() override {
RTC_DCHECK_RUN_ON(&task_queue_thread_);
RTC_DCHECK(task_queue_->IsCurrent());
call_ = nullptr;
}
void PerformTest() override {
ASSERT_TRUE(Wait()) << "Timed out waiting for a valid padding bitrate.";
}
private:
webrtc::SequenceChecker task_queue_thread_;
Call* call_ RTC_GUARDED_BY(task_queue_thread_) = nullptr;
VideoSendStream::Config send_stream_config_{nullptr};
VideoEncoderConfig encoder_config_;
webrtc::SequenceChecker module_process_thread_;
uint32_t packets_sent_ RTC_GUARDED_BY(task_queue_thread_) = 0;
bool running_without_padding_ RTC_GUARDED_BY(task_queue_thread_);
T* const stream_resetter_;
TaskQueueBase* const task_queue_;
};
TEST_F(VideoSendStreamTest, RespectsMinTransmitBitrate) {
auto reset_fun = [](const VideoSendStream::Config& send_stream_config,
const VideoEncoderConfig& encoder_config) {};
MaxPaddingSetTest<decltype(reset_fun)> test(false, &reset_fun, task_queue());
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, RespectsMinTransmitBitrateAfterContentSwitch) {
// Function for removing and recreating the send stream with a new config.
auto reset_fun = [this](const VideoSendStream::Config& send_stream_config,
const VideoEncoderConfig& encoder_config) {
RTC_DCHECK(task_queue()->IsCurrent());
Stop();
DestroyVideoSendStreams();
SetVideoSendConfig(send_stream_config);
SetVideoEncoderConfig(encoder_config);
CreateVideoSendStreams();
SetVideoDegradation(DegradationPreference::MAINTAIN_RESOLUTION);
Start();
};
MaxPaddingSetTest<decltype(reset_fun)> test(true, &reset_fun, task_queue());
RunBaseTest(&test);
}
// This test verifies that new frame sizes reconfigures encoders even though not
// (yet) sending. The purpose of this is to permit encoding as quickly as
// possible once we start sending. Likely the frames being input are from the
// same source that will be sent later, which just means that we're ready
// earlier.
TEST_F(VideoSendStreamTest,
EncoderReconfigureOnResolutionChangeWhenNotSending) {
class EncoderObserver : public test::FakeEncoder {
public:
EncoderObserver()
: FakeEncoder(Clock::GetRealTimeClock()),
last_initialized_frame_width_(0),
last_initialized_frame_height_(0) {}
void WaitForResolution(int width, int height) {
{
MutexLock lock(&mutex_);
if (last_initialized_frame_width_ == width &&
last_initialized_frame_height_ == height) {
return;
}
}
EXPECT_TRUE(
init_encode_called_.Wait(VideoSendStreamTest::kDefaultTimeout));
{
MutexLock lock(&mutex_);
EXPECT_EQ(width, last_initialized_frame_width_);
EXPECT_EQ(height, last_initialized_frame_height_);
}
}
private:
int32_t InitEncode(const VideoCodec* config,
const Settings& settings) override {
MutexLock lock(&mutex_);
last_initialized_frame_width_ = config->width;
last_initialized_frame_height_ = config->height;
init_encode_called_.Set();
return FakeEncoder::InitEncode(config, settings);
}
int32_t Encode(const VideoFrame& input_image,
const std::vector<VideoFrameType>* frame_types) override {
ADD_FAILURE()
<< "Unexpected Encode call since the send stream is not started";
return 0;
}
Mutex mutex_;
rtc::Event init_encode_called_;
int last_initialized_frame_width_ RTC_GUARDED_BY(&mutex_);
int last_initialized_frame_height_ RTC_GUARDED_BY(&mutex_);
};
test::NullTransport transport;
EncoderObserver encoder;
test::VideoEncoderProxyFactory encoder_factory(&encoder);
SendTask(task_queue(), [this, &transport, &encoder_factory]() {
CreateSenderCall();
CreateSendConfig(1, 0, 0, &transport);
GetVideoSendConfig()->encoder_settings.encoder_factory = &encoder_factory;
CreateVideoStreams();
CreateFrameGeneratorCapturer(kDefaultFramerate, kDefaultWidth,
kDefaultHeight);
frame_generator_capturer_->Start();
});
encoder.WaitForResolution(kDefaultWidth, kDefaultHeight);
SendTask(task_queue(), [this]() {
frame_generator_capturer_->ChangeResolution(kDefaultWidth * 2,
kDefaultHeight * 2);
});
encoder.WaitForResolution(kDefaultWidth * 2, kDefaultHeight * 2);
SendTask(task_queue(), [this]() {
DestroyStreams();
DestroyCalls();
});
}
TEST_F(VideoSendStreamTest, CanReconfigureToUseStartBitrateAbovePreviousMax) {
class StartBitrateObserver : public test::FakeEncoder {
public:
StartBitrateObserver()
: FakeEncoder(Clock::GetRealTimeClock()), start_bitrate_kbps_(0) {}
int32_t InitEncode(const VideoCodec* config,
const Settings& settings) override {
MutexLock lock(&mutex_);
start_bitrate_kbps_ = config->startBitrate;
start_bitrate_changed_.Set();
return FakeEncoder::InitEncode(config, settings);
}
void SetRates(const RateControlParameters& parameters) override {
MutexLock lock(&mutex_);
start_bitrate_kbps_ = parameters.bitrate.get_sum_kbps();
start_bitrate_changed_.Set();
FakeEncoder::SetRates(parameters);
}
int GetStartBitrateKbps() const {
MutexLock lock(&mutex_);
return start_bitrate_kbps_;
}
bool WaitForStartBitrate() {
return start_bitrate_changed_.Wait(VideoSendStreamTest::kDefaultTimeout);
}
private:
mutable Mutex mutex_;
rtc::Event start_bitrate_changed_;
int start_bitrate_kbps_ RTC_GUARDED_BY(mutex_);
};
CreateSenderCall();
test::NullTransport transport;
CreateSendConfig(1, 0, 0, &transport);
BitrateConstraints bitrate_config;
bitrate_config.start_bitrate_bps =
2 * GetVideoEncoderConfig()->max_bitrate_bps;
sender_call_->GetTransportControllerSend()->SetSdpBitrateParameters(
bitrate_config);
StartBitrateObserver encoder;
test::VideoEncoderProxyFactory encoder_factory(&encoder);
GetVideoSendConfig()->encoder_settings.encoder_factory = &encoder_factory;
CreateVideoStreams();
// Start capturing and encoding frames to force encoder reconfiguration.
CreateFrameGeneratorCapturer(kDefaultFramerate, kDefaultWidth,
kDefaultHeight);
frame_generator_capturer_->Start();
// TODO(crbug/1255737): Added manual current thread message processing because
// the test code context is interpreted as the worker thread and we assume
// progress on it. The test should probably be ported to use simulated time
// instead (ported to a scenario test perhaps?).
rtc::Thread::Current()->ProcessMessages(5000);
EXPECT_TRUE(encoder.WaitForStartBitrate());
EXPECT_EQ(GetVideoEncoderConfig()->max_bitrate_bps / 1000,
encoder.GetStartBitrateKbps());
GetVideoEncoderConfig()->max_bitrate_bps =
2 * bitrate_config.start_bitrate_bps;
GetVideoSendStream()->ReconfigureVideoEncoder(
GetVideoEncoderConfig()->Copy());
// TODO(crbug/1255737): Added manual current thread message processing because
// the test code context is interpreted as the worker thread and we assume
// progress on it. The test should probably be ported to use simulated time
// instead (ported to a scenario test perhaps?).
rtc::Thread::Current()->ProcessMessages(5000);
// New bitrate should be reconfigured above the previous max. As there's no
// network connection this shouldn't be flaky, as no bitrate should've been
// reported in between.
EXPECT_TRUE(encoder.WaitForStartBitrate());
EXPECT_EQ(bitrate_config.start_bitrate_bps / 1000,
encoder.GetStartBitrateKbps());
DestroyStreams();
}
class StartStopBitrateObserver : public test::FakeEncoder {
public:
StartStopBitrateObserver() : FakeEncoder(Clock::GetRealTimeClock()) {}
int32_t InitEncode(const VideoCodec* config,
const Settings& settings) override {
MutexLock lock(&mutex_);
encoder_init_.Set();
return FakeEncoder::InitEncode(config, settings);
}
void SetRates(const RateControlParameters& parameters) override {
MutexLock lock(&mutex_);
bitrate_kbps_ = parameters.bitrate.get_sum_kbps();
bitrate_changed_.Set();
FakeEncoder::SetRates(parameters);
}
bool WaitForEncoderInit() {
return encoder_init_.Wait(VideoSendStreamTest::kDefaultTimeout);
}
bool WaitBitrateChanged(WaitUntil until) {
do {
absl::optional<int> bitrate_kbps;
{
MutexLock lock(&mutex_);
bitrate_kbps = bitrate_kbps_;
}
if (!bitrate_kbps)
continue;
if ((until == WaitUntil::kNonZero && *bitrate_kbps > 0) ||
(until == WaitUntil::kZero && *bitrate_kbps == 0)) {
return true;
}
} while (bitrate_changed_.Wait(VideoSendStreamTest::kDefaultTimeout));
return false;
}
private:
Mutex mutex_;
rtc::Event encoder_init_;
rtc::Event bitrate_changed_;
absl::optional<int> bitrate_kbps_ RTC_GUARDED_BY(mutex_);
};
TEST_F(VideoSendStreamTest, EncoderIsProperlyInitializedAndDestroyed) {
class EncoderStateObserver : public test::SendTest, public VideoEncoder {
public:
explicit EncoderStateObserver(TaskQueueBase* task_queue)
: SendTest(kDefaultTimeout),
task_queue_(task_queue),
stream_(nullptr),
initialized_(false),
callback_registered_(false),
num_releases_(0),
released_(false),
encoder_factory_(this) {}
bool IsReleased() RTC_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
return released_;
}
bool IsReadyForEncode() RTC_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
return IsReadyForEncodeLocked();
}
size_t num_releases() RTC_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
return num_releases_;
}
private:
bool IsReadyForEncodeLocked() RTC_EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
return initialized_ && callback_registered_;
}
void SetFecControllerOverride(
FecControllerOverride* fec_controller_override) override {
// Ignored.
}
int32_t InitEncode(const VideoCodec* codecSettings,
const Settings& settings) override
RTC_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
EXPECT_FALSE(initialized_);
initialized_ = true;
released_ = false;
return 0;
}
int32_t Encode(const VideoFrame& inputImage,
const std::vector<VideoFrameType>* frame_types) override {
EXPECT_TRUE(IsReadyForEncode());
observation_complete_.Set();
return 0;
}
int32_t RegisterEncodeCompleteCallback(
EncodedImageCallback* callback) override RTC_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
EXPECT_TRUE(initialized_);
callback_registered_ = true;
return 0;
}
int32_t Release() override RTC_LOCKS_EXCLUDED(mutex_) {
MutexLock lock(&mutex_);
EXPECT_TRUE(IsReadyForEncodeLocked());
EXPECT_FALSE(released_);
initialized_ = false;
callback_registered_ = false;
released_ = true;
++num_releases_;
return 0;
}
void SetRates(const RateControlParameters& parameters) override {
EXPECT_TRUE(IsReadyForEncode());
}
void OnVideoStreamsCreated(VideoSendStream* send_stream,
const std::vector<VideoReceiveStreamInterface*>&
receive_streams) override {
stream_ = send_stream;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
encoder_config_ = encoder_config->Copy();
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for Encode.";
SendTask(task_queue_, [this]() {
EXPECT_EQ(0u, num_releases());
stream_->ReconfigureVideoEncoder(std::move(encoder_config_));
EXPECT_EQ(0u, num_releases());
stream_->Stop();
// Encoder should not be released before destroying the VideoSendStream.
EXPECT_FALSE(IsReleased());
EXPECT_TRUE(IsReadyForEncode());
stream_->Start();
});
// Sanity check, make sure we still encode frames with this encoder.
EXPECT_TRUE(Wait()) << "Timed out while waiting for Encode.";
}
TaskQueueBase* const task_queue_;
Mutex mutex_;
VideoSendStream* stream_;
bool initialized_ RTC_GUARDED_BY(mutex_);
bool callback_registered_ RTC_GUARDED_BY(mutex_);
size_t num_releases_ RTC_GUARDED_BY(mutex_);
bool released_ RTC_GUARDED_BY(mutex_);
test::VideoEncoderProxyFactory encoder_factory_;
VideoEncoderConfig encoder_config_;
} test_encoder(task_queue());
RunBaseTest(&test_encoder);
EXPECT_TRUE(test_encoder.IsReleased());
EXPECT_EQ(1u, test_encoder.num_releases());
}
static const size_t kVideoCodecConfigObserverNumberOfTemporalLayers = 3;
template <typename T>
class VideoCodecConfigObserver : public test::SendTest,
public test::FakeEncoder {
public:
VideoCodecConfigObserver(VideoCodecType video_codec_type,
TaskQueueBase* task_queue)
: SendTest(VideoSendStreamTest::kDefaultTimeout),
FakeEncoder(Clock::GetRealTimeClock()),
video_codec_type_(video_codec_type),
stream_(nullptr),
encoder_factory_(this),
task_queue_(task_queue) {
InitCodecSpecifics();
}
private:
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
send_config->rtp.payload_name = CodecTypeToPayloadString(video_codec_type_);
encoder_config->codec_type = video_codec_type_;
encoder_config->encoder_specific_settings = GetEncoderSpecificSettings();
EXPECT_EQ(1u, encoder_config->simulcast_layers.size());
encoder_config->simulcast_layers[0].num_temporal_layers =
kVideoCodecConfigObserverNumberOfTemporalLayers;
encoder_config_ = encoder_config->Copy();
}
void OnVideoStreamsCreated(VideoSendStream* send_stream,
const std::vector<VideoReceiveStreamInterface*>&
receive_streams) override {
stream_ = send_stream;
}
int32_t InitEncode(const VideoCodec* config,
const Settings& settings) override {
EXPECT_EQ(video_codec_type_, config->codecType);
VerifyCodecSpecifics(*config);
int ret = FakeEncoder::InitEncode(config, settings);
init_encode_event_.Set();
return ret;
}
void InitCodecSpecifics();
void VerifyCodecSpecifics(const VideoCodec& config) const;
rtc::scoped_refptr<VideoEncoderConfig::EncoderSpecificSettings>
GetEncoderSpecificSettings() const;
void PerformTest() override {
EXPECT_TRUE(init_encode_event_.Wait(VideoSendStreamTest::kDefaultTimeout));
ASSERT_EQ(1, FakeEncoder::GetNumInitializations())
<< "VideoEncoder not initialized.";
// Change encoder settings to actually trigger reconfiguration.
encoder_config_.frame_drop_enabled = !encoder_config_.frame_drop_enabled;
encoder_config_.encoder_specific_settings = GetEncoderSpecificSettings();
SendTask(task_queue_, [&]() {
stream_->ReconfigureVideoEncoder(std::move(encoder_config_));
});
ASSERT_TRUE(init_encode_event_.Wait(VideoSendStreamTest::kDefaultTimeout));
EXPECT_EQ(2, FakeEncoder::GetNumInitializations())
<< "ReconfigureVideoEncoder did not reinitialize the encoder with "
"new encoder settings.";
}
int32_t Encode(const VideoFrame& input_image,
const std::vector<VideoFrameType>* frame_types) override {
// Silently skip the encode, FakeEncoder::Encode doesn't produce VP8.
return 0;
}
T encoder_settings_;
const VideoCodecType video_codec_type_;
rtc::Event init_encode_event_;
VideoSendStream* stream_;
test::VideoEncoderProxyFactory encoder_factory_;
VideoEncoderConfig encoder_config_;
TaskQueueBase* task_queue_;
};
template <>
void VideoCodecConfigObserver<VideoCodecH264>::InitCodecSpecifics() {}
template <>
void VideoCodecConfigObserver<VideoCodecH264>::VerifyCodecSpecifics(
const VideoCodec& config) const {
// Check that the number of temporal layers has propagated properly to
// VideoCodec.
EXPECT_EQ(kVideoCodecConfigObserverNumberOfTemporalLayers,
config.H264().numberOfTemporalLayers);
for (unsigned char i = 0; i < config.numberOfSimulcastStreams; ++i) {
EXPECT_EQ(kVideoCodecConfigObserverNumberOfTemporalLayers,
config.simulcastStream[i].numberOfTemporalLayers);
}
// Set expected temporal layers as they should have been set when
// reconfiguring the encoder and not match the set config.
VideoCodecH264 encoder_settings = VideoEncoder::GetDefaultH264Settings();
encoder_settings.numberOfTemporalLayers =
kVideoCodecConfigObserverNumberOfTemporalLayers;
EXPECT_EQ(config.H264(), encoder_settings);
}
template <>
rtc::scoped_refptr<VideoEncoderConfig::EncoderSpecificSettings>
VideoCodecConfigObserver<VideoCodecH264>::GetEncoderSpecificSettings() const {
return nullptr;
}
template <>
void VideoCodecConfigObserver<VideoCodecVP8>::InitCodecSpecifics() {
encoder_settings_ = VideoEncoder::GetDefaultVp8Settings();
}
template <>
void VideoCodecConfigObserver<VideoCodecVP8>::VerifyCodecSpecifics(
const VideoCodec& config) const {
// Check that the number of temporal layers has propagated properly to
// VideoCodec.
EXPECT_EQ(kVideoCodecConfigObserverNumberOfTemporalLayers,
config.VP8().numberOfTemporalLayers);
for (unsigned char i = 0; i < config.numberOfSimulcastStreams; ++i) {
EXPECT_EQ(kVideoCodecConfigObserverNumberOfTemporalLayers,
config.simulcastStream[i].numberOfTemporalLayers);
}
// Set expected temporal layers as they should have been set when
// reconfiguring the encoder and not match the set config.
VideoCodecVP8 encoder_settings = encoder_settings_;
encoder_settings.numberOfTemporalLayers =
kVideoCodecConfigObserverNumberOfTemporalLayers;
EXPECT_EQ(
0, memcmp(&config.VP8(), &encoder_settings, sizeof(encoder_settings_)));
}
template <>
rtc::scoped_refptr<VideoEncoderConfig::EncoderSpecificSettings>
VideoCodecConfigObserver<VideoCodecVP8>::GetEncoderSpecificSettings() const {
return rtc::make_ref_counted<VideoEncoderConfig::Vp8EncoderSpecificSettings>(
encoder_settings_);
}
template <>
void VideoCodecConfigObserver<VideoCodecVP9>::InitCodecSpecifics() {
encoder_settings_ = VideoEncoder::GetDefaultVp9Settings();
}
template <>
void VideoCodecConfigObserver<VideoCodecVP9>::VerifyCodecSpecifics(
const VideoCodec& config) const {
// Check that the number of temporal layers has propagated properly to
// VideoCodec.
EXPECT_EQ(kVideoCodecConfigObserverNumberOfTemporalLayers,
config.VP9().numberOfTemporalLayers);
for (unsigned char i = 0; i < config.numberOfSimulcastStreams; ++i) {
EXPECT_EQ(kVideoCodecConfigObserverNumberOfTemporalLayers,
config.simulcastStream[i].numberOfTemporalLayers);
}
// Set expected temporal layers as they should have been set when
// reconfiguring the encoder and not match the set config.
VideoCodecVP9 encoder_settings = encoder_settings_;
encoder_settings.numberOfTemporalLayers =
kVideoCodecConfigObserverNumberOfTemporalLayers;
EXPECT_EQ(
0, memcmp(&(config.VP9()), &encoder_settings, sizeof(encoder_settings_)));
}
template <>
rtc::scoped_refptr<VideoEncoderConfig::EncoderSpecificSettings>
VideoCodecConfigObserver<VideoCodecVP9>::GetEncoderSpecificSettings() const {
return rtc::make_ref_counted<VideoEncoderConfig::Vp9EncoderSpecificSettings>(
encoder_settings_);
}
TEST_F(VideoSendStreamTest, EncoderSetupPropagatesVp8Config) {
VideoCodecConfigObserver<VideoCodecVP8> test(kVideoCodecVP8, task_queue());
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, EncoderSetupPropagatesVp9Config) {
VideoCodecConfigObserver<VideoCodecVP9> test(kVideoCodecVP9, task_queue());
RunBaseTest(&test);
}
// Fails on MSAN: https://bugs.chromium.org/p/webrtc/issues/detail?id=11376.
#if defined(MEMORY_SANITIZER)
#define MAYBE_EncoderSetupPropagatesH264Config \
DISABLED_EncoderSetupPropagatesH264Config
#else
#define MAYBE_EncoderSetupPropagatesH264Config EncoderSetupPropagatesH264Config
#endif
TEST_F(VideoSendStreamTest, MAYBE_EncoderSetupPropagatesH264Config) {
VideoCodecConfigObserver<VideoCodecH264> test(kVideoCodecH264, task_queue());
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, RtcpSenderReportContainsMediaBytesSent) {
class RtcpSenderReportTest : public test::SendTest {
public:
RtcpSenderReportTest()
: SendTest(kDefaultTimeout),
rtp_packets_sent_(0),
media_bytes_sent_(0) {}
private:
Action OnSendRtp(const uint8_t* packet, size_t length) override {
MutexLock lock(&mutex_);
RtpPacket rtp_packet;
EXPECT_TRUE(rtp_packet.Parse(packet, length));
++rtp_packets_sent_;
media_bytes_sent_ += rtp_packet.payload_size();
return SEND_PACKET;
}
Action OnSendRtcp(const uint8_t* packet, size_t length) override {
MutexLock lock(&mutex_);
test::RtcpPacketParser parser;
EXPECT_TRUE(parser.Parse(packet, length));
if (parser.sender_report()->num_packets() > 0) {
// Only compare sent media bytes if SenderPacketCount matches the
// number of sent rtp packets (a new rtp packet could be sent before
// the rtcp packet).
if (parser.sender_report()->sender_octet_count() > 0 &&
parser.sender_report()->sender_packet_count() ==
rtp_packets_sent_) {
EXPECT_EQ(media_bytes_sent_,
parser.sender_report()->sender_octet_count());
observation_complete_.Set();
}
}
return SEND_PACKET;
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for RTCP sender report.";
}
Mutex mutex_;
size_t rtp_packets_sent_ RTC_GUARDED_BY(&mutex_);
size_t media_bytes_sent_ RTC_GUARDED_BY(&mutex_);
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, TranslatesTwoLayerScreencastToTargetBitrate) {
static const int kScreencastMaxTargetBitrateDeltaKbps = 1;
class VideoStreamFactory
: public VideoEncoderConfig::VideoStreamFactoryInterface {
public:
VideoStreamFactory() {}
private:
std::vector<VideoStream> CreateEncoderStreams(
int frame_width,
int frame_height,
const VideoEncoderConfig& encoder_config) override {
std::vector<VideoStream> streams =
test::CreateVideoStreams(frame_width, frame_height, encoder_config);
RTC_CHECK_GT(streams[0].max_bitrate_bps,
kScreencastMaxTargetBitrateDeltaKbps);
streams[0].target_bitrate_bps =
streams[0].max_bitrate_bps -
kScreencastMaxTargetBitrateDeltaKbps * 1000;
return streams;
}
};
class ScreencastTargetBitrateTest : public test::SendTest,
public test::FakeEncoder {
public:
ScreencastTargetBitrateTest()
: SendTest(kDefaultTimeout),
test::FakeEncoder(Clock::GetRealTimeClock()),
encoder_factory_(this) {}
private:
int32_t InitEncode(const VideoCodec* config,
const Settings& settings) override {
EXPECT_EQ(config->numberOfSimulcastStreams, 1);
EXPECT_EQ(static_cast<unsigned int>(kScreencastMaxTargetBitrateDeltaKbps),
config->simulcastStream[0].maxBitrate -
config->simulcastStream[0].targetBitrate);
observation_complete_.Set();
return test::FakeEncoder::InitEncode(config, settings);
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
EXPECT_EQ(1u, encoder_config->number_of_streams);
encoder_config->video_stream_factory =
rtc::make_ref_counted<VideoStreamFactory>();
EXPECT_EQ(1u, encoder_config->simulcast_layers.size());
encoder_config->simulcast_layers[0].num_temporal_layers = 2;
encoder_config->content_type = VideoEncoderConfig::ContentType::kScreen;
}
void PerformTest() override {
EXPECT_TRUE(Wait())
<< "Timed out while waiting for the encoder to be initialized.";
}
test::VideoEncoderProxyFactory encoder_factory_;
} test;
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, ReconfigureBitratesSetsEncoderBitratesCorrectly) {
// These are chosen to be "kind of odd" to not be accidentally checked against
// default values.
static const int kMinBitrateKbps = 137;
static const int kStartBitrateKbps = 345;
static const int kLowerMaxBitrateKbps = 312;
static const int kMaxBitrateKbps = 413;
static const int kIncreasedStartBitrateKbps = 451;
static const int kIncreasedMaxBitrateKbps = 597;
// TODO(bugs.webrtc.org/12058): If these fields trial are on, we get lower
// bitrates than expected by this test, due to encoder pushback and subtracted
// overhead.
webrtc::test::ScopedKeyValueConfig field_trials(
field_trials_, "WebRTC-VideoRateControl/bitrate_adjuster:false/");
class EncoderBitrateThresholdObserver : public test::SendTest,
public VideoBitrateAllocatorFactory,
public test::FakeEncoder {
public:
explicit EncoderBitrateThresholdObserver(TaskQueueBase* task_queue)
: SendTest(kDefaultTimeout),
FakeEncoder(Clock::GetRealTimeClock()),
task_queue_(task_queue),
target_bitrate_(0),
num_rate_allocator_creations_(0),
num_encoder_initializations_(0),
call_(nullptr),
send_stream_(nullptr),
encoder_factory_(this),
bitrate_allocator_factory_(
CreateBuiltinVideoBitrateAllocatorFactory()) {}
private:
std::unique_ptr<VideoBitrateAllocator> CreateVideoBitrateAllocator(
const VideoCodec& codec) override {
EXPECT_GE(codec.startBitrate, codec.minBitrate);
EXPECT_LE(codec.startBitrate, codec.maxBitrate);
if (num_rate_allocator_creations_ == 0) {
EXPECT_EQ(static_cast<unsigned int>(kMinBitrateKbps), codec.minBitrate);
EXPECT_NEAR(static_cast<unsigned int>(kStartBitrateKbps),
codec.startBitrate, 10);
EXPECT_EQ(static_cast<unsigned int>(kMaxBitrateKbps), codec.maxBitrate);
} else if (num_rate_allocator_creations_ == 1) {
EXPECT_EQ(static_cast<unsigned int>(kLowerMaxBitrateKbps),
codec.maxBitrate);
// The start bitrate should be kept (-1) and capped to the max bitrate.
// Since this is not an end-to-end call no receiver should have been
// returning a REMB that could lower this estimate.
EXPECT_EQ(codec.startBitrate, codec.maxBitrate);
} else if (num_rate_allocator_creations_ == 2) {
EXPECT_EQ(static_cast<unsigned int>(kIncreasedMaxBitrateKbps),
codec.maxBitrate);
// The start bitrate will be whatever the rate BitRateController has
// currently configured but in the span of the set max and min bitrate.
}
++num_rate_allocator_creations_;
create_rate_allocator_event_.Set();
return bitrate_allocator_factory_->CreateVideoBitrateAllocator(codec);
}
int32_t InitEncode(const VideoCodec* codecSettings,
const Settings& settings) override {
EXPECT_EQ(0, num_encoder_initializations_);
EXPECT_EQ(static_cast<unsigned int>(kMinBitrateKbps),
codecSettings->minBitrate);
EXPECT_NEAR(static_cast<unsigned int>(kStartBitrateKbps),
codecSettings->startBitrate, 10);
EXPECT_EQ(static_cast<unsigned int>(kMaxBitrateKbps),
codecSettings->maxBitrate);
++num_encoder_initializations_;
observation_complete_.Set();
init_encode_event_.Set();
return FakeEncoder::InitEncode(codecSettings, settings);
}
void SetRates(const RateControlParameters& parameters) override {
{
MutexLock lock(&mutex_);
if (target_bitrate_ == parameters.bitrate.get_sum_kbps()) {
FakeEncoder::SetRates(parameters);
return;
}
target_bitrate_ = parameters.bitrate.get_sum_kbps();
}
bitrate_changed_event_.Set();
FakeEncoder::SetRates(parameters);
}
void WaitForSetRates(uint32_t expected_bitrate, int abs_error) {
// Wait for the expected rate to be set. In some cases there can be
// more than one update pending, in which case we keep waiting
// until the correct value has been observed.
// The target_bitrate_ is reduced by the calculated packet overhead.
const int64_t start_time = rtc::TimeMillis();
do {
MutexLock lock(&mutex_);
int error = target_bitrate_ - expected_bitrate;
if ((error < 0 && error >= -abs_error) ||
(error >= 0 && error <= abs_error)) {
return;
}
} while (bitrate_changed_event_.Wait(
std::max(TimeDelta::Millis(1),
VideoSendStreamTest::kDefaultTimeout -
TimeDelta::Millis(rtc::TimeMillis() - start_time))));
MutexLock lock(&mutex_);
EXPECT_NEAR(target_bitrate_, expected_bitrate, abs_error)
<< "Timed out while waiting encoder rate to be set.";
}
void ModifySenderBitrateConfig(
BitrateConstraints* bitrate_config) override {
bitrate_config->min_bitrate_bps = kMinBitrateKbps * 1000;
bitrate_config->start_bitrate_bps = kStartBitrateKbps * 1000;
bitrate_config->max_bitrate_bps = kMaxBitrateKbps * 1000;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
send_config->encoder_settings.bitrate_allocator_factory = this;
// Set bitrates lower/higher than min/max to make sure they are properly
// capped.
encoder_config->max_bitrate_bps = kMaxBitrateKbps * 1000;
EXPECT_EQ(1u, encoder_config->simulcast_layers.size());
encoder_config->simulcast_layers[0].min_bitrate_bps =
kMinBitrateKbps * 1000;
encoder_config_ = encoder_config->Copy();
}
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
call_ = sender_call;
}
void OnVideoStreamsCreated(VideoSendStream* send_stream,
const std::vector<VideoReceiveStreamInterface*>&
receive_streams) override {
send_stream_ = send_stream;
}
void PerformTest() override {
ASSERT_TRUE(create_rate_allocator_event_.Wait(
VideoSendStreamTest::kDefaultTimeout))
<< "Timed out while waiting for rate allocator to be created.";
ASSERT_TRUE(init_encode_event_.Wait(VideoSendStreamTest::kDefaultTimeout))
<< "Timed out while waiting for encoder to be configured.";
WaitForSetRates(kStartBitrateKbps, 80);
BitrateConstraints bitrate_config;
bitrate_config.start_bitrate_bps = kIncreasedStartBitrateKbps * 1000;
bitrate_config.max_bitrate_bps = kIncreasedMaxBitrateKbps * 1000;
SendTask(task_queue_, [this, &bitrate_config]() {
call_->GetTransportControllerSend()->SetSdpBitrateParameters(
bitrate_config);
});
// Encoder rate is capped by EncoderConfig max_bitrate_bps.
WaitForSetRates(kMaxBitrateKbps, 10);
encoder_config_.max_bitrate_bps = kLowerMaxBitrateKbps * 1000;
SendTask(task_queue_, [&]() {
send_stream_->ReconfigureVideoEncoder(encoder_config_.Copy());
});
ASSERT_TRUE(create_rate_allocator_event_.Wait(
VideoSendStreamTest::kDefaultTimeout));
EXPECT_EQ(2, num_rate_allocator_creations_)
<< "Rate allocator should have been recreated.";
WaitForSetRates(kLowerMaxBitrateKbps, 10);
EXPECT_EQ(1, num_encoder_initializations_);
encoder_config_.max_bitrate_bps = kIncreasedMaxBitrateKbps * 1000;
SendTask(task_queue_, [&]() {
send_stream_->ReconfigureVideoEncoder(encoder_config_.Copy());
});
ASSERT_TRUE(create_rate_allocator_event_.Wait(
VideoSendStreamTest::kDefaultTimeout));
EXPECT_EQ(3, num_rate_allocator_creations_)
<< "Rate allocator should have been recreated.";
// Expected target bitrate is the start bitrate set in the call to
// call_->GetTransportControllerSend()->SetSdpBitrateParameters.
WaitForSetRates(kIncreasedStartBitrateKbps, 10);
EXPECT_EQ(1, num_encoder_initializations_);
}
TaskQueueBase* const task_queue_;
rtc::Event create_rate_allocator_event_;
rtc::Event init_encode_event_;
rtc::Event bitrate_changed_event_;
Mutex mutex_;
uint32_t target_bitrate_ RTC_GUARDED_BY(&mutex_);
int num_rate_allocator_creations_;
int num_encoder_initializations_;
webrtc::Call* call_;
webrtc::VideoSendStream* send_stream_;
test::VideoEncoderProxyFactory encoder_factory_;
std::unique_ptr<VideoBitrateAllocatorFactory> bitrate_allocator_factory_;
webrtc::VideoEncoderConfig encoder_config_;
} test(task_queue());
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, ReportsSentResolution) {
static const size_t kNumStreams = 3;
// Unusual resolutions to make sure that they are the ones being reported.
static const struct {
int width;
int height;
} kEncodedResolution[kNumStreams] = {{241, 181}, {300, 121}, {121, 221}};
class ScreencastTargetBitrateTest : public test::SendTest,
public test::FakeEncoder {
public:
explicit ScreencastTargetBitrateTest(TaskQueueBase* task_queue)
: SendTest(kDefaultTimeout),
test::FakeEncoder(Clock::GetRealTimeClock()),
send_stream_(nullptr),
encoder_factory_(this),
task_queue_(task_queue) {}
private:
int32_t Encode(const VideoFrame& input_image,
const std::vector<VideoFrameType>* frame_types) override {
CodecSpecificInfo specifics;
specifics.codecType = kVideoCodecGeneric;
EncodedImage encoded;
auto buffer = EncodedImageBuffer::Create(16);
memset(buffer->data(), 0, 16);
encoded.SetEncodedData(buffer);
encoded.SetTimestamp(input_image.timestamp());
encoded.capture_time_ms_ = input_image.render_time_ms();
for (size_t i = 0; i < kNumStreams; ++i) {
encoded._frameType = (*frame_types)[i];
encoded._encodedWidth = kEncodedResolution[i].width;
encoded._encodedHeight = kEncodedResolution[i].height;
encoded.SetSpatialIndex(i);
EncodedImageCallback* callback;
{
MutexLock lock(&mutex_);
callback = callback_;
}
RTC_DCHECK(callback);
if (callback->OnEncodedImage(encoded, &specifics).error !=
EncodedImageCallback::Result::OK) {
return -1;
}
}
observation_complete_.Set();
return 0;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
EXPECT_EQ(kNumStreams, encoder_config->number_of_streams);
}
size_t GetNumVideoStreams() const override { return kNumStreams; }
void PerformTest() override {
EXPECT_TRUE(Wait())
<< "Timed out while waiting for the encoder to send one frame.";
VideoSendStream::Stats stats;
SendTask(task_queue_, [&]() { stats = send_stream_->GetStats(); });
for (size_t i = 0; i < kNumStreams; ++i) {
ASSERT_TRUE(stats.substreams.find(kVideoSendSsrcs[i]) !=
stats.substreams.end())
<< "No stats for SSRC: " << kVideoSendSsrcs[i]
<< ", stats should exist as soon as frames have been encoded.";
VideoSendStream::StreamStats ssrc_stats =
stats.substreams[kVideoSendSsrcs[i]];
EXPECT_EQ(kEncodedResolution[i].width, ssrc_stats.width);
EXPECT_EQ(kEncodedResolution[i].height, ssrc_stats.height);
}
}
void OnVideoStreamsCreated(VideoSendStream* send_stream,
const std::vector<VideoReceiveStreamInterface*>&
receive_streams) override {
send_stream_ = send_stream;
}
VideoSendStream* send_stream_;
test::VideoEncoderProxyFactory encoder_factory_;
TaskQueueBase* const task_queue_;
} test(task_queue());
RunBaseTest(&test);
}
#if defined(RTC_ENABLE_VP9)
class Vp9HeaderObserver : public test::SendTest {
public:
explicit Vp9HeaderObserver(const Vp9TestParams& params)
: SendTest(VideoSendStreamTest::kLongTimeout),
encoder_factory_([]() { return VP9Encoder::Create(); }),
params_(params),
vp9_settings_(VideoEncoder::GetDefaultVp9Settings()) {}
virtual void ModifyVideoConfigsHook(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) {}
virtual void InspectHeader(const RTPVideoHeaderVP9& vp9) = 0;
private:
const int kVp9PayloadType = test::CallTest::kVideoSendPayloadType;
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->encoder_settings.encoder_factory = &encoder_factory_;
send_config->rtp.payload_name = "VP9";
send_config->rtp.payload_type = kVp9PayloadType;
ModifyVideoConfigsHook(send_config, receive_configs, encoder_config);
encoder_config->encoder_specific_settings =
rtc::make_ref_counted<VideoEncoderConfig::Vp9EncoderSpecificSettings>(
vp9_settings_);
EXPECT_EQ(1u, encoder_config->number_of_streams);
EXPECT_EQ(1u, encoder_config->simulcast_layers.size());
encoder_config_ = encoder_config->Copy();
}
void ModifyVideoCaptureStartResolution(int* width,
int* height,
int* frame_rate) override {
expected_width_ = *width;
expected_height_ = *height;
}
void PerformTest() override {
bool wait = Wait();
{
// In case of time out, OnSendRtp might still access frames_sent_;
MutexLock lock(&mutex_);
EXPECT_TRUE(wait) << "Test timed out waiting for VP9 packet, num frames "
<< frames_sent_;
}
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
RtpPacket rtp_packet;
EXPECT_TRUE(rtp_packet.Parse(packet, length));
EXPECT_EQ(kVp9PayloadType, rtp_packet.PayloadType());
rtc::ArrayView<const uint8_t> rtp_payload = rtp_packet.payload();
bool new_packet = !last_packet_sequence_number_.has_value() ||
IsNewerSequenceNumber(rtp_packet.SequenceNumber(),
*last_packet_sequence_number_);
if (!rtp_payload.empty() && new_packet) {
RTPVideoHeader video_header;
EXPECT_NE(
VideoRtpDepacketizerVp9::ParseRtpPayload(rtp_payload, &video_header),
0);
EXPECT_EQ(VideoCodecType::kVideoCodecVP9, video_header.codec);
// Verify common fields for all configurations.
const auto& vp9_header =
absl::get<RTPVideoHeaderVP9>(video_header.video_type_header);
VerifyCommonHeader(vp9_header);
CompareConsecutiveFrames(rtp_packet, video_header);
// Verify configuration specific settings.
InspectHeader(vp9_header);
if (rtp_packet.Marker()) {
MutexLock lock(&mutex_);
++frames_sent_;
}
last_packet_marker_ = rtp_packet.Marker();
last_packet_sequence_number_ = rtp_packet.SequenceNumber();
last_packet_timestamp_ = rtp_packet.Timestamp();
last_vp9_ = vp9_header;
last_temporal_idx_by_spatial_idx_[vp9_header.spatial_idx] =
vp9_header.temporal_idx;
}
return SEND_PACKET;
}
protected:
bool ContinuousPictureId(const RTPVideoHeaderVP9& vp9) const {
if (last_vp9_.picture_id > vp9.picture_id) {
return vp9.picture_id == 0; // Wrap.
} else {
return vp9.picture_id == last_vp9_.picture_id + 1;
}
}
bool IsTemporalShiftEnabled() const {
return params_.scalability_mode.find("_SHIFT") != std::string::npos;
}
void VerifySpatialIdxWithinFrame(const RTPVideoHeaderVP9& vp9) const {
bool new_layer = vp9.spatial_idx != last_vp9_.spatial_idx;
EXPECT_EQ(new_layer, vp9.beginning_of_frame);
EXPECT_EQ(new_layer, last_vp9_.end_of_frame);
EXPECT_EQ(new_layer ? last_vp9_.spatial_idx + 1 : last_vp9_.spatial_idx,
vp9.spatial_idx);
}
void VerifyTemporalIdxWithinFrame(const RTPVideoHeaderVP9& vp9) const {
if (!IsTemporalShiftEnabled()) {
EXPECT_EQ(vp9.temporal_idx, last_vp9_.temporal_idx);
return;
}
// Temporal shift.
EXPECT_EQ(params_.num_temporal_layers, 2);
if (vp9.spatial_idx == params_.num_spatial_layers - 1) {
// Lower spatial layers should be shifted.
int expected_tid =
(!vp9.inter_pic_predicted || vp9.temporal_idx == 1) ? 0 : 1;
for (int i = 0; i < vp9.spatial_idx; ++i) {
EXPECT_EQ(last_temporal_idx_by_spatial_idx_.at(i), expected_tid);
}
}
// Same within spatial layer.
bool new_layer = vp9.spatial_idx != last_vp9_.spatial_idx;
if (!new_layer) {
EXPECT_EQ(vp9.temporal_idx, last_vp9_.temporal_idx);
}
}
void VerifyFixedTemporalLayerStructure(const RTPVideoHeaderVP9& vp9,
uint8_t num_layers) const {
switch (num_layers) {
case 0:
VerifyTemporalLayerStructure0(vp9);
break;
case 1:
VerifyTemporalLayerStructure1(vp9);
break;
case 2:
VerifyTemporalLayerStructure2(vp9);
break;
case 3:
VerifyTemporalLayerStructure3(vp9);
break;
default:
RTC_DCHECK_NOTREACHED();
}
}
void VerifyTemporalLayerStructure0(const RTPVideoHeaderVP9& vp9) const {
EXPECT_EQ(kNoTl0PicIdx, vp9.tl0_pic_idx);
EXPECT_EQ(kNoTemporalIdx, vp9.temporal_idx); // no tid
// Technically true, but layer indices not available.
EXPECT_FALSE(vp9.temporal_up_switch);
}
void VerifyTemporalLayerStructure1(const RTPVideoHeaderVP9& vp9) const {
EXPECT_NE(kNoTl0PicIdx, vp9.tl0_pic_idx);
EXPECT_EQ(0, vp9.temporal_idx); // 0,0,0,...
}
void VerifyTemporalLayerStructure2(const RTPVideoHeaderVP9& vp9) const {
EXPECT_NE(kNoTl0PicIdx, vp9.tl0_pic_idx);
EXPECT_GE(vp9.temporal_idx, 0); // 0,1,0,1,... (tid reset on I-frames).
EXPECT_LE(vp9.temporal_idx, 1);
EXPECT_TRUE(vp9.temporal_up_switch);
// Verify temporal structure for the highest spatial layer (the structure
// may be shifted for lower spatial layer if temporal shift is configured).
if (IsHighestSpatialLayer(vp9) && vp9.beginning_of_frame) {
int expected_tid =
(!vp9.inter_pic_predicted ||
last_temporal_idx_by_spatial_idx_.at(vp9.spatial_idx) == 1)
? 0
: 1;
EXPECT_EQ(vp9.temporal_idx, expected_tid);
}
}
void VerifyTemporalLayerStructure3(const RTPVideoHeaderVP9& vp9) const {
EXPECT_NE(kNoTl0PicIdx, vp9.tl0_pic_idx);
EXPECT_GE(vp9.temporal_idx, 0); // 0,2,1,2,... (tid reset on I-frames).
EXPECT_LE(vp9.temporal_idx, 2);
if (IsNewPictureId(vp9) && vp9.inter_pic_predicted) {
EXPECT_NE(vp9.temporal_idx, last_vp9_.temporal_idx);
EXPECT_TRUE(vp9.temporal_up_switch);
switch (vp9.temporal_idx) {
case 0:
EXPECT_EQ(last_vp9_.temporal_idx, 2);
break;
case 1:
EXPECT_EQ(last_vp9_.temporal_idx, 2);
break;
case 2:
EXPECT_LT(last_vp9_.temporal_idx, 2);
break;
}
}
}
void VerifyTl0Idx(const RTPVideoHeaderVP9& vp9) const {
if (vp9.tl0_pic_idx == kNoTl0PicIdx)
return;
uint8_t expected_tl0_idx = last_vp9_.tl0_pic_idx;
if (vp9.temporal_idx == 0)
++expected_tl0_idx;
EXPECT_EQ(expected_tl0_idx, vp9.tl0_pic_idx);
}
bool IsNewPictureId(const RTPVideoHeaderVP9& vp9) const {
return frames_sent_ > 0 && (vp9.picture_id != last_vp9_.picture_id);
}
bool IsHighestSpatialLayer(const RTPVideoHeaderVP9& vp9) const {
return vp9.spatial_idx == params_.num_spatial_layers - 1 ||
vp9.spatial_idx == kNoSpatialIdx;
}
// Flexible mode (F=1): Non-flexible mode (F=0):
//
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// |I|P|L|F|B|E|V|-| |I|P|L|F|B|E|V|-|
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// I: |M| PICTURE ID | I: |M| PICTURE ID |
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// M: | EXTENDED PID | M: | EXTENDED PID |
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// L: | T |U| S |D| L: | T |U| S |D|
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// P,F: | P_DIFF |X|N| | TL0PICIDX |
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// X: |EXTENDED P_DIFF| V: | SS .. |
// +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
// V: | SS .. |
// +-+-+-+-+-+-+-+-+
void VerifyCommonHeader(const RTPVideoHeaderVP9& vp9) const {
EXPECT_EQ(kMaxTwoBytePictureId, vp9.max_picture_id); // M:1
EXPECT_NE(kNoPictureId, vp9.picture_id); // I:1
EXPECT_EQ(vp9_settings_.flexibleMode, vp9.flexible_mode); // F
if (params_.num_spatial_layers > 1) {
EXPECT_LT(vp9.spatial_idx, params_.num_spatial_layers);
} else if (params_.num_temporal_layers > 1) {
EXPECT_EQ(vp9.spatial_idx, 0);
} else {
EXPECT_EQ(vp9.spatial_idx, kNoSpatialIdx);
}
if (params_.num_temporal_layers > 1) {
EXPECT_LT(vp9.temporal_idx, params_.num_temporal_layers);
} else if (params_.num_spatial_layers > 1) {
EXPECT_EQ(vp9.temporal_idx, 0);
} else {
EXPECT_EQ(vp9.temporal_idx, kNoTemporalIdx);
}
if (vp9.ss_data_available) // V
VerifySsData(vp9);
if (frames_sent_ == 0)
EXPECT_FALSE(vp9.inter_pic_predicted); // P
if (!vp9.inter_pic_predicted) {
if (vp9.temporal_idx == kNoTemporalIdx) {
EXPECT_FALSE(vp9.temporal_up_switch);
} else {
EXPECT_EQ(vp9.temporal_idx, 0);
EXPECT_TRUE(vp9.temporal_up_switch);
}
}
}
// Scalability structure (SS).
//
// +-+-+-+-+-+-+-+-+
// V: | N_S |Y|G|-|-|-|
// +-+-+-+-+-+-+-+-+
// Y: | WIDTH | N_S + 1 times
// +-+-+-+-+-+-+-+-+
// | HEIGHT |
// +-+-+-+-+-+-+-+-+
// G: | N_G |
// +-+-+-+-+-+-+-+-+
// N_G: | T |U| R |-|-| N_G times
// +-+-+-+-+-+-+-+-+
// | P_DIFF | R times
// +-+-+-+-+-+-+-+-+
void VerifySsData(const RTPVideoHeaderVP9& vp9) const {
EXPECT_TRUE(vp9.ss_data_available); // V
EXPECT_EQ(params_.num_spatial_layers, // N_S + 1
vp9.num_spatial_layers);
EXPECT_TRUE(vp9.spatial_layer_resolution_present); // Y:1
ScalableVideoController::StreamLayersConfig config = GetScalabilityConfig();
for (int i = config.num_spatial_layers - 1; i >= 0; --i) {
double ratio = static_cast<double>(config.scaling_factor_num[i]) /
config.scaling_factor_den[i];
EXPECT_EQ(expected_width_ * ratio, vp9.width[i]); // WIDTH
EXPECT_EQ(expected_height_ * ratio, vp9.height[i]); // HEIGHT
}
}
void CompareConsecutiveFrames(const RtpPacket& rtp_packet,
const RTPVideoHeader& video) const {
const auto& vp9_header =
absl::get<RTPVideoHeaderVP9>(video.video_type_header);
const bool new_temporal_unit =
!last_packet_timestamp_.has_value() ||
IsNewerTimestamp(rtp_packet.Timestamp(), *last_packet_timestamp_);
const bool new_frame =
new_temporal_unit || last_vp9_.spatial_idx != vp9_header.spatial_idx;
EXPECT_EQ(new_frame, video.is_first_packet_in_frame);
if (!new_temporal_unit) {
EXPECT_FALSE(last_packet_marker_);
EXPECT_EQ(*last_packet_timestamp_, rtp_packet.Timestamp());
EXPECT_EQ(last_vp9_.picture_id, vp9_header.picture_id);
EXPECT_EQ(last_vp9_.tl0_pic_idx, vp9_header.tl0_pic_idx);
VerifySpatialIdxWithinFrame(vp9_header);
VerifyTemporalIdxWithinFrame(vp9_header);
return;
}
// New frame.
EXPECT_TRUE(vp9_header.beginning_of_frame);
// Compare with last packet in previous frame.
if (frames_sent_ == 0)
return;
EXPECT_TRUE(last_vp9_.end_of_frame);
EXPECT_TRUE(last_packet_marker_);
EXPECT_TRUE(ContinuousPictureId(vp9_header));
VerifyTl0Idx(vp9_header);
}
ScalableVideoController::StreamLayersConfig GetScalabilityConfig() const {
absl::optional<ScalabilityMode> scalability_mode =
ScalabilityModeFromString(params_.scalability_mode);
EXPECT_TRUE(scalability_mode.has_value());
absl::optional<ScalableVideoController::StreamLayersConfig> config =
ScalabilityStructureConfig(*scalability_mode);
EXPECT_TRUE(config.has_value());
EXPECT_EQ(config->num_spatial_layers, params_.num_spatial_layers);
return *config;
}
test::FunctionVideoEncoderFactory encoder_factory_;
const Vp9TestParams params_;
VideoCodecVP9 vp9_settings_;
webrtc::VideoEncoderConfig encoder_config_;
bool last_packet_marker_ = false;
absl::optional<uint16_t> last_packet_sequence_number_;
absl::optional<uint32_t> last_packet_timestamp_;
RTPVideoHeaderVP9 last_vp9_;
std::map<int, int> last_temporal_idx_by_spatial_idx_;
Mutex mutex_;
size_t frames_sent_ = 0;
int expected_width_ = 0;
int expected_height_ = 0;
};
class Vp9Test : public VideoSendStreamTest,
public ::testing::WithParamInterface<ParameterizationType> {
public:
Vp9Test()
: params_(::testing::get<Vp9TestParams>(GetParam())),
use_scalability_mode_identifier_(::testing::get<bool>(GetParam())) {}
protected:
const Vp9TestParams params_;
const bool use_scalability_mode_identifier_;
};
INSTANTIATE_TEST_SUITE_P(
ScalabilityMode,
Vp9Test,
::testing::Combine(
::testing::ValuesIn<Vp9TestParams>(
{{"L1T1", 1, 1, InterLayerPredMode::kOn},
{"L1T2", 1, 2, InterLayerPredMode::kOn},
{"L1T3", 1, 3, InterLayerPredMode::kOn},
{"L2T1", 2, 1, InterLayerPredMode::kOn},
{"L2T1_KEY", 2, 1, InterLayerPredMode::kOnKeyPic},
{"L2T2", 2, 2, InterLayerPredMode::kOn},
{"L2T2_KEY", 2, 2, InterLayerPredMode::kOnKeyPic},
{"L2T3", 2, 3, InterLayerPredMode::kOn},
{"L2T3_KEY", 2, 3, InterLayerPredMode::kOnKeyPic},
{"L3T1", 3, 1, InterLayerPredMode::kOn},
{"L3T1_KEY", 3, 1, InterLayerPredMode::kOnKeyPic},
{"L3T2", 3, 2, InterLayerPredMode::kOn},
{"L3T2_KEY", 3, 2, InterLayerPredMode::kOnKeyPic},
{"L3T3", 3, 3, InterLayerPredMode::kOn},
{"L3T3_KEY", 3, 3, InterLayerPredMode::kOnKeyPic},
{"S2T1", 2, 1, InterLayerPredMode::kOff},
{"S2T2", 2, 2, InterLayerPredMode::kOff},
{"S2T3", 2, 3, InterLayerPredMode::kOff},
{"S3T1", 3, 1, InterLayerPredMode::kOff},
{"S3T2", 3, 2, InterLayerPredMode::kOff},
{"S3T3", 3, 3, InterLayerPredMode::kOff}}),
::testing::Values(false, true)), // use_scalability_mode_identifier
ParamInfoToStr);
INSTANTIATE_TEST_SUITE_P(
ScalabilityModeOn,
Vp9Test,
::testing::Combine(
::testing::ValuesIn<Vp9TestParams>(
{{"L2T1h", 2, 1, InterLayerPredMode::kOn},
{"L2T2h", 2, 2, InterLayerPredMode::kOn},
{"L2T3h", 2, 3, InterLayerPredMode::kOn},
{"L2T2_KEY_SHIFT", 2, 2, InterLayerPredMode::kOnKeyPic},
{"L3T1h", 3, 1, InterLayerPredMode::kOn},
{"L3T2h", 3, 2, InterLayerPredMode::kOn},
{"L3T3h", 3, 3, InterLayerPredMode::kOn},
{"S2T1h", 2, 1, InterLayerPredMode::kOff},
{"S2T2h", 2, 2, InterLayerPredMode::kOff},
{"S2T3h", 2, 3, InterLayerPredMode::kOff},
{"S3T1h", 3, 1, InterLayerPredMode::kOff},
{"S3T2h", 3, 2, InterLayerPredMode::kOff},
{"S3T3h", 3, 3, InterLayerPredMode::kOff}}),
::testing::Values(true)), // use_scalability_mode_identifier
ParamInfoToStr);
TEST_P(Vp9Test, NonFlexMode) {
TestVp9NonFlexMode(params_, use_scalability_mode_identifier_);
}
void VideoSendStreamTest::TestVp9NonFlexMode(
const Vp9TestParams& params,
bool use_scalability_mode_identifier) {
static const size_t kNumFramesToSend = 100;
// Set to < kNumFramesToSend and coprime to length of temporal layer
// structures to verify temporal id reset on key frame.
static const int kKeyFrameInterval = 31;
static const int kWidth = kMinVp9SpatialLayerLongSideLength;
static const int kHeight = kMinVp9SpatialLayerShortSideLength;
static const float kGoodBitsPerPixel = 0.1f;
class NonFlexibleMode : public Vp9HeaderObserver {
public:
NonFlexibleMode(const Vp9TestParams& params,
bool use_scalability_mode_identifier)
: Vp9HeaderObserver(params),
use_scalability_mode_identifier_(use_scalability_mode_identifier),
l_field_(params.num_temporal_layers > 1 ||
params.num_spatial_layers > 1) {}
void ModifyVideoConfigsHook(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
encoder_config->codec_type = kVideoCodecVP9;
int bitrate_bps = 0;
for (int sl_idx = 0; sl_idx < params_.num_spatial_layers; ++sl_idx) {
const int width = kWidth << sl_idx;
const int height = kHeight << sl_idx;
const float bpp = kGoodBitsPerPixel / (1 << sl_idx);
bitrate_bps += static_cast<int>(width * height * bpp * 30);
}
encoder_config->max_bitrate_bps = bitrate_bps * 2;
encoder_config->frame_drop_enabled = false;
vp9_settings_.flexibleMode = false;
vp9_settings_.automaticResizeOn = false;
vp9_settings_.keyFrameInterval = kKeyFrameInterval;
if (!use_scalability_mode_identifier_) {
vp9_settings_.numberOfTemporalLayers = params_.num_temporal_layers;
vp9_settings_.numberOfSpatialLayers = params_.num_spatial_layers;
vp9_settings_.interLayerPred = params_.inter_layer_pred;
} else {
absl::optional<ScalabilityMode> mode =
ScalabilityModeFromString(params_.scalability_mode);
encoder_config->simulcast_layers[0].scalability_mode = mode;
EXPECT_TRUE(mode.has_value());
}
}
int GetRequiredDivisibility() const {
ScalableVideoController::StreamLayersConfig config =
GetScalabilityConfig();
int required_divisibility = 1;
for (int sl_idx = 0; sl_idx < config.num_spatial_layers; ++sl_idx) {
required_divisibility = cricket::LeastCommonMultiple(
required_divisibility, config.scaling_factor_den[sl_idx]);
}
return required_divisibility;
}
void ModifyVideoCaptureStartResolution(int* width,
int* height,
int* frame_rate) override {
expected_width_ = kWidth << (params_.num_spatial_layers - 1);
expected_height_ = kHeight << (params_.num_spatial_layers - 1);
*width = expected_width_;
*height = expected_height_;
// Top layer may be adjusted to ensure evenly divided layers.
int divisibility = GetRequiredDivisibility();
expected_width_ -= (expected_width_ % divisibility);
expected_height_ -= (expected_height_ % divisibility);
}
void InspectHeader(const RTPVideoHeaderVP9& vp9) override {
bool ss_data_expected = !vp9.inter_pic_predicted &&
vp9.beginning_of_frame &&
!vp9.inter_layer_predicted;
EXPECT_EQ(ss_data_expected, vp9.ss_data_available);
bool is_key_frame = frames_sent_ % kKeyFrameInterval == 0;
if (params_.num_spatial_layers > 1) {
switch (params_.inter_layer_pred) {
case InterLayerPredMode::kOff:
EXPECT_FALSE(vp9.inter_layer_predicted);
break;
case InterLayerPredMode::kOn:
EXPECT_EQ(vp9.spatial_idx > 0, vp9.inter_layer_predicted);
break;
case InterLayerPredMode::kOnKeyPic:
EXPECT_EQ(is_key_frame && vp9.spatial_idx > 0,
vp9.inter_layer_predicted);
break;
}
} else {
EXPECT_FALSE(vp9.inter_layer_predicted);
}
EXPECT_EQ(is_key_frame, !vp9.inter_pic_predicted);
if (IsNewPictureId(vp9)) {
if (params_.num_temporal_layers == 1 &&
params_.num_spatial_layers == 1) {
EXPECT_EQ(kNoSpatialIdx, vp9.spatial_idx);
} else {
EXPECT_EQ(0, vp9.spatial_idx);
}
if (params_.num_spatial_layers > 1)
EXPECT_EQ(params_.num_spatial_layers - 1, last_vp9_.spatial_idx);
}
VerifyFixedTemporalLayerStructure(
vp9, l_field_ ? params_.num_temporal_layers : 0);
if (frames_sent_ > kNumFramesToSend)
observation_complete_.Set();
}
const bool use_scalability_mode_identifier_;
const bool l_field_;
private:
void ModifySenderBitrateConfig(
BitrateConstraints* bitrate_config) override {
const int kBitrateBps = 800000;
bitrate_config->min_bitrate_bps = kBitrateBps;
bitrate_config->start_bitrate_bps = kBitrateBps;
}
} test(params, use_scalability_mode_identifier);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, Vp9NonFlexModeSmallResolution) {
static const size_t kNumFramesToSend = 50;
static const int kWidth = 4;
static const int kHeight = 4;
class NonFlexibleModeResolution : public Vp9HeaderObserver {
public:
explicit NonFlexibleModeResolution(const Vp9TestParams& params)
: Vp9HeaderObserver(params) {}
private:
void ModifyVideoConfigsHook(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
encoder_config->codec_type = kVideoCodecVP9;
vp9_settings_.flexibleMode = false;
vp9_settings_.numberOfTemporalLayers = params_.num_temporal_layers;
vp9_settings_.numberOfSpatialLayers = params_.num_spatial_layers;
vp9_settings_.interLayerPred = params_.inter_layer_pred;
}
void InspectHeader(const RTPVideoHeaderVP9& vp9_header) override {
if (frames_sent_ > kNumFramesToSend)
observation_complete_.Set();
}
void ModifyVideoCaptureStartResolution(int* width,
int* height,
int* frame_rate) override {
expected_width_ = kWidth;
expected_height_ = kHeight;
*width = kWidth;
*height = kHeight;
}
};
Vp9TestParams params{"L1T1", 1, 1, InterLayerPredMode::kOn};
NonFlexibleModeResolution test(params);
RunBaseTest(&test);
}
#if defined(WEBRTC_ANDROID)
// Crashes on Android; bugs.webrtc.org/7401
#define MAYBE_Vp9FlexModeRefCount DISABLED_Vp9FlexModeRefCount
#else
// TODO(webrtc:9270): Support of flexible mode is temporarily disabled. Enable
// the test after webrtc:9270 is implemented.
#define MAYBE_Vp9FlexModeRefCount DISABLED_Vp9FlexModeRefCount
// #define MAYBE_Vp9FlexModeRefCount Vp9FlexModeRefCount
#endif
TEST_F(VideoSendStreamTest, MAYBE_Vp9FlexModeRefCount) {
class FlexibleMode : public Vp9HeaderObserver {
public:
explicit FlexibleMode(const Vp9TestParams& params)
: Vp9HeaderObserver(params) {}
private:
void ModifyVideoConfigsHook(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
encoder_config->codec_type = kVideoCodecVP9;
encoder_config->content_type = VideoEncoderConfig::ContentType::kScreen;
vp9_settings_.flexibleMode = true;
vp9_settings_.numberOfTemporalLayers = params_.num_temporal_layers;
vp9_settings_.numberOfSpatialLayers = params_.num_spatial_layers;
vp9_settings_.interLayerPred = params_.inter_layer_pred;
}
void InspectHeader(const RTPVideoHeaderVP9& vp9_header) override {
EXPECT_TRUE(vp9_header.flexible_mode);
EXPECT_EQ(kNoTl0PicIdx, vp9_header.tl0_pic_idx);
if (vp9_header.inter_pic_predicted) {
EXPECT_GT(vp9_header.num_ref_pics, 0u);
observation_complete_.Set();
}
}
};
Vp9TestParams params{"L2T1", 2, 1, InterLayerPredMode::kOn};
FlexibleMode test(params);
RunBaseTest(&test);
}
#endif // defined(RTC_ENABLE_VP9)
void VideoSendStreamTest::TestRequestSourceRotateVideo(
bool support_orientation_ext) {
CreateSenderCall();
test::NullTransport transport;
CreateSendConfig(1, 0, 0, &transport);
GetVideoSendConfig()->rtp.extensions.clear();
if (support_orientation_ext) {
GetVideoSendConfig()->rtp.extensions.push_back(
RtpExtension(RtpExtension::kVideoRotationUri, 1));
}
CreateVideoStreams();
test::FrameForwarder forwarder;
GetVideoSendStream()->SetSource(&forwarder,
DegradationPreference::MAINTAIN_FRAMERATE);
EXPECT_TRUE(forwarder.sink_wants().rotation_applied !=
support_orientation_ext);
DestroyStreams();
}
TEST_F(VideoSendStreamTest,
RequestSourceRotateIfVideoOrientationExtensionNotSupported) {
TestRequestSourceRotateVideo(false);
}
TEST_F(VideoSendStreamTest,
DoNotRequestsRotationIfVideoOrientationExtensionSupported) {
TestRequestSourceRotateVideo(true);
}
TEST_F(VideoSendStreamTest, EncoderConfigMaxFramerateReportedToSource) {
static const int kMaxFps = 22;
class FpsObserver : public test::SendTest,
public test::FrameGeneratorCapturer::SinkWantsObserver {
public:
FpsObserver() : SendTest(kDefaultTimeout) {}
void OnFrameGeneratorCapturerCreated(
test::FrameGeneratorCapturer* frame_generator_capturer) override {
frame_generator_capturer->SetSinkWantsObserver(this);
}
void OnSinkWantsChanged(rtc::VideoSinkInterface<VideoFrame>* sink,
const rtc::VideoSinkWants& wants) override {
if (wants.max_framerate_fps == kMaxFps)
observation_complete_.Set();
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
encoder_config->simulcast_layers[0].max_framerate = kMaxFps;
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for fps to be reported.";
}
} test;
RunBaseTest(&test);
}
// This test verifies that overhead is removed from the bandwidth estimate by
// testing that the maximum possible target payload rate is smaller than the
// maximum bandwidth estimate by the overhead rate.
TEST_F(VideoSendStreamTest, RemoveOverheadFromBandwidth) {
class RemoveOverheadFromBandwidthTest : public test::EndToEndTest,
public test::FakeEncoder {
public:
explicit RemoveOverheadFromBandwidthTest(TaskQueueBase* task_queue)
: EndToEndTest(test::CallTest::kDefaultTimeout),
FakeEncoder(Clock::GetRealTimeClock()),
task_queue_(task_queue),
encoder_factory_(this),
call_(nullptr),
max_bitrate_bps_(0),
first_packet_sent_(false) {}
void SetRates(const RateControlParameters& parameters) override {
MutexLock lock(&mutex_);
// Wait for the first sent packet so that videosendstream knows
// rtp_overhead.
if (first_packet_sent_) {
max_bitrate_bps_ = parameters.bitrate.get_sum_bps();
bitrate_changed_event_.Set();
}
return FakeEncoder::SetRates(parameters);
}
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
call_ = sender_call;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
send_config->rtp.max_packet_size = 1200;
send_config->encoder_settings.encoder_factory = &encoder_factory_;
EXPECT_FALSE(send_config->rtp.extensions.empty());
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
MutexLock lock(&mutex_);
first_packet_sent_ = true;
return SEND_PACKET;
}
void PerformTest() override {
BitrateConstraints bitrate_config;
constexpr int kStartBitrateBps = 60000;
constexpr int kMaxBitrateBps = 60000;
constexpr int kMinBitrateBps = 10000;
bitrate_config.start_bitrate_bps = kStartBitrateBps;
bitrate_config.max_bitrate_bps = kMaxBitrateBps;
bitrate_config.min_bitrate_bps = kMinBitrateBps;
SendTask(task_queue_, [this, &bitrate_config]() {
call_->GetTransportControllerSend()->SetSdpBitrateParameters(
bitrate_config);
call_->GetTransportControllerSend()->OnTransportOverheadChanged(40);
});
// At a bitrate of 60kbps with a packet size of 1200B video and an
// overhead of 40B per packet video produces 2240bps overhead.
// So the encoder BW should be set to 57760bps.
EXPECT_TRUE(
bitrate_changed_event_.Wait(VideoSendStreamTest::kDefaultTimeout));
{
MutexLock lock(&mutex_);
EXPECT_LE(max_bitrate_bps_, 57760u);
}
}
private:
TaskQueueBase* const task_queue_;
test::VideoEncoderProxyFactory encoder_factory_;
Call* call_;
Mutex mutex_;
uint32_t max_bitrate_bps_ RTC_GUARDED_BY(&mutex_);
bool first_packet_sent_ RTC_GUARDED_BY(&mutex_);
rtc::Event bitrate_changed_event_;
} test(task_queue());
RunBaseTest(&test);
}
class PacingFactorObserver : public test::SendTest {
public:
PacingFactorObserver(bool configure_send_side,
absl::optional<float> expected_pacing_factor)
: test::SendTest(VideoSendStreamTest::kDefaultTimeout),
configure_send_side_(configure_send_side),
expected_pacing_factor_(expected_pacing_factor) {}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
// Check if send-side bwe extension is already present, and remove it if
// it is not desired.
bool has_send_side = false;
for (auto it = send_config->rtp.extensions.begin();
it != send_config->rtp.extensions.end(); ++it) {
if (it->uri == RtpExtension::kTransportSequenceNumberUri) {
if (configure_send_side_) {
has_send_side = true;
} else {
send_config->rtp.extensions.erase(it);
}
break;
}
}
if (configure_send_side_ && !has_send_side) {
rtc::UniqueNumberGenerator<int> unique_id_generator;
unique_id_generator.AddKnownId(0); // First valid RTP extension ID is 1.
for (const RtpExtension& extension : send_config->rtp.extensions) {
unique_id_generator.AddKnownId(extension.id);
}
// Want send side, not present by default, so add it.
send_config->rtp.extensions.emplace_back(
RtpExtension::kTransportSequenceNumberUri, unique_id_generator());
}
// ALR only enabled for screenshare.
encoder_config->content_type = VideoEncoderConfig::ContentType::kScreen;
}
void OnVideoStreamsCreated(VideoSendStream* send_stream,
const std::vector<VideoReceiveStreamInterface*>&
receive_streams) override {
auto internal_send_peer = test::VideoSendStreamPeer(send_stream);
// Video streams created, check that pacing factor is correctly configured.
EXPECT_EQ(expected_pacing_factor_,
internal_send_peer.GetPacingFactorOverride());
observation_complete_.Set();
}
void PerformTest() override {
EXPECT_TRUE(Wait()) << "Timed out while waiting for stream creation.";
}
private:
const bool configure_send_side_;
const absl::optional<float> expected_pacing_factor_;
};
std::string GetAlrProbingExperimentString() {
return std::string(
AlrExperimentSettings::kScreenshareProbingBweExperimentName) +
"/1.0,2875,80,40,-60,3/";
}
const float kAlrProbingExperimentPaceMultiplier = 1.0f;
TEST_F(VideoSendStreamTest, AlrConfiguredWhenSendSideOn) {
test::ScopedFieldTrials alr_experiment(GetAlrProbingExperimentString());
// Send-side bwe on, use pacing factor from `kAlrProbingExperiment` above.
PacingFactorObserver test_with_send_side(true,
kAlrProbingExperimentPaceMultiplier);
RunBaseTest(&test_with_send_side);
}
TEST_F(VideoSendStreamTest, AlrNotConfiguredWhenSendSideOff) {
test::ScopedFieldTrials alr_experiment(GetAlrProbingExperimentString());
// Send-side bwe off, use configuration should not be overridden.
PacingFactorObserver test_without_send_side(false, absl::nullopt);
RunBaseTest(&test_without_send_side);
}
// Test class takes as argument a function pointer to reset the send
// stream and call OnVideoStreamsCreated. This is necessary since you cannot
// change the content type of a VideoSendStream, you need to recreate it.
// Stopping and recreating the stream can only be done on the main thread and in
// the context of VideoSendStreamTest (not BaseTest). The test switches from
// realtime to screenshare and back.
template <typename T>
class ContentSwitchTest : public test::SendTest {
public:
enum class StreamState {
kBeforeSwitch = 0,
kInScreenshare = 1,
kAfterSwitchBack = 2,
};
static const uint32_t kMinPacketsToSend = 50;
explicit ContentSwitchTest(T* stream_reset_fun, TaskQueueBase* task_queue)
: SendTest(test::CallTest::kDefaultTimeout),
call_(nullptr),
state_(StreamState::kBeforeSwitch),
send_stream_(nullptr),
send_stream_config_(nullptr),
packets_sent_(0),
stream_resetter_(stream_reset_fun),
task_queue_(task_queue) {
RTC_DCHECK(stream_resetter_);
}
void OnVideoStreamsCreated(VideoSendStream* send_stream,
const std::vector<VideoReceiveStreamInterface*>&
receive_streams) override {
MutexLock lock(&mutex_);
send_stream_ = send_stream;
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
RTC_DCHECK_EQ(1, encoder_config->number_of_streams);
encoder_config->min_transmit_bitrate_bps = 0;
encoder_config->content_type =
VideoEncoderConfig::ContentType::kRealtimeVideo;
send_stream_config_ = send_config->Copy();
encoder_config_ = encoder_config->Copy();
}
void OnCallsCreated(Call* sender_call, Call* receiver_call) override {
call_ = sender_call;
}
void OnStreamsStopped() override {
MutexLock lock(&mutex_);
done_ = true;
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
task_queue_->PostTask([this]() {
MutexLock lock(&mutex_);
if (done_)
return;
auto internal_send_peer = test::VideoSendStreamPeer(send_stream_);
float pacing_factor =
internal_send_peer.GetPacingFactorOverride().value_or(0.0f);
float expected_pacing_factor = 1.1; // Strict pacing factor.
VideoSendStream::Stats stats = send_stream_->GetStats();
if (stats.content_type == webrtc::VideoContentType::SCREENSHARE) {
expected_pacing_factor = 1.0f; // Currently used pacing factor in ALR.
}
EXPECT_NEAR(expected_pacing_factor, pacing_factor, 1e-6);
// Wait until at least kMinPacketsToSend packets to be sent, so that
// some frames would be encoded.
if (++packets_sent_ < kMinPacketsToSend)
return;
if (state_ != StreamState::kAfterSwitchBack) {
// We've sent kMinPacketsToSend packets, switch the content type and
// move move to the next state. Note that we need to recreate the stream
// if changing content type.
packets_sent_ = 0;
if (encoder_config_.content_type ==
VideoEncoderConfig::ContentType::kRealtimeVideo) {
encoder_config_.content_type =
VideoEncoderConfig::ContentType::kScreen;
} else {
encoder_config_.content_type =
VideoEncoderConfig::ContentType::kRealtimeVideo;
}
switch (state_) {
case StreamState::kBeforeSwitch:
state_ = StreamState::kInScreenshare;
break;
case StreamState::kInScreenshare:
state_ = StreamState::kAfterSwitchBack;
break;
case StreamState::kAfterSwitchBack:
RTC_DCHECK_NOTREACHED();
break;
}
content_switch_event_.Set();
return;
}
observation_complete_.Set();
});
return SEND_PACKET;
}
void PerformTest() override {
while (GetStreamState() != StreamState::kAfterSwitchBack) {
ASSERT_TRUE(content_switch_event_.Wait(test::CallTest::kDefaultTimeout));
(*stream_resetter_)(send_stream_config_, encoder_config_, this);
}
ASSERT_TRUE(Wait())
<< "Timed out waiting for a frame sent after switch back";
}
private:
StreamState GetStreamState() {
MutexLock lock(&mutex_);
return state_;
}
Mutex mutex_;
rtc::Event content_switch_event_;
Call* call_;
bool done_ RTC_GUARDED_BY(mutex_) = false;
StreamState state_ RTC_GUARDED_BY(mutex_);
VideoSendStream* send_stream_ RTC_GUARDED_BY(mutex_);
VideoSendStream::Config send_stream_config_;
VideoEncoderConfig encoder_config_;
uint32_t packets_sent_ RTC_GUARDED_BY(mutex_);
T* stream_resetter_;
TaskQueueBase* task_queue_;
};
TEST_F(VideoSendStreamTest, SwitchesToScreenshareAndBack) {
auto reset_fun = [this](const VideoSendStream::Config& send_stream_config,
const VideoEncoderConfig& encoder_config,
test::BaseTest* test) {
SendTask(task_queue(),
[this, &send_stream_config, &encoder_config, &test]() {
Stop();
DestroyVideoSendStreams();
SetVideoSendConfig(send_stream_config);
SetVideoEncoderConfig(encoder_config);
CreateVideoSendStreams();
SetVideoDegradation(DegradationPreference::MAINTAIN_RESOLUTION);
test->OnVideoStreamsCreated(GetVideoSendStream(),
video_receive_streams_);
Start();
});
};
ContentSwitchTest<decltype(reset_fun)> test(&reset_fun, task_queue());
RunBaseTest(&test);
}
void VideoSendStreamTest::TestTemporalLayers(
VideoEncoderFactory* encoder_factory,
const std::string& payload_name,
const std::vector<int>& num_temporal_layers,
const std::vector<ScalabilityMode>& scalability_mode) {
static constexpr int kMaxBitrateBps = 1000000;
static constexpr int kMinFramesToObservePerStream = 8;
class TemporalLayerObserver
: public test::EndToEndTest,
public test::FrameGeneratorCapturer::SinkWantsObserver {
public:
TemporalLayerObserver(VideoEncoderFactory* encoder_factory,
const std::string& payload_name,
const std::vector<int>& num_temporal_layers,
const std::vector<ScalabilityMode>& scalability_mode)
: EndToEndTest(kDefaultTimeout),
encoder_factory_(encoder_factory),
payload_name_(payload_name),
num_temporal_layers_(num_temporal_layers),
scalability_mode_(scalability_mode),
depacketizer_(CreateVideoRtpDepacketizer(
PayloadStringToCodecType(payload_name))) {}
private:
void OnFrameGeneratorCapturerCreated(
test::FrameGeneratorCapturer* frame_generator_capturer) override {
frame_generator_capturer->ChangeResolution(640, 360);
}
void OnSinkWantsChanged(rtc::VideoSinkInterface<VideoFrame>* sink,
const rtc::VideoSinkWants& wants) override {}
void ModifySenderBitrateConfig(
BitrateConstraints* bitrate_config) override {
bitrate_config->start_bitrate_bps = kMaxBitrateBps / 2;
}
size_t GetNumVideoStreams() const override {
if (scalability_mode_.empty()) {
return num_temporal_layers_.size();
} else {
return scalability_mode_.size();
}
}
void ModifyVideoConfigs(
VideoSendStream::Config* send_config,
std::vector<VideoReceiveStreamInterface::Config>* receive_configs,
VideoEncoderConfig* encoder_config) override {
webrtc::VideoEncoder::EncoderInfo encoder_info;
send_config->encoder_settings.encoder_factory = encoder_factory_;
send_config->rtp.payload_name = payload_name_;
send_config->rtp.payload_type = test::CallTest::kVideoSendPayloadType;
encoder_config->video_format.name = payload_name_;
encoder_config->codec_type = PayloadStringToCodecType(payload_name_);
encoder_config->video_stream_factory =
rtc::make_ref_counted<cricket::EncoderStreamFactory>(
payload_name_, /*max_qp=*/56, /*is_screenshare=*/false,
/*conference_mode=*/false, encoder_info);
encoder_config->max_bitrate_bps = kMaxBitrateBps;
if (absl::EqualsIgnoreCase(payload_name_, "VP9")) {
encoder_config->encoder_specific_settings = rtc::make_ref_counted<
VideoEncoderConfig::Vp9EncoderSpecificSettings>(
VideoEncoder::GetDefaultVp9Settings());
}
if (scalability_mode_.empty()) {
for (size_t i = 0; i < num_temporal_layers_.size(); ++i) {
VideoStream& stream = encoder_config->simulcast_layers[i];
stream.num_temporal_layers = num_temporal_layers_[i];
configured_num_temporal_layers_[send_config->rtp.ssrcs[i]] =
num_temporal_layers_[i];
}
} else {
for (size_t i = 0; i < scalability_mode_.size(); ++i) {
VideoStream& stream = encoder_config->simulcast_layers[i];
stream.scalability_mode = scalability_mode_[i];
configured_num_temporal_layers_[send_config->rtp.ssrcs[i]] =
ScalabilityModeToNumTemporalLayers(scalability_mode_[i]);
}
}
}
struct ParsedPacket {
uint32_t timestamp;
uint32_t ssrc;
int temporal_idx;
};
bool ParsePayload(const uint8_t* packet,
size_t length,
ParsedPacket& parsed) const {
RtpPacket rtp_packet;
EXPECT_TRUE(rtp_packet.Parse(packet, length));
if (rtp_packet.payload_size() == 0) {
return false; // Padding packet.
}
parsed.timestamp = rtp_packet.Timestamp();
parsed.ssrc = rtp_packet.Ssrc();
absl::optional<VideoRtpDepacketizer::ParsedRtpPayload> parsed_payload =
depacketizer_->Parse(rtp_packet.PayloadBuffer());
EXPECT_TRUE(parsed_payload);
if (const auto* vp8_header = absl::get_if<RTPVideoHeaderVP8>(
&parsed_payload->video_header.video_type_header)) {
parsed.temporal_idx = vp8_header->temporalIdx;
} else if (const auto* vp9_header = absl::get_if<RTPVideoHeaderVP9>(
&parsed_payload->video_header.video_type_header)) {
parsed.temporal_idx = vp9_header->temporal_idx;
} else {
RTC_DCHECK_NOTREACHED();
}
return true;
}
Action OnSendRtp(const uint8_t* packet, size_t length) override {
ParsedPacket parsed;
if (!ParsePayload(packet, length, parsed))
return SEND_PACKET;
uint32_t ssrc = parsed.ssrc;
int temporal_idx =
parsed.temporal_idx == kNoTemporalIdx ? 0 : parsed.temporal_idx;
max_observed_tl_idxs_[ssrc] =
std::max(temporal_idx, max_observed_tl_idxs_[ssrc]);
if (last_observed_packet_.count(ssrc) == 0 ||
parsed.timestamp != last_observed_packet_[ssrc].timestamp) {
num_observed_frames_[ssrc]++;
}
last_observed_packet_[ssrc] = parsed;
if (HighestTemporalLayerSentPerStream())
observation_complete_.Set();
return SEND_PACKET;
}
bool HighestTemporalLayerSentPerStream() const {
if (num_observed_frames_.size() !=
configured_num_temporal_layers_.size()) {
return false;
}
for (const auto& num_frames : num_observed_frames_) {
if (num_frames.second < kMinFramesToObservePerStream) {
return false;
}
}
if (max_observed_tl_idxs_.size() !=
configured_num_temporal_layers_.size()) {
return false;
}
for (const auto& max_tl_idx : max_observed_tl_idxs_) {
uint32_t ssrc = max_tl_idx.first;
int configured_num_tls =
configured_num_temporal_layers_.find(ssrc)->second;
if (max_tl_idx.second != configured_num_tls - 1)
return false;
}
return true;
}
void PerformTest() override { EXPECT_TRUE(Wait()); }
VideoEncoderFactory* const encoder_factory_;
const std::string payload_name_;
const std::vector<int> num_temporal_layers_;
const std::vector<ScalabilityMode> scalability_mode_;
const std::unique_ptr<VideoRtpDepacketizer> depacketizer_;
// Mapped by SSRC.
std::map<uint32_t, int> configured_num_temporal_layers_;
std::map<uint32_t, int> max_observed_tl_idxs_;
std::map<uint32_t, int> num_observed_frames_;
std::map<uint32_t, ParsedPacket> last_observed_packet_;
} test(encoder_factory, payload_name, num_temporal_layers, scalability_mode);
RunBaseTest(&test);
}
TEST_F(VideoSendStreamTest, TestTemporalLayersVp8) {
InternalEncoderFactory internal_encoder_factory;
test::FunctionVideoEncoderFactory encoder_factory(
[&internal_encoder_factory]() {
return std::make_unique<SimulcastEncoderAdapter>(
&internal_encoder_factory, SdpVideoFormat("VP8"));
});
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{2},
/*scalability_mode=*/{});
}
TEST_F(VideoSendStreamTest, TestTemporalLayersVp8Simulcast) {
InternalEncoderFactory internal_encoder_factory;
test::FunctionVideoEncoderFactory encoder_factory(
[&internal_encoder_factory]() {
return std::make_unique<SimulcastEncoderAdapter>(
&internal_encoder_factory, SdpVideoFormat("VP8"));
});
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{2, 2},
/*scalability_mode=*/{});
}
TEST_F(VideoSendStreamTest, TestTemporalLayersVp8SimulcastWithDifferentNumTls) {
InternalEncoderFactory internal_encoder_factory;
test::FunctionVideoEncoderFactory encoder_factory(
[&internal_encoder_factory]() {
return std::make_unique<SimulcastEncoderAdapter>(
&internal_encoder_factory, SdpVideoFormat("VP8"));
});
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{3, 1},
/*scalability_mode=*/{});
}
TEST_F(VideoSendStreamTest, TestTemporalLayersVp8SimulcastWithoutSimAdapter) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{2, 2},
/*scalability_mode=*/{});
}
TEST_F(VideoSendStreamTest, TestScalabilityModeVp8L1T2) {
InternalEncoderFactory internal_encoder_factory;
test::FunctionVideoEncoderFactory encoder_factory(
[&internal_encoder_factory]() {
return std::make_unique<SimulcastEncoderAdapter>(
&internal_encoder_factory, SdpVideoFormat("VP8"));
});
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{}, {ScalabilityMode::kL1T2});
}
TEST_F(VideoSendStreamTest, TestScalabilityModeVp8Simulcast) {
InternalEncoderFactory internal_encoder_factory;
test::FunctionVideoEncoderFactory encoder_factory(
[&internal_encoder_factory]() {
return std::make_unique<SimulcastEncoderAdapter>(
&internal_encoder_factory, SdpVideoFormat("VP8"));
});
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{},
{ScalabilityMode::kL1T2, ScalabilityMode::kL1T2});
}
TEST_F(VideoSendStreamTest, TestScalabilityModeVp8SimulcastWithDifferentMode) {
InternalEncoderFactory internal_encoder_factory;
test::FunctionVideoEncoderFactory encoder_factory(
[&internal_encoder_factory]() {
return std::make_unique<SimulcastEncoderAdapter>(
&internal_encoder_factory, SdpVideoFormat("VP8"));
});
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{},
{ScalabilityMode::kL1T3, ScalabilityMode::kL1T1});
}
TEST_F(VideoSendStreamTest, TestScalabilityModeVp8SimulcastWithoutSimAdapter) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP8Encoder::Create(); });
TestTemporalLayers(&encoder_factory, "VP8",
/*num_temporal_layers=*/{},
{ScalabilityMode::kL1T2, ScalabilityMode::kL1T2});
}
TEST_F(VideoSendStreamTest, TestTemporalLayersVp9) {
test::FunctionVideoEncoderFactory encoder_factory(
[]() { return VP9Encoder::Create(); });
TestTemporalLayers(&encoder_factory, "VP9",
/*num_temporal_layers=*/{2},
/*scalability_mode=*/{});
}
} // namespace webrtc
|