summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/mediasource/source_buffer.cc
blob: b3653f110cb5a9c2c6ad5fb13b57b7bd16c065be (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
/*
 * Copyright (C) 2013 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "third_party/blink/renderer/modules/mediasource/source_buffer.h"

#include <limits>
#include <memory>
#include <sstream>
#include <utility>

#include "base/numerics/checked_math.h"
#include "media/base/logging_override_if_enabled.h"
#include "media/base/stream_parser_buffer.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_source_buffer.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/encoded_audio_chunk_or_encoded_video_chunk.h"
#include "third_party/blink/renderer/bindings/modules/v8/encoded_av_chunk_sequence_or_encoded_av_chunk.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_audio_decoder_config.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_encoded_audio_chunk.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_encoded_video_chunk.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_source_buffer_config.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_union_encodedaudiochunk_encodedaudiochunkorencodedvideochunksequence_encodedvideochunk.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_union_encodedaudiochunk_encodedvideochunk.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_video_decoder_config.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/events/event_queue.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html/time_ranges.h"
#include "third_party/blink/renderer/core/html/track/audio_track.h"
#include "third_party/blink/renderer/core/html/track/audio_track_list.h"
#include "third_party/blink/renderer/core/html/track/video_track.h"
#include "third_party/blink/renderer/core/html/track/video_track_list.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_buffer_view.h"
#include "third_party/blink/renderer/modules/mediasource/media_source.h"
#include "third_party/blink/renderer/modules/mediasource/source_buffer_track_base_supplement.h"
#include "third_party/blink/renderer/modules/webcodecs/encoded_audio_chunk.h"
#include "third_party/blink/renderer/modules/webcodecs/encoded_video_chunk.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
#include "third_party/blink/renderer/platform/instrumentation/use_counter.h"
#include "third_party/blink/renderer/platform/network/mime/content_type.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
#include "third_party/blink/renderer/platform/wtf/math_extras.h"

using blink::WebSourceBuffer;

namespace blink {

namespace {

static bool ThrowExceptionIfRemovedOrUpdating(bool is_removed,
                                              bool is_updating,
                                              ExceptionState& exception_state) {
  if (is_removed) {
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "This SourceBuffer has been removed from the parent media source.");
    return true;
  }
  if (is_updating) {
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "This SourceBuffer is still processing an 'appendBuffer' or "
        "'remove' operation.");
    return true;
  }

  return false;
}

WTF::String WebTimeRangesToString(const WebTimeRanges& ranges) {
  StringBuilder string_builder;
  string_builder.Append('{');
  for (auto& r : ranges) {
    string_builder.Append(" [");
    string_builder.AppendNumber(r.start);
    string_builder.Append(';');
    string_builder.AppendNumber(r.end);
    string_builder.Append(']');
  }
  string_builder.Append(" }");
  return string_builder.ToString();
}

// These track IDs are used as to differentiate tracks within a SourceBuffer.
// They can be duplicated across SourceBuffers, since these are not the
// TrackList identifiers exposed to the web app; these are instead equivalents
// of bytestream format's in-band track identifiers.
// TODO(crbug.com/1144908): Consider standardizing these especially if
// TrackDefaults makes a return to MSE spec, so that apps can provide
// name/label/kind/etc metadata for tracks originating from appended WebCodecs
// chunks.
// TODO(crbug.com/1144908): Since these must be identical to those generated
// in the underlying WebCodecsEncodedChunkStreamParser, consider moving these
// to possibly stream_parser.h. Meanwhile, must be kept in sync with similar
// constexpr in that parser manually.
constexpr media::StreamParser::TrackId kWebCodecsAudioTrackId = 1;
constexpr media::StreamParser::TrackId kWebCodecsVideoTrackId = 2;

// TODO(crbug.com/1144908): Move these converters into a WebCodecs decoder
// helper abstraction. Beyond reuse (instead of copying the various
// MakeDecoderBuffer methods), that will also help enable buffering h264 where
// bitstream conversion might be necessary during conversion.
// Note, caller updates results further as necessary (e.g. duration, DTS, etc).
scoped_refptr<media::StreamParserBuffer> MakeAudioStreamParserBuffer(
    const EncodedAudioChunk& audio_chunk) {
  // TODO(crbug.com/1144908): DecoderBuffer takes size_t size, but
  // StreamParserBuffer takes int. Fix this. For now, checked_cast is used.
  auto stream_parser_buffer = media::StreamParserBuffer::CopyFrom(
      static_cast<uint8_t*>(audio_chunk.data()->Data()),
      base::checked_cast<int>(audio_chunk.data()->ByteLength()),
      audio_chunk.type() == "key", media::DemuxerStream::AUDIO,
      kWebCodecsAudioTrackId);

  // TODO(crbug.com/1144908): Remove or change the following to DCHECK once
  // StreamParserBuffer::CopyFrom takes size_t, not int.
  CHECK_EQ(audio_chunk.data()->ByteLength(), stream_parser_buffer->data_size());

  // Currently, we do not populate any side_data in these converters.
  DCHECK_EQ(0U, stream_parser_buffer->side_data_size());
  DCHECK_EQ(nullptr, stream_parser_buffer->side_data());

  stream_parser_buffer->set_timestamp(
      base::TimeDelta::FromMicroseconds(audio_chunk.timestamp()));
  // TODO(crbug.com/1144908): Get EncodedAudioChunk to have an optional duration
  // attribute, and require it to be populated for use by MSE-for-WebCodecs,
  // here. For initial prototype, hard-coded 22ms is used as estimated duration.
  stream_parser_buffer->set_duration(base::TimeDelta::FromMilliseconds(22));
  stream_parser_buffer->set_is_duration_estimated(true);
  return stream_parser_buffer;
}

// Caller must verify that video_chunk.duration().has_value().
scoped_refptr<media::StreamParserBuffer> MakeVideoStreamParserBuffer(
    const EncodedVideoChunk& video_chunk) {
  // TODO(crbug.com/1144908): DecoderBuffer takes size_t size, but
  // StreamParserBuffer takes int. Fix this. For now, checked_cast is used.
  auto stream_parser_buffer = media::StreamParserBuffer::CopyFrom(
      static_cast<uint8_t*>(video_chunk.data()->Data()),
      base::checked_cast<int>(video_chunk.data()->ByteLength()),
      video_chunk.type() == "key", media::DemuxerStream::VIDEO,
      kWebCodecsVideoTrackId);

  // TODO(crbug.com/1144908): Remove or change the following to DCHECK once
  // StreamParserBuffer::CopyFrom takes size_t, not int.
  CHECK_EQ(video_chunk.data()->ByteLength(), stream_parser_buffer->data_size());

  // Currently, we do not populate any side_data in these converters.
  DCHECK_EQ(0U, stream_parser_buffer->side_data_size());
  DCHECK_EQ(nullptr, stream_parser_buffer->side_data());

  stream_parser_buffer->set_timestamp(
      base::TimeDelta::FromMicroseconds(video_chunk.timestamp()));
  // TODO(crbug.com/1144908): Get EncodedVideoChunk to have an optional decode
  // timestamp attribute. If it is populated, use it for the DTS of the
  // StreamParserBuffer, here. For initial prototype, only in-order PTS==DTS
  // chunks are supported. Out-of-order chunks may result in buffered range gaps
  // or decode errors.
  DCHECK(video_chunk.duration().has_value());
  stream_parser_buffer->set_duration(
      base::TimeDelta::FromMicroseconds(video_chunk.duration().value()));
  return stream_parser_buffer;
}

}  // namespace

SourceBuffer::SourceBuffer(std::unique_ptr<WebSourceBuffer> web_source_buffer,
                           MediaSource* source,
                           EventQueue* async_event_queue)
    : ExecutionContextLifecycleObserver(source->GetExecutionContext()),
      web_source_buffer_(std::move(web_source_buffer)),
      source_(source),
      track_defaults_(MakeGarbageCollected<TrackDefaultList>()),
      async_event_queue_(async_event_queue),
      mode_(SegmentsKeyword()),
      updating_(false),
      timestamp_offset_(0),
      append_window_start_(0),
      append_window_end_(std::numeric_limits<double>::infinity()),
      first_initialization_segment_received_(false),
      pending_append_data_offset_(0),
      pending_remove_start_(-1),
      pending_remove_end_(-1) {
  DVLOG(1) << __func__ << " this=" << this;

  DCHECK(web_source_buffer_);
  DCHECK(source_);

  scoped_refptr<MediaSourceAttachmentSupplement> attachment;
  MediaSourceTracer* tracer;
  std::tie(attachment, tracer) = source_->AttachmentAndTracer();
  DCHECK(attachment);

  if (GetExecutionContext()->IsWindow()) {
    DCHECK(IsMainThread());
    DCHECK(tracer);  // Same-thread attachments must use a tracer.

    // Have the attachment construct our audio and video tracklist members for
    // us, since it knows how to do this with knowledge of the attached media
    // element.
    audio_tracks_ = attachment->CreateAudioTrackList(tracer);
    DCHECK(audio_tracks_);
    video_tracks_ = attachment->CreateVideoTrackList(tracer);
    DCHECK(video_tracks_);
  } else {
    DCHECK(RuntimeEnabledFeatures::MediaSourceInWorkersEnabled() &&
           GetExecutionContext()->IsDedicatedWorkerGlobalScope());
    DCHECK(!IsMainThread());

    // TODO(https://crbug.com/878133): Enable construction of media tracks that
    // don't reference the media element if, for instance, they are owned by a
    // different execution context. For now, AudioVideoTracks experimental
    // feature implementation is not complete when MediaSource is in worker.
    DCHECK(!audio_tracks_);
    DCHECK(!video_tracks_);
  }

  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();
  web_source_buffer_->SetClient(this);
}

SourceBuffer::~SourceBuffer() {
  DVLOG(1) << __func__ << " this=" << this;
}

void SourceBuffer::Dispose() {
  // Promptly clears a raw reference from content/ to an on-heap object
  // so that content/ doesn't access it in a lazy sweeping phase.
  web_source_buffer_.reset();
}

AtomicString SourceBuffer::SegmentsKeyword() {
  return "segments";
}

AtomicString SourceBuffer::SequenceKeyword() {
  return "sequence";
}

void SourceBuffer::setMode(const AtomicString& new_mode,
                           ExceptionState& exception_state) {
  DVLOG(3) << __func__ << " this=" << this << " new_mode=" << new_mode;

  // Section 3.1 On setting mode attribute steps.
  // https://www.w3.org/TR/media-source/#dom-sourcebuffer-mode
  // 1. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source, then throw an INVALID_STATE_ERR exception and abort
  //    these steps.
  // 2. If the updating attribute equals true, then throw an INVALID_STATE_ERR
  //    exception and abort these steps.
  // 3. Let new mode equal the new value being assigned to this attribute.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // Do remainder of steps only if attachment is usable and underlying demuxer
  // is protected from destruction (applicable especially for MSE-in-Worker
  // case). Note, we must have |source_| and |source_| must have an attachment
  // because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::SetMode_Locked, WrapPersistent(this),
                    new_mode, WTF::Unretained(&exception_state)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::SetMode_Locked(
    AtomicString new_mode,
    ExceptionState* exception_state,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // 4. If generate timestamps flag equals true and new mode equals "segments",
  //    then throw a TypeError exception and abort these steps.
  if (web_source_buffer_->GetGenerateTimestampsFlag() &&
      new_mode == SegmentsKeyword()) {
    MediaSource::LogAndThrowTypeError(
        *exception_state, "The mode value provided (" + SegmentsKeyword() +
                              ") is invalid for a byte stream format that uses "
                              "generated timestamps.");
    return;
  }

  // 5. If the readyState attribute of the parent media source is in the "ended"
  //    state then run the following steps:
  // 5.1 Set the readyState attribute of the parent media source to "open"
  // 5.2 Queue a task to fire a simple event named sourceopen at the parent
  //     media source.
  source_->OpenIfInEndedState();

  // 6. If the append state equals PARSING_MEDIA_SEGMENT, then throw an
  //    INVALID_STATE_ERR and abort these steps.
  // 7. If the new mode equals "sequence", then set the group start timestamp to
  //    the highest presentation end timestamp.
  WebSourceBuffer::AppendMode append_mode =
      WebSourceBuffer::kAppendModeSegments;
  if (new_mode == SequenceKeyword())
    append_mode = WebSourceBuffer::kAppendModeSequence;
  if (!web_source_buffer_->SetMode(append_mode)) {
    MediaSource::LogAndThrowDOMException(
        *exception_state, DOMExceptionCode::kInvalidStateError,
        "The mode may not be set while the SourceBuffer's append state is "
        "'PARSING_MEDIA_SEGMENT'.");
    return;
  }

  // 8. Update the attribute to new mode.
  mode_ = new_mode;
}

TimeRanges* SourceBuffer::buffered(ExceptionState& exception_state) const {
  // Section 3.1 buffered attribute steps.
  // 1. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source then throw an InvalidStateError exception and abort
  //    these steps.
  if (IsRemoved()) {
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "This SourceBuffer has been removed from the parent media source.");
    return nullptr;
  }

  // Obtain the current buffered ranges only if attachment is usable and
  // underlying demuxer is protected from destruction (applicable especially for
  // MSE-in-Worker case). Note, we must have |source_| and |source_| must have
  // an attachment because !IsRemoved().
  WebTimeRanges ranges;
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::GetBuffered_Locked, WrapPersistent(this),
                    WTF::Unretained(&ranges)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
    return nullptr;
  }

  // 2. Return a new static normalized TimeRanges object for the media segments
  //    buffered.
  return MakeGarbageCollected<TimeRanges>(ranges);
}

void SourceBuffer::GetBuffered_Locked(
    WebTimeRanges* ranges /* out parameter */,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) const {
  DCHECK(!IsRemoved());
  DCHECK(ranges);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  *ranges = web_source_buffer_->Buffered();
}

double SourceBuffer::timestampOffset() const {
  return timestamp_offset_;
}

void SourceBuffer::setTimestampOffset(double offset,
                                      ExceptionState& exception_state) {
  DVLOG(3) << __func__ << " this=" << this << " offset=" << offset;
  // Section 3.1 timestampOffset attribute setter steps.
  // https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-SourceBuffer-timestampOffset
  // 1. Let new timestamp offset equal the new value being assigned to this
  //    attribute.
  // 2. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source, then throw an InvalidStateError exception and abort
  //    these steps.
  // 3. If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // Do the remainder of steps only if attachment is usable and underlying
  // demuxer is protected from destruction (applicable especially for
  // MSE-in-Worker case). Note, we must have |source_| and |source_| must have
  // an attachment because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(WTF::Bind(
          &SourceBuffer::SetTimestampOffset_Locked, WrapPersistent(this),
          offset, WTF::Unretained(&exception_state)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::SetTimestampOffset_Locked(
    double offset,
    ExceptionState* exception_state,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // 4. If the readyState attribute of the parent media source is in the "ended"
  //    state then run the following steps:
  // 4.1 Set the readyState attribute of the parent media source to "open"
  // 4.2 Queue a task to fire a simple event named sourceopen at the parent
  //     media source.
  source_->OpenIfInEndedState();

  // 5. If the append state equals PARSING_MEDIA_SEGMENT, then throw an
  //    INVALID_STATE_ERR and abort these steps.
  // 6. If the mode attribute equals "sequence", then set the group start
  //    timestamp to new timestamp offset.
  if (!web_source_buffer_->SetTimestampOffset(offset)) {
    MediaSource::LogAndThrowDOMException(
        *exception_state, DOMExceptionCode::kInvalidStateError,
        "The timestamp offset may not be set while the SourceBuffer's append "
        "state is 'PARSING_MEDIA_SEGMENT'.");
    return;
  }

  // 7. Update the attribute to new timestamp offset.
  timestamp_offset_ = offset;
}

AudioTrackList& SourceBuffer::audioTracks() {
  DCHECK(HTMLMediaElement::MediaTracksEnabledInternally());

  // TODO(https://crbug.com/878133): Complete the AudioVideoTracks function
  // necessary to enable successful experimental usage of it when MSE is in
  // worker. Note that if this is consulted as part of parent |source_|'s
  // context destruction, then we cannot consult GetExecutionContext() here.
  CHECK(IsMainThread());

  return *audio_tracks_;
}

VideoTrackList& SourceBuffer::videoTracks() {
  DCHECK(HTMLMediaElement::MediaTracksEnabledInternally());

  // TODO(https://crbug.com/878133): Complete the AudioVideoTracks function
  // necessary to enable successful experimental usage of it when MSE is in
  // worker. Note that if this is consulted as part of parent |source_|'s
  // context destruction, then we cannot consult GetExecutionContext() here.
  CHECK(IsMainThread());

  return *video_tracks_;
}

double SourceBuffer::appendWindowStart() const {
  return append_window_start_;
}

void SourceBuffer::setAppendWindowStart(double start,
                                        ExceptionState& exception_state) {
  DVLOG(3) << __func__ << " this=" << this << " start=" << start;
  // Section 3.1 appendWindowStart attribute setter steps.
  // https://www.w3.org/TR/media-source/#widl-SourceBuffer-appendWindowStart
  // 1. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source then throw an InvalidStateError exception and abort
  //    these steps.
  // 2. If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // 3. If the new value is less than 0 or greater than or equal to
  //    appendWindowEnd then throw a TypeError exception and abort these steps.
  if (start < 0 || start >= append_window_end_) {
    MediaSource::LogAndThrowTypeError(
        exception_state,
        ExceptionMessages::IndexOutsideRange(
            "value", start, 0.0, ExceptionMessages::kExclusiveBound,
            append_window_end_, ExceptionMessages::kInclusiveBound));
    return;
  }

  // Do remainder of steps only if attachment is usable and underlying demuxer
  // is protected from destruction (applicable especially for MSE-in-Worker
  // case). Note, we must have |source_| and |source_| must have an attachment
  // because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::SetAppendWindowStart_Locked,
                    WrapPersistent(this), start))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::SetAppendWindowStart_Locked(
    double start,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // 4. Update the attribute to the new value.
  web_source_buffer_->SetAppendWindowStart(start);
  append_window_start_ = start;
}

double SourceBuffer::appendWindowEnd() const {
  return append_window_end_;
}

void SourceBuffer::setAppendWindowEnd(double end,
                                      ExceptionState& exception_state) {
  DVLOG(3) << __func__ << " this=" << this << " end=" << end;
  // Section 3.1 appendWindowEnd attribute setter steps.
  // https://www.w3.org/TR/media-source/#widl-SourceBuffer-appendWindowEnd
  // 1. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source then throw an InvalidStateError exception and abort
  //    these steps.
  // 2. If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // 3. If the new value equals NaN, then throw a TypeError and abort these
  //    steps.
  if (std::isnan(end)) {
    MediaSource::LogAndThrowTypeError(exception_state,
                                      ExceptionMessages::NotAFiniteNumber(end));
    return;
  }
  // 4. If the new value is less than or equal to appendWindowStart then throw a
  //    TypeError exception and abort these steps.
  if (end <= append_window_start_) {
    MediaSource::LogAndThrowTypeError(
        exception_state, ExceptionMessages::IndexExceedsMinimumBound(
                             "value", end, append_window_start_));
    return;
  }

  // Do remainder of steps only if attachment is usable and underlying demuxer
  // is protected from destruction (applicable especially for MSE-in-Worker
  // case). Note, we must have |source_| and |source_| must have an attachment
  // because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::SetAppendWindowEnd_Locked,
                    WrapPersistent(this), end))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::SetAppendWindowEnd_Locked(
    double end,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // 5. Update the attribute to the new value.
  web_source_buffer_->SetAppendWindowEnd(end);
  append_window_end_ = end;
}

void SourceBuffer::appendBuffer(DOMArrayBuffer* data,
                                ExceptionState& exception_state) {
  DVLOG(2) << __func__ << " this=" << this << " size=" << data->ByteLength();
  // Section 3.2 appendBuffer()
  // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data
  AppendBufferInternal(static_cast<const unsigned char*>(data->Data()),
                       data->ByteLength(), exception_state);
}

void SourceBuffer::appendBuffer(NotShared<DOMArrayBufferView> data,
                                ExceptionState& exception_state) {
  DVLOG(3) << __func__ << " this=" << this << " size=" << data->byteLength();
  // Section 3.2 appendBuffer()
  // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data
  AppendBufferInternal(static_cast<const unsigned char*>(data->BaseAddress()),
                       data->byteLength(), exception_state);
}

// Note that |chunks| may be a sequence of mixed audio and video encoded chunks
// (which should cause underlying buffering validation to emit error akin to
// appending video to an audio track or vice-versa). It was impossible to get
// the bindings generator to disambiguate sequence<audio> vs sequence<video>,
// hence we could not use simple overloading in the IDL for these two. Neither
// could the IDL union attempt similar. We must enforce that semantic in
// implementation. Further note, |chunks| may instead be a single audio or a
// single video chunk as a helpful additional overload for one-chunk-at-a-time
// append use-cases.
ScriptPromise SourceBuffer::appendEncodedChunks(
    ScriptState* script_state,
#if defined(USE_BLINK_V8_BINDING_NEW_IDL_UNION)
    const V8EncodedChunks* chunks,
#else   // defined(USE_BLINK_V8_BINDING_NEW_IDL_UNION)
    const EncodedChunks& chunks,
#endif  // defined(USE_BLINK_V8_BINDING_NEW_IDL_UNION)
    ExceptionState& exception_state) {
  DVLOG(2) << __func__ << " this=" << this;

  TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
      "media", "SourceBuffer::appendEncodedChunks", TRACE_ID_LOCAL(this));

  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    TRACE_EVENT_NESTABLE_ASYNC_END0(
        "media", "SourceBuffer::appendEncodedChunks", TRACE_ID_LOCAL(this));
    return ScriptPromise();
  }

  // Convert |chunks| to a StreamParser::BufferQueue.
  // TODO(crbug.com/1144908): Support out-of-order DTS vs PTS sequences. For
  // now, PTS is assumed to be DTS (as is common in some formats like WebM).
  // TODO(crbug.com/1144908): Add optional EncodedAudioChunk duration attribute
  // and require it to be populated for use with MSE. For now, all audio chunks
  // are estimated.
  DCHECK(!pending_chunks_to_buffer_);
  auto buffer_queue = std::make_unique<media::StreamParser::BufferQueue>();
  size_t size = 0;

#if defined(USE_BLINK_V8_BINDING_NEW_IDL_UNION)
  switch (chunks->GetContentType()) {
    case V8EncodedChunks::ContentType::kEncodedAudioChunk:
      buffer_queue->emplace_back(
          MakeAudioStreamParserBuffer(*(chunks->GetAsEncodedAudioChunk())));
      size += buffer_queue->back()->data_size() +
              buffer_queue->back()->side_data_size();
      break;
    case V8EncodedChunks::ContentType::kEncodedVideoChunk: {
      const auto& video_chunk = *(chunks->GetAsEncodedVideoChunk());
      if (!video_chunk.duration().has_value()) {
        MediaSource::LogAndThrowTypeError(
            exception_state,
            "EncodedVideoChunk is missing duration, required for use with "
            "SourceBuffer.");
        return ScriptPromise();
      }
      buffer_queue->emplace_back(MakeVideoStreamParserBuffer(video_chunk));
      size += buffer_queue->back()->data_size() +
              buffer_queue->back()->side_data_size();
      break;
    }
    case V8EncodedChunks::ContentType::
        kEncodedAudioChunkOrEncodedVideoChunkSequence:
      for (const auto& av_chunk :
           chunks->GetAsEncodedAudioChunkOrEncodedVideoChunkSequence()) {
        DCHECK(av_chunk);
        switch (av_chunk->GetContentType()) {
          case V8UnionEncodedAudioChunkOrEncodedVideoChunk::ContentType::
              kEncodedAudioChunk:
            buffer_queue->emplace_back(MakeAudioStreamParserBuffer(
                *(av_chunk->GetAsEncodedAudioChunk())));
            size += buffer_queue->back()->data_size() +
                    buffer_queue->back()->side_data_size();
            break;
          case V8UnionEncodedAudioChunkOrEncodedVideoChunk::ContentType::
              kEncodedVideoChunk: {
            const auto& video_chunk = *(av_chunk->GetAsEncodedVideoChunk());
            if (!video_chunk.duration().has_value()) {
              MediaSource::LogAndThrowTypeError(
                  exception_state,
                  "EncodedVideoChunk is missing duration, required for use "
                  "with SourceBuffer.");
              return ScriptPromise();
            }
            buffer_queue->emplace_back(
                MakeVideoStreamParserBuffer(video_chunk));
            size += buffer_queue->back()->data_size() +
                    buffer_queue->back()->side_data_size();
            break;
          }
        }
      }
      break;
  }
#else   // defined(USE_BLINK_V8_BINDING_NEW_IDL_UNION)
  if (chunks.IsEncodedAudioChunk()) {
    buffer_queue->emplace_back(
        MakeAudioStreamParserBuffer(*(chunks.GetAsEncodedAudioChunk())));
    size += buffer_queue->back()->data_size() +
            buffer_queue->back()->side_data_size();
  } else if (chunks.IsEncodedVideoChunk()) {
    const auto& video_chunk = *(chunks.GetAsEncodedVideoChunk());
    if (!video_chunk.duration().has_value()) {
      MediaSource::LogAndThrowTypeError(
          exception_state,
          "EncodedVideoChunk is missing duration, required for use with "
          "SourceBuffer.");
      return ScriptPromise();
      ;
    }
    buffer_queue->emplace_back(MakeVideoStreamParserBuffer(video_chunk));
    size += buffer_queue->back()->data_size() +
            buffer_queue->back()->side_data_size();
  } else if (chunks.IsEncodedAudioChunkOrEncodedVideoChunkSequence()) {
    for (const auto& av_chunk :
         chunks.GetAsEncodedAudioChunkOrEncodedVideoChunkSequence()) {
      // TODO(crbug.com/1144908): Can null entries occur in the sequence, and
      // should they be ignored or should they cause exception? Ignoring for
      // now, if they occur.
      if (av_chunk.IsNull())
        continue;
      if (av_chunk.IsEncodedAudioChunk()) {
        buffer_queue->emplace_back(
            MakeAudioStreamParserBuffer(*(av_chunk.GetAsEncodedAudioChunk())));
        size += buffer_queue->back()->data_size() +
                buffer_queue->back()->side_data_size();
      } else if (av_chunk.IsEncodedVideoChunk()) {
        const auto& video_chunk = *(av_chunk.GetAsEncodedVideoChunk());
        if (!video_chunk.duration().has_value()) {
          MediaSource::LogAndThrowTypeError(
              exception_state,
              "EncodedVideoChunk is missing duration, required for use with "
              "SourceBuffer.");
          return ScriptPromise();
          ;
        }
        buffer_queue->emplace_back(MakeVideoStreamParserBuffer(video_chunk));
        size += buffer_queue->back()->data_size() +
                buffer_queue->back()->side_data_size();
      }
    }
  }
#endif  // defined(USE_BLINK_V8_BINDING_NEW_IDL_UNION)

  DCHECK(!append_encoded_chunks_resolver_);
  append_encoded_chunks_resolver_ =
      MakeGarbageCollected<ScriptPromiseResolver>(script_state);
  auto promise = append_encoded_chunks_resolver_->Promise();

  // Do remainder of steps of analogue of prepare append algorithm and sending
  // the |buffer_queue| to be buffered by |web_source_buffer_| asynchronously
  // only if attachment is usable and underlying demuxer is protected from
  // destruction (applicable especially for MSE-in-Worker case). Note, we must
  // have |source_| and |source_| must have an attachment because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(WTF::Bind(
          &SourceBuffer::AppendEncodedChunks_Locked, WrapPersistent(this),
          std::move(buffer_queue), size, WTF::Unretained(&exception_state)))) {
    // TODO(crbug.com/878133): Determine in specification what the specific,
    // app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
    append_encoded_chunks_resolver_ = nullptr;
    return ScriptPromise();
  }

  return promise;
}

void SourceBuffer::AppendEncodedChunks_Locked(
    std::unique_ptr<media::StreamParser::BufferQueue> buffer_queue,
    size_t size,
    ExceptionState* exception_state,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DVLOG(2) << __func__ << " this=" << this << ", size=" << size;

  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();
  DCHECK(append_encoded_chunks_resolver_);
  DCHECK(buffer_queue);
  DCHECK(!pending_chunks_to_buffer_);

  double media_time = GetMediaTime();
  if (!PrepareAppend(media_time, size, *exception_state)) {
    TRACE_EVENT_NESTABLE_ASYNC_END0(
        "media", "SourceBuffer::appendEncodedChunks", TRACE_ID_LOCAL(this));
    append_encoded_chunks_resolver_ = nullptr;
    return;
  }

  pending_chunks_to_buffer_ = std::move(buffer_queue);
  updating_ = true;

  // Note, this promisified API does not queue for dispatch events like
  // 'updatestart', 'update', 'error', 'abort', nor 'updateend' during the scope
  // of synchronous and asynchronous operation, because the promise's resolution
  // or rejection indicates the same information and lets us not wait until
  // those events are dispatched before resolving them. See verbose reasons in
  // AbortIfUpdating().

  // Asynchronously run the analogue of the buffer append algorithm.
  append_encoded_chunks_async_task_handle_ = PostCancellableTask(
      *GetExecutionContext()->GetTaskRunner(TaskType::kMediaElementEvent),
      FROM_HERE,
      WTF::Bind(&SourceBuffer::AppendEncodedChunksAsyncPart,
                WrapPersistent(this)));

  TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("media", "delay", TRACE_ID_LOCAL(this),
                                    "type", "initialDelay");
}

void SourceBuffer::abort(ExceptionState& exception_state) {
  DVLOG(2) << __func__ << " this=" << this;
  // http://w3c.github.io/media-source/#widl-SourceBuffer-abort-void
  // 1. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source then throw an InvalidStateError exception and abort
  //    these steps.
  // 2. If the readyState attribute of the parent media source is not in the
  //    "open" state then throw an InvalidStateError exception and abort these
  //    steps.
  if (IsRemoved()) {
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "This SourceBuffer has been removed from the parent media source.");
    return;
  }
  if (!source_->IsOpen()) {
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "The parent media source's readyState is not 'open'.");
    return;
  }

  // 3. If the range removal algorithm is running, then throw an
  //    InvalidStateError exception and abort these steps.
  if (pending_remove_start_ != -1) {
    DCHECK(updating_);
    // Throwing the exception and aborting these steps is new behavior that
    // is implemented behind the MediaSourceNewAbortAndDuration
    // RuntimeEnabledFeature.
    if (RuntimeEnabledFeatures::MediaSourceNewAbortAndDurationEnabled()) {
      MediaSource::LogAndThrowDOMException(
          exception_state, DOMExceptionCode::kInvalidStateError,
          "Aborting asynchronous remove() operation is disallowed.");
      return;
    }

    Deprecation::CountDeprecation(GetExecutionContext(),
                                  WebFeature::kMediaSourceAbortRemove);
    CancelRemove();
  }

  // 4. If the sourceBuffer.updating attribute equals true, then run the
  //    following steps: ...
  AbortIfUpdating();

  // Do remainder of steps only if attachment is usable and underlying demuxer
  // is protected from destruction (applicable especially for MSE-in-Worker
  // case). Note, we must have |source_| and |source_| must have an attachment
  // because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::Abort_Locked, WrapPersistent(this)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::Abort_Locked(
    MediaSourceAttachmentSupplement::ExclusiveKey pass_key) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // 5. Run the reset parser state algorithm.
  web_source_buffer_->ResetParserState();

  // 6. Set appendWindowStart to 0.
  // Note, there can be no exception, since appendWindowEnd can never be 0
  // (appendWindowStart can never be < 0, nor === appendWindowEnd in regular
  // setAppendWindow{Start,End} steps). Therefore, we can elide some checks and
  // reuse the existing internal helpers here that do not throw JS exception.
  SetAppendWindowStart_Locked(0, pass_key);

  // 7. Set appendWindowEnd to positive Infinity.
  // Note, likewise, no possible exception here, so reusing internal helper.
  SetAppendWindowEnd_Locked(std::numeric_limits<double>::infinity(), pass_key);
}

void SourceBuffer::remove(double start,
                          double end,
                          ExceptionState& exception_state) {
  DVLOG(2) << __func__ << " this=" << this << " start=" << start
           << " end=" << end;

  // Section 3.2 remove() method steps.
  // https://www.w3.org/TR/media-source/#widl-SourceBuffer-remove-void-double-start-unrestricted-double-end
  // 1. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source then throw an InvalidStateError exception and abort
  //    these steps.
  // 2. If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // Do remainder of steps only if attachment is usable and underlying demuxer
  // is protected from destruction (applicable especially for MSE-in-Worker
  // case). Note, we must have |source_| and |source_| must have an attachment
  // because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::Remove_Locked, WrapPersistent(this), start,
                    end, WTF::Unretained(&exception_state)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::Remove_Locked(
    double start,
    double end,
    ExceptionState* exception_state,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // 3. If duration equals NaN, then throw a TypeError exception and abort these
  //    steps.
  // 4. If start is negative or greater than duration, then throw a TypeError
  //    exception and abort these steps.
  double duration = source_->duration();
  if (start < 0 || std::isnan(duration) || start > duration) {
    MediaSource::LogAndThrowTypeError(
        *exception_state,
        ExceptionMessages::IndexOutsideRange(
            "start", start, 0.0, ExceptionMessages::kExclusiveBound,
            std::isnan(duration) ? 0 : duration,
            ExceptionMessages::kExclusiveBound));
    return;
  }

  // 5. If end is less than or equal to start or end equals NaN, then throw a
  //    TypeError exception and abort these steps.
  if (end <= start || std::isnan(end)) {
    MediaSource::LogAndThrowTypeError(
        *exception_state,
        "The end value provided (" + String::Number(end) +
            ") must be greater than the start value provided (" +
            String::Number(start) + ").");
    return;
  }

  TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("media", "SourceBuffer::remove",
                                    TRACE_ID_LOCAL(this));

  // 6. If the readyState attribute of the parent media source is in the "ended"
  //    state then run the following steps:
  // 6.1. Set the readyState attribute of the parent media source to "open"
  // 6.2. Queue a task to fire a simple event named sourceopen at the parent
  //      media source .
  source_->OpenIfInEndedState();

  // 7. Run the range removal algorithm with start and end as the start and end
  //    of the removal range.
  // 7.3. Set the updating attribute to true.
  updating_ = true;

  // 7.4. Queue a task to fire a simple event named updatestart at this
  //      SourceBuffer object.
  ScheduleEvent(event_type_names::kUpdatestart);

  // 7.5. Return control to the caller and run the rest of the steps
  //      asynchronously.
  pending_remove_start_ = start;
  pending_remove_end_ = end;
  remove_async_task_handle_ = PostCancellableTask(
      *GetExecutionContext()->GetTaskRunner(TaskType::kMediaElementEvent),
      FROM_HERE,
      WTF::Bind(&SourceBuffer::RemoveAsyncPart, WrapPersistent(this)));
}

void SourceBuffer::changeType(const String& type,
                              ExceptionState& exception_state) {
  DVLOG(2) << __func__ << " this=" << this << " type=" << type;

  // Per 30 May 2018 Codec Switching feature incubation spec:
  // https://rawgit.com/WICG/media-source/3b3742ea788999bb7ae4a4553ac7d574b0547dbe/index.html#dom-sourcebuffer-changetype
  // 1. If type is an empty string then throw a TypeError exception and abort
  //    these steps.
  if (type.IsEmpty()) {
    MediaSource::LogAndThrowTypeError(exception_state,
                                      "The type provided is empty");
    return;
  }

  // 2. If this object has been removed from the sourceBuffers attribute of the
  //    parent media source, then throw an InvalidStateError exception and abort
  //    these steps.
  // 3. If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // Do remainder of steps only if attachment is usable and underlying demuxer
  // is protected from destruction (applicable especially for MSE-in-Worker
  // case). Note, we must have |source_| and |source_| must have an attachment
  // because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::ChangeType_Locked, WrapPersistent(this),
                    type, WTF::Unretained(&exception_state)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::ChangeTypeUsingConfig(const SourceBufferConfig* config,
                                         ExceptionState& exception_state) {
  DVLOG(2) << __func__ << " this=" << this;

  // If this object has been removed from the sourceBuffers attribute of the
  //    parent media source, then throw an InvalidStateError exception and abort
  //    these steps.
  // If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // Before this IDL overload was added, changeType(null) yielded a
  // kNotSupportedError, so preserve that behavior if the bindings resolve us
  // instead of the original changeType(DOMString) when given a null parameter.
  // Fortunately, a null or empty SourceBufferConfig here similarly should yield
  // a kNotSupportedError.
  if (!config || (!config->hasAudioConfig() && !config->hasVideoConfig())) {
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kNotSupportedError,
        "Changing to the type provided ('null' config) is not supported.");
    return;
  }

  // TODO(crbug.com/1144908): Further validate allowed in current state (and
  // take lock at appropriate point), unwrap the config, validate it, update
  // internals to new config, etc.
  exception_state.ThrowTypeError(
      "unimplemented - see https://crbug.com/1144908");
}

void SourceBuffer::ChangeType_Locked(
    const String& type,
    ExceptionState* exception_state,
    MediaSourceAttachmentSupplement::ExclusiveKey pass_key) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // 4. If type contains a MIME type that is not supported or contains a MIME
  //    type that is not supported with the types specified (currently or
  //    previously) of SourceBuffer objects in the sourceBuffers attribute of
  //    the parent media source, then throw a NotSupportedError exception and
  //    abort these steps.
  ContentType content_type(type);
  String codecs = content_type.Parameter("codecs");
  // TODO(wolenetz): Refactor and use a less-strict version of isTypeSupported
  // here. As part of that, CanChangeType in Chromium should inherit relaxation
  // of impl's StreamParserFactory (since it returns true iff a stream parser
  // can be constructed with |type|). See https://crbug.com/535738.
  if (!MediaSource::IsTypeSupportedInternal(
          GetExecutionContext(), type,
          false /* allow underspecified codecs in |type| */) ||
      !web_source_buffer_->CanChangeType(content_type.GetType(), codecs)) {
    MediaSource::LogAndThrowDOMException(
        *exception_state, DOMExceptionCode::kNotSupportedError,
        "Changing to the type provided ('" + type + "') is not supported.");
    return;
  }

  // 5. If the readyState attribute of the parent media source is in the "ended"
  //    state then run the following steps:
  //    1. Set the readyState attribute of the parent media source to "open"
  //    2. Queue a task to fire a simple event named sourceopen at the parent
  //       media source.
  source_->OpenIfInEndedState();

  // 6. Run the reset parser state algorithm.
  web_source_buffer_->ResetParserState();

  // 7. Update the generate timestamps flag on this SourceBuffer object to the
  //    value in the "Generate Timestamps Flag" column of the byte stream format
  //    registry entry that is associated with type.
  // This call also updates the pipeline to switch bytestream parser and codecs.
  web_source_buffer_->ChangeType(content_type.GetType(), codecs);

  // 8. If the generate timestamps flag equals true: Set the mode attribute on
  //    this SourceBuffer object to "sequence", including running the associated
  //    steps for that attribute being set. Otherwise: keep the previous value
  //    of the mode attribute on this SourceBuffer object, without running any
  //    associated steps for that attribute being set.
  if (web_source_buffer_->GetGenerateTimestampsFlag())
    SetMode_Locked(SequenceKeyword(), exception_state, pass_key);

  // 9. Set pending initialization segment for changeType flag to true.
  // The logic for this flag is handled by the pipeline (the new bytestream
  // parser will expect an initialization segment first).
}

void SourceBuffer::setTrackDefaults(TrackDefaultList* track_defaults,
                                    ExceptionState& exception_state) {
  // Per 02 Dec 2014 Editor's Draft
  // http://w3c.github.io/media-source/#widl-SourceBuffer-trackDefaults
  // 1. If this object has been removed from the sourceBuffers attribute of
  //    the parent media source, then throw an InvalidStateError exception
  //    and abort these steps.
  // 2. If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    return;
  }

  // 3. Update the attribute to the new value.
  track_defaults_ = track_defaults;
}

void SourceBuffer::CancelRemove() {
  DCHECK(updating_);
  DCHECK_NE(pending_remove_start_, -1);
  remove_async_task_handle_.Cancel();
  pending_remove_start_ = -1;
  pending_remove_end_ = -1;
  updating_ = false;

  if (!RuntimeEnabledFeatures::MediaSourceNewAbortAndDurationEnabled()) {
    ScheduleEvent(event_type_names::kAbort);
    ScheduleEvent(event_type_names::kUpdateend);
  }

  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::remove",
                                  TRACE_ID_LOCAL(this));
}

void SourceBuffer::AbortIfUpdating() {
  // Section 3.2 abort() method step 4 substeps.
  // http://w3c.github.io/media-source/#widl-SourceBuffer-abort-void

  if (!updating_)
    return;

  DCHECK_EQ(pending_remove_start_, -1);

  // 4.1. Abort the buffer append and stream append loop algorithms if they are
  //      running.
  // 4.2. Set the updating attribute to false.
  updating_ = false;

  if (pending_chunks_to_buffer_) {
    append_encoded_chunks_async_task_handle_.Cancel();
    pending_chunks_to_buffer_.reset();

    // For async Promise resolution/rejection, we do not use events to notify
    // the app, since event dispatch could occur after the promise callback
    // microtask dispatch and violate the design principle, "Events should fire
    // before Promises resolve", unless we introduced unnecessary further
    // latency to enqueue a task to resolve/reject the promise. In this case,
    // the elision of the "abort" and "updateend" events is synonymous with
    // rejection with an AbortError DOMException, enabling faster abort
    // notification. See
    // https://w3ctag.github.io/design-principles/#promises-and-events
    // TODO(crbug.com/1144908): Consider moving this verbosity to eventual
    // specification.
    DCHECK(append_encoded_chunks_resolver_);
    append_encoded_chunks_resolver_->Reject(MakeGarbageCollected<DOMException>(
        DOMExceptionCode::kAbortError, "Aborted by explicit abort()"));
    append_encoded_chunks_resolver_ = nullptr;
    TRACE_EVENT_NESTABLE_ASYNC_END0(
        "media", "SourceBuffer::appendEncodedChunks", TRACE_ID_LOCAL(this));
    return;
  }

  DCHECK(!append_encoded_chunks_resolver_);
  append_buffer_async_task_handle_.Cancel();
  pending_append_data_.clear();
  pending_append_data_offset_ = 0;
  // For the regular, non-promisified appendBuffer abort, use events to notify
  // result.
  // 4.3. Queue a task to fire a simple event named abort at this SourceBuffer
  //      object.
  ScheduleEvent(event_type_names::kAbort);

  // 4.4. Queue a task to fire a simple event named updateend at this
  //      SourceBuffer object.
  ScheduleEvent(event_type_names::kUpdateend);

  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::appendBuffer",
                                  TRACE_ID_LOCAL(this));
}

void SourceBuffer::RemovedFromMediaSource() {
  if (IsRemoved())
    return;

  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  DVLOG(3) << __func__ << " this=" << this;
  if (pending_remove_start_ != -1) {
    CancelRemove();
  } else {
    AbortIfUpdating();
  }

  if (HTMLMediaElement::MediaTracksEnabledInternally()) {
    DCHECK(source_);
    RemoveMediaTracks();
  }

  // Update the underlying demuxer except in the cross-thread attachment case
  // where detachment or element context destruction may have already begun.
  scoped_refptr<MediaSourceAttachmentSupplement> attachment;
  MediaSourceTracer* tracer;
  std::tie(attachment, tracer) = source_->AttachmentAndTracer();
  DCHECK(attachment);
  if (attachment->FullyAttachedOrSameThread(
          MediaSourceAttachmentSupplement::SourceBufferPassKey())) {
    web_source_buffer_->RemovedFromMediaSource();
  }

  web_source_buffer_.reset();
  source_ = nullptr;
  async_event_queue_ = nullptr;
}

double SourceBuffer::HighestPresentationTimestamp() {
  DCHECK(!IsRemoved());
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  double pts = web_source_buffer_->HighestPresentationTimestamp();
  DVLOG(3) << __func__ << " this=" << this << ", pts=" << pts;
  return pts;
}

void SourceBuffer::RemoveMediaTracks() {
  // Spec:
  // http://w3c.github.io/media-source/#widl-MediaSource-removeSourceBuffer-void-SourceBuffer-sourceBuffer
  DCHECK(HTMLMediaElement::MediaTracksEnabledInternally());
  DCHECK(source_);

  scoped_refptr<MediaSourceAttachmentSupplement> attachment;
  MediaSourceTracer* tracer;
  std::tie(attachment, tracer) = source_->AttachmentAndTracer();
  DCHECK(attachment);

  // One path leading to here is from |source_|'s ContextDestroyed(), so we
  // cannot consult GetExecutionContext() here to determine if this is a
  // worker-thread-owned or main-thread-owned SourceBuffer. Rather, we will rely
  // on IsMainThread().
  if (!IsMainThread()) {
    RemovePlaceholderCrossThreadTracks(attachment, tracer);
    return;
  }

  // For safety, ensure we are using SameThreadAttachment behavior. This is just
  // in case we somehow are incorrectly running on the main thread, but are a
  // worker-thread-owned SourceBuffer with a cross-thread attachment.
  CHECK(tracer);  // Only same-thread attachments have a tracer.

  // 3. Let SourceBuffer audioTracks list equal the AudioTrackList object
  //    returned by sourceBuffer.audioTracks.
  // 4. If the SourceBuffer audioTracks list is not empty, then run the
  //    following steps:
  // 4.1 Let HTMLMediaElement audioTracks list equal the AudioTrackList object
  //     returned by the audioTracks attribute on the HTMLMediaElement.
  // 4.2 Let the removed enabled audio track flag equal false.
  bool removed_enabled_audio_track = false;
  Vector<String> audio_track_removal_ids;
  // 4.3 For each AudioTrack object in the SourceBuffer audioTracks list, run
  //     the following steps:
  while (audioTracks().length() > 0) {
    AudioTrack* audio_track = audioTracks().AnonymousIndexedGetter(0);
    // 4.3.1 Set the sourceBuffer attribute on the AudioTrack object to null.
    SourceBufferTrackBaseSupplement::SetSourceBuffer(*audio_track, nullptr);
    // 4.3.2 If the enabled attribute on the AudioTrack object is true, then set
    //       the removed enabled audio track flag to true.
    if (audio_track->enabled())
      removed_enabled_audio_track = true;
    // 4.3.3 Remove the AudioTrack object from the HTMLMediaElement audioTracks
    //       list.
    // 4.3.4 Queue a task to fire a trusted event named removetrack, that does
    //       not bubble and is not cancelable, and that uses the TrackEvent
    //       interface, at the HTMLMediaElement audioTracks list.
    // We compile the list of audio tracks to remove from the media element here
    // and tell the element to remove them, below, with step 4.4.
    audio_track_removal_ids.push_back(audio_track->id());
    // 4.3.5 Remove the AudioTrack object from the SourceBuffer audioTracks
    //       list.
    // 4.3.6 Queue a task to fire a trusted event named removetrack, that does
    //       not bubble and is not cancelable, and that uses the TrackEvent
    //       interface, at the SourceBuffer audioTracks list.
    audioTracks().Remove(audio_track->id());
  }
  // 4.4 If the removed enabled audio track flag equals true, then queue a task
  //     to fire a simple event named change at the HTMLMediaElement audioTracks
  //     list.
  // Here, we perform batch removal of audio tracks, compiled in step 4.3.4,
  // above, along with conditional enqueueing of change event.
  if (!audio_track_removal_ids.IsEmpty()) {
    attachment->RemoveAudioTracksFromMediaElement(
        tracer, audio_track_removal_ids,
        removed_enabled_audio_track /* enqueue_change_event */);
  }

  // 5. Let SourceBuffer videoTracks list equal the VideoTrackList object
  //    returned by sourceBuffer.videoTracks.
  // 6. If the SourceBuffer videoTracks list is not empty, then run the
  //    following steps:
  // 6.1 Let HTMLMediaElement videoTracks list equal the VideoTrackList object
  //     returned by the videoTracks attribute on the HTMLMediaElement.
  // 6.2 Let the removed selected video track flag equal false.
  bool removed_selected_video_track = false;
  Vector<String> video_track_removal_ids;
  // 6.3 For each VideoTrack object in the SourceBuffer videoTracks list, run
  //     the following steps:
  while (videoTracks().length() > 0) {
    VideoTrack* video_track = videoTracks().AnonymousIndexedGetter(0);
    // 6.3.1 Set the sourceBuffer attribute on the VideoTrack object to null.
    SourceBufferTrackBaseSupplement::SetSourceBuffer(*video_track, nullptr);
    // 6.3.2 If the selected attribute on the VideoTrack object is true, then
    //       set the removed selected video track flag to true.
    if (video_track->selected())
      removed_selected_video_track = true;
    // 6.3.3 Remove the VideoTrack object from the HTMLMediaElement videoTracks
    //       list.
    // 6.3.4 Queue a task to fire a trusted event named removetrack, that does
    //       not bubble and is not cancelable, and that uses the TrackEvent
    //       interface, at the HTMLMediaElement videoTracks list.
    // We compile the list of video tracks to remove from the media element here
    // and tell the element to remove them, below, with step 6.4.
    video_track_removal_ids.push_back(video_track->id());
    // 6.3.5 Remove the VideoTrack object from the SourceBuffer videoTracks
    //       list.
    // 6.3.6 Queue a task to fire a trusted event named removetrack, that does
    //       not bubble and is not cancelable, and that uses the TrackEvent
    //       interface, at the SourceBuffer videoTracks list.
    videoTracks().Remove(video_track->id());
  }
  // 6.4 If the removed selected video track flag equals true, then queue a task
  //     to fire a simple event named change at the HTMLMediaElement videoTracks
  //     list.
  // Here, we perform batch removal of video tracks, compiled in step 6.3.4,
  // above, along with conditional enqueueing of change event.
  if (!video_track_removal_ids.IsEmpty()) {
    attachment->RemoveVideoTracksFromMediaElement(
        tracer, video_track_removal_ids,
        removed_selected_video_track /* enqueue_change_event */);
  }

  // 7-8. TODO(servolk): Remove text tracks once SourceBuffer has text tracks.
}

double SourceBuffer::GetMediaTime() {
  DCHECK(source_);
  scoped_refptr<MediaSourceAttachmentSupplement> attachment;
  MediaSourceTracer* tracer;
  std::tie(attachment, tracer) = source_->AttachmentAndTracer();
  DCHECK(attachment);
  return attachment->GetRecentMediaTime(tracer);
}

template <class T>
T* FindExistingTrackById(const TrackListBase<T>& track_list, const String& id) {
  // According to MSE specification
  // (https://w3c.github.io/media-source/#sourcebuffer-init-segment-received)
  // step 3.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.
  // I.e. we only need to search by TrackID if there is more than one track,
  // otherwise we can assume that the only track of the given type is the same
  // one that we had in previous init segments.
  if (track_list.length() == 1)
    return track_list.AnonymousIndexedGetter(0);
  return track_list.getTrackById(id);
}

const TrackDefault* SourceBuffer::GetTrackDefault(
    const AtomicString& track_type,
    const AtomicString& byte_stream_track_id) const {
  // This is a helper for implementation of default track label and default
  // track language algorithms.
  // defaultTrackLabel spec:
  // https://w3c.github.io/media-source/#sourcebuffer-default-track-label
  // defaultTrackLanguage spec:
  // https://w3c.github.io/media-source/#sourcebuffer-default-track-language

  // 1. If trackDefaults contains a TrackDefault object with a type attribute
  //    equal to type and a byteStreamTrackID attribute equal to
  //    byteStreamTrackID, then return the value of the label/language attribute
  //    on this matching object and abort these steps.
  // 2. If trackDefaults contains a TrackDefault object with a type attribute
  //    equal to type and a byteStreamTrackID attribute equal to an empty
  //    string, then return the value of the label/language attribute on this
  //    matching object and abort these steps.
  // 3. Return an empty string to the caller
  const TrackDefault* track_default_with_empty_bytestream_id = nullptr;
  for (unsigned i = 0; i < track_defaults_->length(); ++i) {
    const TrackDefault* track_default = track_defaults_->item(i);
    if (track_default->type() != track_type)
      continue;
    if (track_default->byteStreamTrackID() == byte_stream_track_id)
      return track_default;
    if (!track_default_with_empty_bytestream_id &&
        track_default->byteStreamTrackID() == "")
      track_default_with_empty_bytestream_id = track_default;
  }
  return track_default_with_empty_bytestream_id;
}

AtomicString SourceBuffer::DefaultTrackLabel(
    const AtomicString& track_type,
    const AtomicString& byte_stream_track_id) const {
  // Spec: https://w3c.github.io/media-source/#sourcebuffer-default-track-label
  const TrackDefault* track_default =
      GetTrackDefault(track_type, byte_stream_track_id);
  return track_default ? AtomicString(track_default->label()) : "";
}

AtomicString SourceBuffer::DefaultTrackLanguage(
    const AtomicString& track_type,
    const AtomicString& byte_stream_track_id) const {
  // Spec:
  // https://w3c.github.io/media-source/#sourcebuffer-default-track-language
  const TrackDefault* track_default =
      GetTrackDefault(track_type, byte_stream_track_id);
  return track_default ? AtomicString(track_default->language()) : "";
}

void SourceBuffer::AddPlaceholderCrossThreadTracks(
    const WebVector<MediaTrackInfo>& new_tracks,
    scoped_refptr<MediaSourceAttachmentSupplement> attachment) {
  // TODO(https://crbug.com/878133): Complete the MSE-in-Workers function
  // necessary to enable successful experimental usage of AudioVideoTracks
  // feature when MSE is in worker. Meanwhile, at least notify the attachment
  // to tell the media element to populate appropriately identified tracks so
  // that the BackgroundVideoOptimization feature functions for MSE-in-Workers
  // playbacks.
  DCHECK(RuntimeEnabledFeatures::MediaSourceInWorkersEnabled());
  DCHECK(!IsMainThread());
  DCHECK(!first_initialization_segment_received_);
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // Perform placeholder track additions on the main thread for each audio
  // and video track in the initialization segment. Note that this depends
  // on the caller already verifying correctness of the track metadata (see
  // SourceBufferState::OnNewConfigs()).
  bool enable_next_audio_track = true;
  bool select_next_video_track = true;
  DCHECK(audio_track_ids_for_crossthread_removal_.IsEmpty());
  DCHECK(video_track_ids_for_crossthread_removal_.IsEmpty());
  for (const MediaTrackInfo& track_info : new_tracks) {
    if (track_info.track_type == WebMediaPlayer::kAudioTrack) {
      WebString label = track_info.label;
      if (label.IsEmpty()) {
        label = DefaultTrackLabel(TrackDefault::AudioKeyword(),
                                  track_info.byte_stream_track_id);
      }

      WebString language = track_info.language;
      if (language.IsEmpty()) {
        language = DefaultTrackLanguage(TrackDefault::AudioKeyword(),
                                        track_info.byte_stream_track_id);
      }

      attachment->AddMainThreadAudioTrackToMediaElement(
          track_info.id, track_info.kind, std::move(label), std::move(language),
          enable_next_audio_track);

      // Only enable the first audio track for this SourceBuffer.
      enable_next_audio_track = false;

      // Remember to remove this track from the element later.
      audio_track_ids_for_crossthread_removal_.push_back(track_info.id);
    } else if (track_info.track_type == WebMediaPlayer::kVideoTrack) {
      WebString label = track_info.label;
      if (label.IsEmpty()) {
        label = DefaultTrackLabel(TrackDefault::VideoKeyword(),
                                  track_info.byte_stream_track_id);
      }

      WebString language = track_info.language;
      if (language.IsEmpty()) {
        language = DefaultTrackLanguage(TrackDefault::VideoKeyword(),
                                        track_info.byte_stream_track_id);
      }
      attachment->AddMainThreadVideoTrackToMediaElement(
          track_info.id, track_info.kind, std::move(label), std::move(language),
          select_next_video_track);

      // Only select the first video track for this SourceBuffer.
      select_next_video_track = false;

      // Remember to remove this track from the element later.
      video_track_ids_for_crossthread_removal_.push_back(track_info.id);
    }
  }
}

void SourceBuffer::RemovePlaceholderCrossThreadTracks(
    scoped_refptr<MediaSourceAttachmentSupplement> attachment,
    MediaSourceTracer* tracer) {
  // TODO(https://crbug.com/878133): Remove this special-casing once worker
  // thread track creation and tracklist modifications are supported.
  DCHECK(RuntimeEnabledFeatures::MediaSourceInWorkersEnabled());
  DCHECK(!IsMainThread());
  DCHECK(!tracer);  // Cross-thread attachments don't use a tracer.

  // Remove all of this SourceBuffer's cross-thread media element audio and
  // video tracks, and enqueue a change event against the appropriate track
  // lists on the media element. The event(s) may be extra, but likely unseen by
  // application unless it is attempting experimental AudioVideoTracks usage,
  // too.
  if (!audio_track_ids_for_crossthread_removal_.IsEmpty()) {
    attachment->RemoveAudioTracksFromMediaElement(
        tracer, std::move(audio_track_ids_for_crossthread_removal_),
        true /* enqueue_change_event */);
  }

  if (!video_track_ids_for_crossthread_removal_.IsEmpty()) {
    attachment->RemoveVideoTracksFromMediaElement(
        tracer, std::move(video_track_ids_for_crossthread_removal_),
        true /* enqueue_change_event */);
  }
}

bool SourceBuffer::InitializationSegmentReceived(
    const WebVector<MediaTrackInfo>& new_tracks) {
  DVLOG(3) << __func__ << " this=" << this << " tracks=" << new_tracks.size();
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  scoped_refptr<MediaSourceAttachmentSupplement> attachment;
  MediaSourceTracer* tracer;
  std::tie(attachment, tracer) = source_->AttachmentAndTracer();
  DCHECK(attachment);
  DCHECK_EQ(!tracer, !IsMainThread());

  DCHECK(updating_);

  // Feature and execution-context conditioning may disable full population of
  // tracks in SourceBuffer (and maybe even in media element).
  bool finish_early = false;

  if (!HTMLMediaElement::MediaTracksEnabledInternally()) {
    // Don't populate SourceBuffer tracks. Let the media element figure out
    // internally any tracks it wants to populate (it may do placeholders).
    finish_early = true;
  } else if (GetExecutionContext()->IsDedicatedWorkerGlobalScope()) {
    finish_early = true;
    if (!first_initialization_segment_received_) {
      AddPlaceholderCrossThreadTracks(new_tracks, attachment);
    }
  }

  if (finish_early) {
    if (!first_initialization_segment_received_) {
      source_->SetSourceBufferActive(this, true);
      first_initialization_segment_received_ = true;
    }
    return true;
  }

  DCHECK(GetExecutionContext()->IsWindow());
  DCHECK(IsMainThread());

  // Implementation of Initialization Segment Received, see
  // https://w3c.github.io/media-source/#sourcebuffer-init-segment-received

  // Sort newTracks into audio and video tracks to facilitate implementation
  // of subsequent steps of this algorithm.
  Vector<MediaTrackInfo> new_audio_tracks;
  Vector<MediaTrackInfo> new_video_tracks;
  for (const MediaTrackInfo& track_info : new_tracks) {
    const TrackBase* track = nullptr;
    if (track_info.track_type == WebMediaPlayer::kAudioTrack) {
      new_audio_tracks.push_back(track_info);
      if (first_initialization_segment_received_)
        track = FindExistingTrackById(audioTracks(), track_info.id);
    } else if (track_info.track_type == WebMediaPlayer::kVideoTrack) {
      new_video_tracks.push_back(track_info);
      if (first_initialization_segment_received_)
        track = FindExistingTrackById(videoTracks(), track_info.id);
    } else {
      DVLOG(3) << __func__ << " this=" << this
               << " failed: unsupported track type " << track_info.track_type;
      // TODO(servolk): Add handling of text tracks.
      NOTREACHED();
    }
    if (first_initialization_segment_received_ && !track) {
      DVLOG(3) << __func__ << " this=" << this
               << " failed: tracks mismatch the first init segment.";
      return false;
    }
#if DCHECK_IS_ON()
    const char* log_track_type_str =
        (track_info.track_type == WebMediaPlayer::kAudioTrack) ? "audio"
                                                               : "video";
    DVLOG(3) << __func__ << " this=" << this << " : " << log_track_type_str
             << " track "
             << " id=" << String(track_info.id)
             << " byteStreamTrackID=" << String(track_info.byte_stream_track_id)
             << " kind=" << String(track_info.kind)
             << " label=" << String(track_info.label)
             << " language=" << String(track_info.language);
#endif
  }

  // 1. Update the duration attribute if it currently equals NaN:
  // TODO(servolk): Pass also stream duration into initSegmentReceived.

  // 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 (new_tracks.empty()) {
    DVLOG(3) << __func__ << " this=" << this
             << " failed: no tracks found in the init segment.";
    // The append error algorithm will be called at the top level after we
    // return false here to indicate failure.
    return false;
  }

  // 3. If the first initialization segment received flag is true, then run the
  //    following steps:
  if (first_initialization_segment_received_) {
    // 3.1 Verify the following properties. If any of the checks fail then run
    //     the append error algorithm with the decode error parameter set to
    //     true and abort these steps.
    bool tracks_match_first_init_segment = true;
    // - The number of audio, video, and text tracks match what was in the first
    //   initialization segment.
    if (new_audio_tracks.size() != audioTracks().length() ||
        new_video_tracks.size() != videoTracks().length()) {
      tracks_match_first_init_segment = false;
    }
    // - The codecs for each track, match what was specified in the first
    //   initialization segment.
    // This is currently done in MediaSourceState::OnNewConfigs.
    // - 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.
    if (tracks_match_first_init_segment && new_audio_tracks.size() > 1) {
      for (wtf_size_t i = 0; i < new_audio_tracks.size(); ++i) {
        const String& new_track_id = new_video_tracks[i].id;
        if (new_track_id !=
            String(audioTracks().AnonymousIndexedGetter(i)->id())) {
          tracks_match_first_init_segment = false;
          break;
        }
      }
    }

    if (tracks_match_first_init_segment && new_video_tracks.size() > 1) {
      for (wtf_size_t i = 0; i < new_video_tracks.size(); ++i) {
        const String& new_track_id = new_video_tracks[i].id;
        if (new_track_id !=
            String(videoTracks().AnonymousIndexedGetter(i)->id())) {
          tracks_match_first_init_segment = false;
          break;
        }
      }
    }

    if (!tracks_match_first_init_segment) {
      DVLOG(3) << __func__ << " this=" << this
               << " failed: tracks mismatch the first init segment.";
      // The append error algorithm will be called at the top level after we
      // return false here to indicate failure.
      return false;
    }

    // 3.2 Add the appropriate track descriptions from this initialization
    //     segment to each of the track buffers.  This is done in Chromium code
    //     in stream parsers and demuxer implementations.

    // 3.3 Set the need random access point flag on all track buffers to true.
    // This is done in Chromium code, see MediaSourceState::OnNewConfigs.
  }

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

  // 5. If the first initialization segment received flag is false, then run the
  //    following steps:
  if (!first_initialization_segment_received_) {
    // 5.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.
    // This is done in Chromium code, see MediaSourceState::OnNewConfigs.

    // 5.2 For each audio track in the initialization segment, run following
    //     steps:
    for (const MediaTrackInfo& track_info : new_audio_tracks) {
      // 5.2.1 Let audio byte stream track ID be the Track ID for the current
      //       track being processed.
      const auto& byte_stream_track_id = track_info.byte_stream_track_id;
      // 5.2.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.
      WebString language = track_info.language;
      // 5.2.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.
      if (language.IsEmpty() || language == "und")
        language = DefaultTrackLanguage(TrackDefault::AudioKeyword(),
                                        byte_stream_track_id);
      // 5.2.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.
      WebString label = track_info.label;
      // 5.3.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.
      if (label.IsEmpty())
        label = DefaultTrackLabel(TrackDefault::AudioKeyword(),
                                  byte_stream_track_id);
      // 5.2.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.
      const auto& kind = track_info.kind;
      // 5.2.7 TODO(servolk): Implement track kind processing.
      // 5.2.8.2 Let new audio track be a new AudioTrack object.
      auto* audio_track = MakeGarbageCollected<AudioTrack>(
          track_info.id, kind, std::move(label), std::move(language), false);
      SourceBufferTrackBaseSupplement::SetSourceBuffer(*audio_track, this);
      // 5.2.8.7 If audioTracks.length equals 0, then run the following steps:
      if (audioTracks().length() == 0) {
        // 5.2.8.7.1 Set the enabled property on new audio track to true.
        audio_track->setEnabled(true);
        // 5.2.8.7.2 Set active track flag to true.
        active_track = true;
      }
      // 5.2.8.8 Add new audio track to the audioTracks attribute on this
      //         SourceBuffer object.
      // 5.2.8.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.
      audioTracks().Add(audio_track);
      // 5.2.8.10 Add new audio track to the audioTracks attribute on the
      //          HTMLMediaElement.
      // 5.2.8.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.
      attachment->AddAudioTrackToMediaElement(tracer, audio_track);
    }

    // 5.3. For each video track in the initialization segment, run following
    //      steps:
    for (const MediaTrackInfo& track_info : new_video_tracks) {
      // 5.3.1 Let video byte stream track ID be the Track ID for the current
      //       track being processed.
      const auto& byte_stream_track_id = track_info.byte_stream_track_id;
      // 5.3.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.
      WebString language = track_info.language;
      // 5.3.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.
      if (language.IsEmpty() || language == "und")
        language = DefaultTrackLanguage(TrackDefault::VideoKeyword(),
                                        byte_stream_track_id);
      // 5.3.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.
      WebString label = track_info.label;
      // 5.3.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.
      if (label.IsEmpty())
        label = DefaultTrackLabel(TrackDefault::VideoKeyword(),
                                  byte_stream_track_id);
      // 5.3.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.
      const auto& kind = track_info.kind;
      // 5.3.7 TODO(servolk): Implement track kind processing.
      // 5.3.8.2 Let new video track be a new VideoTrack object.
      auto* video_track = MakeGarbageCollected<VideoTrack>(
          track_info.id, kind, std::move(label), std::move(language), false);
      SourceBufferTrackBaseSupplement::SetSourceBuffer(*video_track, this);
      // 5.3.8.7 If videoTracks.length equals 0, then run the following steps:
      if (videoTracks().length() == 0) {
        // 5.3.8.7.1 Set the selected property on new audio track to true.
        video_track->setSelected(true);
        // 5.3.8.7.2 Set active track flag to true.
        active_track = true;
      }
      // 5.3.8.8 Add new video track to the videoTracks attribute on this
      //         SourceBuffer object.
      // 5.3.8.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.
      videoTracks().Add(video_track);
      // 5.3.8.10 Add new video track to the videoTracks attribute on the
      //          HTMLMediaElement.
      // 5.3.8.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.
      attachment->AddVideoTrackToMediaElement(tracer, video_track);
    }

    // 5.4 TODO(servolk): Add text track processing here.

    // 5.5 If active track flag equals true, then run the following steps:
    // activesourcebuffers.
    if (active_track) {
      // 5.5.1 Add this SourceBuffer to activeSourceBuffers.
      // 5.5.2 Queue a task to fire a simple event named addsourcebuffer at
      //       activeSourceBuffers
      source_->SetSourceBufferActive(this, true);
    }

    // 5.6. Set first initialization segment received flag to true.
    first_initialization_segment_received_ = true;
  }

  return true;
}

void SourceBuffer::NotifyParseWarning(const ParseWarning warning) {
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  switch (warning) {
    case WebSourceBufferClient::kKeyframeTimeGreaterThanDependant:
      // Report this problematic GOP structure to help inform follow-up work.
      // TODO(wolenetz): Use the data to scope additional work. See
      // https://crbug.com/739931.
      UseCounter::Count(
          GetExecutionContext(),
          WebFeature::kMediaSourceKeyframeTimeGreaterThanDependant);
      break;
    case WebSourceBufferClient::kMuxedSequenceMode:
      // Report this problematic API usage to help inform follow-up work.
      // TODO(wolenetz): Use the data to scope additional work. See
      // https://crbug.com/737757.
      UseCounter::Count(GetExecutionContext(),
                        WebFeature::kMediaSourceMuxedSequenceMode);
      break;
    case WebSourceBufferClient::kGroupEndTimestampDecreaseWithinMediaSegment:
      // Report this problematic Media Segment structure usage to help inform
      // follow-up work.
      // TODO(wolenetz): Use the data to scope additional work. See
      // https://crbug.com/920853 and
      // https://github.com/w3c/media-source/issues/203.
      UseCounter::Count(
          GetExecutionContext(),
          WebFeature::kMediaSourceGroupEndTimestampDecreaseWithinMediaSegment);
      break;
  }
}

bool SourceBuffer::HasPendingActivity() const {
  return updating_ || append_buffer_async_task_handle_.IsActive() ||
         append_encoded_chunks_async_task_handle_.IsActive() ||
         remove_async_task_handle_.IsActive() ||
         (async_event_queue_ && async_event_queue_->HasPendingEvents());
}

void SourceBuffer::ContextDestroyed() {
  append_buffer_async_task_handle_.Cancel();
  pending_append_data_.clear();
  pending_append_data_offset_ = 0;

  append_encoded_chunks_async_task_handle_.Cancel();
  pending_chunks_to_buffer_.reset();
  append_encoded_chunks_resolver_ = nullptr;

  remove_async_task_handle_.Cancel();
  pending_remove_start_ = -1;
  pending_remove_end_ = -1;

  updating_ = false;
}

ExecutionContext* SourceBuffer::GetExecutionContext() const {
  return ExecutionContextLifecycleObserver::GetExecutionContext();
}

const AtomicString& SourceBuffer::InterfaceName() const {
  return event_target_names::kSourceBuffer;
}

bool SourceBuffer::IsRemoved() const {
  return !source_;
}

void SourceBuffer::ScheduleEvent(const AtomicString& event_name) {
  DCHECK(async_event_queue_);

  Event* event = Event::Create(event_name);
  event->SetTarget(this);

  async_event_queue_->EnqueueEvent(FROM_HERE, *event);
}

bool SourceBuffer::PrepareAppend(double media_time,
                                 size_t new_data_size,
                                 ExceptionState& exception_state) {
  // Runs the remainder of prepare append algorithm steps beyond those already
  // done by the caller.
  // http://w3c.github.io/media-source/#sourcebuffer-prepare-append
  // 3.5.4 Prepare Append Algorithm
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("media", "SourceBuffer::prepareAppend",
                                    TRACE_ID_LOCAL(this));
  // 3. If the HTMLMediaElement.error attribute is not null, then throw an
  //    InvalidStateError exception and abort these steps.
  DCHECK(source_);
  scoped_refptr<MediaSourceAttachmentSupplement> attachment;
  MediaSourceTracer* tracer;
  std::tie(attachment, tracer) = source_->AttachmentAndTracer();
  DCHECK(attachment);
  DCHECK_EQ(!tracer, !IsMainThread());
  if (attachment->GetElementError(tracer)) {
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "The HTMLMediaElement.error attribute is not null.");
    TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::prepareAppend",
                                    TRACE_ID_LOCAL(this));
    return false;
  }

  // 4. If the readyState attribute of the parent media source is in the "ended"
  //    state then run the following steps:
  //    1. Set the readyState attribute of the parent media source to "open"
  //    2. Queue a task to fire a simple event named sourceopen at the parent
  //       media source.
  source_->OpenIfInEndedState();

  // 5. Run the coded frame eviction algorithm.
  if (!EvictCodedFrames(media_time, new_data_size) ||
      !base::CheckedNumeric<wtf_size_t>(new_data_size).IsValid()) {
    // 6. If the buffer full flag equals true, then throw a QUOTA_EXCEEDED_ERR
    //    exception and abort these steps.
    //    If the incoming data exceeds wtf_size_t::max, then our implementation
    //    cannot deal with it, so we also throw a QuotaExceededError.
    DVLOG(3) << __func__ << " this=" << this << " -> throw QuotaExceededError";
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kQuotaExceededError,
        "The SourceBuffer is full, and cannot free space to append additional "
        "buffers.");
    TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::prepareAppend",
                                    TRACE_ID_LOCAL(this));
    return false;
  }

  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::prepareAppend",
                                  TRACE_ID_LOCAL(this));
  return true;
}

bool SourceBuffer::EvictCodedFrames(double media_time, size_t new_data_size) {
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // Nothing to do if this SourceBuffer does not yet have frames to evict.
  if (!first_initialization_segment_received_)
    return true;

  bool result = web_source_buffer_->EvictCodedFrames(media_time, new_data_size);
  if (!result) {
    DVLOG(3) << __func__ << " this=" << this
             << " failed. newDataSize=" << new_data_size
             << " media_time=" << media_time << " buffered="
             << WebTimeRangesToString(web_source_buffer_->Buffered());
  }
  return result;
}

void SourceBuffer::AppendBufferInternal(const unsigned char* data,
                                        size_t size,
                                        ExceptionState& exception_state) {
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("media", "SourceBuffer::appendBuffer",
                                    TRACE_ID_LOCAL(this), "size", size);
  // Section 3.2 appendBuffer()
  // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data
  //
  // 1. Run the prepare append algorithm.
  //
  // http://w3c.github.io/media-source/#sourcebuffer-prepare-append
  // 3.5.4 Prepare Append Algorithm
  //
  // Do the first two steps of the prepare append algorithm here, so that we can
  // be assured if they succeed that the remainder of this scope runs with the
  // attachment's |attachment_state_lock_| mutex held.
  //
  // 1. If the SourceBuffer has been removed from the sourceBuffers attribute of
  //    the parent media source then throw an InvalidStateError exception and
  //    abort these steps.
  // 2. If the updating attribute equals true, then throw an InvalidStateError
  //    exception and abort these steps.
  if (ThrowExceptionIfRemovedOrUpdating(IsRemoved(), updating_,
                                        exception_state)) {
    TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::appendBuffer",
                                    TRACE_ID_LOCAL(this));
    return;
  }

  // Do remainder of steps of prepare append algorithm and appendBuffer only if
  // attachment is usable and underlying demuxer is protected from destruction
  // (applicable especially for MSE-in-Worker case). Note, we must have
  // |source_| and |source_| must have an attachment because !IsRemoved().
  if (!source_->RunUnlessElementGoneOrClosingUs(WTF::Bind(
          &SourceBuffer::AppendBufferInternal_Locked, WrapPersistent(this),
          WTF::Unretained(data), size, WTF::Unretained(&exception_state)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, exception should be for this case.
    MediaSource::LogAndThrowDOMException(
        exception_state, DOMExceptionCode::kInvalidStateError,
        "Worker MediaSource attachment is closing");
  }
}

void SourceBuffer::AppendBufferInternal_Locked(
    const unsigned char* data,
    size_t size,
    ExceptionState* exception_state,
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DCHECK(source_);
  DCHECK(!updating_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // Finish the prepare append algorithm begun by the caller.
  double media_time = GetMediaTime();
  if (!PrepareAppend(media_time, size, *exception_state)) {
    TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::appendBuffer",
                                    TRACE_ID_LOCAL(this));
    return;
  }
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN0("media", "prepareAsyncAppend",
                                    TRACE_ID_LOCAL(this));

  // 2. Add data to the end of the input buffer.
  DCHECK(data || size == 0);
  if (data)
    pending_append_data_.Append(data, base::checked_cast<wtf_size_t>(size));
  pending_append_data_offset_ = 0;

  // 3. Set the updating attribute to true.
  updating_ = true;

  // 4. Queue a task to fire a simple event named updatestart at this
  //    SourceBuffer object.
  ScheduleEvent(event_type_names::kUpdatestart);

  // 5. Asynchronously run the buffer append algorithm.
  append_buffer_async_task_handle_ = PostCancellableTask(
      *GetExecutionContext()->GetTaskRunner(TaskType::kMediaElementEvent),
      FROM_HERE,
      WTF::Bind(&SourceBuffer::AppendBufferAsyncPart, WrapPersistent(this)));

  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "prepareAsyncAppend",
                                  TRACE_ID_LOCAL(this));
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("media", "delay", TRACE_ID_LOCAL(this),
                                    "type", "initialDelay");
}

void SourceBuffer::AppendEncodedChunksAsyncPart() {
  // Do the async append operation only if attachment is usable and underlying
  // demuxer is protected from destruction (applicable especially for
  // MSE-in-Worker case).
  DCHECK(!IsRemoved());  // So must have |source_| and it must have attachment.
  if (!source_->RunUnlessElementGoneOrClosingUs(
          WTF::Bind(&SourceBuffer::AppendEncodedChunksAsyncPart_Locked,
                    WrapPersistent(this)))) {
    // TODO(crbug.com/878133): Determine in specification what the specific,
    // app-visible, behavior should be for this case. In this implementation,
    // the safest thing to do is nothing here now. See more verbose reason in
    // similar AppendBufferAsyncPart() implementation.
    DVLOG(1) << __func__ << " this=" << this
             << ": Worker MediaSource attachment is closing";
  }
}

void SourceBuffer::AppendBufferAsyncPart() {
  // Do the async append operation only if attachment is usable and underlying
  // demuxer is protected from destruction (applicable especially for
  // MSE-in-Worker case).
  DCHECK(!IsRemoved());  // So must have |source_| and it must have attachment.
  if (!source_->RunUnlessElementGoneOrClosingUs(WTF::Bind(
          &SourceBuffer::AppendBufferAsyncPart_Locked, WrapPersistent(this)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, behavior should be for this case. In this
    // implementation:
    // 1) If main context isn't destroyed yet, then there must be a pending
    // MediaSource::Close() call which will call RemovedFromMediaSource()
    // eventually if still safe to do so (and that will cleanly shutdown pending
    // async append state if we just do nothing here now, or
    // 2) If main context is destroyed, then our context will be destroyed soon.
    // We cannot safely access the underlying demuxer. So the safest thing to do
    // is nothing here now.
    DVLOG(1) << __func__ << " this=" << this
             << ": Worker MediaSource attachment is closing";
  }
}

void SourceBuffer::AppendEncodedChunksAsyncPart_Locked(
    MediaSourceAttachmentSupplement::ExclusiveKey pass_key) {
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();
  DCHECK(updating_);
  DCHECK(append_encoded_chunks_resolver_);
  DCHECK(pending_chunks_to_buffer_);

  // Run the analogue to the segment parser loop.
  // TODO(crbug.com/1144908): Consider buffering |pending_chunks_to_buffer_| in
  // multiple async iterations if it contains many buffers. It is unclear if
  // this is necessary when buffering encoded chunks.
  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "delay", TRACE_ID_LOCAL(this));
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("media", "appending", TRACE_ID_LOCAL(this),
                                    "chunkCount",
                                    pending_chunks_to_buffer_->size());

  bool append_success = web_source_buffer_->AppendChunks(
      std::move(pending_chunks_to_buffer_), &timestamp_offset_);

  if (!append_success) {
    AppendError(pass_key);
    append_encoded_chunks_resolver_->Reject(MakeGarbageCollected<DOMException>(
        DOMExceptionCode::kSyntaxError,
        "Parsing or frame processing error while buffering encoded chunks."));
    append_encoded_chunks_resolver_ = nullptr;
  } else {
    updating_ = false;

    // Don't schedule 'update' or 'updateend' for this promisified async
    // method's completion. Promise resolution/rejection will signal same,
    // faster.
    append_encoded_chunks_resolver_->Resolve();
    append_encoded_chunks_resolver_ = nullptr;
  }

  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "appending", TRACE_ID_LOCAL(this));
  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::appendEncodedChunks",
                                  TRACE_ID_LOCAL(this));

  DVLOG(3) << __func__ << " done. this=" << this
           << " media_time=" << GetMediaTime() << " buffered="
           << WebTimeRangesToString(web_source_buffer_->Buffered());
}

void SourceBuffer::AppendBufferAsyncPart_Locked(
    MediaSourceAttachmentSupplement::ExclusiveKey pass_key) {
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();
  DCHECK(updating_);

  // Section 3.5.4 Buffer Append Algorithm
  // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-buffer-append

  // 1. Run the segment parser loop algorithm.
  // Step 2 doesn't apply since we run Step 1 synchronously here.
  DCHECK_GE(pending_append_data_.size(), pending_append_data_offset_);
  wtf_size_t append_size =
      pending_append_data_.size() - pending_append_data_offset_;

  // Impose an arbitrary max size for a single append() call so that an append
  // doesn't block the renderer event loop very long. This value was selected
  // by looking at YouTube SourceBuffer usage across a variety of bitrates.
  // This value allows relatively large appends while keeping append() call
  // duration in the ~5-15ms range. Note that even in MSE-in-Worker case, we
  // retain this behavior because some synchronous operations done by the main
  // thread media element on our attachment block until we are finished and have
  // exited the attachment's RunExclusively() callback scope.
  const wtf_size_t kMaxAppendSize = 128 * 1024;
  if (append_size > kMaxAppendSize)
    append_size = kMaxAppendSize;

  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "delay", TRACE_ID_LOCAL(this));
  TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("media", "appending", TRACE_ID_LOCAL(this),
                                    "appendSize", append_size);

  // |zero| is used for 0 byte appends so we always have a valid pointer.
  // We need to convey all appends, even 0 byte ones to |m_webSourceBuffer|
  // so that it can clear its end of stream state if necessary.
  unsigned char zero = 0;
  unsigned char* append_data = &zero;
  if (append_size)
    append_data = pending_append_data_.data() + pending_append_data_offset_;

  bool append_success =
      web_source_buffer_->Append(append_data, append_size, &timestamp_offset_);

  if (!append_success) {
    pending_append_data_.clear();
    pending_append_data_offset_ = 0;
    AppendError(pass_key);
  } else {
    pending_append_data_offset_ += append_size;

    if (pending_append_data_offset_ < pending_append_data_.size()) {
      append_buffer_async_task_handle_ = PostCancellableTask(
          *GetExecutionContext()->GetTaskRunner(TaskType::kMediaElementEvent),
          FROM_HERE,
          WTF::Bind(&SourceBuffer::AppendBufferAsyncPart,
                    WrapPersistent(this)));
      TRACE_EVENT_NESTABLE_ASYNC_END0("media", "appending",
                                      TRACE_ID_LOCAL(this));
      TRACE_EVENT_NESTABLE_ASYNC_BEGIN1("media", "delay", TRACE_ID_LOCAL(this),
                                        "type", "nextPieceDelay");
      return;
    }

    // 3. Set the updating attribute to false.
    updating_ = false;
    pending_append_data_.clear();
    pending_append_data_offset_ = 0;

    // 4. Queue a task to fire a simple event named update at this SourceBuffer
    //    object.
    ScheduleEvent(event_type_names::kUpdate);

    // 5. Queue a task to fire a simple event named updateend at this
    //    SourceBuffer object.
    ScheduleEvent(event_type_names::kUpdateend);
  }

  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "appending", TRACE_ID_LOCAL(this));
  TRACE_EVENT_NESTABLE_ASYNC_END0("media", "SourceBuffer::appendBuffer",
                                  TRACE_ID_LOCAL(this));

  double media_time = GetMediaTime();
  DVLOG(3) << __func__ << " done. this=" << this << " media_time=" << media_time
           << " buffered="
           << WebTimeRangesToString(web_source_buffer_->Buffered());
}

void SourceBuffer::RemoveAsyncPart() {
  // Do the async remove operation only if attachment is usable and underlying
  // demuxer is protected from destruction (applicable especially for
  // MSE-in-Worker case).
  DCHECK(!IsRemoved());  // So must have |source_| and it must have attachment.
  if (!source_->RunUnlessElementGoneOrClosingUs(WTF::Bind(
          &SourceBuffer::RemoveAsyncPart_Locked, WrapPersistent(this)))) {
    // TODO(https://crbug.com/878133): Determine in specification what the
    // specific, app-visible, behavior should be for this case. This
    // implementation takes the safest route and does nothing. See similar case
    // in AppendBufferAsyncPart for reasoning.
    DVLOG(1) << __func__ << " this=" << this
             << ": Worker MediaSource attachment is closing";
  }
}

void SourceBuffer::RemoveAsyncPart_Locked(
    MediaSourceAttachmentSupplement::ExclusiveKey /* passkey */) {
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();
  DCHECK(updating_);
  DCHECK_GE(pending_remove_start_, 0);
  DCHECK_LT(pending_remove_start_, pending_remove_end_);

  // Section 3.2 remove() method steps
  // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-remove-void-double-start-double-end

  // 9. Run the coded frame removal algorithm with start and end as the start
  //    and end of the removal range.
  web_source_buffer_->Remove(pending_remove_start_, pending_remove_end_);

  // 10. Set the updating attribute to false.
  updating_ = false;
  pending_remove_start_ = -1;
  pending_remove_end_ = -1;

  // 11. Queue a task to fire a simple event named update at this SourceBuffer
  //     object.
  ScheduleEvent(event_type_names::kUpdate);

  // 12. Queue a task to fire a simple event named updateend at this
  //     SourceBuffer object.
  ScheduleEvent(event_type_names::kUpdateend);
}

void SourceBuffer::AppendError(
    MediaSourceAttachmentSupplement::ExclusiveKey pass_key) {
  DVLOG(3) << __func__ << " this=" << this;
  DCHECK(source_);
  source_->AssertAttachmentsMutexHeldIfCrossThreadForDebugging();

  // Section 3.5.3 Append Error Algorithm
  // https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-append-error

  // 1. Run the reset parser state algorithm.
  web_source_buffer_->ResetParserState();

  // 2. Set the updating attribute to false.
  updating_ = false;

  // Only schedule 'error' and 'updateend' here for the non-promisified regular
  // appendBuffer asynchronous operation error. The promisified
  // appendEncodedChunks rejection will be handled by caller.
  if (!append_encoded_chunks_resolver_) {
    // 3. Queue a task to fire a simple event named error at this SourceBuffer
    //    object.
    ScheduleEvent(event_type_names::kError);

    // 4. Queue a task to fire a simple event named updateend at this
    //    SourceBuffer object.
    ScheduleEvent(event_type_names::kUpdateend);
  }

  // 5. If decode error is true, then run the end of stream algorithm with the
  // error parameter set to "decode".
  source_->EndOfStreamAlgorithm(WebMediaSource::kEndOfStreamStatusDecodeError,
                                pass_key);
}

void SourceBuffer::Trace(Visitor* visitor) const {
  visitor->Trace(source_);
  visitor->Trace(track_defaults_);
  visitor->Trace(async_event_queue_);
  visitor->Trace(append_encoded_chunks_resolver_);
  visitor->Trace(audio_tracks_);
  visitor->Trace(video_tracks_);
  EventTargetWithInlineData::Trace(visitor);
  ExecutionContextLifecycleObserver::Trace(visitor);
}

}  // namespace blink