summaryrefslogtreecommitdiffstats
path: root/dom/media/mediasource/TrackBuffersManager.cpp
blob: 779e1bd9d11ac26c4e9ae59b56142b5243f02ea8 (plain)
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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "TrackBuffersManager.h"
#include "ContainerParser.h"
#include "MediaSourceDemuxer.h"
#include "MediaSourceUtils.h"
#include "SourceBuffer.h"
#include "SourceBufferResource.h"
#include "SourceBufferTask.h"
#include "WebMDemuxer.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/Preferences.h"
#include "mozilla/ProfilerLabels.h"
#include "mozilla/ProfilerMarkers.h"
#include "mozilla/StaticPrefs_media.h"
#include "nsMimeTypes.h"

#ifdef MOZ_FMP4
#  include "MP4Demuxer.h"
#endif

#include <limits>

extern mozilla::LogModule* GetMediaSourceLog();

#define MSE_DEBUG(arg, ...)                                              \
  DDMOZ_LOG(GetMediaSourceLog(), mozilla::LogLevel::Debug, "::%s: " arg, \
            __func__, ##__VA_ARGS__)
#define MSE_DEBUGV(arg, ...)                                               \
  DDMOZ_LOG(GetMediaSourceLog(), mozilla::LogLevel::Verbose, "::%s: " arg, \
            __func__, ##__VA_ARGS__)

mozilla::LogModule* GetMediaSourceSamplesLog() {
  static mozilla::LazyLogModule sLogModule("MediaSourceSamples");
  return sLogModule;
}
#define SAMPLE_DEBUG(arg, ...)                                    \
  DDMOZ_LOG(GetMediaSourceSamplesLog(), mozilla::LogLevel::Debug, \
            "::%s: " arg, __func__, ##__VA_ARGS__)

namespace mozilla {

using dom::SourceBufferAppendMode;
using media::TimeInterval;
using media::TimeIntervals;
using media::TimeUnit;
typedef SourceBufferTask::AppendBufferResult AppendBufferResult;
typedef SourceBufferAttributes::AppendState AppendState;

static const char* AppendStateToStr(AppendState aState) {
  switch (aState) {
    case AppendState::WAITING_FOR_SEGMENT:
      return "WAITING_FOR_SEGMENT";
    case AppendState::PARSING_INIT_SEGMENT:
      return "PARSING_INIT_SEGMENT";
    case AppendState::PARSING_MEDIA_SEGMENT:
      return "PARSING_MEDIA_SEGMENT";
    default:
      return "IMPOSSIBLE";
  }
}

static Atomic<uint32_t> sStreamSourceID(0u);

class DispatchKeyNeededEvent : public Runnable {
 public:
  DispatchKeyNeededEvent(MediaSourceDecoder* aDecoder,
                         const nsTArray<uint8_t>& aInitData,
                         const nsString& aInitDataType)
      : Runnable("DispatchKeyNeededEvent"),
        mDecoder(aDecoder),
        mInitData(aInitData.Clone()),
        mInitDataType(aInitDataType) {}
  NS_IMETHOD Run() override {
    // Note: Null check the owner, as the decoder could have been shutdown
    // since this event was dispatched.
    MediaDecoderOwner* owner = mDecoder->GetOwner();
    if (owner) {
      owner->DispatchEncrypted(mInitData, mInitDataType);
    }
    mDecoder = nullptr;
    return NS_OK;
  }

 private:
  RefPtr<MediaSourceDecoder> mDecoder;
  nsTArray<uint8_t> mInitData;
  nsString mInitDataType;
};

TrackBuffersManager::TrackBuffersManager(MediaSourceDecoder* aParentDecoder,
                                         const MediaContainerType& aType)
    : mBufferFull(false),
      mFirstInitializationSegmentReceived(false),
      mChangeTypeReceived(false),
      mNewMediaSegmentStarted(false),
      mActiveTrack(false),
      mType(aType),
      mParser(ContainerParser::CreateForMIMEType(aType)),
      mProcessedInput(0),
      mParentDecoder(new nsMainThreadPtrHolder<MediaSourceDecoder>(
          "TrackBuffersManager::mParentDecoder", aParentDecoder,
          false /* strict */)),
      mAbstractMainThread(aParentDecoder->AbstractMainThread()),
      mEnded(false),
      mVideoEvictionThreshold(Preferences::GetUint(
          "media.mediasource.eviction_threshold.video", 100 * 1024 * 1024)),
      mAudioEvictionThreshold(Preferences::GetUint(
          "media.mediasource.eviction_threshold.audio", 20 * 1024 * 1024)),
      mEvictionState(EvictionState::NO_EVICTION_NEEDED),
      mMutex("TrackBuffersManager"),
      mTaskQueue(aParentDecoder->GetDemuxer()->GetTaskQueue()),
      mTaskQueueCapability(Some(EventTargetCapability{mTaskQueue.get()})) {
  MOZ_ASSERT(NS_IsMainThread(), "Must be instanciated on the main thread");
  DDLINKCHILD("parser", mParser.get());
}

TrackBuffersManager::~TrackBuffersManager() { ShutdownDemuxers(); }

RefPtr<TrackBuffersManager::AppendPromise> TrackBuffersManager::AppendData(
    already_AddRefed<MediaByteBuffer> aData,
    const SourceBufferAttributes& aAttributes) {
  MOZ_ASSERT(NS_IsMainThread());
  RefPtr<MediaByteBuffer> data(aData);
  MSE_DEBUG("Appending %zu bytes", data->Length());

  mEnded = false;

  return InvokeAsync(static_cast<AbstractThread*>(GetTaskQueueSafe().get()),
                     this, __func__, &TrackBuffersManager::DoAppendData,
                     data.forget(), aAttributes);
}

RefPtr<TrackBuffersManager::AppendPromise> TrackBuffersManager::DoAppendData(
    already_AddRefed<MediaByteBuffer> aData,
    const SourceBufferAttributes& aAttributes) {
  RefPtr<AppendBufferTask> task =
      new AppendBufferTask(std::move(aData), aAttributes);
  RefPtr<AppendPromise> p = task->mPromise.Ensure(__func__);
  QueueTask(task);

  return p;
}

void TrackBuffersManager::QueueTask(SourceBufferTask* aTask) {
  // The source buffer is a wrapped native, it would be unlinked twice and so
  // the TrackBuffersManager::Detach() would also be called twice. Since the
  // detach task has been done before, we could ignore this task.
  RefPtr<TaskQueue> taskQueue = GetTaskQueueSafe();
  if (!taskQueue) {
    MOZ_ASSERT(aTask->GetType() == SourceBufferTask::Type::Detach,
               "only detach task could happen here!");
    MSE_DEBUG("Could not queue the task '%s' without task queue",
              aTask->GetTypeName());
    return;
  }

  if (!taskQueue->IsCurrentThreadIn()) {
    nsresult rv =
        taskQueue->Dispatch(NewRunnableMethod<RefPtr<SourceBufferTask>>(
            "TrackBuffersManager::QueueTask", this,
            &TrackBuffersManager::QueueTask, aTask));
    MOZ_DIAGNOSTIC_ASSERT(NS_SUCCEEDED(rv));
    Unused << rv;
    return;
  }
  mQueue.Push(aTask);
  ProcessTasks();
}

void TrackBuffersManager::ProcessTasks() {
  // ProcessTask is always called OnTaskQueue, however it is possible that it is
  // called once again after a first Detach task has run, in which case
  // mTaskQueue would be null.
  // This can happen under two conditions:
  // 1- Two Detach tasks were queued in a row due to a double cycle collection.
  // 2- An call to ProcessTasks() had queued another run of ProcessTasks while
  //    a Detach task is pending.
  // We handle these two cases by aborting early.
  // A second Detach task was queued, prior the first one running, ignore it.
  if (!mTaskQueue) {
    RefPtr<SourceBufferTask> task = mQueue.Pop();
    if (!task) {
      return;
    }
    MOZ_RELEASE_ASSERT(task->GetType() == SourceBufferTask::Type::Detach,
                       "only detach task could happen here!");
    MSE_DEBUG("Could not process the task '%s' after detached",
              task->GetTypeName());
    return;
  }

  mTaskQueueCapability->AssertOnCurrentThread();
  typedef SourceBufferTask::Type Type;

  if (mCurrentTask) {
    // Already have a task pending. ProcessTask will be scheduled once the
    // current task complete.
    return;
  }
  RefPtr<SourceBufferTask> task = mQueue.Pop();
  if (!task) {
    // nothing to do.
    return;
  }

  MSE_DEBUG("Process task '%s'", task->GetTypeName());
  switch (task->GetType()) {
    case Type::AppendBuffer:
      mCurrentTask = task;
      if (!mInputBuffer || mInputBuffer->IsEmpty()) {
        // Note: we reset mInputBuffer here to ensure it doesn't grow unbounded.
        mInputBuffer.reset();
        mInputBuffer = Some(MediaSpan(task->As<AppendBufferTask>()->mBuffer));
      } else {
        // mInputBuffer wasn't empty, so we can't just reset it, but we move
        // the data into a new buffer to clear out data no longer in the span.
        MSE_DEBUG(
            "mInputBuffer not empty during append -- data will be copied to "
            "new buffer. mInputBuffer->Length()=%zu "
            "mInputBuffer->Buffer()->Length()=%zu",
            mInputBuffer->Length(), mInputBuffer->Buffer()->Length());
        const RefPtr<MediaByteBuffer> newBuffer{new MediaByteBuffer()};
        // Set capacity outside of ctor to let us explicitly handle OOM.
        const size_t newCapacity =
            mInputBuffer->Length() +
            task->As<AppendBufferTask>()->mBuffer->Length();
        if (!newBuffer->SetCapacity(newCapacity, fallible)) {
          RejectAppend(NS_ERROR_OUT_OF_MEMORY, __func__);
          return;
        }
        // Use infallible appends as we've already set capacity above.
        newBuffer->AppendElements(mInputBuffer->Elements(),
                                  mInputBuffer->Length());
        newBuffer->AppendElements(*task->As<AppendBufferTask>()->mBuffer);
        mInputBuffer = Some(MediaSpan(newBuffer));
      }
      mSourceBufferAttributes = MakeUnique<SourceBufferAttributes>(
          task->As<AppendBufferTask>()->mAttributes);
      mAppendWindow = TimeInterval(
          TimeUnit::FromSeconds(
              mSourceBufferAttributes->GetAppendWindowStart()),
          TimeUnit::FromSeconds(mSourceBufferAttributes->GetAppendWindowEnd()));
      ScheduleSegmentParserLoop();
      break;
    case Type::RangeRemoval: {
      bool rv = CodedFrameRemoval(task->As<RangeRemovalTask>()->mRange);
      task->As<RangeRemovalTask>()->mPromise.Resolve(rv, __func__);
      break;
    }
    case Type::EvictData:
      DoEvictData(task->As<EvictDataTask>()->mPlaybackTime,
                  task->As<EvictDataTask>()->mSizeToEvict);
      break;
    case Type::Abort:
      // not handled yet, and probably never.
      break;
    case Type::Reset:
      CompleteResetParserState();
      break;
    case Type::Detach:
      mCurrentInputBuffer = nullptr;
      MOZ_DIAGNOSTIC_ASSERT(mQueue.Length() == 0,
                            "Detach task must be the last");
      mVideoTracks.Reset();
      mAudioTracks.Reset();
      ShutdownDemuxers();
      ResetTaskQueue();
      return;
    case Type::ChangeType:
      MOZ_RELEASE_ASSERT(!mCurrentTask);
      MSE_DEBUG("Processing type change from %s -> %s",
                mType.OriginalString().get(),
                task->As<ChangeTypeTask>()->mType.OriginalString().get());
      mType = task->As<ChangeTypeTask>()->mType;
      mChangeTypeReceived = true;
      mInitData = nullptr;
      // A new input buffer will be created once we receive a new init segment.
      // The first segment received after a changeType call must be an init
      // segment.
      mCurrentInputBuffer = nullptr;
      CompleteResetParserState();
      break;
    default:
      NS_WARNING("Invalid Task");
  }
  TaskQueueFromTaskQueue()->Dispatch(
      NewRunnableMethod("TrackBuffersManager::ProcessTasks", this,
                        &TrackBuffersManager::ProcessTasks));
}

// The MSE spec requires that we abort the current SegmentParserLoop
// which is then followed by a call to ResetParserState.
// However due to our asynchronous design this causes inherent difficulties.
// As the spec behaviour is non deterministic anyway, we instead process all
// pending frames found in the input buffer.
void TrackBuffersManager::AbortAppendData() {
  MOZ_ASSERT(NS_IsMainThread());
  MSE_DEBUG("");

  QueueTask(new AbortTask());
}

void TrackBuffersManager::ResetParserState(
    SourceBufferAttributes& aAttributes) {
  MOZ_ASSERT(NS_IsMainThread());
  MSE_DEBUG("");

  // Spec states:
  // 1. If the append state equals PARSING_MEDIA_SEGMENT and the input buffer
  // contains some complete coded frames, then run the coded frame processing
  // algorithm until all of these complete coded frames have been processed.
  // However, we will wait until all coded frames have been processed regardless
  // of the value of append state.
  QueueTask(new ResetTask());

  // ResetParserState has some synchronous steps that much be performed now.
  // The remaining steps will be performed once the ResetTask gets executed.

  // 6. If the mode attribute equals "sequence", then set the group start
  // timestamp to the group end timestamp
  if (aAttributes.GetAppendMode() == SourceBufferAppendMode::Sequence) {
    aAttributes.SetGroupStartTimestamp(aAttributes.GetGroupEndTimestamp());
  }
  // 8. Set append state to WAITING_FOR_SEGMENT.
  aAttributes.SetAppendState(AppendState::WAITING_FOR_SEGMENT);
}

RefPtr<TrackBuffersManager::RangeRemovalPromise>
TrackBuffersManager::RangeRemoval(TimeUnit aStart, TimeUnit aEnd) {
  MOZ_ASSERT(NS_IsMainThread());
  MSE_DEBUG("From %.2f to %.2f", aStart.ToSeconds(), aEnd.ToSeconds());

  mEnded = false;

  return InvokeAsync(static_cast<AbstractThread*>(GetTaskQueueSafe().get()),
                     this, __func__,
                     &TrackBuffersManager::CodedFrameRemovalWithPromise,
                     TimeInterval(aStart, aEnd));
}

TrackBuffersManager::EvictDataResult TrackBuffersManager::EvictData(
    const TimeUnit& aPlaybackTime, int64_t aSize) {
  MOZ_ASSERT(NS_IsMainThread());

  if (aSize > EvictionThreshold()) {
    // We're adding more data than we can hold.
    return EvictDataResult::BUFFER_FULL;
  }
  const int64_t toEvict = GetSize() + aSize - EvictionThreshold();

  const uint32_t canEvict =
      Evictable(HasVideo() ? TrackInfo::kVideoTrack : TrackInfo::kAudioTrack);

  MSE_DEBUG("currentTime=%" PRId64 " buffered=%" PRId64
            "kB, eviction threshold=%" PRId64
            "kB, "
            "evict=%" PRId64 "kB canevict=%" PRIu32 "kB",
            aPlaybackTime.ToMicroseconds(), GetSize() / 1024,
            EvictionThreshold() / 1024, toEvict / 1024, canEvict / 1024);

  if (toEvict <= 0) {
    mEvictionState = EvictionState::NO_EVICTION_NEEDED;
    return EvictDataResult::NO_DATA_EVICTED;
  }

  EvictDataResult result;

  if (mBufferFull && mEvictionState == EvictionState::EVICTION_COMPLETED &&
      canEvict < uint32_t(toEvict)) {
    // Our buffer is currently full. We will make another eviction attempt.
    // However, the current appendBuffer will fail as we can't know ahead of
    // time if the eviction will later succeed.
    result = EvictDataResult::BUFFER_FULL;
  } else {
    mEvictionState = EvictionState::EVICTION_NEEDED;
    result = EvictDataResult::NO_DATA_EVICTED;
  }
  MSE_DEBUG("Reached our size limit, schedule eviction of %" PRId64
            " bytes (%s)",
            toEvict,
            result == EvictDataResult::BUFFER_FULL ? "buffer full"
                                                   : "no data evicted");
  QueueTask(new EvictDataTask(aPlaybackTime, toEvict));

  return result;
}

void TrackBuffersManager::ChangeType(const MediaContainerType& aType) {
  MOZ_ASSERT(NS_IsMainThread());

  QueueTask(new ChangeTypeTask(aType));
}

TimeIntervals TrackBuffersManager::Buffered() const {
  MSE_DEBUG("");

  // http://w3c.github.io/media-source/index.html#widl-SourceBuffer-buffered

  MutexAutoLock mut(mMutex);
  nsTArray<const TimeIntervals*> tracks;
  if (HasVideo()) {
    tracks.AppendElement(&mVideoBufferedRanges);
  }
  if (HasAudio()) {
    tracks.AppendElement(&mAudioBufferedRanges);
  }

  // 2. Let highest end time be the largest track buffer ranges end time across
  // all the track buffers managed by this SourceBuffer object.
  TimeUnit highestEndTime = HighestEndTime(tracks);

  // 3. Let intersection ranges equal a TimeRange object containing a single
  // range from 0 to highest end time.
  TimeIntervals intersection{
      TimeInterval(TimeUnit::FromSeconds(0), highestEndTime)};

  // 4. For each track buffer managed by this SourceBuffer, run the following
  // steps:
  //   1. Let track ranges equal the track buffer ranges for the current track
  //   buffer.
  for (const TimeIntervals* trackRanges : tracks) {
    // 2. If readyState is "ended", then set the end time on the last range in
    // track ranges to highest end time.
    // 3. Let new intersection ranges equal the intersection between the
    // intersection ranges and the track ranges.
    if (mEnded) {
      TimeIntervals tR = *trackRanges;
      tR.Add(TimeInterval(tR.GetEnd(), highestEndTime));
      intersection.Intersection(tR);
    } else {
      intersection.Intersection(*trackRanges);
    }
  }
  return intersection;
}

int64_t TrackBuffersManager::GetSize() const { return mSizeSourceBuffer; }

void TrackBuffersManager::Ended() { mEnded = true; }

void TrackBuffersManager::Detach() {
  MOZ_ASSERT(NS_IsMainThread());
  MSE_DEBUG("");
  QueueTask(new DetachTask());
}

void TrackBuffersManager::CompleteResetParserState() {
  mTaskQueueCapability->AssertOnCurrentThread();
  AUTO_PROFILER_LABEL("TrackBuffersManager::CompleteResetParserState",
                      MEDIA_PLAYBACK);
  MSE_DEBUG("");

  // We shouldn't change mInputDemuxer while a demuxer init/reset request is
  // being processed. See bug 1239983.
  MOZ_DIAGNOSTIC_ASSERT(!mDemuxerInitRequest.Exists(),
                        "Previous AppendBuffer didn't complete");

  for (auto& track : GetTracksList()) {
    // 2. Unset the last decode timestamp on all track buffers.
    // 3. Unset the last frame duration on all track buffers.
    // 4. Unset the highest end timestamp on all track buffers.
    // 5. Set the need random access point flag on all track buffers to true.
    track->ResetAppendState();

    // if we have been aborted, we may have pending frames that we are going
    // to discard now.
    track->mQueuedSamples.Clear();
  }

  // 7. Remove all bytes from the input buffer.
  mPendingInputBuffer.reset();
  mInputBuffer.reset();
  if (mCurrentInputBuffer) {
    mCurrentInputBuffer->EvictAll();
    // The demuxer will be recreated during the next run of SegmentParserLoop.
    // As such we don't need to notify it that data has been removed.
    mCurrentInputBuffer = new SourceBufferResource();
  }

  // We could be left with a demuxer in an unusable state. It needs to be
  // recreated. Unless we have a pending changeType operation, we store in the
  // InputBuffer an init segment which will be parsed during the next Segment
  // Parser Loop and a new demuxer will be created and initialized.
  // If we are in the middle of a changeType operation, then we do not have an
  // init segment yet. The next appendBuffer operation will need to provide such
  // init segment.
  if (mFirstInitializationSegmentReceived && !mChangeTypeReceived) {
    MOZ_ASSERT(mInitData && mInitData->Length(),
               "we must have an init segment");
    // The aim here is really to destroy our current demuxer.
    CreateDemuxerforMIMEType();
    // Recreate our input buffer. We can't directly assign the initData buffer
    // to mInputBuffer as it will get modified in the Segment Parser Loop.
    mInputBuffer = Some(MediaSpan::WithCopyOf(mInitData));
    RecreateParser(true);
  } else {
    RecreateParser(false);
  }
}

int64_t TrackBuffersManager::EvictionThreshold() const {
  if (HasVideo()) {
    return mVideoEvictionThreshold;
  }
  return mAudioEvictionThreshold;
}

void TrackBuffersManager::DoEvictData(const TimeUnit& aPlaybackTime,
                                      int64_t aSizeToEvict) {
  mTaskQueueCapability->AssertOnCurrentThread();
  AUTO_PROFILER_LABEL("TrackBuffersManager::DoEvictData", MEDIA_PLAYBACK);

  mEvictionState = EvictionState::EVICTION_COMPLETED;

  // Video is what takes the most space, only evict there if we have video.
  auto& track = HasVideo() ? mVideoTracks : mAudioTracks;
  const auto& buffer = track.GetTrackBuffer();
  if (buffer.IsEmpty()) {
    // Buffer has been emptied while the eviction was queued, nothing to do.
    return;
  }
  if (track.mBufferedRanges.IsEmpty()) {
    MSE_DEBUG(
        "DoEvictData running with no buffered ranges. 0 duration data likely "
        "present in our buffer(s). Evicting all data!");
    // We have no buffered ranges, but may still have data. This happens if the
    // buffer is full of 0 duration data. Normal removal procedures don't clear
    // 0 duration data, so blow away all our data.
    RemoveAllCodedFrames();
    return;
  }
  // Remove any data we've already played, or before the next sample to be
  // demuxed whichever is lowest.
  TimeUnit lowerLimit = std::min(track.mNextSampleTime, aPlaybackTime);
  uint32_t lastKeyFrameIndex = 0;
  int64_t toEvict = aSizeToEvict;
  int64_t partialEvict = 0;
  for (uint32_t i = 0; i < buffer.Length(); i++) {
    const auto& frame = buffer[i];
    if (frame->mKeyframe) {
      lastKeyFrameIndex = i;
      toEvict -= partialEvict;
      if (toEvict < 0) {
        break;
      }
      partialEvict = 0;
    }
    if (frame->GetEndTime() >= lowerLimit) {
      break;
    }
    partialEvict += frame->ComputedSizeOfIncludingThis();
  }

  const int64_t finalSize = mSizeSourceBuffer - aSizeToEvict;

  if (lastKeyFrameIndex > 0) {
    MSE_DEBUG("Step1. Evicting %" PRId64 " bytes prior currentTime",
              aSizeToEvict - toEvict);
    TimeUnit start = track.mBufferedRanges[0].mStart;
    TimeUnit end =
        buffer[lastKeyFrameIndex]->mTime - TimeUnit::FromMicroseconds(1);
    if (end > start) {
      CodedFrameRemoval(TimeInterval(start, end));
    }
  }

  if (mSizeSourceBuffer <= finalSize) {
    return;
  }

  toEvict = mSizeSourceBuffer - finalSize;

  // See if we can evict data into the future.
  // We do not evict data from the currently used buffered interval.

  TimeUnit currentPosition = std::max(aPlaybackTime, track.mNextSampleTime);
  TimeIntervals futureBuffered(
      TimeInterval(currentPosition, TimeUnit::FromInfinity()));
  futureBuffered.Intersection(track.mBufferedRanges);
  futureBuffered.SetFuzz(MediaSourceDemuxer::EOS_FUZZ / 2);
  if (futureBuffered.Length() <= 1) {
    // We have one continuous segment ahead of us:
    // nothing further can be evicted.
    return;
  }

  // Don't evict before the end of the current segment
  TimeUnit upperLimit = futureBuffered[0].mEnd;
  uint32_t evictedFramesStartIndex = buffer.Length();
  for (int32_t i = buffer.Length() - 1; i >= 0; i--) {
    const auto& frame = buffer[i];
    if (frame->mTime <= upperLimit || toEvict < 0) {
      // We've reached a frame that shouldn't be evicted -> Evict after it ->
      // i+1. Or the previous loop reached the eviction threshold -> Evict from
      // it -> i+1.
      evictedFramesStartIndex = i + 1;
      break;
    }
    toEvict -= frame->ComputedSizeOfIncludingThis();
  }
  if (evictedFramesStartIndex < buffer.Length()) {
    MSE_DEBUG("Step2. Evicting %" PRId64 " bytes from trailing data",
              mSizeSourceBuffer - finalSize - toEvict);
    CodedFrameRemoval(TimeInterval(buffer[evictedFramesStartIndex]->mTime,
                                   TimeUnit::FromInfinity()));
  }
}

RefPtr<TrackBuffersManager::RangeRemovalPromise>
TrackBuffersManager::CodedFrameRemovalWithPromise(TimeInterval aInterval) {
  mTaskQueueCapability->AssertOnCurrentThread();

  RefPtr<RangeRemovalTask> task = new RangeRemovalTask(aInterval);
  RefPtr<RangeRemovalPromise> p = task->mPromise.Ensure(__func__);
  QueueTask(task);

  return p;
}

bool TrackBuffersManager::CodedFrameRemoval(TimeInterval aInterval) {
  MOZ_ASSERT(OnTaskQueue());
  AUTO_PROFILER_LABEL("TrackBuffersManager::CodedFrameRemoval", MEDIA_PLAYBACK);
  MSE_DEBUG("From %.2fs to %.2f", aInterval.mStart.ToSeconds(),
            aInterval.mEnd.ToSeconds());

#if DEBUG
  if (HasVideo()) {
    MSE_DEBUG("before video ranges=%s",
              DumpTimeRangesRaw(mVideoTracks.mBufferedRanges).get());
  }
  if (HasAudio()) {
    MSE_DEBUG("before audio ranges=%s",
              DumpTimeRangesRaw(mAudioTracks.mBufferedRanges).get());
  }
#endif

  // 1. Let start be the starting presentation timestamp for the removal range.
  TimeUnit start = aInterval.mStart;
  // 2. Let end be the end presentation timestamp for the removal range.
  TimeUnit end = aInterval.mEnd;

  bool dataRemoved = false;

  // 3. For each track buffer in this source buffer, run the following steps:
  for (auto track : GetTracksList()) {
    MSE_DEBUGV("Processing %s track", track->mInfo->mMimeType.get());
    // 1. Let remove end timestamp be the current value of duration
    // See bug: https://www.w3.org/Bugs/Public/show_bug.cgi?id=28727
    // At worse we will remove all frames until the end, unless a key frame is
    // found between the current interval's end and the trackbuffer's end.
    TimeUnit removeEndTimestamp = track->mBufferedRanges.GetEnd();

    if (start > removeEndTimestamp) {
      // Nothing to remove.
      continue;
    }

    // 2. If this track buffer has a random access point timestamp that is
    // greater than or equal to end, then update remove end timestamp to that
    // random access point timestamp.
    if (end < track->mBufferedRanges.GetEnd()) {
      for (auto& frame : track->GetTrackBuffer()) {
        if (frame->mKeyframe && frame->mTime >= end) {
          removeEndTimestamp = frame->mTime;
          break;
        }
      }
    }

    // 3. Remove all media data, from this track buffer, that contain starting
    // timestamps greater than or equal to start and less than the remove end
    // timestamp.
    // 4. Remove decoding dependencies of the coded frames removed in the
    // previous step: Remove all coded frames between the coded frames removed
    // in the previous step and the next random access point after those removed
    // frames.
    TimeIntervals removedInterval{TimeInterval(start, removeEndTimestamp)};
    RemoveFrames(removedInterval, *track, 0, RemovalMode::kRemoveFrame);

    // 5. If this object is in activeSourceBuffers, the current playback
    // position is greater than or equal to start and less than the remove end
    // timestamp, and HTMLMediaElement.readyState is greater than HAVE_METADATA,
    // then set the HTMLMediaElement.readyState attribute to HAVE_METADATA and
    // stall playback. This will be done by the MDSM during playback.
    // TODO properly, so it works even if paused.
  }

  UpdateBufferedRanges();

  // Update our reported total size.
  mSizeSourceBuffer = mVideoTracks.mSizeBuffer + mAudioTracks.mSizeBuffer;

  // 4. If buffer full flag equals true and this object is ready to accept more
  // bytes, then set the buffer full flag to false.
  if (mBufferFull && mSizeSourceBuffer < EvictionThreshold()) {
    mBufferFull = false;
  }

  return dataRemoved;
}

void TrackBuffersManager::RemoveAllCodedFrames() {
  // This is similar to RemoveCodedFrames, but will attempt to remove ALL
  // the frames. This is not to spec, as explained below at step 3.1. Steps
  // below coincide with Remove Coded Frames algorithm from the spec.
  MSE_DEBUG("RemoveAllCodedFrames called.");
  MOZ_ASSERT(OnTaskQueue());
  AUTO_PROFILER_LABEL("TrackBuffersManager::RemoveAllCodedFrames",
                      MEDIA_PLAYBACK);

  // 1. Let start be the starting presentation timestamp for the removal range.
  TimeUnit start{};
  // 2. Let end be the end presentation timestamp for the removal range.
  TimeUnit end = TimeUnit::FromMicroseconds(1);
  // Find an end time such that our range will include every frame in every
  // track. We do this by setting the end of our interval to the largest end
  // time seen + 1 microsecond.
  for (TrackData* track : GetTracksList()) {
    for (auto& frame : track->GetTrackBuffer()) {
      MOZ_ASSERT(frame->mTime >= start,
                 "Shouldn't have frame at negative time!");
      TimeUnit frameEnd = frame->mTime + frame->mDuration;
      if (frameEnd > end) {
        end = frameEnd + TimeUnit::FromMicroseconds(1);
      }
    }
  }

  // 3. For each track buffer in this source buffer, run the following steps:
  TimeIntervals removedInterval{TimeInterval(start, end)};
  for (TrackData* track : GetTracksList()) {
    // 1. Let remove end timestamp be the current value of duration
    // ^ It's off spec, but we ignore this in order to clear 0 duration frames.
    // If we don't ignore this rule and our buffer is full of 0 duration frames
    // at timestamp n, we get an eviction range of [0, n). When we get to step
    // 3.3 below, the 0 duration frames will not be evicted because their
    // timestamp is not less than remove end timestamp -- it will in fact be
    // equal to remove end timestamp.
    //
    // 2. If this track buffer has a random access point timestamp that is
    // greater than or equal to end, then update remove end timestamp to that
    // random access point timestamp.
    // ^ We've made sure end > any sample's timestamp, so can skip this.
    //
    // 3. Remove all media data, from this track buffer, that contain starting
    // timestamps greater than or equal to start and less than the remove end
    // timestamp.
    // 4. Remove decoding dependencies of the coded frames removed in the
    // previous step: Remove all coded frames between the coded frames removed
    // in the previous step and the next random access point after those removed
    // frames.

    // This should remove every frame in the track because removedInterval was
    // constructed such that every frame in any track falls into that interval.
    RemoveFrames(removedInterval, *track, 0, RemovalMode::kRemoveFrame);

    // 5. If this object is in activeSourceBuffers, the current playback
    // position is greater than or equal to start and less than the remove end
    // timestamp, and HTMLMediaElement.readyState is greater than HAVE_METADATA,
    // then set the HTMLMediaElement.readyState attribute to HAVE_METADATA and
    // stall playback. This will be done by the MDSM during playback.
    // TODO properly, so it works even if paused.
  }

  UpdateBufferedRanges();
#ifdef DEBUG
  {
    MutexAutoLock lock(mMutex);
    MOZ_ASSERT(
        mAudioBufferedRanges.IsEmpty(),
        "Should have no buffered video ranges after evicting everything.");
    MOZ_ASSERT(
        mVideoBufferedRanges.IsEmpty(),
        "Should have no buffered video ranges after evicting everything.");
  }
#endif
  mSizeSourceBuffer = mVideoTracks.mSizeBuffer + mAudioTracks.mSizeBuffer;
  MOZ_ASSERT(mSizeSourceBuffer == 0,
             "Buffer should be empty after evicting everything!");
  if (mBufferFull && mSizeSourceBuffer < EvictionThreshold()) {
    mBufferFull = false;
  }
}

void TrackBuffersManager::UpdateBufferedRanges() {
  MutexAutoLock mut(mMutex);

  mVideoBufferedRanges = mVideoTracks.mSanitizedBufferedRanges;
  mAudioBufferedRanges = mAudioTracks.mSanitizedBufferedRanges;

#if DEBUG
  if (HasVideo()) {
    MSE_DEBUG("after video ranges=%s",
              DumpTimeRangesRaw(mVideoTracks.mBufferedRanges).get());
  }
  if (HasAudio()) {
    MSE_DEBUG("after audio ranges=%s",
              DumpTimeRangesRaw(mAudioTracks.mBufferedRanges).get());
  }
#endif
}

void TrackBuffersManager::SegmentParserLoop() {
  MOZ_ASSERT(OnTaskQueue());
  AUTO_PROFILER_LABEL("TrackBuffersManager::SegmentParserLoop", MEDIA_PLAYBACK);

  while (true) {
    // 1. If the input buffer is empty, then jump to the need more data step
    // below.
    if (!mInputBuffer || mInputBuffer->IsEmpty()) {
      NeedMoreData();
      return;
    }
    // 2. If the input buffer contains bytes that violate the SourceBuffer
    // byte stream format specification, then run the append error algorithm
    // with the decode error parameter set to true and abort this algorithm.
    // TODO

    // 3. Remove any bytes that the byte stream format specifications say must
    // be ignored from the start of the input buffer. We do not remove bytes
    // from our input buffer. Instead we enforce that our ContainerParser is
    // able to skip over all data that is supposed to be ignored.

    // 4. If the append state equals WAITING_FOR_SEGMENT, then run the following
    // steps:
    if (mSourceBufferAttributes->GetAppendState() ==
        AppendState::WAITING_FOR_SEGMENT) {
      MediaResult haveInitSegment =
          mParser->IsInitSegmentPresent(*mInputBuffer);
      if (NS_SUCCEEDED(haveInitSegment)) {
        SetAppendState(AppendState::PARSING_INIT_SEGMENT);
        if (mFirstInitializationSegmentReceived && !mChangeTypeReceived) {
          // This is a new initialization segment. Obsolete the old one.
          RecreateParser(false);
        }
        continue;
      }
      MediaResult haveMediaSegment =
          mParser->IsMediaSegmentPresent(*mInputBuffer);
      if (NS_SUCCEEDED(haveMediaSegment)) {
        SetAppendState(AppendState::PARSING_MEDIA_SEGMENT);
        mNewMediaSegmentStarted = true;
        continue;
      }
      // We have neither an init segment nor a media segment.
      // Check if it was invalid data.
      if (haveInitSegment != NS_ERROR_NOT_AVAILABLE) {
        MSE_DEBUG("Found invalid data.");
        RejectAppend(haveInitSegment, __func__);
        return;
      }
      if (haveMediaSegment != NS_ERROR_NOT_AVAILABLE) {
        MSE_DEBUG("Found invalid data.");
        RejectAppend(haveMediaSegment, __func__);
        return;
      }
      MSE_DEBUG("Found incomplete data.");
      NeedMoreData();
      return;
    }

    MOZ_ASSERT(mSourceBufferAttributes->GetAppendState() ==
                   AppendState::PARSING_INIT_SEGMENT ||
               mSourceBufferAttributes->GetAppendState() ==
                   AppendState::PARSING_MEDIA_SEGMENT);

    TimeUnit start, end;
    MediaResult newData = NS_ERROR_NOT_AVAILABLE;

    if (mSourceBufferAttributes->GetAppendState() ==
            AppendState::PARSING_INIT_SEGMENT ||
        (mSourceBufferAttributes->GetAppendState() ==
             AppendState::PARSING_MEDIA_SEGMENT &&
         mFirstInitializationSegmentReceived && !mChangeTypeReceived)) {
      newData = mParser->ParseStartAndEndTimestamps(*mInputBuffer, start, end);
      if (NS_FAILED(newData) && newData.Code() != NS_ERROR_NOT_AVAILABLE) {
        RejectAppend(newData, __func__);
        return;
      }
      mProcessedInput += mInputBuffer->Length();
    }

    // 5. If the append state equals PARSING_INIT_SEGMENT, then run the
    // following steps:
    if (mSourceBufferAttributes->GetAppendState() ==
        AppendState::PARSING_INIT_SEGMENT) {
      if (mParser->InitSegmentRange().IsEmpty()) {
        mInputBuffer.reset();
        NeedMoreData();
        return;
      }
      InitializationSegmentReceived();
      return;
    }
    if (mSourceBufferAttributes->GetAppendState() ==
        AppendState::PARSING_MEDIA_SEGMENT) {
      // 1. If the first initialization segment received flag is false, then run
      //    the append error algorithm with the decode error parameter set to
      //    true and abort this algorithm.
      //    Or we are in the process of changeType, in which case we must first
      //    get an init segment before getting a media segment.
      if (!mFirstInitializationSegmentReceived || mChangeTypeReceived) {
        RejectAppend(NS_ERROR_FAILURE, __func__);
        return;
      }

      // We can't feed some demuxers (WebMDemuxer) with data that do not have
      // monotonizally increasing timestamps. So we check if we have a
      // discontinuity from the previous segment parsed.
      // If so, recreate a new demuxer to ensure that the demuxer is only fed
      // monotonically increasing data.
      if (mNewMediaSegmentStarted) {
        if (NS_SUCCEEDED(newData) && mLastParsedEndTime.isSome() &&
            start < mLastParsedEndTime.ref()) {
          MSE_DEBUG("Re-creating demuxer");
          ResetDemuxingState();
          return;
        }
        if (NS_SUCCEEDED(newData) || !mParser->MediaSegmentRange().IsEmpty()) {
          if (mPendingInputBuffer) {
            // We now have a complete media segment header. We can resume
            // parsing the data.
            AppendDataToCurrentInputBuffer(*mPendingInputBuffer);
            mPendingInputBuffer.reset();
          }
          mNewMediaSegmentStarted = false;
        } else {
          // We don't have any data to demux yet, stash aside the data.
          // This also handles the case:
          // 2. If the input buffer does not contain a complete media segment
          // header yet, then jump to the need more data step below.
          if (!mPendingInputBuffer) {
            mPendingInputBuffer = Some(MediaSpan(*mInputBuffer));
          } else {
            // Note we reset mInputBuffer below, so this won't end up appending
            // the contents of mInputBuffer to itself.
            mPendingInputBuffer->Append(*mInputBuffer);
          }

          mInputBuffer.reset();
          NeedMoreData();
          return;
        }
      }

      // 3. If the input buffer contains one or more complete coded frames, then
      // run the coded frame processing algorithm.
      RefPtr<TrackBuffersManager> self = this;
      CodedFrameProcessing()
          ->Then(
              TaskQueueFromTaskQueue(), __func__,
              [self](bool aNeedMoreData) {
                self->mTaskQueueCapability->AssertOnCurrentThread();
                self->mProcessingRequest.Complete();
                if (aNeedMoreData) {
                  self->NeedMoreData();
                } else {
                  self->ScheduleSegmentParserLoop();
                }
              },
              [self](const MediaResult& aRejectValue) {
                self->mTaskQueueCapability->AssertOnCurrentThread();
                self->mProcessingRequest.Complete();
                self->RejectAppend(aRejectValue, __func__);
              })
          ->Track(mProcessingRequest);
      return;
    }
  }
}

void TrackBuffersManager::NeedMoreData() {
  MSE_DEBUG("");
  MOZ_DIAGNOSTIC_ASSERT(mCurrentTask &&
                        mCurrentTask->GetType() ==
                            SourceBufferTask::Type::AppendBuffer);
  MOZ_DIAGNOSTIC_ASSERT(mSourceBufferAttributes);

  mCurrentTask->As<AppendBufferTask>()->mPromise.Resolve(
      SourceBufferTask::AppendBufferResult(mActiveTrack,
                                           *mSourceBufferAttributes),
      __func__);
  mSourceBufferAttributes = nullptr;
  mCurrentTask = nullptr;
  ProcessTasks();
}

void TrackBuffersManager::RejectAppend(const MediaResult& aRejectValue,
                                       const char* aName) {
  MSE_DEBUG("rv=%" PRIu32, static_cast<uint32_t>(aRejectValue.Code()));
  MOZ_DIAGNOSTIC_ASSERT(mCurrentTask &&
                        mCurrentTask->GetType() ==
                            SourceBufferTask::Type::AppendBuffer);

  mCurrentTask->As<AppendBufferTask>()->mPromise.Reject(aRejectValue, __func__);
  mSourceBufferAttributes = nullptr;
  mCurrentTask = nullptr;
  ProcessTasks();
}

void TrackBuffersManager::ScheduleSegmentParserLoop() {
  MOZ_ASSERT(OnTaskQueue());
  TaskQueueFromTaskQueue()->Dispatch(
      NewRunnableMethod("TrackBuffersManager::SegmentParserLoop", this,
                        &TrackBuffersManager::SegmentParserLoop));
}

void TrackBuffersManager::ShutdownDemuxers() {
  if (mVideoTracks.mDemuxer) {
    mVideoTracks.mDemuxer->BreakCycles();
    mVideoTracks.mDemuxer = nullptr;
  }
  if (mAudioTracks.mDemuxer) {
    mAudioTracks.mDemuxer->BreakCycles();
    mAudioTracks.mDemuxer = nullptr;
  }
  // We shouldn't change mInputDemuxer while a demuxer init/reset request is
  // being processed. See bug 1239983.
  MOZ_DIAGNOSTIC_ASSERT(!mDemuxerInitRequest.Exists());
  mInputDemuxer = nullptr;
  mLastParsedEndTime.reset();
}

void TrackBuffersManager::CreateDemuxerforMIMEType() {
  mTaskQueueCapability->AssertOnCurrentThread();
  MSE_DEBUG("mType.OriginalString=%s", mType.OriginalString().get());
  ShutdownDemuxers();

  if (mType.Type() == MEDIAMIMETYPE(VIDEO_WEBM) ||
      mType.Type() == MEDIAMIMETYPE(AUDIO_WEBM)) {
    mInputDemuxer =
        new WebMDemuxer(mCurrentInputBuffer, true /* IsMediaSource*/);
    DDLINKCHILD("demuxer", mInputDemuxer.get());
    return;
  }

#ifdef MOZ_FMP4
  if (mType.Type() == MEDIAMIMETYPE(VIDEO_MP4) ||
      mType.Type() == MEDIAMIMETYPE(AUDIO_MP4)) {
    mInputDemuxer = new MP4Demuxer(mCurrentInputBuffer);
    DDLINKCHILD("demuxer", mInputDemuxer.get());
    return;
  }
#endif
  NS_WARNING("Not supported (yet)");
}

// We reset the demuxer by creating a new one and initializing it.
void TrackBuffersManager::ResetDemuxingState() {
  MOZ_ASSERT(OnTaskQueue());
  MOZ_ASSERT(mParser && mParser->HasInitData());
  AUTO_PROFILER_LABEL("TrackBuffersManager::ResetDemuxingState",
                      MEDIA_PLAYBACK);
  RecreateParser(true);
  mCurrentInputBuffer = new SourceBufferResource();
  // The demuxer isn't initialized yet ; we don't want to notify it
  // that data has been appended yet ; so we simply append the init segment
  // to the resource.
  mCurrentInputBuffer->AppendData(mParser->InitData());
  CreateDemuxerforMIMEType();
  if (!mInputDemuxer) {
    RejectAppend(NS_ERROR_FAILURE, __func__);
    return;
  }
  mInputDemuxer->Init()
      ->Then(TaskQueueFromTaskQueue(), __func__, this,
             &TrackBuffersManager::OnDemuxerResetDone,
             &TrackBuffersManager::OnDemuxerInitFailed)
      ->Track(mDemuxerInitRequest);
}

void TrackBuffersManager::OnDemuxerResetDone(const MediaResult& aResult) {
  MOZ_ASSERT(OnTaskQueue());
  mDemuxerInitRequest.Complete();

  if (NS_FAILED(aResult) && StaticPrefs::media_playback_warnings_as_errors()) {
    RejectAppend(aResult, __func__);
    return;
  }

  // mInputDemuxer shouldn't have been destroyed while a demuxer init/reset
  // request was being processed. See bug 1239983.
  MOZ_DIAGNOSTIC_ASSERT(mInputDemuxer);

  if (aResult != NS_OK && mParentDecoder) {
    RefPtr<TrackBuffersManager> self = this;
    mAbstractMainThread->Dispatch(NS_NewRunnableFunction(
        "TrackBuffersManager::OnDemuxerResetDone", [self, aResult]() {
          if (self->mParentDecoder && self->mParentDecoder->GetOwner()) {
            self->mParentDecoder->GetOwner()->DecodeWarning(aResult);
          }
        }));
  }

  // Recreate track demuxers.
  uint32_t numVideos = mInputDemuxer->GetNumberTracks(TrackInfo::kVideoTrack);
  if (numVideos) {
    // We currently only handle the first video track.
    mVideoTracks.mDemuxer =
        mInputDemuxer->GetTrackDemuxer(TrackInfo::kVideoTrack, 0);
    MOZ_ASSERT(mVideoTracks.mDemuxer);
    DDLINKCHILD("video demuxer", mVideoTracks.mDemuxer.get());
  }

  uint32_t numAudios = mInputDemuxer->GetNumberTracks(TrackInfo::kAudioTrack);
  if (numAudios) {
    // We currently only handle the first audio track.
    mAudioTracks.mDemuxer =
        mInputDemuxer->GetTrackDemuxer(TrackInfo::kAudioTrack, 0);
    MOZ_ASSERT(mAudioTracks.mDemuxer);
    DDLINKCHILD("audio demuxer", mAudioTracks.mDemuxer.get());
  }

  if (mPendingInputBuffer) {
    // We had a partial media segment header stashed aside.
    // Reparse its content so we can continue parsing the current input buffer.
    TimeUnit start, end;
    mParser->ParseStartAndEndTimestamps(*mPendingInputBuffer, start, end);
    mProcessedInput += mPendingInputBuffer->Length();
  }

  SegmentParserLoop();
}

void TrackBuffersManager::AppendDataToCurrentInputBuffer(
    const MediaSpan& aData) {
  MOZ_ASSERT(mCurrentInputBuffer);
  mCurrentInputBuffer->AppendData(aData);
  mInputDemuxer->NotifyDataArrived();
}

void TrackBuffersManager::InitializationSegmentReceived() {
  MOZ_ASSERT(OnTaskQueue());
  MOZ_ASSERT(mParser->HasCompleteInitData());
  AUTO_PROFILER_LABEL("TrackBuffersManager::InitializationSegmentReceived",
                      MEDIA_PLAYBACK);

  int64_t endInit = mParser->InitSegmentRange().mEnd;
  if (mInputBuffer->Length() > mProcessedInput ||
      int64_t(mProcessedInput - mInputBuffer->Length()) > endInit) {
    // Something is not quite right with the data appended. Refuse it.
    RejectAppend(MediaResult(NS_ERROR_FAILURE,
                             "Invalid state following initialization segment"),
                 __func__);
    return;
  }

  mCurrentInputBuffer = new SourceBufferResource();
  // The demuxer isn't initialized yet ; we don't want to notify it
  // that data has been appended yet ; so we simply append the init segment
  // to the resource.
  mCurrentInputBuffer->AppendData(mParser->InitData());
  uint32_t length = endInit - (mProcessedInput - mInputBuffer->Length());
  MOZ_RELEASE_ASSERT(length <= mInputBuffer->Length());
  mInputBuffer->RemoveFront(length);
  CreateDemuxerforMIMEType();
  if (!mInputDemuxer) {
    NS_WARNING("TODO type not supported");
    RejectAppend(NS_ERROR_DOM_NOT_SUPPORTED_ERR, __func__);
    return;
  }
  mInputDemuxer->Init()
      ->Then(TaskQueueFromTaskQueue(), __func__, this,
             &TrackBuffersManager::OnDemuxerInitDone,
             &TrackBuffersManager::OnDemuxerInitFailed)
      ->Track(mDemuxerInitRequest);
}

bool TrackBuffersManager::IsRepeatInitData(
    const MediaInfo& aNewMediaInfo) const {
  MOZ_ASSERT(OnTaskQueue());
  if (!mInitData) {
    // There is no previous init data, so this cannot be a repeat.
    return false;
  }

  if (mChangeTypeReceived) {
    // If we're received change type we want to reprocess init data.
    return false;
  }

  MOZ_DIAGNOSTIC_ASSERT(mInitData, "Init data should be non-null");
  if (*mInitData == *mParser->InitData()) {
    // We have previous init data, and it's the same binary data as we've just
    // parsed.
    return true;
  }

  // At this point the binary data doesn't match, but it's possible to have the
  // different binary representations for the same logical init data. These
  // checks can be revised as we encounter such cases in the wild.

  bool audioInfoIsRepeat = false;
  if (aNewMediaInfo.HasAudio()) {
    if (!mAudioTracks.mLastInfo) {
      // There is no old audio info, so this can't be a repeat.
      return false;
    }
    audioInfoIsRepeat =
        *mAudioTracks.mLastInfo->GetAsAudioInfo() == aNewMediaInfo.mAudio;
    if (!aNewMediaInfo.HasVideo()) {
      // Only have audio.
      return audioInfoIsRepeat;
    }
  }

  bool videoInfoIsRepeat = false;
  if (aNewMediaInfo.HasVideo()) {
    if (!mVideoTracks.mLastInfo) {
      // There is no old video info, so this can't be a repeat.
      return false;
    }
    videoInfoIsRepeat =
        *mVideoTracks.mLastInfo->GetAsVideoInfo() == aNewMediaInfo.mVideo;
    if (!aNewMediaInfo.HasAudio()) {
      // Only have video.
      return videoInfoIsRepeat;
    }
  }

  if (audioInfoIsRepeat && videoInfoIsRepeat) {
    MOZ_DIAGNOSTIC_ASSERT(
        aNewMediaInfo.HasVideo() && aNewMediaInfo.HasAudio(),
        "This should only be reachable if audio and video are present");
    // Video + audio are present and both have the same init data.
    return true;
  }

  return false;
}

void TrackBuffersManager::OnDemuxerInitDone(const MediaResult& aResult) {
  mTaskQueueCapability->AssertOnCurrentThread();
  MOZ_DIAGNOSTIC_ASSERT(mInputDemuxer, "mInputDemuxer has been destroyed");
  AUTO_PROFILER_LABEL("TrackBuffersManager::OnDemuxerInitDone", MEDIA_PLAYBACK);

  mDemuxerInitRequest.Complete();

  if (NS_FAILED(aResult) && StaticPrefs::media_playback_warnings_as_errors()) {
    RejectAppend(aResult, __func__);
    return;
  }

  MediaInfo info;

  uint32_t numVideos = mInputDemuxer->GetNumberTracks(TrackInfo::kVideoTrack);
  if (numVideos) {
    // We currently only handle the first video track.
    mVideoTracks.mDemuxer =
        mInputDemuxer->GetTrackDemuxer(TrackInfo::kVideoTrack, 0);
    MOZ_ASSERT(mVideoTracks.mDemuxer);
    DDLINKCHILD("video demuxer", mVideoTracks.mDemuxer.get());
    info.mVideo = *mVideoTracks.mDemuxer->GetInfo()->GetAsVideoInfo();
    info.mVideo.mTrackId = 2;
  }

  uint32_t numAudios = mInputDemuxer->GetNumberTracks(TrackInfo::kAudioTrack);
  if (numAudios) {
    // We currently only handle the first audio track.
    mAudioTracks.mDemuxer =
        mInputDemuxer->GetTrackDemuxer(TrackInfo::kAudioTrack, 0);
    MOZ_ASSERT(mAudioTracks.mDemuxer);
    DDLINKCHILD("audio demuxer", mAudioTracks.mDemuxer.get());
    info.mAudio = *mAudioTracks.mDemuxer->GetInfo()->GetAsAudioInfo();
    info.mAudio.mTrackId = 1;
  }

  TimeUnit videoDuration = numVideos ? info.mVideo.mDuration : TimeUnit::Zero();
  TimeUnit audioDuration = numAudios ? info.mAudio.mDuration : TimeUnit::Zero();

  TimeUnit duration = std::max(videoDuration, audioDuration);
  // 1. Update the duration attribute if it currently equals NaN.
  // Those steps are performed by the MediaSourceDecoder::SetInitialDuration
  mAbstractMainThread->Dispatch(NewRunnableMethod<TimeUnit>(
      "MediaSourceDecoder::SetInitialDuration", mParentDecoder.get(),
      &MediaSourceDecoder::SetInitialDuration,
      !duration.IsZero() ? duration : TimeUnit::FromInfinity()));

  // 2. If the initialization segment has no audio, video, or text tracks, then
  // run the append error algorithm with the decode error parameter set to true
  // and abort these steps.
  if (!numVideos && !numAudios) {
    RejectAppend(NS_ERROR_FAILURE, __func__);
    return;
  }

  // 3. If the first initialization segment received flag is true, then run the
  // following steps:
  if (mFirstInitializationSegmentReceived) {
    if (numVideos != mVideoTracks.mNumTracks ||
        numAudios != mAudioTracks.mNumTracks) {
      RejectAppend(NS_ERROR_FAILURE, __func__);
      return;
    }
    // 1. If more than one track for a single type are present (ie 2 audio
    // tracks), then the Track IDs match the ones in the first initialization
    // segment.
    // TODO
    // 2. Add the appropriate track descriptions from this initialization
    // segment to each of the track buffers.
    // TODO
    // 3. Set the need random access point flag on all track buffers to true.
    mVideoTracks.mNeedRandomAccessPoint = true;
    mAudioTracks.mNeedRandomAccessPoint = true;
  }

  // Check if we've received the same init data again. Some streams will
  // resend the same data. In these cases we don't need to change the stream
  // id as it's the same stream. Doing so would recreate decoders, possibly
  // leading to gaps in audio and/or video (see bug 1450952).
  bool isRepeatInitData = IsRepeatInitData(info);

  MOZ_ASSERT(mFirstInitializationSegmentReceived || !isRepeatInitData,
             "Should never detect repeat init data for first segment!");

  // If we have new init data we configure and set track info as needed. If we
  // have repeat init data we carry forward our existing track info.
  if (!isRepeatInitData) {
    // Increase our stream id.
    uint32_t streamID = sStreamSourceID++;

    // 4. Let active track flag equal false.
    bool activeTrack = false;

    // 5. If the first initialization segment received flag is false, then run
    // the following steps:
    if (!mFirstInitializationSegmentReceived) {
      MSE_DEBUG("Get first init data");
      mAudioTracks.mNumTracks = numAudios;
      // TODO:
      // 1. If the initialization segment contains tracks with codecs the user
      // agent does not support, then run the append error algorithm with the
      // decode error parameter set to true and abort these steps.

      // 2. For each audio track in the initialization segment, run following
      // steps: for (uint32_t i = 0; i < numAudios; i++) {
      if (numAudios) {
        // 1. Let audio byte stream track ID be the Track ID for the current
        // track being processed.
        // 2. Let audio language be a BCP 47 language tag for the language
        // specified in the initialization segment for this track or an empty
        // string if no language info is present.
        // 3. If audio language equals an empty string or the 'und' BCP 47
        // value, then run the default track language algorithm with
        // byteStreamTrackID set to audio byte stream track ID and type set to
        // "audio" and assign the value returned by the algorithm to audio
        // language.
        // 4. Let audio label be a label specified in the initialization segment
        // for this track or an empty string if no label info is present.
        // 5. If audio label equals an empty string, then run the default track
        // label algorithm with byteStreamTrackID set to audio byte stream track
        // ID and type set to "audio" and assign the value returned by the
        // algorithm to audio label.
        // 6. Let audio kinds be an array of kind strings specified in the
        // initialization segment for this track or an empty array if no kind
        // information is provided.
        // 7. If audio kinds equals an empty array, then run the default track
        // kinds algorithm with byteStreamTrackID set to audio byte stream track
        // ID and type set to "audio" and assign the value returned by the
        // algorithm to audio kinds.
        // 8. For each value in audio kinds, run the following steps:
        //   1. Let current audio kind equal the value from audio kinds for this
        //   iteration of the loop.
        //   2. Let new audio track be a new AudioTrack object.
        //   3. Generate a unique ID and assign it to the id property on new
        //   audio track.
        //   4. Assign audio language to the language property on new audio
        //   track.
        //   5. Assign audio label to the label property on new audio track.
        //   6. Assign current audio kind to the kind property on new audio
        //   track.
        //   7. If audioTracks.length equals 0, then run the following steps:
        //     1. Set the enabled property on new audio track to true.
        //     2. Set active track flag to true.
        activeTrack = true;
        //   8. Add new audio track to the audioTracks attribute on this
        //   SourceBuffer object.
        //   9. Queue a task to fire a trusted event named addtrack, that does
        //   not bubble and is not cancelable, and that uses the TrackEvent
        //   interface, at the AudioTrackList object referenced by the
        //   audioTracks attribute on this SourceBuffer object.
        //   10. Add new audio track to the audioTracks attribute on the
        //   HTMLMediaElement.
        //   11. Queue a task to fire a trusted event named addtrack, that does
        //   not bubble and is not cancelable, and that uses the TrackEvent
        //   interface, at the AudioTrackList object referenced by the
        //   audioTracks attribute on the HTMLMediaElement.
        mAudioTracks.mBuffers.AppendElement(TrackBuffer());
        // 10. Add the track description for this track to the track buffer.
        mAudioTracks.mInfo = new TrackInfoSharedPtr(info.mAudio, streamID);
        mAudioTracks.mLastInfo = mAudioTracks.mInfo;
      }

      mVideoTracks.mNumTracks = numVideos;
      // 3. For each video track in the initialization segment, run following
      // steps: for (uint32_t i = 0; i < numVideos; i++) {
      if (numVideos) {
        // 1. Let video byte stream track ID be the Track ID for the current
        // track being processed.
        // 2. Let video language be a BCP 47 language tag for the language
        // specified in the initialization segment for this track or an empty
        // string if no language info is present.
        // 3. If video language equals an empty string or the 'und' BCP 47
        // value, then run the default track language algorithm with
        // byteStreamTrackID set to video byte stream track ID and type set to
        // "video" and assign the value returned by the algorithm to video
        // language.
        // 4. Let video label be a label specified in the initialization segment
        // for this track or an empty string if no label info is present.
        // 5. If video label equals an empty string, then run the default track
        // label algorithm with byteStreamTrackID set to video byte stream track
        // ID and type set to "video" and assign the value returned by the
        // algorithm to video label.
        // 6. Let video kinds be an array of kind strings specified in the
        // initialization segment for this track or an empty array if no kind
        // information is provided.
        // 7. If video kinds equals an empty array, then run the default track
        // kinds algorithm with byteStreamTrackID set to video byte stream track
        // ID and type set to "video" and assign the value returned by the
        // algorithm to video kinds.
        // 8. For each value in video kinds, run the following steps:
        //   1. Let current video kind equal the value from video kinds for this
        //   iteration of the loop.
        //   2. Let new video track be a new VideoTrack object.
        //   3. Generate a unique ID and assign it to the id property on new
        //   video track.
        //   4. Assign video language to the language property on new video
        //   track.
        //   5. Assign video label to the label property on new video track.
        //   6. Assign current video kind to the kind property on new video
        //   track.
        //   7. If videoTracks.length equals 0, then run the following steps:
        //     1. Set the selected property on new video track to true.
        //     2. Set active track flag to true.
        activeTrack = true;
        //   8. Add new video track to the videoTracks attribute on this
        //   SourceBuffer object.
        //   9. Queue a task to fire a trusted event named addtrack, that does
        //   not bubble and is not cancelable, and that uses the TrackEvent
        //   interface, at the VideoTrackList object referenced by the
        //   videoTracks attribute on this SourceBuffer object.
        //   10. Add new video track to the videoTracks attribute on the
        //   HTMLMediaElement.
        //   11. Queue a task to fire a trusted event named addtrack, that does
        //   not bubble and is not cancelable, and that uses the TrackEvent
        //   interface, at the VideoTrackList object referenced by the
        //   videoTracks attribute on the HTMLMediaElement.
        mVideoTracks.mBuffers.AppendElement(TrackBuffer());
        // 10. Add the track description for this track to the track buffer.
        mVideoTracks.mInfo = new TrackInfoSharedPtr(info.mVideo, streamID);
        mVideoTracks.mLastInfo = mVideoTracks.mInfo;
      }
      // 4. For each text track in the initialization segment, run following
      // steps:
      // 5. If active track flag equals true, then run the following steps:
      // This is handled by SourceBuffer once the promise is resolved.
      if (activeTrack) {
        mActiveTrack = true;
      }

      // 6. Set first initialization segment received flag to true.
      mFirstInitializationSegmentReceived = true;
    } else {
      MSE_DEBUG("Get new init data");
      mAudioTracks.mLastInfo = new TrackInfoSharedPtr(info.mAudio, streamID);
      mVideoTracks.mLastInfo = new TrackInfoSharedPtr(info.mVideo, streamID);
    }

    UniquePtr<EncryptionInfo> crypto = mInputDemuxer->GetCrypto();
    if (crypto && crypto->IsEncrypted()) {
      // Try and dispatch 'encrypted'. Won't go if ready state still
      // HAVE_NOTHING.
      for (uint32_t i = 0; i < crypto->mInitDatas.Length(); i++) {
        nsCOMPtr<nsIRunnable> r = new DispatchKeyNeededEvent(
            mParentDecoder, crypto->mInitDatas[i].mInitData,
            crypto->mInitDatas[i].mType);
        mAbstractMainThread->Dispatch(r.forget());
      }
      info.mCrypto = *crypto;
      // We clear our crypto init data array, so the MediaFormatReader will
      // not emit an encrypted event for the same init data again.
      info.mCrypto.mInitDatas.Clear();
    }

    {
      MutexAutoLock mut(mMutex);
      mInfo = info;
    }
  }
  // We now have a valid init data ; we can store it for later use.
  mInitData = mParser->InitData();

  // We have now completed the changeType operation.
  mChangeTypeReceived = false;

  // 3. Remove the initialization segment bytes from the beginning of the input
  // buffer. This step has already been done in InitializationSegmentReceived
  // when we transferred the content into mCurrentInputBuffer.
  mCurrentInputBuffer->EvictAll();
  mInputDemuxer->NotifyDataRemoved();
  RecreateParser(true);

  // 4. Set append state to WAITING_FOR_SEGMENT.
  SetAppendState(AppendState::WAITING_FOR_SEGMENT);
  // 5. Jump to the loop top step above.
  ScheduleSegmentParserLoop();

  if (aResult != NS_OK && mParentDecoder) {
    RefPtr<TrackBuffersManager> self = this;
    mAbstractMainThread->Dispatch(NS_NewRunnableFunction(
        "TrackBuffersManager::OnDemuxerInitDone", [self, aResult]() {
          if (self->mParentDecoder && self->mParentDecoder->GetOwner()) {
            self->mParentDecoder->GetOwner()->DecodeWarning(aResult);
          }
        }));
  }
}

void TrackBuffersManager::OnDemuxerInitFailed(const MediaResult& aError) {
  mTaskQueueCapability->AssertOnCurrentThread();
  MSE_DEBUG("");
  MOZ_ASSERT(aError != NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA);
  mDemuxerInitRequest.Complete();

  RejectAppend(aError, __func__);
}

RefPtr<TrackBuffersManager::CodedFrameProcessingPromise>
TrackBuffersManager::CodedFrameProcessing() {
  MOZ_ASSERT(OnTaskQueue());
  MOZ_ASSERT(mProcessingPromise.IsEmpty());
  AUTO_PROFILER_LABEL("TrackBuffersManager::CodedFrameProcessing",
                      MEDIA_PLAYBACK);

  MediaByteRange mediaRange = mParser->MediaSegmentRange();
  if (mediaRange.IsEmpty()) {
    AppendDataToCurrentInputBuffer(*mInputBuffer);
    mInputBuffer.reset();
  } else {
    MOZ_ASSERT(mProcessedInput >= mInputBuffer->Length());
    if (int64_t(mProcessedInput - mInputBuffer->Length()) > mediaRange.mEnd) {
      // Something is not quite right with the data appended. Refuse it.
      // This would typically happen if the previous media segment was partial
      // yet a new complete media segment was added.
      return CodedFrameProcessingPromise::CreateAndReject(NS_ERROR_FAILURE,
                                                          __func__);
    }
    // The mediaRange is offset by the init segment position previously added.
    uint32_t length =
        mediaRange.mEnd - (mProcessedInput - mInputBuffer->Length());
    if (!length) {
      // We've completed our earlier media segment and no new data is to be
      // processed. This happens with some containers that can't detect that a
      // media segment is ending until a new one starts.
      RefPtr<CodedFrameProcessingPromise> p =
          mProcessingPromise.Ensure(__func__);
      CompleteCodedFrameProcessing();
      return p;
    }
    AppendDataToCurrentInputBuffer(mInputBuffer->To(length));
    mInputBuffer->RemoveFront(length);
  }

  RefPtr<CodedFrameProcessingPromise> p = mProcessingPromise.Ensure(__func__);

  DoDemuxVideo();

  return p;
}

void TrackBuffersManager::OnDemuxFailed(TrackType aTrack,
                                        const MediaResult& aError) {
  MOZ_ASSERT(OnTaskQueue());
  MSE_DEBUG("Failed to demux %s, failure:%s",
            aTrack == TrackType::kVideoTrack ? "video" : "audio",
            aError.ErrorName().get());
  switch (aError.Code()) {
    case NS_ERROR_DOM_MEDIA_END_OF_STREAM:
    case NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA:
      if (aTrack == TrackType::kVideoTrack) {
        DoDemuxAudio();
      } else {
        CompleteCodedFrameProcessing();
      }
      break;
    default:
      RejectProcessing(aError, __func__);
      break;
  }
}

void TrackBuffersManager::DoDemuxVideo() {
  MOZ_ASSERT(OnTaskQueue());
  if (!HasVideo()) {
    DoDemuxAudio();
    return;
  }
  mVideoTracks.mDemuxer->GetSamples(-1)
      ->Then(TaskQueueFromTaskQueue(), __func__, this,
             &TrackBuffersManager::OnVideoDemuxCompleted,
             &TrackBuffersManager::OnVideoDemuxFailed)
      ->Track(mVideoTracks.mDemuxRequest);
}

void TrackBuffersManager::MaybeDispatchEncryptedEvent(
    const nsTArray<RefPtr<MediaRawData>>& aSamples) {
  // Try and dispatch 'encrypted'. Won't go if ready state still HAVE_NOTHING.
  for (const RefPtr<MediaRawData>& sample : aSamples) {
    for (const nsTArray<uint8_t>& initData : sample->mCrypto.mInitDatas) {
      nsCOMPtr<nsIRunnable> r = new DispatchKeyNeededEvent(
          mParentDecoder, initData, sample->mCrypto.mInitDataType);
      mAbstractMainThread->Dispatch(r.forget());
    }
  }
}

void TrackBuffersManager::OnVideoDemuxCompleted(
    RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples) {
  mTaskQueueCapability->AssertOnCurrentThread();
  MSE_DEBUG("%zu video samples demuxed", aSamples->GetSamples().Length());
  mVideoTracks.mDemuxRequest.Complete();
  mVideoTracks.mQueuedSamples.AppendElements(aSamples->GetSamples());

  MaybeDispatchEncryptedEvent(aSamples->GetSamples());
  DoDemuxAudio();
}

void TrackBuffersManager::DoDemuxAudio() {
  MOZ_ASSERT(OnTaskQueue());
  if (!HasAudio()) {
    CompleteCodedFrameProcessing();
    return;
  }
  mAudioTracks.mDemuxer->GetSamples(-1)
      ->Then(TaskQueueFromTaskQueue(), __func__, this,
             &TrackBuffersManager::OnAudioDemuxCompleted,
             &TrackBuffersManager::OnAudioDemuxFailed)
      ->Track(mAudioTracks.mDemuxRequest);
}

void TrackBuffersManager::OnAudioDemuxCompleted(
    RefPtr<MediaTrackDemuxer::SamplesHolder> aSamples) {
  mTaskQueueCapability->AssertOnCurrentThread();
  MSE_DEBUG("%zu audio samples demuxed", aSamples->GetSamples().Length());
  // When using MSE, it's possible for each fragments to have their own
  // duration, with a duration that is incorrectly rounded. Ignore the trimming
  // information set by the demuxer to ensure a continous playback.
  for (const auto& sample : aSamples->GetSamples()) {
    sample->mOriginalPresentationWindow = Nothing();
  }
  mAudioTracks.mDemuxRequest.Complete();
  mAudioTracks.mQueuedSamples.AppendElements(aSamples->GetSamples());
  CompleteCodedFrameProcessing();

  MaybeDispatchEncryptedEvent(aSamples->GetSamples());
}

void TrackBuffersManager::CompleteCodedFrameProcessing() {
  MOZ_ASSERT(OnTaskQueue());
  AUTO_PROFILER_LABEL("TrackBuffersManager::CompleteCodedFrameProcessing",
                      MEDIA_PLAYBACK);

  // 1. For each coded frame in the media segment run the following steps:
  // Coded Frame Processing steps 1.1 to 1.21.

  if (mSourceBufferAttributes->GetAppendMode() ==
          SourceBufferAppendMode::Sequence &&
      mVideoTracks.mQueuedSamples.Length() &&
      mAudioTracks.mQueuedSamples.Length()) {
    // When we are in sequence mode, the order in which we process the frames is
    // important as it determines the future value of timestampOffset.
    // So we process the earliest sample first. See bug 1293576.
    TimeInterval videoInterval =
        PresentationInterval(mVideoTracks.mQueuedSamples);
    TimeInterval audioInterval =
        PresentationInterval(mAudioTracks.mQueuedSamples);
    if (audioInterval.mStart < videoInterval.mStart) {
      ProcessFrames(mAudioTracks.mQueuedSamples, mAudioTracks);
      ProcessFrames(mVideoTracks.mQueuedSamples, mVideoTracks);
    } else {
      ProcessFrames(mVideoTracks.mQueuedSamples, mVideoTracks);
      ProcessFrames(mAudioTracks.mQueuedSamples, mAudioTracks);
    }
  } else {
    ProcessFrames(mVideoTracks.mQueuedSamples, mVideoTracks);
    ProcessFrames(mAudioTracks.mQueuedSamples, mAudioTracks);
  }

#if defined(DEBUG)
  if (HasVideo()) {
    const auto& track = mVideoTracks.GetTrackBuffer();
    MOZ_ASSERT(track.IsEmpty() || track[0]->mKeyframe);
    for (uint32_t i = 1; i < track.Length(); i++) {
      MOZ_ASSERT(
          (track[i - 1]->mTrackInfo->GetID() == track[i]->mTrackInfo->GetID() &&
           track[i - 1]->mTimecode <= track[i]->mTimecode) ||
          track[i]->mKeyframe);
    }
  }
  if (HasAudio()) {
    const auto& track = mAudioTracks.GetTrackBuffer();
    MOZ_ASSERT(track.IsEmpty() || track[0]->mKeyframe);
    for (uint32_t i = 1; i < track.Length(); i++) {
      MOZ_ASSERT(
          (track[i - 1]->mTrackInfo->GetID() == track[i]->mTrackInfo->GetID() &&
           track[i - 1]->mTimecode <= track[i]->mTimecode) ||
          track[i]->mKeyframe);
    }
  }
#endif

  mVideoTracks.mQueuedSamples.Clear();
  mAudioTracks.mQueuedSamples.Clear();

  UpdateBufferedRanges();

  // Update our reported total size.
  mSizeSourceBuffer = mVideoTracks.mSizeBuffer + mAudioTracks.mSizeBuffer;

  // Return to step 6.4 of Segment Parser Loop algorithm
  // 4. If this SourceBuffer is full and cannot accept more media data, then set
  // the buffer full flag to true.
  if (mSizeSourceBuffer >= EvictionThreshold()) {
    mBufferFull = true;
  }

  // 5. If the input buffer does not contain a complete media segment, then jump
  // to the need more data step below.
  if (mParser->MediaSegmentRange().IsEmpty()) {
    ResolveProcessing(true, __func__);
    return;
  }

  mLastParsedEndTime = Some(std::max(mAudioTracks.mLastParsedEndTime,
                                     mVideoTracks.mLastParsedEndTime));

  // 6. Remove the media segment bytes from the beginning of the input buffer.
  // Clear our demuxer from any already processed data.
  int64_t safeToEvict =
      std::min(HasVideo() ? mVideoTracks.mDemuxer->GetEvictionOffset(
                                mVideoTracks.mLastParsedEndTime)
                          : INT64_MAX,
               HasAudio() ? mAudioTracks.mDemuxer->GetEvictionOffset(
                                mAudioTracks.mLastParsedEndTime)
                          : INT64_MAX);
  mCurrentInputBuffer->EvictBefore(safeToEvict);

  mInputDemuxer->NotifyDataRemoved();
  RecreateParser(true);

  // 7. Set append state to WAITING_FOR_SEGMENT.
  SetAppendState(AppendState::WAITING_FOR_SEGMENT);

  // 8. Jump to the loop top step above.
  ResolveProcessing(false, __func__);
}

void TrackBuffersManager::RejectProcessing(const MediaResult& aRejectValue,
                                           const char* aName) {
  mProcessingPromise.RejectIfExists(aRejectValue, __func__);
}

void TrackBuffersManager::ResolveProcessing(bool aResolveValue,
                                            const char* aName) {
  mProcessingPromise.ResolveIfExists(aResolveValue, __func__);
}

void TrackBuffersManager::CheckSequenceDiscontinuity(
    const TimeUnit& aPresentationTime) {
  if (mSourceBufferAttributes->GetAppendMode() ==
          SourceBufferAppendMode::Sequence &&
      mSourceBufferAttributes->HaveGroupStartTimestamp()) {
    mSourceBufferAttributes->SetTimestampOffset(
        mSourceBufferAttributes->GetGroupStartTimestamp() - aPresentationTime);
    mSourceBufferAttributes->SetGroupEndTimestamp(
        mSourceBufferAttributes->GetGroupStartTimestamp());
    mVideoTracks.mNeedRandomAccessPoint = true;
    mAudioTracks.mNeedRandomAccessPoint = true;
    mSourceBufferAttributes->ResetGroupStartTimestamp();
  }
}

TimeInterval TrackBuffersManager::PresentationInterval(
    const TrackBuffer& aSamples) const {
  TimeInterval presentationInterval =
      TimeInterval(aSamples[0]->mTime, aSamples[0]->GetEndTime());

  for (uint32_t i = 1; i < aSamples.Length(); i++) {
    auto& sample = aSamples[i];
    presentationInterval = presentationInterval.Span(
        TimeInterval(sample->mTime, sample->GetEndTime()));
  }
  return presentationInterval;
}

void TrackBuffersManager::ProcessFrames(TrackBuffer& aSamples,
                                        TrackData& aTrackData) {
  AUTO_PROFILER_LABEL("TrackBuffersManager::ProcessFrames", MEDIA_PLAYBACK);
  if (!aSamples.Length()) {
    return;
  }

  // 1. If generate timestamps flag equals true
  // Let presentation timestamp equal 0.
  // Otherwise
  // Let presentation timestamp be a double precision floating point
  // representation of the coded frame's presentation timestamp in seconds.
  TimeUnit presentationTimestamp = mSourceBufferAttributes->mGenerateTimestamps
                                       ? TimeUnit::Zero()
                                       : aSamples[0]->mTime;

  // 3. If mode equals "sequence" and group start timestamp is set, then run the
  // following steps:
  CheckSequenceDiscontinuity(presentationTimestamp);

  // 5. Let track buffer equal the track buffer that the coded frame will be
  // added to.
  auto& trackBuffer = aTrackData;

  TimeIntervals samplesRange;
  uint32_t sizeNewSamples = 0;
  TrackBuffer samples;  // array that will contain the frames to be added
                        // to our track buffer.

  // We assume that no frames are contiguous within a media segment and as such
  // don't need to check for discontinuity except for the first frame and should
  // a frame be ignored due to the target window.
  bool needDiscontinuityCheck = true;

  // Highest presentation time seen in samples block.
  TimeUnit highestSampleTime;

  if (aSamples.Length()) {
    aTrackData.mLastParsedEndTime = TimeUnit();
  }

  auto addToSamples = [&](MediaRawData* aSample,
                          const TimeInterval& aInterval) {
    aSample->mTime = aInterval.mStart;
    aSample->mDuration = aInterval.Length();
    aSample->mTrackInfo = trackBuffer.mLastInfo;
    MOZ_DIAGNOSTIC_ASSERT(aSample->HasValidTime());
    samplesRange += aInterval;
    sizeNewSamples += aSample->ComputedSizeOfIncludingThis();
    samples.AppendElement(aSample);
  };

  // Will be set to the last frame dropped due to being outside mAppendWindow.
  // It will be added prior the first following frame which can be added to the
  // track buffer.
  // This sample will be set with a duration of only 1us which will cause it to
  // be dropped once returned by the decoder.
  // This sample is required to "prime" the decoder so that the following frame
  // can be fully decoded.
  RefPtr<MediaRawData> previouslyDroppedSample;
  for (auto& sample : aSamples) {
    const TimeUnit sampleEndTime = sample->GetEndTime();
    if (sampleEndTime > aTrackData.mLastParsedEndTime) {
      aTrackData.mLastParsedEndTime = sampleEndTime;
    }

    // We perform step 10 right away as we can't do anything should a keyframe
    // be needed until we have one.

    // 10. If the need random access point flag on track buffer equals true,
    // then run the following steps:
    if (trackBuffer.mNeedRandomAccessPoint) {
      // 1. If the coded frame is not a random access point, then drop the coded
      // frame and jump to the top of the loop to start processing the next
      // coded frame.
      if (!sample->mKeyframe) {
        previouslyDroppedSample = nullptr;
        continue;
      }
      // 2. Set the need random access point flag on track buffer to false.
      trackBuffer.mNeedRandomAccessPoint = false;
    }

    // We perform step 1,2 and 4 at once:
    // 1. If generate timestamps flag equals true:
    //   Let presentation timestamp equal 0.
    //   Let decode timestamp equal 0.
    // Otherwise:
    //   Let presentation timestamp be a double precision floating point
    //   representation of the coded frame's presentation timestamp in seconds.
    //   Let decode timestamp be a double precision floating point
    //   representation of the coded frame's decode timestamp in seconds.

    // 2. Let frame duration be a double precision floating point representation
    // of the coded frame's duration in seconds. Step 3 is performed earlier or
    // when a discontinuity has been detected.
    // 4. If timestampOffset is not 0, then run the following steps:

    TimeUnit sampleTime = sample->mTime;
    TimeUnit sampleTimecode = sample->mTimecode;
    TimeUnit sampleDuration = sample->mDuration;
    // Keep the timestamp, set by js, in the time base of the container.
    TimeUnit timestampOffset =
        mSourceBufferAttributes->GetTimestampOffset().ToBase(sample->mTime);

    TimeInterval sampleInterval =
        mSourceBufferAttributes->mGenerateTimestamps
            ? TimeInterval(timestampOffset, timestampOffset + sampleDuration)
            : TimeInterval(timestampOffset + sampleTime,
                           timestampOffset + sampleTime + sampleDuration);
    TimeUnit decodeTimestamp = mSourceBufferAttributes->mGenerateTimestamps
                                   ? timestampOffset
                                   : timestampOffset + sampleTimecode;

    SAMPLE_DEBUG(
        "Processing %s frame [%" PRId64 ",%" PRId64 "] (adjusted:[%" PRId64
        ",%" PRId64 "]), dts:%" PRId64 ", duration:%" PRId64 ", kf:%d)",
        aTrackData.mInfo->mMimeType.get(), sample->mTime.ToMicroseconds(),
        sample->GetEndTime().ToMicroseconds(),
        sampleInterval.mStart.ToMicroseconds(),
        sampleInterval.mEnd.ToMicroseconds(),
        sample->mTimecode.ToMicroseconds(), sample->mDuration.ToMicroseconds(),
        sample->mKeyframe);

    // 6. If last decode timestamp for track buffer is set and decode timestamp
    // is less than last decode timestamp: OR If last decode timestamp for track
    // buffer is set and the difference between decode timestamp and last decode
    // timestamp is greater than 2 times last frame duration:
    if (needDiscontinuityCheck && trackBuffer.mLastDecodeTimestamp.isSome() &&
        (decodeTimestamp < trackBuffer.mLastDecodeTimestamp.ref() ||
         (decodeTimestamp - trackBuffer.mLastDecodeTimestamp.ref() >
          trackBuffer.mLongestFrameDuration * 2))) {
      MSE_DEBUG("Discontinuity detected.");
      SourceBufferAppendMode appendMode =
          mSourceBufferAttributes->GetAppendMode();

      // 1a. If mode equals "segments":
      if (appendMode == SourceBufferAppendMode::Segments) {
        // Set group end timestamp to presentation timestamp.
        mSourceBufferAttributes->SetGroupEndTimestamp(sampleInterval.mStart);
      }
      // 1b. If mode equals "sequence":
      if (appendMode == SourceBufferAppendMode::Sequence) {
        // Set group start timestamp equal to the group end timestamp.
        mSourceBufferAttributes->SetGroupStartTimestamp(
            mSourceBufferAttributes->GetGroupEndTimestamp());
      }
      for (auto& track : GetTracksList()) {
        // 2. Unset the last decode timestamp on all track buffers.
        // 3. Unset the last frame duration on all track buffers.
        // 4. Unset the highest end timestamp on all track buffers.
        // 5. Set the need random access point flag on all track buffers to
        // true.
        track->ResetAppendState();
      }
      // 6. Jump to the Loop Top step above to restart processing of the current
      // coded frame. Rather that restarting the process for the frame, we run
      // the first steps again instead.
      // 3. If mode equals "sequence" and group start timestamp is set, then run
      // the following steps:
      TimeUnit presentationTimestamp =
          mSourceBufferAttributes->mGenerateTimestamps ? TimeUnit()
                                                       : sampleTime;
      CheckSequenceDiscontinuity(presentationTimestamp);

      if (!sample->mKeyframe) {
        previouslyDroppedSample = nullptr;
        continue;
      }
      if (appendMode == SourceBufferAppendMode::Sequence) {
        // mSourceBufferAttributes->GetTimestampOffset() was modified during
        // CheckSequenceDiscontinuity. We need to update our variables.
        timestampOffset = mSourceBufferAttributes->GetTimestampOffset();
        sampleInterval =
            mSourceBufferAttributes->mGenerateTimestamps
                ? TimeInterval(timestampOffset,
                               timestampOffset + sampleDuration)
                : TimeInterval(timestampOffset + sampleTime,
                               timestampOffset + sampleTime + sampleDuration);
        decodeTimestamp = mSourceBufferAttributes->mGenerateTimestamps
                              ? timestampOffset
                              : timestampOffset + sampleTimecode;
      }
      trackBuffer.mNeedRandomAccessPoint = false;
      needDiscontinuityCheck = false;
    }

    // 7. Let frame end timestamp equal the sum of presentation timestamp and
    // frame duration. This is sampleInterval.mEnd

    // 8. If presentation timestamp is less than appendWindowStart, then set the
    // need random access point flag to true, drop the coded frame, and jump to
    // the top of the loop to start processing the next coded frame.
    // 9. If frame end timestamp is greater than appendWindowEnd, then set the
    // need random access point flag to true, drop the coded frame, and jump to
    // the top of the loop to start processing the next coded frame.
    if (!mAppendWindow.ContainsStrict(sampleInterval)) {
      if (mAppendWindow.IntersectsStrict(sampleInterval)) {
        // 8. Note: Some implementations MAY choose to collect some of these
        //    coded frames with presentation timestamp less than
        //    appendWindowStart and use them to generate a splice at the first
        //    coded frame that has a presentation timestamp greater than or
        //    equal to appendWindowStart even if that frame is not a random
        //    access point. Supporting this requires multiple decoders or faster
        //    than real-time decoding so for now this behavior will not be a
        //    normative requirement.
        // 9. Note: Some implementations MAY choose to collect coded frames with
        //    presentation timestamp less than appendWindowEnd and frame end
        //    timestamp greater than appendWindowEnd and use them to generate a
        //    splice across the portion of the collected coded frames within the
        //    append window at time of collection, and the beginning portion of
        //    later processed frames which only partially overlap the end of the
        //    collected coded frames. Supporting this requires multiple decoders
        //    or faster than real-time decoding so for now this behavior will
        //    not be a normative requirement. In conjunction with collecting
        //    coded frames that span appendWindowStart, implementations MAY thus
        //    support gapless audio splicing.
        TimeInterval intersection = mAppendWindow.Intersection(sampleInterval);
        sample->mOriginalPresentationWindow = Some(sampleInterval);
        MSE_DEBUGV("will truncate frame from [%" PRId64 ",%" PRId64
                   "] to [%" PRId64 ",%" PRId64 "]",
                   sampleInterval.mStart.ToMicroseconds(),
                   sampleInterval.mEnd.ToMicroseconds(),
                   intersection.mStart.ToMicroseconds(),
                   intersection.mEnd.ToMicroseconds());
        sampleInterval = intersection;
      } else {
        sample->mOriginalPresentationWindow = Some(sampleInterval);
        sample->mTimecode = decodeTimestamp;
        previouslyDroppedSample = sample;
        MSE_DEBUGV("frame [%" PRId64 ",%" PRId64
                   "] outside appendWindow [%" PRId64 ",%" PRId64 "] dropping",
                   sampleInterval.mStart.ToMicroseconds(),
                   sampleInterval.mEnd.ToMicroseconds(),
                   mAppendWindow.mStart.ToMicroseconds(),
                   mAppendWindow.mEnd.ToMicroseconds());
        if (samples.Length()) {
          // We are creating a discontinuity in the samples.
          // Insert the samples processed so far.
          InsertFrames(samples, samplesRange, trackBuffer);
          samples.Clear();
          samplesRange = TimeIntervals();
          trackBuffer.mSizeBuffer += sizeNewSamples;
          sizeNewSamples = 0;
          UpdateHighestTimestamp(trackBuffer, highestSampleTime);
        }
        trackBuffer.mNeedRandomAccessPoint = true;
        needDiscontinuityCheck = true;
        continue;
      }
    }
    if (previouslyDroppedSample) {
      MSE_DEBUGV("Adding silent frame");
      // This "silent" sample will be added so that it starts exactly before the
      // first usable one. The duration of the actual sample will be adjusted so
      // that the total duration staty the same.
      // Setting a dummy presentation window of 1us will cause this sample to be
      // dropped after decoding by the AudioTrimmer (if audio).
      TimeInterval previouslyDroppedSampleInterval =
          TimeInterval(sampleInterval.mStart,
                       sampleInterval.mStart + TimeUnit::FromMicroseconds(1));
      addToSamples(previouslyDroppedSample, previouslyDroppedSampleInterval);
      previouslyDroppedSample = nullptr;
      sampleInterval.mStart += previouslyDroppedSampleInterval.Length();
    }

    sample->mTimecode = decodeTimestamp;
    addToSamples(sample, sampleInterval);

    // Steps 11,12,13,14, 15 and 16 will be done in one block in InsertFrames.

    trackBuffer.mLongestFrameDuration =
        trackBuffer.mLastFrameDuration.isSome()
            ? sample->mKeyframe
                  ? sampleDuration
                  : std::max(sampleDuration, trackBuffer.mLongestFrameDuration)
            : sampleDuration;

    // 17. Set last decode timestamp for track buffer to decode timestamp.
    trackBuffer.mLastDecodeTimestamp = Some(decodeTimestamp);
    // 18. Set last frame duration for track buffer to frame duration.
    trackBuffer.mLastFrameDuration = Some(sampleDuration);

    // 19. If highest end timestamp for track buffer is unset or frame end
    // timestamp is greater than highest end timestamp, then set highest end
    // timestamp for track buffer to frame end timestamp.
    if (trackBuffer.mHighestEndTimestamp.isNothing() ||
        sampleInterval.mEnd > trackBuffer.mHighestEndTimestamp.ref()) {
      trackBuffer.mHighestEndTimestamp = Some(sampleInterval.mEnd);
    }
    if (sampleInterval.mStart > highestSampleTime) {
      highestSampleTime = sampleInterval.mStart;
    }
    // 20. If frame end timestamp is greater than group end timestamp, then set
    // group end timestamp equal to frame end timestamp.
    if (sampleInterval.mEnd > mSourceBufferAttributes->GetGroupEndTimestamp()) {
      mSourceBufferAttributes->SetGroupEndTimestamp(sampleInterval.mEnd);
    }
    // 21. If generate timestamps flag equals true, then set timestampOffset
    // equal to frame end timestamp.
    if (mSourceBufferAttributes->mGenerateTimestamps) {
      mSourceBufferAttributes->SetTimestampOffset(sampleInterval.mEnd);
    }
  }

  if (samples.Length()) {
    InsertFrames(samples, samplesRange, trackBuffer);
    trackBuffer.mSizeBuffer += sizeNewSamples;
    UpdateHighestTimestamp(trackBuffer, highestSampleTime);
  }
}

bool TrackBuffersManager::CheckNextInsertionIndex(TrackData& aTrackData,
                                                  const TimeUnit& aSampleTime) {
  if (aTrackData.mNextInsertionIndex.isSome()) {
    return true;
  }

  const TrackBuffer& data = aTrackData.GetTrackBuffer();

  if (data.IsEmpty() || aSampleTime < aTrackData.mBufferedRanges.GetStart()) {
    aTrackData.mNextInsertionIndex = Some(0u);
    return true;
  }

  // Find which discontinuity we should insert the frame before.
  TimeInterval target;
  for (const auto& interval : aTrackData.mBufferedRanges) {
    if (aSampleTime < interval.mStart) {
      target = interval;
      break;
    }
  }
  if (target.IsEmpty()) {
    // No target found, it will be added at the end of the track buffer.
    aTrackData.mNextInsertionIndex = Some(uint32_t(data.Length()));
    return true;
  }
  // We now need to find the first frame of the searched interval.
  // We will insert our new frames right before.
  for (uint32_t i = 0; i < data.Length(); i++) {
    const RefPtr<MediaRawData>& sample = data[i];
    if (sample->mTime >= target.mStart ||
        sample->GetEndTime() > target.mStart) {
      aTrackData.mNextInsertionIndex = Some(i);
      return true;
    }
  }
  NS_ASSERTION(false, "Insertion Index Not Found");
  return false;
}

void TrackBuffersManager::InsertFrames(TrackBuffer& aSamples,
                                       const TimeIntervals& aIntervals,
                                       TrackData& aTrackData) {
  AUTO_PROFILER_LABEL("TrackBuffersManager::InsertFrames", MEDIA_PLAYBACK);
  // 5. Let track buffer equal the track buffer that the coded frame will be
  // added to.
  auto& trackBuffer = aTrackData;

  MSE_DEBUGV("Processing %zu %s frames(start:%" PRId64 " end:%" PRId64 ")",
             aSamples.Length(), aTrackData.mInfo->mMimeType.get(),
             aIntervals.GetStart().ToMicroseconds(),
             aIntervals.GetEnd().ToMicroseconds());
  if (profiler_thread_is_being_profiled_for_markers()) {
    nsPrintfCString markerString(
        "Processing %zu %s frames(start:%" PRId64 " end:%" PRId64 ")",
        aSamples.Length(), aTrackData.mInfo->mMimeType.get(),
        aIntervals.GetStart().ToMicroseconds(),
        aIntervals.GetEnd().ToMicroseconds());
    PROFILER_MARKER_TEXT("InsertFrames", MEDIA_PLAYBACK, {}, markerString);
  }

  // 11. Let spliced audio frame be an unset variable for holding audio splice
  // information
  // 12. Let spliced timed text frame be an unset variable for holding timed
  // text splice information

  // 13. If last decode timestamp for track buffer is unset and presentation
  // timestamp falls within the presentation interval of a coded frame in track
  // buffer,then run the following steps: For now we only handle replacing
  // existing frames with the new ones. So we skip this step.

  // 14. Remove existing coded frames in track buffer:
  //   a) If highest end timestamp for track buffer is not set:
  //      Remove all coded frames from track buffer that have a presentation
  //      timestamp greater than or equal to presentation timestamp and less
  //      than frame end timestamp.
  //   b) If highest end timestamp for track buffer is set and less than or
  //   equal to presentation timestamp:
  //      Remove all coded frames from track buffer that have a presentation
  //      timestamp greater than or equal to highest end timestamp and less than
  //      frame end timestamp

  // There is an ambiguity on how to remove frames, which was lodged with:
  // https://www.w3.org/Bugs/Public/show_bug.cgi?id=28710, implementing as per
  // bug description.

  // 15. Remove decoding dependencies of the coded frames removed in the
  // previous step: Remove all coded frames between the coded frames removed in
  // the previous step and the next random access point after those removed
  // frames.

  if (trackBuffer.mBufferedRanges.IntersectsStrict(aIntervals)) {
    if (aSamples[0]->mKeyframe &&
        (mType.Type() == MEDIAMIMETYPE("video/webm") ||
         mType.Type() == MEDIAMIMETYPE("audio/webm"))) {
      // We are starting a new GOP, we do not have to worry about breaking an
      // existing current coded frame group. Reset the next insertion index
      // so the search for when to start our frames removal can be exhaustive.
      // This is a workaround for bug 1276184 and only until either bug 1277733
      // or bug 1209386 is fixed.
      // With the webm container, we can't always properly determine the
      // duration of the last frame, which may cause the last frame of a cluster
      // to overlap the following frame.
      trackBuffer.mNextInsertionIndex.reset();
    }
    uint32_t index = RemoveFrames(aIntervals, trackBuffer,
                                  trackBuffer.mNextInsertionIndex.refOr(0),
                                  RemovalMode::kTruncateFrame);
    if (index) {
      trackBuffer.mNextInsertionIndex = Some(index);
    }
  }

  // 16. Add the coded frame with the presentation timestamp, decode timestamp,
  // and frame duration to the track buffer.
  if (!CheckNextInsertionIndex(aTrackData, aSamples[0]->mTime)) {
    RejectProcessing(NS_ERROR_FAILURE, __func__);
    return;
  }

  // Adjust our demuxing index if necessary.
  if (trackBuffer.mNextGetSampleIndex.isSome()) {
    if (trackBuffer.mNextInsertionIndex.ref() ==
            trackBuffer.mNextGetSampleIndex.ref() &&
        aIntervals.GetEnd() >= trackBuffer.mNextSampleTime) {
      MSE_DEBUG("Next sample to be played got overwritten");
      trackBuffer.mNextGetSampleIndex.reset();
      ResetEvictionIndex(trackBuffer);
    } else if (trackBuffer.mNextInsertionIndex.ref() <=
               trackBuffer.mNextGetSampleIndex.ref()) {
      trackBuffer.mNextGetSampleIndex.ref() += aSamples.Length();
      // We could adjust the eviction index so that the new data gets added to
      // the evictable amount (as it is prior currentTime). However, considering
      // new data is being added prior the current playback, it's likely that
      // this data will be played next, and as such we probably don't want to
      // have it evicted too early. So instead reset the eviction index instead.
      ResetEvictionIndex(trackBuffer);
    }
  }

  TrackBuffer& data = trackBuffer.GetTrackBuffer();
  data.InsertElementsAt(trackBuffer.mNextInsertionIndex.ref(), aSamples);
  trackBuffer.mNextInsertionIndex.ref() += aSamples.Length();

  // Update our buffered range with new sample interval.
  trackBuffer.mBufferedRanges += aIntervals;
  // We allow a fuzz factor in our interval of half a frame length,
  // as fuzz is +/- value, giving an effective leeway of a full frame
  // length.
  if (!aIntervals.IsEmpty()) {
    TimeIntervals range(aIntervals);
    range.SetFuzz(trackBuffer.mLongestFrameDuration / 2);
    trackBuffer.mSanitizedBufferedRanges += range;
  }
}

void TrackBuffersManager::UpdateHighestTimestamp(
    TrackData& aTrackData, const media::TimeUnit& aHighestTime) {
  if (aHighestTime > aTrackData.mHighestStartTimestamp) {
    MutexAutoLock mut(mMutex);
    aTrackData.mHighestStartTimestamp = aHighestTime;
  }
}

uint32_t TrackBuffersManager::RemoveFrames(const TimeIntervals& aIntervals,
                                           TrackData& aTrackData,
                                           uint32_t aStartIndex,
                                           RemovalMode aMode) {
  AUTO_PROFILER_LABEL("TrackBuffersManager::RemoveFrames", MEDIA_PLAYBACK);
  TrackBuffer& data = aTrackData.GetTrackBuffer();
  Maybe<uint32_t> firstRemovedIndex;
  uint32_t lastRemovedIndex = 0;

  // We loop from aStartIndex to avoid removing frames that we inserted earlier
  // and part of the current coded frame group. This is allows to handle step
  // 14 of the coded frame processing algorithm without having to check the
  // value of highest end timestamp: "Remove existing coded frames in track
  // buffer:
  //  If highest end timestamp for track buffer is not set:
  //   Remove all coded frames from track buffer that have a presentation
  //   timestamp greater than or equal to presentation timestamp and less than
  //   frame end timestamp.
  //  If highest end timestamp for track buffer is set and less than or equal to
  //  presentation timestamp:
  //   Remove all coded frames from track buffer that have a presentation
  //   timestamp greater than or equal to highest end timestamp and less than
  //   frame end timestamp"
  TimeUnit intervalsEnd = aIntervals.GetEnd();
  for (uint32_t i = aStartIndex; i < data.Length(); i++) {
    RefPtr<MediaRawData>& sample = data[i];
    if (aIntervals.ContainsStrict(sample->mTime)) {
      // The start of this existing frame will be overwritten, we drop that
      // entire frame.
      MSE_DEBUGV("overridding start of frame [%" PRId64 ",%" PRId64
                 "] with [%" PRId64 ",%" PRId64 "] dropping",
                 sample->mTime.ToMicroseconds(),
                 sample->GetEndTime().ToMicroseconds(),
                 aIntervals.GetStart().ToMicroseconds(),
                 aIntervals.GetEnd().ToMicroseconds());
      if (firstRemovedIndex.isNothing()) {
        firstRemovedIndex = Some(i);
      }
      lastRemovedIndex = i;
      continue;
    }
    TimeInterval sampleInterval(sample->mTime, sample->GetEndTime());
    if (aMode == RemovalMode::kTruncateFrame &&
        aIntervals.IntersectsStrict(sampleInterval)) {
      // The sample to be overwritten is only partially covered.
      TimeIntervals intersection =
          Intersection(aIntervals, TimeIntervals(sampleInterval));
      bool found = false;
      TimeUnit startTime = intersection.GetStart(&found);
      MOZ_DIAGNOSTIC_ASSERT(found, "Must intersect with added coded frames");
      Unused << found;
      // Signal that this frame should be truncated when decoded.
      if (!sample->mOriginalPresentationWindow) {
        sample->mOriginalPresentationWindow = Some(sampleInterval);
      }
      MOZ_ASSERT(startTime > sample->mTime);
      sample->mDuration = startTime - sample->mTime;
      MOZ_DIAGNOSTIC_ASSERT(sample->mDuration.IsValid());
      MSE_DEBUGV("partial overwrite of frame [%" PRId64 ",%" PRId64
                 "] with [%" PRId64 ",%" PRId64
                 "] trim to "
                 "[%" PRId64 ",%" PRId64 "]",
                 sampleInterval.mStart.ToMicroseconds(),
                 sampleInterval.mEnd.ToMicroseconds(),
                 aIntervals.GetStart().ToMicroseconds(),
                 aIntervals.GetEnd().ToMicroseconds(),
                 sample->mTime.ToMicroseconds(),
                 sample->GetEndTime().ToMicroseconds());
      continue;
    }

    if (sample->mTime >= intervalsEnd) {
      // We can break the loop now. All frames up to the next keyframe will be
      // removed during the next step.
      break;
    }
  }

  if (firstRemovedIndex.isNothing()) {
    return 0;
  }

  // Remove decoding dependencies of the coded frames removed in the previous
  // step: Remove all coded frames between the coded frames removed in the
  // previous step and the next random access point after those removed frames.
  for (uint32_t i = lastRemovedIndex + 1; i < data.Length(); i++) {
    const RefPtr<MediaRawData>& sample = data[i];
    if (sample->mKeyframe) {
      break;
    }
    lastRemovedIndex = i;
  }

  TimeUnit maxSampleDuration;
  uint32_t sizeRemoved = 0;
  TimeIntervals removedIntervals;
  for (uint32_t i = firstRemovedIndex.ref(); i <= lastRemovedIndex; i++) {
    const RefPtr<MediaRawData> sample = data[i];
    TimeInterval sampleInterval =
        TimeInterval(sample->mTime, sample->GetEndTime());
    removedIntervals += sampleInterval;
    if (sample->mDuration > maxSampleDuration) {
      maxSampleDuration = sample->mDuration;
    }
    sizeRemoved += sample->ComputedSizeOfIncludingThis();
  }
  aTrackData.mSizeBuffer -= sizeRemoved;

  MSE_DEBUG("Removing frames from:%u (frames:%u) ([%f, %f))",
            firstRemovedIndex.ref(),
            lastRemovedIndex - firstRemovedIndex.ref() + 1,
            removedIntervals.GetStart().ToSeconds(),
            removedIntervals.GetEnd().ToSeconds());
  if (profiler_thread_is_being_profiled_for_markers()) {
    nsPrintfCString markerString(
        "Removing frames from:%u (frames:%u) ([%f, %f))",
        firstRemovedIndex.ref(), lastRemovedIndex - firstRemovedIndex.ref() + 1,
        removedIntervals.GetStart().ToSeconds(),
        removedIntervals.GetEnd().ToSeconds());
    PROFILER_MARKER_TEXT("RemoveFrames", MEDIA_PLAYBACK, {}, markerString);
  }

  if (aTrackData.mNextGetSampleIndex.isSome()) {
    if (aTrackData.mNextGetSampleIndex.ref() >= firstRemovedIndex.ref() &&
        aTrackData.mNextGetSampleIndex.ref() <= lastRemovedIndex) {
      MSE_DEBUG("Next sample to be played got evicted");
      aTrackData.mNextGetSampleIndex.reset();
      ResetEvictionIndex(aTrackData);
    } else if (aTrackData.mNextGetSampleIndex.ref() > lastRemovedIndex) {
      uint32_t samplesRemoved = lastRemovedIndex - firstRemovedIndex.ref() + 1;
      aTrackData.mNextGetSampleIndex.ref() -= samplesRemoved;
      if (aTrackData.mEvictionIndex.mLastIndex > lastRemovedIndex) {
        MOZ_DIAGNOSTIC_ASSERT(
            aTrackData.mEvictionIndex.mLastIndex >= samplesRemoved &&
                aTrackData.mEvictionIndex.mEvictable >= sizeRemoved,
            "Invalid eviction index");
        MutexAutoLock mut(mMutex);
        aTrackData.mEvictionIndex.mLastIndex -= samplesRemoved;
        aTrackData.mEvictionIndex.mEvictable -= sizeRemoved;
      } else {
        ResetEvictionIndex(aTrackData);
      }
    }
  }

  if (aTrackData.mNextInsertionIndex.isSome()) {
    if (aTrackData.mNextInsertionIndex.ref() > firstRemovedIndex.ref() &&
        aTrackData.mNextInsertionIndex.ref() <= lastRemovedIndex + 1) {
      aTrackData.ResetAppendState();
      MSE_DEBUG("NextInsertionIndex got reset.");
    } else if (aTrackData.mNextInsertionIndex.ref() > lastRemovedIndex + 1) {
      aTrackData.mNextInsertionIndex.ref() -=
          lastRemovedIndex - firstRemovedIndex.ref() + 1;
    }
  }

  // Update our buffered range to exclude the range just removed.
  aTrackData.mBufferedRanges -= removedIntervals;

  // Recalculate sanitized buffered ranges.
  aTrackData.mSanitizedBufferedRanges = aTrackData.mBufferedRanges;
  aTrackData.mSanitizedBufferedRanges.SetFuzz(maxSampleDuration / 2);

  data.RemoveElementsAt(firstRemovedIndex.ref(),
                        lastRemovedIndex - firstRemovedIndex.ref() + 1);

  if (removedIntervals.GetEnd() >= aTrackData.mHighestStartTimestamp &&
      removedIntervals.GetStart() <= aTrackData.mHighestStartTimestamp) {
    // The sample with the highest presentation time got removed.
    // Rescan the trackbuffer to determine the new one.
    TimeUnit highestStartTime;
    for (const auto& sample : data) {
      if (sample->mTime > highestStartTime) {
        highestStartTime = sample->mTime;
      }
    }
    MutexAutoLock mut(mMutex);
    aTrackData.mHighestStartTimestamp = highestStartTime;
  }

  return firstRemovedIndex.ref();
}

void TrackBuffersManager::RecreateParser(bool aReuseInitData) {
  MOZ_ASSERT(OnTaskQueue());
  // Recreate our parser for only the data remaining. This is required
  // as it has parsed the entire InputBuffer provided.
  // Once the old TrackBuffer/MediaSource implementation is removed
  // we can optimize this part. TODO
  if (mParser) {
    DDUNLINKCHILD(mParser.get());
  }
  mParser = ContainerParser::CreateForMIMEType(mType);
  DDLINKCHILD("parser", mParser.get());
  if (aReuseInitData && mInitData) {
    TimeUnit start, end;
    mParser->ParseStartAndEndTimestamps(MediaSpan(mInitData), start, end);
    mProcessedInput = mInitData->Length();
  } else {
    mProcessedInput = 0;
  }
}

nsTArray<TrackBuffersManager::TrackData*> TrackBuffersManager::GetTracksList() {
  nsTArray<TrackData*> tracks;
  if (HasVideo()) {
    tracks.AppendElement(&mVideoTracks);
  }
  if (HasAudio()) {
    tracks.AppendElement(&mAudioTracks);
  }
  return tracks;
}

nsTArray<const TrackBuffersManager::TrackData*>
TrackBuffersManager::GetTracksList() const {
  nsTArray<const TrackData*> tracks;
  if (HasVideo()) {
    tracks.AppendElement(&mVideoTracks);
  }
  if (HasAudio()) {
    tracks.AppendElement(&mAudioTracks);
  }
  return tracks;
}

void TrackBuffersManager::SetAppendState(AppendState aAppendState) {
  MSE_DEBUG("AppendState changed from %s to %s",
            AppendStateToStr(mSourceBufferAttributes->GetAppendState()),
            AppendStateToStr(aAppendState));
  mSourceBufferAttributes->SetAppendState(aAppendState);
}

MediaInfo TrackBuffersManager::GetMetadata() const {
  MutexAutoLock mut(mMutex);
  return mInfo;
}

const TimeIntervals& TrackBuffersManager::Buffered(
    TrackInfo::TrackType aTrack) const {
  MOZ_ASSERT(OnTaskQueue());
  return GetTracksData(aTrack).mBufferedRanges;
}

const media::TimeUnit& TrackBuffersManager::HighestStartTime(
    TrackInfo::TrackType aTrack) const {
  MOZ_ASSERT(OnTaskQueue());
  return GetTracksData(aTrack).mHighestStartTimestamp;
}

TimeIntervals TrackBuffersManager::SafeBuffered(
    TrackInfo::TrackType aTrack) const {
  MutexAutoLock mut(mMutex);
  return aTrack == TrackInfo::kVideoTrack ? mVideoBufferedRanges
                                          : mAudioBufferedRanges;
}

TimeUnit TrackBuffersManager::HighestStartTime() const {
  MutexAutoLock mut(mMutex);
  TimeUnit highestStartTime;
  for (auto& track : GetTracksList()) {
    highestStartTime =
        std::max(track->mHighestStartTimestamp, highestStartTime);
  }
  return highestStartTime;
}

TimeUnit TrackBuffersManager::HighestEndTime() const {
  MutexAutoLock mut(mMutex);

  nsTArray<const TimeIntervals*> tracks;
  if (HasVideo()) {
    tracks.AppendElement(&mVideoBufferedRanges);
  }
  if (HasAudio()) {
    tracks.AppendElement(&mAudioBufferedRanges);
  }
  return HighestEndTime(tracks);
}

TimeUnit TrackBuffersManager::HighestEndTime(
    nsTArray<const TimeIntervals*>& aTracks) const {
  mMutex.AssertCurrentThreadOwns();

  TimeUnit highestEndTime;

  for (const auto& trackRanges : aTracks) {
    highestEndTime = std::max(trackRanges->GetEnd(), highestEndTime);
  }
  return highestEndTime;
}

void TrackBuffersManager::ResetEvictionIndex(TrackData& aTrackData) {
  MutexAutoLock mut(mMutex);
  aTrackData.mEvictionIndex.Reset();
}

void TrackBuffersManager::UpdateEvictionIndex(TrackData& aTrackData,
                                              uint32_t currentIndex) {
  uint32_t evictable = 0;
  TrackBuffer& data = aTrackData.GetTrackBuffer();
  MOZ_DIAGNOSTIC_ASSERT(currentIndex >= aTrackData.mEvictionIndex.mLastIndex,
                        "Invalid call");
  MOZ_DIAGNOSTIC_ASSERT(
      currentIndex == data.Length() || data[currentIndex]->mKeyframe,
      "Must stop at keyframe");

  for (uint32_t i = aTrackData.mEvictionIndex.mLastIndex; i < currentIndex;
       i++) {
    evictable += data[i]->ComputedSizeOfIncludingThis();
  }
  aTrackData.mEvictionIndex.mLastIndex = currentIndex;
  MutexAutoLock mut(mMutex);
  aTrackData.mEvictionIndex.mEvictable += evictable;
}

const TrackBuffersManager::TrackBuffer& TrackBuffersManager::GetTrackBuffer(
    TrackInfo::TrackType aTrack) const {
  MOZ_ASSERT(OnTaskQueue());
  return GetTracksData(aTrack).GetTrackBuffer();
}

uint32_t TrackBuffersManager::FindSampleIndex(const TrackBuffer& aTrackBuffer,
                                              const TimeInterval& aInterval) {
  TimeUnit target = aInterval.mStart - aInterval.mFuzz;

  for (uint32_t i = 0; i < aTrackBuffer.Length(); i++) {
    const RefPtr<MediaRawData>& sample = aTrackBuffer[i];
    if (sample->mTime >= target || sample->GetEndTime() > target) {
      return i;
    }
  }
  NS_ASSERTION(false, "FindSampleIndex called with invalid arguments");

  return 0;
}

TimeUnit TrackBuffersManager::Seek(TrackInfo::TrackType aTrack,
                                   const TimeUnit& aTime,
                                   const TimeUnit& aFuzz) {
  MOZ_ASSERT(OnTaskQueue());
  AUTO_PROFILER_LABEL("TrackBuffersManager::Seek", MEDIA_PLAYBACK);
  auto& trackBuffer = GetTracksData(aTrack);
  const TrackBuffersManager::TrackBuffer& track = GetTrackBuffer(aTrack);

  if (!track.Length()) {
    // This a reset. It will be followed by another valid seek.
    trackBuffer.mNextGetSampleIndex = Some(uint32_t(0));
    trackBuffer.mNextSampleTimecode = TimeUnit();
    trackBuffer.mNextSampleTime = TimeUnit();
    ResetEvictionIndex(trackBuffer);
    return TimeUnit();
  }

  uint32_t i = 0;

  if (aTime != TimeUnit()) {
    // Determine the interval of samples we're attempting to seek to.
    TimeIntervals buffered = trackBuffer.mBufferedRanges;
    // Fuzz factor is +/- aFuzz; as we want to only eliminate gaps
    // that are less than aFuzz wide, we set a fuzz factor aFuzz/2.
    buffered.SetFuzz(aFuzz / 2);
    TimeIntervals::IndexType index = buffered.Find(aTime);
    MOZ_ASSERT(index != TimeIntervals::NoIndex,
               "We shouldn't be called if aTime isn't buffered");
    TimeInterval target = buffered[index];
    target.mFuzz = aFuzz;
    i = FindSampleIndex(track, target);
  }

  Maybe<TimeUnit> lastKeyFrameTime;
  TimeUnit lastKeyFrameTimecode;
  uint32_t lastKeyFrameIndex = 0;
  for (; i < track.Length(); i++) {
    const RefPtr<MediaRawData>& sample = track[i];
    TimeUnit sampleTime = sample->mTime;
    if (sampleTime > aTime && lastKeyFrameTime.isSome()) {
      break;
    }
    if (sample->mKeyframe) {
      lastKeyFrameTimecode = sample->mTimecode;
      lastKeyFrameTime = Some(sampleTime);
      lastKeyFrameIndex = i;
    }
    if (sampleTime == aTime ||
        (sampleTime > aTime && lastKeyFrameTime.isSome())) {
      break;
    }
  }
  MSE_DEBUG("Keyframe %s found at %" PRId64 " @ %u",
            lastKeyFrameTime.isSome() ? "" : "not",
            lastKeyFrameTime.refOr(TimeUnit()).ToMicroseconds(),
            lastKeyFrameIndex);

  trackBuffer.mNextGetSampleIndex = Some(lastKeyFrameIndex);
  trackBuffer.mNextSampleTimecode = lastKeyFrameTimecode;
  trackBuffer.mNextSampleTime = lastKeyFrameTime.refOr(TimeUnit());
  ResetEvictionIndex(trackBuffer);
  UpdateEvictionIndex(trackBuffer, lastKeyFrameIndex);

  return lastKeyFrameTime.refOr(TimeUnit());
}

uint32_t TrackBuffersManager::SkipToNextRandomAccessPoint(
    TrackInfo::TrackType aTrack, const TimeUnit& aTimeThreadshold,
    const media::TimeUnit& aFuzz, bool& aFound) {
  mTaskQueueCapability->AssertOnCurrentThread();
  AUTO_PROFILER_LABEL("TrackBuffersManager::SkipToNextRandomAccessPoint",
                      MEDIA_PLAYBACK);
  uint32_t parsed = 0;
  auto& trackData = GetTracksData(aTrack);
  const TrackBuffer& track = GetTrackBuffer(aTrack);
  aFound = false;

  // SkipToNextRandomAccessPoint can only be called if aTimeThreadshold is known
  // to be buffered.

  if (NS_FAILED(SetNextGetSampleIndexIfNeeded(aTrack, aFuzz))) {
    return 0;
  }

  TimeUnit nextSampleTimecode = trackData.mNextSampleTimecode;
  TimeUnit nextSampleTime = trackData.mNextSampleTime;
  uint32_t i = trackData.mNextGetSampleIndex.ref();
  int32_t originalPos = i;

  for (; i < track.Length(); i++) {
    const MediaRawData* sample =
        GetSample(aTrack, i, nextSampleTimecode, nextSampleTime, aFuzz);
    if (!sample) {
      break;
    }
    if (sample->mKeyframe && sample->mTime >= aTimeThreadshold) {
      aFound = true;
      break;
    }
    nextSampleTimecode = sample->GetEndTimecode();
    nextSampleTime = sample->GetEndTime();
    parsed++;
  }

  // Adjust the next demux time and index so that the next call to
  // SkipToNextRandomAccessPoint will not count again the parsed sample as
  // skipped.
  if (aFound) {
    trackData.mNextSampleTimecode = track[i]->mTimecode;
    trackData.mNextSampleTime = track[i]->mTime;
    trackData.mNextGetSampleIndex = Some(i);
  } else if (i > 0) {
    // Go back to the previous keyframe or the original position so the next
    // demux can succeed and be decoded.
    for (int j = i - 1; j >= originalPos; j--) {
      const RefPtr<MediaRawData>& sample = track[j];
      if (sample->mKeyframe) {
        trackData.mNextSampleTimecode = sample->mTimecode;
        trackData.mNextSampleTime = sample->mTime;
        trackData.mNextGetSampleIndex = Some(uint32_t(j));
        // We are unable to skip to a keyframe past aTimeThreshold, however
        // we are speeding up decoding by dropping the unplayable frames.
        // So we can mark aFound as true.
        aFound = true;
        break;
      }
      parsed--;
    }
  }

  if (aFound) {
    UpdateEvictionIndex(trackData, trackData.mNextGetSampleIndex.ref());
  }

  return parsed;
}

const MediaRawData* TrackBuffersManager::GetSample(TrackInfo::TrackType aTrack,
                                                   uint32_t aIndex,
                                                   const TimeUnit& aExpectedDts,
                                                   const TimeUnit& aExpectedPts,
                                                   const TimeUnit& aFuzz) {
  MOZ_ASSERT(OnTaskQueue());
  const TrackBuffer& track = GetTrackBuffer(aTrack);

  if (aIndex >= track.Length()) {
    // reached the end.
    return nullptr;
  }

  if (!(aExpectedDts + aFuzz).IsValid() || !(aExpectedPts + aFuzz).IsValid()) {
    // Time overflow, it seems like we also reached the end.
    return nullptr;
  }

  const RefPtr<MediaRawData>& sample = track[aIndex];
  if (!aIndex || sample->mTimecode <= aExpectedDts + aFuzz ||
      sample->mTime <= aExpectedPts + aFuzz) {
    MOZ_DIAGNOSTIC_ASSERT(sample->HasValidTime());
    return sample;
  }

  // Gap is too big. End of Stream or Waiting for Data.
  // TODO, check that we have continuous data based on the sanitized buffered
  // range instead.
  return nullptr;
}

already_AddRefed<MediaRawData> TrackBuffersManager::GetSample(
    TrackInfo::TrackType aTrack, const TimeUnit& aFuzz, MediaResult& aResult) {
  mTaskQueueCapability->AssertOnCurrentThread();
  AUTO_PROFILER_LABEL("TrackBuffersManager::GetSample", MEDIA_PLAYBACK);
  auto& trackData = GetTracksData(aTrack);
  const TrackBuffer& track = GetTrackBuffer(aTrack);

  aResult = NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA;

  if (trackData.mNextGetSampleIndex.isSome()) {
    if (trackData.mNextGetSampleIndex.ref() >= track.Length()) {
      aResult = NS_ERROR_DOM_MEDIA_END_OF_STREAM;
      return nullptr;
    }
    const MediaRawData* sample = GetSample(
        aTrack, trackData.mNextGetSampleIndex.ref(),
        trackData.mNextSampleTimecode, trackData.mNextSampleTime, aFuzz);
    if (!sample) {
      return nullptr;
    }

    RefPtr<MediaRawData> p = sample->Clone();
    if (!p) {
      aResult = MediaResult(NS_ERROR_OUT_OF_MEMORY, __func__);
      return nullptr;
    }
    if (p->mKeyframe) {
      UpdateEvictionIndex(trackData, trackData.mNextGetSampleIndex.ref());
    }
    trackData.mNextGetSampleIndex.ref()++;
    // Estimate decode timestamp and timestamp of the next sample.
    TimeUnit nextSampleTimecode = sample->GetEndTimecode();
    TimeUnit nextSampleTime = sample->GetEndTime();
    const MediaRawData* nextSample =
        GetSample(aTrack, trackData.mNextGetSampleIndex.ref(),
                  nextSampleTimecode, nextSampleTime, aFuzz);
    if (nextSample) {
      // We have a valid next sample, can use exact values.
      trackData.mNextSampleTimecode = nextSample->mTimecode;
      trackData.mNextSampleTime = nextSample->mTime;
    } else {
      // Next sample isn't available yet. Use estimates.
      trackData.mNextSampleTimecode = nextSampleTimecode;
      trackData.mNextSampleTime = nextSampleTime;
    }
    aResult = NS_OK;
    return p.forget();
  }

  aResult = SetNextGetSampleIndexIfNeeded(aTrack, aFuzz);

  if (NS_FAILED(aResult)) {
    return nullptr;
  }

  MOZ_RELEASE_ASSERT(trackData.mNextGetSampleIndex.isSome() &&
                     trackData.mNextGetSampleIndex.ref() < track.Length());
  const RefPtr<MediaRawData>& sample =
      track[trackData.mNextGetSampleIndex.ref()];
  RefPtr<MediaRawData> p = sample->Clone();
  if (!p) {
    // OOM
    aResult = MediaResult(NS_ERROR_OUT_OF_MEMORY, __func__);
    return nullptr;
  }
  MOZ_DIAGNOSTIC_ASSERT(p->HasValidTime());

  // Find the previous keyframe to calculate the evictable amount.
  uint32_t i = trackData.mNextGetSampleIndex.ref();
  for (; !track[i]->mKeyframe; i--) {
  }
  UpdateEvictionIndex(trackData, i);

  trackData.mNextGetSampleIndex.ref()++;
  trackData.mNextSampleTimecode = sample->GetEndTimecode();
  trackData.mNextSampleTime = sample->GetEndTime();
  return p.forget();
}

int32_t TrackBuffersManager::FindCurrentPosition(TrackInfo::TrackType aTrack,
                                                 const TimeUnit& aFuzz) const {
  MOZ_ASSERT(OnTaskQueue());
  auto& trackData = GetTracksData(aTrack);
  const TrackBuffer& track = GetTrackBuffer(aTrack);

  // Perform an exact search first.
  for (uint32_t i = 0; i < track.Length(); i++) {
    const RefPtr<MediaRawData>& sample = track[i];
    TimeInterval sampleInterval{sample->mTimecode, sample->GetEndTimecode()};

    if (sampleInterval.ContainsStrict(trackData.mNextSampleTimecode)) {
      return i;
    }
    if (sampleInterval.mStart > trackData.mNextSampleTimecode) {
      // Samples are ordered by timecode. There's no need to search
      // any further.
      break;
    }
  }

  for (uint32_t i = 0; i < track.Length(); i++) {
    const RefPtr<MediaRawData>& sample = track[i];
    TimeInterval sampleInterval{sample->mTimecode, sample->GetEndTimecode(),
                                aFuzz};

    if (sampleInterval.ContainsWithStrictEnd(trackData.mNextSampleTimecode)) {
      return i;
    }
    if (sampleInterval.mStart - aFuzz > trackData.mNextSampleTimecode) {
      // Samples are ordered by timecode. There's no need to search
      // any further.
      break;
    }
  }

  // We couldn't find our sample by decode timestamp. Attempt to find it using
  // presentation timestamp. There will likely be small jerkiness.
  for (uint32_t i = 0; i < track.Length(); i++) {
    const RefPtr<MediaRawData>& sample = track[i];
    TimeInterval sampleInterval{sample->mTime, sample->GetEndTime(), aFuzz};

    if (sampleInterval.ContainsWithStrictEnd(trackData.mNextSampleTimecode)) {
      return i;
    }
  }

  // Still not found.
  return -1;
}

uint32_t TrackBuffersManager::Evictable(TrackInfo::TrackType aTrack) const {
  MutexAutoLock mut(mMutex);
  return GetTracksData(aTrack).mEvictionIndex.mEvictable;
}

TimeUnit TrackBuffersManager::GetNextRandomAccessPoint(
    TrackInfo::TrackType aTrack, const TimeUnit& aFuzz) {
  mTaskQueueCapability->AssertOnCurrentThread();

  // So first determine the current position in the track buffer if necessary.
  if (NS_FAILED(SetNextGetSampleIndexIfNeeded(aTrack, aFuzz))) {
    return TimeUnit::FromInfinity();
  }

  auto& trackData = GetTracksData(aTrack);
  const TrackBuffersManager::TrackBuffer& track = GetTrackBuffer(aTrack);

  uint32_t i = trackData.mNextGetSampleIndex.ref();
  TimeUnit nextSampleTimecode = trackData.mNextSampleTimecode;
  TimeUnit nextSampleTime = trackData.mNextSampleTime;

  for (; i < track.Length(); i++) {
    const MediaRawData* sample =
        GetSample(aTrack, i, nextSampleTimecode, nextSampleTime, aFuzz);
    if (!sample) {
      break;
    }
    if (sample->mKeyframe) {
      return sample->mTime;
    }
    nextSampleTimecode = sample->GetEndTimecode();
    nextSampleTime = sample->GetEndTime();
  }
  return TimeUnit::FromInfinity();
}

nsresult TrackBuffersManager::SetNextGetSampleIndexIfNeeded(
    TrackInfo::TrackType aTrack, const TimeUnit& aFuzz) {
  MOZ_ASSERT(OnTaskQueue());
  auto& trackData = GetTracksData(aTrack);
  const TrackBuffer& track = GetTrackBuffer(aTrack);

  if (trackData.mNextGetSampleIndex.isSome()) {
    // We already know the next GetSample index.
    return NS_OK;
  }

  if (!track.Length()) {
    // There's nothing to find yet.
    return NS_ERROR_DOM_MEDIA_END_OF_STREAM;
  }

  if (trackData.mNextSampleTimecode == TimeUnit()) {
    // First demux, get first sample.
    trackData.mNextGetSampleIndex = Some(0u);
    return NS_OK;
  }

  if (trackData.mNextSampleTimecode > track.LastElement()->GetEndTimecode()) {
    // The next element is past our last sample. We're done.
    trackData.mNextGetSampleIndex = Some(uint32_t(track.Length()));
    return NS_ERROR_DOM_MEDIA_END_OF_STREAM;
  }

  int32_t pos = FindCurrentPosition(aTrack, aFuzz);
  if (pos < 0) {
    // Not found, must wait for more data.
    MSE_DEBUG("Couldn't find sample (pts:%" PRId64 " dts:%" PRId64 ")",
              trackData.mNextSampleTime.ToMicroseconds(),
              trackData.mNextSampleTimecode.ToMicroseconds());
    return NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA;
  }
  trackData.mNextGetSampleIndex = Some(uint32_t(pos));
  return NS_OK;
}

void TrackBuffersManager::TrackData::AddSizeOfResources(
    MediaSourceDecoder::ResourceSizes* aSizes) const {
  for (const TrackBuffer& buffer : mBuffers) {
    for (const MediaRawData* data : buffer) {
      aSizes->mByteSize += data->SizeOfIncludingThis(aSizes->mMallocSizeOf);
    }
  }
}

RefPtr<GenericPromise> TrackBuffersManager::RequestDebugInfo(
    dom::TrackBuffersManagerDebugInfo& aInfo) const {
  const RefPtr<TaskQueue> taskQueue = GetTaskQueueSafe();
  if (!taskQueue) {
    return GenericPromise::CreateAndResolve(true, __func__);
  }
  if (!taskQueue->IsCurrentThreadIn()) {
    // Run the request on the task queue if it's not already.
    return InvokeAsync(taskQueue.get(), __func__,
                       [this, self = RefPtr{this}, &aInfo] {
                         return RequestDebugInfo(aInfo);
                       });
  }
  mTaskQueueCapability->AssertOnCurrentThread();
  GetDebugInfo(aInfo);
  return GenericPromise::CreateAndResolve(true, __func__);
}

void TrackBuffersManager::GetDebugInfo(
    dom::TrackBuffersManagerDebugInfo& aInfo) const {
  MOZ_ASSERT(OnTaskQueue(),
             "This shouldn't be called off the task queue because we're about "
             "to touch a lot of data that is used on the task queue");
  CopyUTF8toUTF16(mType.Type().AsString(), aInfo.mType);

  if (HasAudio()) {
    aInfo.mNextSampleTime = mAudioTracks.mNextSampleTime.ToSeconds();
    aInfo.mNumSamples = mAudioTracks.mBuffers[0].Length();
    aInfo.mBufferSize = mAudioTracks.mSizeBuffer;
    aInfo.mEvictable = Evictable(TrackInfo::kAudioTrack);
    aInfo.mNextGetSampleIndex = mAudioTracks.mNextGetSampleIndex.valueOr(-1);
    aInfo.mNextInsertionIndex = mAudioTracks.mNextInsertionIndex.valueOr(-1);
    media::TimeIntervals ranges = SafeBuffered(TrackInfo::kAudioTrack);
    dom::Sequence<dom::BufferRange> items;
    for (uint32_t i = 0; i < ranges.Length(); ++i) {
      // dom::Sequence is a FallibleTArray
      dom::BufferRange* range = items.AppendElement(fallible);
      if (!range) {
        break;
      }
      range->mStart = ranges.Start(i).ToSeconds();
      range->mEnd = ranges.End(i).ToSeconds();
    }
    aInfo.mRanges = std::move(items);
  } else if (HasVideo()) {
    aInfo.mNextSampleTime = mVideoTracks.mNextSampleTime.ToSeconds();
    aInfo.mNumSamples = mVideoTracks.mBuffers[0].Length();
    aInfo.mBufferSize = mVideoTracks.mSizeBuffer;
    aInfo.mEvictable = Evictable(TrackInfo::kVideoTrack);
    aInfo.mNextGetSampleIndex = mVideoTracks.mNextGetSampleIndex.valueOr(-1);
    aInfo.mNextInsertionIndex = mVideoTracks.mNextInsertionIndex.valueOr(-1);
    media::TimeIntervals ranges = SafeBuffered(TrackInfo::kVideoTrack);
    dom::Sequence<dom::BufferRange> items;
    for (uint32_t i = 0; i < ranges.Length(); ++i) {
      // dom::Sequence is a FallibleTArray
      dom::BufferRange* range = items.AppendElement(fallible);
      if (!range) {
        break;
      }
      range->mStart = ranges.Start(i).ToSeconds();
      range->mEnd = ranges.End(i).ToSeconds();
    }
    aInfo.mRanges = std::move(items);
  }
}

void TrackBuffersManager::AddSizeOfResources(
    MediaSourceDecoder::ResourceSizes* aSizes) const {
  mTaskQueueCapability->AssertOnCurrentThread();

  if (mInputBuffer.isSome() && mInputBuffer->Buffer()) {
    // mInputBuffer should be the sole owner of the underlying buffer, so this
    // won't double count.
    aSizes->mByteSize += mInputBuffer->Buffer()->ShallowSizeOfIncludingThis(
        aSizes->mMallocSizeOf);
  }
  if (mInitData) {
    aSizes->mByteSize +=
        mInitData->ShallowSizeOfIncludingThis(aSizes->mMallocSizeOf);
  }
  if (mPendingInputBuffer.isSome() && mPendingInputBuffer->Buffer()) {
    // mPendingInputBuffer should be the sole owner of the underlying buffer, so
    // this won't double count.
    aSizes->mByteSize +=
        mPendingInputBuffer->Buffer()->ShallowSizeOfIncludingThis(
            aSizes->mMallocSizeOf);
  }

  mVideoTracks.AddSizeOfResources(aSizes);
  mAudioTracks.AddSizeOfResources(aSizes);
}

}  // namespace mozilla
#undef MSE_DEBUG
#undef MSE_DEBUGV
#undef SAMPLE_DEBUG