summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/modules/media_controls/media_controls_impl.cc
blob: 00b9f48e9c92770435c1ec88ec0bfc195fbacad3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
/*
 * Copyright (C) 2011, 2012 Apple Inc. All rights reserved.
 * Copyright (C) 2011, 2012 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:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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/media_controls/media_controls_impl.h"

#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/public/platform/web_size.h"
#include "third_party/blink/renderer/bindings/core/v8/string_or_trusted_html.h"
#include "third_party/blink/renderer/core/css/css_property_value_set.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/mutation_observer.h"
#include "third_party/blink/renderer/core/dom/mutation_observer_init.h"
#include "third_party/blink/renderer/core/dom/mutation_record.h"
#include "third_party/blink/renderer/core/dom/shadow_root.h"
#include "third_party/blink/renderer/core/events/gesture_event.h"
#include "third_party/blink/renderer/core/events/keyboard_event.h"
#include "third_party/blink/renderer/core/events/pointer_event.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/fullscreen/fullscreen.h"
#include "third_party/blink/renderer/core/geometry/dom_rect.h"
#include "third_party/blink/renderer/core/html/media/autoplay_policy.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html/media/html_media_element_controls_list.h"
#include "third_party/blink/renderer/core/html/media/html_video_element.h"
#include "third_party/blink/renderer/core/html/track/text_track.h"
#include "third_party/blink/renderer/core/html/track/text_track_container.h"
#include "third_party/blink/renderer/core/html/track/text_track_list.h"
#include "third_party/blink/renderer/core/layout/layout_object.h"
#include "third_party/blink/renderer/core/page/spatial_navigation.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer.h"
#include "third_party/blink/renderer/core/resize_observer/resize_observer_entry.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_animated_arrow_container_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_button_panel_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_cast_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_consts.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_current_time_display_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_display_cutout_fullscreen_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_download_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_elements_helper.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_fullscreen_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_loading_panel_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_mute_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overflow_menu_list_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_enclosure_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_overlay_play_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_panel_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_panel_enclosure_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_picture_in_picture_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_play_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_remaining_time_display_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_scrubbing_message_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_timeline_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_volume_control_container_element.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_volume_slider_element.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_display_cutout_delegate.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_media_event_listener.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_orientation_lock_delegate.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_resource_loader.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_rotate_to_fullscreen_delegate.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_shared_helper.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_text_track_manager.h"
#include "third_party/blink/renderer/modules/remoteplayback/remote_playback.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
#include "third_party/blink/renderer/platform/web_test_support.h"

namespace blink {

namespace {

// TODO(steimel): should have better solution than hard-coding pixel values.
// Defined in core/css/mediaControls.css, core/css/mediaControlsAndroid.css,
// and core/paint/MediaControlsPainter.cpp.
constexpr int kOverlayPlayButtonWidth = 48;
constexpr int kOverlayPlayButtonHeight = 48;
constexpr int kOverlayBottomMargin = 10;
constexpr int kAndroidMediaPanelHeight = 48;

constexpr int kMinWidthForOverlayPlayButton = kOverlayPlayButtonWidth;
constexpr int kMinHeightForOverlayPlayButton = kOverlayPlayButtonHeight +
                                               kAndroidMediaPanelHeight +
                                               (2 * kOverlayBottomMargin);

// TODO(steimel): When modern media controls launches, remove above constants
// and rename below constants.
// (2px left border + 6px left padding + 56px button + 6px right padding + 2px
// right border) = 72px.
constexpr int kModernMinWidthForOverlayPlayButton = 72;

constexpr int kMinScrubbingMessageWidth = 300;

const char* kStateCSSClasses[7] = {
    "state-no-source",         // kNoSource
    "state-no-metadata",       // kNotLoaded
    "state-loading-metadata",  // kLoadingMetadata
    "state-stopped",           // kStopped
    "state-playing",           // kPlaying
    "state-buffering",         // kBuffering
    "state-scrubbing",         // kScrubbing
};

// The padding in pixels inside the button panel.
constexpr int kModernControlsAudioButtonPadding = 20;
constexpr int kModernControlsVideoButtonPadding = 26;

const char kShowDefaultPosterCSSClass[] = "use-default-poster";
const char kActAsAudioControlsCSSClass[] = "audio-only";
const char kScrubbingMessageCSSClass[] = "scrubbing-message";
const char kTestModeCSSClass[] = "test-mode";
const char kImmersiveModeCSSClass[] = "immersive-mode";
const char kPipPresentedCSSClass[] = "pip-presented";

// The delay between two taps to be recognized as a double tap gesture.
constexpr WTF::TimeDelta kDoubleTapDelay = TimeDelta::FromMilliseconds(300);

// The time user have to hover on mute button to show volume slider.
// If this value is changed, you need to change the corresponding value in
// media_controls_impl_test.cc
constexpr WTF::TimeDelta kTimeToShowVolumeSlider =
    TimeDelta::FromMilliseconds(200);
constexpr WTF::TimeDelta kTimeToShowVolumeSliderTest =
    TimeDelta::FromMilliseconds(0);

// The number of seconds to jump when double tapping.
constexpr int kNumberOfSecondsToJump = 10;

void MaybeParserAppendChild(Element* parent, Element* child) {
  DCHECK(parent);
  if (child)
    parent->ParserAppendChild(child);
}

bool ShouldShowPictureInPictureButton(HTMLMediaElement& media_element) {
  return media_element.SupportsPictureInPicture();
}

bool ShouldShowCastButton(HTMLMediaElement& media_element) {
  if (media_element.FastHasAttribute(html_names::kDisableremoteplaybackAttr))
    return false;

  // Explicitly do not show cast button when:
  // - the mediaControlsEnabled setting is false, to make sure the overlay does
  //   not appear;
  // - the immersiveModeEnabled setting is true.
  Document& document = media_element.GetDocument();
  if (document.GetSettings() &&
      (!document.GetSettings()->GetMediaControlsEnabled() ||
       document.GetSettings()->GetImmersiveModeEnabled())) {
    return false;
  }

  // The page disabled the button via the attribute.
  if (media_element.ControlsListInternal()->ShouldHideRemotePlayback()) {
    UseCounter::Count(
        media_element.GetDocument(),
        WebFeature::kHTMLMediaElementControlsListNoRemotePlayback);
    return false;
  }

  return RemotePlayback::From(media_element).RemotePlaybackAvailable();
}

bool PreferHiddenVolumeControls(const Document& document) {
  return !document.GetSettings() ||
         document.GetSettings()->GetPreferHiddenVolumeControls();
}

// If you change this value, then also update the corresponding value in
// web_tests/media/media-controls.js.
constexpr TimeDelta kTimeWithoutMouseMovementBeforeHidingMediaControls =
    TimeDelta::FromSeconds(3);
constexpr TimeDelta kModernTimeWithoutMouseMovementBeforeHidingMediaControls =
    TimeDelta::FromSecondsD(2.5);

TimeDelta GetTimeWithoutMouseMovementBeforeHidingMediaControls() {
  return MediaControlsImpl::IsModern()
             ? kModernTimeWithoutMouseMovementBeforeHidingMediaControls
             : kTimeWithoutMouseMovementBeforeHidingMediaControls;
}

}  // namespace

class MediaControlsImpl::BatchedControlUpdate {
  STACK_ALLOCATED();

 public:
  explicit BatchedControlUpdate(MediaControlsImpl* controls)
      : controls_(controls) {
    DCHECK(IsMainThread());
    DCHECK_GE(batch_depth_, 0);
    ++batch_depth_;
  }
  ~BatchedControlUpdate() {
    DCHECK(IsMainThread());
    DCHECK_GT(batch_depth_, 0);
    if (!(--batch_depth_))
      controls_->ComputeWhichControlsFit();
  }

 private:
  Member<MediaControlsImpl> controls_;
  static int batch_depth_;

  DISALLOW_COPY_AND_ASSIGN(BatchedControlUpdate);
};

// Count of number open batches for controls visibility.
int MediaControlsImpl::BatchedControlUpdate::batch_depth_ = 0;

class MediaControlsImpl::MediaControlsResizeObserverDelegate final
    : public ResizeObserver::Delegate {
 public:
  explicit MediaControlsResizeObserverDelegate(MediaControlsImpl* controls)
      : controls_(controls) {
    DCHECK(controls);
  }
  ~MediaControlsResizeObserverDelegate() override = default;

  void OnResize(
      const HeapVector<Member<ResizeObserverEntry>>& entries) override {
    DCHECK_EQ(1u, entries.size());
    DCHECK_EQ(entries[0]->target(), controls_->MediaElement());
    controls_->NotifyElementSizeChanged(entries[0]->contentRect());
  }

  void Trace(blink::Visitor* visitor) override {
    visitor->Trace(controls_);
    ResizeObserver::Delegate::Trace(visitor);
  }

 private:
  Member<MediaControlsImpl> controls_;
};

// Observes changes to the HTMLMediaElement attributes that affect controls.
class MediaControlsImpl::MediaElementMutationCallback
    : public MutationObserver::Delegate {
 public:
  explicit MediaElementMutationCallback(MediaControlsImpl* controls)
      : controls_(controls), observer_(MutationObserver::Create(this)) {
    MutationObserverInit* init = MutationObserverInit::Create();
    init->setAttributeOldValue(true);
    init->setAttributes(true);
    init->setAttributeFilter(
        {html_names::kDisableremoteplaybackAttr.ToString(),
         html_names::kDisablepictureinpictureAttr.ToString(),
         html_names::kPosterAttr.ToString()});
    observer_->observe(&controls_->MediaElement(), init, ASSERT_NO_EXCEPTION);
  }

  ExecutionContext* GetExecutionContext() const override {
    return &controls_->GetDocument();
  }

  void Deliver(const MutationRecordVector& records,
               MutationObserver&) override {
    for (const auto& record : records) {
      if (record->type() != "attributes")
        continue;

      const Element& element = *ToElement(record->target());
      if (record->oldValue() == element.getAttribute(record->attributeName()))
        continue;

      if (record->attributeName() ==
          html_names::kDisableremoteplaybackAttr.ToString()) {
        controls_->RefreshCastButtonVisibilityWithoutUpdate();
      }

      if (record->attributeName() ==
              html_names::kDisablepictureinpictureAttr.ToString() &&
          controls_->picture_in_picture_button_) {
        controls_->picture_in_picture_button_->SetIsWanted(
            ShouldShowPictureInPictureButton(controls_->MediaElement()));
      }

      if (record->attributeName() == html_names::kPosterAttr.ToString())
        controls_->UpdateCSSClassFromState();

      BatchedControlUpdate batch(controls_);
    }
  }

  void Disconnect() { observer_->disconnect(); }

  void Trace(blink::Visitor* visitor) override {
    visitor->Trace(controls_);
    visitor->Trace(observer_);
    MutationObserver::Delegate::Trace(visitor);
  }

 private:
  Member<MediaControlsImpl> controls_;
  Member<MutationObserver> observer_;
};

// static
bool MediaControlsImpl::IsModern() {
  return RuntimeEnabledFeatures::ModernMediaControlsEnabled();
}

bool MediaControlsImpl::IsTouchEvent(Event* event) {
  return event->IsTouchEvent() || event->IsGestureEvent() ||
         (event->IsMouseEvent() && ToMouseEvent(event)->FromTouch());
}

MediaControlsImpl::MediaControlsImpl(HTMLMediaElement& media_element)
    : HTMLDivElement(media_element.GetDocument()),
      MediaControls(media_element),
      overlay_enclosure_(nullptr),
      overlay_play_button_(nullptr),
      overlay_cast_button_(nullptr),
      enclosure_(nullptr),
      panel_(nullptr),
      play_button_(nullptr),
      timeline_(nullptr),
      scrubbing_message_(nullptr),
      current_time_display_(nullptr),
      duration_display_(nullptr),
      mute_button_(nullptr),
      volume_slider_(nullptr),
      volume_control_container_(nullptr),
      toggle_closed_captions_button_(nullptr),
      text_track_list_(nullptr),
      overflow_list_(nullptr),
      media_button_panel_(nullptr),
      loading_panel_(nullptr),
      picture_in_picture_button_(nullptr),
      animated_arrow_container_element_(nullptr),
      cast_button_(nullptr),
      fullscreen_button_(nullptr),
      display_cutout_fullscreen_button_(nullptr),
      download_button_(nullptr),
      media_event_listener_(
          MakeGarbageCollected<MediaControlsMediaEventListener>(this)),
      orientation_lock_delegate_(nullptr),
      rotate_to_fullscreen_delegate_(nullptr),
      display_cutout_delegate_(nullptr),
      hide_media_controls_timer_(
          media_element.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
          this,
          &MediaControlsImpl::HideMediaControlsTimerFired),
      hide_timer_behavior_flags_(kIgnoreNone),
      is_mouse_over_controls_(false),
      is_paused_for_scrubbing_(false),
      resize_observer_(ResizeObserver::Create(
          media_element.GetDocument(),
          MakeGarbageCollected<MediaControlsResizeObserverDelegate>(this))),
      element_size_changed_timer_(
          media_element.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
          this,
          &MediaControlsImpl::ElementSizeChangedTimerFired),
      keep_showing_until_timer_fires_(false),
      tap_timer_(
          media_element.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
          this,
          &MediaControlsImpl::TapTimerFired),
      volume_slider_wanted_timer_(
          media_element.GetDocument().GetTaskRunner(TaskType::kInternalMedia),
          this,
          &MediaControlsImpl::VolumeSliderWantedTimerFired),
      text_track_manager_(
          MakeGarbageCollected<MediaControlsTextTrackManager>(media_element)) {
  // On touch devices, start with the assumption that the user will interact via
  // touch events.
  Settings* settings = media_element.GetDocument().GetSettings();
  is_touch_interaction_ = settings ? settings->GetMaxTouchPoints() > 0 : false;

  resize_observer_->observe(&media_element);
}

MediaControlsImpl* MediaControlsImpl::Create(HTMLMediaElement& media_element,
                                             ShadowRoot& shadow_root) {
  MediaControlsImpl* controls =
      MakeGarbageCollected<MediaControlsImpl>(media_element);
  controls->SetShadowPseudoId(AtomicString("-webkit-media-controls"));
  controls->InitializeControls();
  controls->Reset();

  if (RuntimeEnabledFeatures::VideoFullscreenOrientationLockEnabled() &&
      media_element.IsHTMLVideoElement()) {
    // Initialize the orientation lock when going fullscreen feature.
    controls->orientation_lock_delegate_ =
        MakeGarbageCollected<MediaControlsOrientationLockDelegate>(
            ToHTMLVideoElement(media_element));
  }

  if (MediaControlsDisplayCutoutDelegate::IsEnabled() &&
      media_element.IsHTMLVideoElement()) {
    // Initialize the pinch gesture to expand into the display cutout feature.
    controls->display_cutout_delegate_ =
        MakeGarbageCollected<MediaControlsDisplayCutoutDelegate>(
            ToHTMLVideoElement(media_element));
  }

  if (RuntimeEnabledFeatures::VideoRotateToFullscreenEnabled() &&
      media_element.IsHTMLVideoElement()) {
    // Initialize the rotate-to-fullscreen feature.
    controls->rotate_to_fullscreen_delegate_ =
        MakeGarbageCollected<MediaControlsRotateToFullscreenDelegate>(
            ToHTMLVideoElement(media_element));
  }

  MediaControlsResourceLoader::InjectMediaControlsUAStyleSheet();

  shadow_root.ParserAppendChild(controls);
  return controls;
}

// The media controls DOM structure looks like:
//
// MediaControlsImpl
//     (-webkit-media-controls)
// +-MediaControlLoadingPanelElement
// |    (-internal-media-controls-loading-panel)
// |    {if ModernMediaControlsEnabled}
// +-MediaControlOverlayEnclosureElement
// |    (-webkit-media-controls-overlay-enclosure)
// | +-MediaControlOverlayPlayButtonElement
// | |    (-webkit-media-controls-overlay-play-button)
// | | {if mediaControlsOverlayPlayButtonEnabled}
// | \-MediaControlCastButtonElement
// |     (-internal-media-controls-overlay-cast-button)
// \-MediaControlPanelEnclosureElement
//   |    (-webkit-media-controls-enclosure)
//   \-MediaControlPanelElement
//     |    (-webkit-media-controls-panel)
//     |  {if ModernMediaControlsEnabled and is video element and is Android}
//     +-MediaControlScrubbingMessageElement
//     |  (-internal-media-controls-scrubbing-message)
//     |  {if ModernMediaControlsEnabled, otherwise
//     |   contents are directly attached to parent.
//     +-MediaControlOverlayPlayButtonElement
//     |  (-webkit-media-controls-overlay-play-button)
//     |  {if ModernMediaControlsEnabled}
//     +-MediaControlButtonPanelElement
//     |  |  (-internal-media-controls-button-panel)
//     |  |  <video> only, otherwise children are directly attached to parent
//     |  +-MediaControlPlayButtonElement
//     |  |    (-webkit-media-controls-play-button)
//     |  |    {only present if audio only or ModernMediaControls is disabled}
//     |  +-MediaControlCurrentTimeDisplayElement
//     |  |    (-webkit-media-controls-current-time-display)
//     |  +-MediaControlRemainingTimeDisplayElement
//     |  |    (-webkit-media-controls-time-remaining-display)
//     |  +-HTMLDivElement
//     |  |    (-internal-media-controls-button-spacer)
//     |  |    {if ModernMediaControls is enabled and is video element}
//     |  +-MediaControlVolumeControlContainerElement
//     |  |  |  (-webkit-media-controls-volume-control-container)
//     |  |  +-HTMLDivElement
//     |  |  |    (-webkit-media-controls-volume-control-hover-background)
//     |  |  +-MediaControlMuteButtonElement
//     |  |  |    (-webkit-media-controls-mute-button)
//     |  |  +-MediaControlVolumeSliderElement
//     |  |       (-webkit-media-controls-volume-slider)
//     |  |       {if not ModernMediaControlsEnabled}
//     |  +-MediaControlPictureInPictureButtonElement
//     |  |    (-webkit-media-controls-picture-in-picture-button)
//     |  +-MediaControlFullscreenButtonElement
//     |  |    (-webkit-media-controls-fullscreen-button)
//     |  +-MediaControlDownloadButtonElement
//     |  |    (-internal-media-controls-download-button)
//     |  |    {on the overflow menu if ModernMediaControls is enabled}
//     |  +-MediaControlToggleClosedCaptionsButtonElement
//     |  |    (-webkit-media-controls-toggle-closed-captions-button)
//     |  |    {on the overflow menu if ModernMediaControls is enabled}
//     |  +-MediaControlCastButtonElement
//     |       (-internal-media-controls-cast-button)
//     |       {on the overflow menu if ModernMediaControls is enabled}
//     \-MediaControlTimelineElement
//          (-webkit-media-controls-timeline)
// +-MediaControlTextTrackListElement
// |    (-internal-media-controls-text-track-list)
// | {for each renderable text track}
//  \-MediaControlTextTrackListItem
//  |   (-internal-media-controls-text-track-list-item)
//  +-MediaControlTextTrackListItemInput
//  |    (-internal-media-controls-text-track-list-item-input)
//  +-MediaControlTextTrackListItemCaptions
//  |    (-internal-media-controls-text-track-list-kind-captions)
//  +-MediaControlTextTrackListItemSubtitles
//       (-internal-media-controls-text-track-list-kind-subtitles)
// +-MediaControlDisplayCutoutFullscreenElement
//       (-internal-media-controls-display-cutout-fullscreen-button)
void MediaControlsImpl::InitializeControls() {
  if (IsModern() && ShouldShowVideoControls()) {
    loading_panel_ =
        MakeGarbageCollected<MediaControlLoadingPanelElement>(*this);
    ParserAppendChild(loading_panel_);
  }

  overlay_enclosure_ =
      MakeGarbageCollected<MediaControlOverlayEnclosureElement>(*this);

  if (RuntimeEnabledFeatures::MediaControlsOverlayPlayButtonEnabled()) {
    overlay_play_button_ =
        MakeGarbageCollected<MediaControlOverlayPlayButtonElement>(*this);

    if (!IsModern())
      overlay_enclosure_->ParserAppendChild(overlay_play_button_);
  }

  overlay_cast_button_ =
      MakeGarbageCollected<MediaControlCastButtonElement>(*this, true);
  overlay_enclosure_->ParserAppendChild(overlay_cast_button_);

  ParserAppendChild(overlay_enclosure_);

  // Create an enclosing element for the panel so we can visually offset the
  // controls correctly.
  enclosure_ = MakeGarbageCollected<MediaControlPanelEnclosureElement>(*this);

  panel_ = MakeGarbageCollected<MediaControlPanelElement>(*this);

  // If using the modern media controls, the buttons should belong to a
  // seperate button panel. This is because they are displayed in two lines.
  if (IsModern() && ShouldShowVideoControls()) {
    media_button_panel_ =
        MakeGarbageCollected<MediaControlButtonPanelElement>(*this);
    scrubbing_message_ =
        MakeGarbageCollected<MediaControlScrubbingMessageElement>(*this);
  }

  play_button_ = MakeGarbageCollected<MediaControlPlayButtonElement>(*this);

  current_time_display_ =
      MakeGarbageCollected<MediaControlCurrentTimeDisplayElement>(*this);
  current_time_display_->SetIsWanted(true);

  duration_display_ =
      MakeGarbageCollected<MediaControlRemainingTimeDisplayElement>(*this);
  timeline_ = MakeGarbageCollected<MediaControlTimelineElement>(*this);
  mute_button_ = MakeGarbageCollected<MediaControlMuteButtonElement>(*this);

  volume_slider_ = MakeGarbageCollected<MediaControlVolumeSliderElement>(*this);
  volume_control_container_ =
      MakeGarbageCollected<MediaControlVolumeControlContainerElement>(*this);
  if (PreferHiddenVolumeControls(GetDocument()))
    volume_slider_->SetIsWanted(false);

  if (RuntimeEnabledFeatures::PictureInPictureEnabled() &&
      GetDocument().GetSettings() &&
      GetDocument().GetSettings()->GetPictureInPictureEnabled() &&
      MediaElement().IsHTMLVideoElement()) {
    picture_in_picture_button_ =
        MakeGarbageCollected<MediaControlPictureInPictureButtonElement>(*this);
    picture_in_picture_button_->SetIsWanted(
        ShouldShowPictureInPictureButton(MediaElement()));
  }

  if (RuntimeEnabledFeatures::DisplayCutoutAPIEnabled() &&
      MediaElement().IsHTMLVideoElement()) {
    display_cutout_fullscreen_button_ =
        MakeGarbageCollected<MediaControlDisplayCutoutFullscreenButtonElement>(
            *this);
  }

  fullscreen_button_ =
      MakeGarbageCollected<MediaControlFullscreenButtonElement>(*this);
  download_button_ =
      MakeGarbageCollected<MediaControlDownloadButtonElement>(*this);
  cast_button_ =
      MakeGarbageCollected<MediaControlCastButtonElement>(*this, false);
  toggle_closed_captions_button_ =
      MakeGarbageCollected<MediaControlToggleClosedCaptionsButtonElement>(
          *this);
  overflow_menu_ =
      MakeGarbageCollected<MediaControlOverflowMenuButtonElement>(*this);

  PopulatePanel();
  enclosure_->ParserAppendChild(panel_);

  ParserAppendChild(enclosure_);

  text_track_list_ =
      MakeGarbageCollected<MediaControlTextTrackListElement>(*this);
  ParserAppendChild(text_track_list_);

  overflow_list_ =
      MakeGarbageCollected<MediaControlOverflowMenuListElement>(*this);
  ParserAppendChild(overflow_list_);

  // The order in which we append elements to the overflow list is significant
  // because it determines how the elements show up in the overflow menu
  // relative to each other.  The first item appended appears at the top of the
  // overflow menu.
  overflow_list_->ParserAppendChild(play_button_->CreateOverflowElement(
      MakeGarbageCollected<MediaControlPlayButtonElement>(*this)));
  overflow_list_->ParserAppendChild(fullscreen_button_->CreateOverflowElement(
      MakeGarbageCollected<MediaControlFullscreenButtonElement>(*this)));
  overflow_list_->ParserAppendChild(download_button_->CreateOverflowElement(
      MakeGarbageCollected<MediaControlDownloadButtonElement>(*this)));
  overflow_list_->ParserAppendChild(mute_button_->CreateOverflowElement(
      MakeGarbageCollected<MediaControlMuteButtonElement>(*this)));
  overflow_list_->ParserAppendChild(cast_button_->CreateOverflowElement(
      MakeGarbageCollected<MediaControlCastButtonElement>(*this, false)));
  overflow_list_->ParserAppendChild(
      toggle_closed_captions_button_->CreateOverflowElement(
          MakeGarbageCollected<MediaControlToggleClosedCaptionsButtonElement>(
              *this)));
  if (picture_in_picture_button_) {
    overflow_list_->ParserAppendChild(
        picture_in_picture_button_->CreateOverflowElement(
            MakeGarbageCollected<MediaControlPictureInPictureButtonElement>(
                *this)));
  }

  // Set the default CSS classes.
  UpdateCSSClassFromState();
}

void MediaControlsImpl::PopulatePanel() {
  // Clear the panels.
  panel_->setInnerHTML(StringOrTrustedHTML::FromString(""));
  if (media_button_panel_)
    media_button_panel_->setInnerHTML(StringOrTrustedHTML::FromString(""));

  Element* button_panel = panel_;
  if (IsModern() && ShouldShowVideoControls()) {
    MaybeParserAppendChild(panel_, scrubbing_message_);
    if (display_cutout_fullscreen_button_)
      panel_->ParserAppendChild(display_cutout_fullscreen_button_);

    MaybeParserAppendChild(panel_, overlay_play_button_);
    panel_->ParserAppendChild(media_button_panel_);
    button_panel = media_button_panel_;
  }

  button_panel->ParserAppendChild(play_button_);
  button_panel->ParserAppendChild(current_time_display_);
  button_panel->ParserAppendChild(duration_display_);

  if (IsModern() && ShouldShowVideoControls()) {
    MediaControlElementsHelper::CreateDiv(
        "-internal-media-controls-button-spacer", button_panel);
  }

  panel_->ParserAppendChild(timeline_);

  // On modern controls, the volume slider is to the left of the mute button.
  if (IsModern()) {
    MaybeParserAppendChild(volume_control_container_, volume_slider_);
    volume_control_container_->ParserAppendChild(mute_button_);
    button_panel->ParserAppendChild(volume_control_container_);
  } else {
    button_panel->ParserAppendChild(mute_button_);
    MaybeParserAppendChild(button_panel, volume_slider_);
  }

  MaybeParserAppendChild(button_panel, picture_in_picture_button_);

  button_panel->ParserAppendChild(fullscreen_button_);

  // The download, cast and captions buttons should not be present on the modern
  // controls button panel.
  if (!IsModern()) {
    button_panel->ParserAppendChild(download_button_);
    button_panel->ParserAppendChild(cast_button_);
    button_panel->ParserAppendChild(toggle_closed_captions_button_);
  }

  button_panel->ParserAppendChild(overflow_menu_);

  // Attach hover background div to modern controls
  if (IsModern()) {
    AttachHoverBackground(play_button_);
    AttachHoverBackground(fullscreen_button_);
    AttachHoverBackground(overflow_menu_);
  }
}

void MediaControlsImpl::AttachHoverBackground(Element* element) {
  MediaControlElementsHelper::CreateDiv(
      "-internal-media-controls-button-hover-background",
      element->GetShadowRoot());
}

Node::InsertionNotificationRequest MediaControlsImpl::InsertedInto(
    ContainerNode& root) {
  if (!MediaElement().isConnected())
    return HTMLDivElement::InsertedInto(root);

  // TODO(mlamouri): we should show the controls instead of having
  // HTMLMediaElement do it.

  // m_windowEventListener doesn't need to be re-attached as it's only needed
  // when a menu is visible.
  media_event_listener_->Attach();
  if (orientation_lock_delegate_)
    orientation_lock_delegate_->Attach();
  if (rotate_to_fullscreen_delegate_)
    rotate_to_fullscreen_delegate_->Attach();
  if (display_cutout_delegate_)
    display_cutout_delegate_->Attach();

  if (!resize_observer_) {
    resize_observer_ = ResizeObserver::Create(
        MediaElement().GetDocument(),
        MakeGarbageCollected<MediaControlsResizeObserverDelegate>(this));
    HTMLMediaElement& html_media_element = MediaElement();
    resize_observer_->observe(&html_media_element);
  }

  if (!element_mutation_callback_) {
    element_mutation_callback_ =
        MakeGarbageCollected<MediaElementMutationCallback>(this);
  }

  return HTMLDivElement::InsertedInto(root);
}

void MediaControlsImpl::UpdateCSSClassFromState() {
  const ControlsState state = State();

  Vector<String> toAdd;
  Vector<String> toRemove;

  if (state < kLoadingMetadata)
    toAdd.push_back("phase-pre-ready");
  else
    toRemove.push_back("phase-pre-ready");

  if (state > kLoadingMetadata)
    toAdd.push_back("phase-ready");
  else
    toRemove.push_back("phase-ready");

  for (int i = 0; i < 7; i++) {
    if (i == state)
      toAdd.push_back(kStateCSSClasses[i]);
    else
      toRemove.push_back(kStateCSSClasses[i]);
  }

  if (MediaElement().ShouldShowControls() && ShouldShowVideoControls() &&
      !VideoElement().HasAvailableVideoFrame() &&
      VideoElement().PosterImageURL().IsEmpty() &&
      state <= ControlsState::kLoadingMetadata) {
    toAdd.push_back(kShowDefaultPosterCSSClass);
  } else {
    toRemove.push_back(kShowDefaultPosterCSSClass);
  }

  if (ShouldShowVideoControls() && GetDocument().GetSettings() &&
      GetDocument().GetSettings()->GetImmersiveModeEnabled()) {
    toAdd.push_back(kImmersiveModeCSSClass);
  } else {
    toRemove.push_back(kImmersiveModeCSSClass);
  }

  classList().add(toAdd, ASSERT_NO_EXCEPTION);
  classList().remove(toRemove, ASSERT_NO_EXCEPTION);

  if (loading_panel_)
    loading_panel_->UpdateDisplayState();

  // If we are in the "no-source" state we should show the overflow menu on a
  // video element.
  // TODO(https://crbug.org/930001): Reconsider skipping this block when not
  // connected.
  if (IsModern() && MediaElement().isConnected()) {
    bool updated = false;

    if (state == kNoSource) {
      // Check if the play button or overflow menu has the "disabled" attribute
      // set so we avoid unnecessarily resetting it.
      if (!play_button_->hasAttribute(html_names::kDisabledAttr)) {
        play_button_->setAttribute(html_names::kDisabledAttr, "");
        updated = true;
      }

      if (ShouldShowVideoControls() &&
          !overflow_menu_->hasAttribute(html_names::kDisabledAttr)) {
        overflow_menu_->setAttribute(html_names::kDisabledAttr, "");
        updated = true;
      }
    } else {
      if (play_button_->hasAttribute(html_names::kDisabledAttr)) {
        play_button_->removeAttribute(html_names::kDisabledAttr);
        updated = true;
      }

      if (overflow_menu_->hasAttribute(html_names::kDisabledAttr)) {
        overflow_menu_->removeAttribute(html_names::kDisabledAttr);
        updated = true;
      }
    }

    if (state == kNoSource || state == kNotLoaded) {
      if (!timeline_->hasAttribute(html_names::kDisabledAttr)) {
        timeline_->setAttribute(html_names::kDisabledAttr, "");
        updated = true;
      }
    } else {
      if (timeline_->hasAttribute(html_names::kDisabledAttr)) {
        timeline_->removeAttribute(html_names::kDisabledAttr);
        updated = true;
      }
    }

    if (updated)
      UpdateOverflowMenuWanted();
  }
}

void MediaControlsImpl::SetClass(const AtomicString& class_name,
                                 bool should_have_class) {
  if (should_have_class && !classList().contains(class_name))
    classList().Add(class_name);
  else if (!should_have_class && classList().contains(class_name))
    classList().Remove(class_name);
}

MediaControlsImpl::ControlsState MediaControlsImpl::State() const {
  HTMLMediaElement::NetworkState network_state =
      MediaElement().getNetworkState();
  HTMLMediaElement::ReadyState ready_state = MediaElement().getReadyState();

  if (is_scrubbing_ && ready_state != HTMLMediaElement::kHaveNothing)
    return ControlsState::kScrubbing;

  switch (network_state) {
    case HTMLMediaElement::kNetworkEmpty:
    case HTMLMediaElement::kNetworkNoSource:
      return ControlsState::kNoSource;
    case HTMLMediaElement::kNetworkLoading:
      if (ready_state == HTMLMediaElement::kHaveNothing)
        return ControlsState::kLoadingMetadata;
      if (!MediaElement().paused() &&
          ready_state != HTMLMediaElement::kHaveEnoughData) {
        return ControlsState::kBuffering;
      }
      break;
    case HTMLMediaElement::kNetworkIdle:
      if (ready_state == HTMLMediaElement::kHaveNothing)
        return ControlsState::kNotLoaded;
      break;
  }

  if (!MediaElement().paused())
    return ControlsState::kPlaying;
  return ControlsState::kStopped;
}

void MediaControlsImpl::RemovedFrom(ContainerNode& insertion_point) {
  DCHECK(!MediaElement().isConnected());

  HTMLDivElement::RemovedFrom(insertion_point);

  Hide();

  media_event_listener_->Detach();
  if (orientation_lock_delegate_)
    orientation_lock_delegate_->Detach();
  if (rotate_to_fullscreen_delegate_)
    rotate_to_fullscreen_delegate_->Detach();
  if (display_cutout_delegate_)
    display_cutout_delegate_->Detach();

  if (resize_observer_) {
    resize_observer_->disconnect();
    resize_observer_.Clear();
  }

  if (element_mutation_callback_) {
    element_mutation_callback_->Disconnect();
    element_mutation_callback_.Clear();
  }
}

void MediaControlsImpl::Reset() {
  EventDispatchForbiddenScope::AllowUserAgentEvents allow_events_in_shadow;
  BatchedControlUpdate batch(this);

  OnDurationChange();

  // Show everything that we might hide.
  current_time_display_->SetIsWanted(true);
  timeline_->SetIsWanted(true);

  // If the player has entered an error state, force it into the paused state.
  if (MediaElement().error())
    MediaElement().pause();

  UpdatePlayState();

  UpdateTimeIndicators();

  OnVolumeChange();
  OnTextTracksAddedOrRemoved();

  if (picture_in_picture_button_) {
    picture_in_picture_button_->SetIsWanted(
        ShouldShowPictureInPictureButton(MediaElement()));
  }

  UpdateCSSClassFromState();
  UpdateSizingCSSClass();
  OnControlsListUpdated();
}

void MediaControlsImpl::UpdateTimeIndicators() {
  timeline_->SetPosition(MediaElement().currentTime());
  UpdateCurrentTimeDisplay();
}

void MediaControlsImpl::OnControlsListUpdated() {
  BatchedControlUpdate batch(this);

  if (IsModern() && ShouldShowVideoControls()) {
    fullscreen_button_->SetIsWanted(true);
    fullscreen_button_->setAttribute(
        html_names::kDisabledAttr,
        MediaControlsSharedHelpers::ShouldShowFullscreenButton(MediaElement())
            ? AtomicString()
            : AtomicString(""));
  } else {
    fullscreen_button_->SetIsWanted(
        MediaControlsSharedHelpers::ShouldShowFullscreenButton(MediaElement()));
    fullscreen_button_->removeAttribute(html_names::kDisabledAttr);
  }

  RefreshCastButtonVisibilityWithoutUpdate();

  download_button_->SetIsWanted(
      download_button_->ShouldDisplayDownloadButton());
}

LayoutObject* MediaControlsImpl::PanelLayoutObject() {
  return panel_->GetLayoutObject();
}

LayoutObject* MediaControlsImpl::TimelineLayoutObject() {
  return timeline_->GetLayoutObject();
}

LayoutObject* MediaControlsImpl::ButtonPanelLayoutObject() {
  return media_button_panel_->GetLayoutObject();
}

LayoutObject* MediaControlsImpl::ContainerLayoutObject() {
  return GetLayoutObject();
}

void MediaControlsImpl::SetTestMode(bool enable) {
  is_test_mode_ = enable;
  SetClass(kTestModeCSSClass, enable);
}

void MediaControlsImpl::MaybeShow() {
  panel_->SetIsWanted(true);
  panel_->SetIsDisplayed(true);

  UpdateCurrentTimeDisplay();

  if (overlay_play_button_ && !is_paused_for_scrubbing_)
    overlay_play_button_->UpdateDisplayType();
  // Only make the controls visible if they won't get hidden by OnTimeUpdate.
  if (MediaElement().paused() || !ShouldHideMediaControls())
    MakeOpaque();
  if (loading_panel_)
    loading_panel_->OnControlsShown();

  timeline_->OnControlsShown();
  UpdateCSSClassFromState();
  UpdateActingAsAudioControls();
}

void MediaControlsImpl::Hide() {
  panel_->SetIsWanted(false);
  panel_->SetIsDisplayed(false);

  // When we permanently hide the native media controls, we no longer want to
  // hide the cursor, since the video will be using custom controls.
  ShowCursor();

  if (overlay_play_button_)
    overlay_play_button_->SetIsWanted(false);
  if (loading_panel_)
    loading_panel_->OnControlsHidden();

  // Cancel scrubbing if necessary.
  if (is_scrubbing_) {
    is_paused_for_scrubbing_ = false;
    EndScrubbing();
  }
  timeline_->OnControlsHidden();

  UpdateCSSClassFromState();

  // Hide is called when the HTMLMediaElement is removed from a document. If we
  // stop acting as audio controls during this removal, we end up inserting
  // nodes during the removal, firing a DCHECK. To avoid this, only update here
  // when the media element is connected.
  if (MediaElement().isConnected())
    UpdateActingAsAudioControls();
}

bool MediaControlsImpl::IsVisible() const {
  return panel_->IsOpaque();
}

void MediaControlsImpl::MaybeShowOverlayPlayButton() {
  if (overlay_play_button_)
    overlay_play_button_->SetIsDisplayed(true);
}

void MediaControlsImpl::MakeOpaque() {
  ShowCursor();
  panel_->MakeOpaque();
  MaybeShowOverlayPlayButton();
}

void MediaControlsImpl::MakeOpaqueFromPointerEvent() {
  // If we have quickly hidden the controls we should always show them when we
  // have a pointer event. If the controls are hidden the play button will
  // remain hidden.
  MaybeShowOverlayPlayButton();

  if (IsVisible())
    return;

  MakeOpaque();
}

void MediaControlsImpl::MakeTransparent() {
  // Only hide the cursor if the controls are enabled.
  if (MediaElement().ShouldShowControls())
    HideCursor();
  panel_->MakeTransparent();
}

bool MediaControlsImpl::ShouldHideMediaControls(unsigned behavior_flags) const {
  // Never hide for a media element without visual representation.
  if (!MediaElement().IsHTMLVideoElement() || !MediaElement().HasVideo() ||
      ToHTMLVideoElement(MediaElement()).IsRemotingInterstitialVisible()) {
    return false;
  }

  if (RemotePlayback::From(MediaElement()).GetState() !=
      mojom::blink::PresentationConnectionState::CLOSED) {
    return false;
  }

  // Keep the controls visible as long as the timer is running.
  const bool ignore_wait_for_timer = behavior_flags & kIgnoreWaitForTimer;
  if (!ignore_wait_for_timer && keep_showing_until_timer_fires_)
    return false;

  // Don't hide if the mouse is over the controls.
  // Touch focus shouldn't affect controls visibility.
  const bool ignore_controls_hover = behavior_flags & kIgnoreControlsHover;
  if (!ignore_controls_hover && AreVideoControlsHovered() &&
      !is_touch_interaction_)
    return false;

  // Don't hide if the mouse is over the video area.
  const bool ignore_video_hover = behavior_flags & kIgnoreVideoHover;
  if (!ignore_video_hover && is_mouse_over_controls_)
    return false;

  // Don't hide if focus is on the HTMLMediaElement or within the
  // controls/shadow tree. (Perform the checks separately to avoid going
  // through all the potential ancestor hosts for the focused element.)
  const bool ignore_focus = behavior_flags & kIgnoreFocus;
  if (!ignore_focus && (MediaElement().IsFocused() ||
                        contains(GetDocument().FocusedElement()))) {
    return false;
  }

  // Don't hide the media controls when a panel is showing.
  if (text_track_list_->IsWanted() || overflow_list_->IsWanted())
    return false;

  // Don't hide if we have accessiblity focus.
  if (panel_->KeepDisplayedForAccessibility())
    return false;

  if (MediaElement().seeking())
    return false;

  return true;
}

bool MediaControlsImpl::AreVideoControlsHovered() const {
  DCHECK(MediaElement().IsHTMLVideoElement());

  if (IsModern())
    return media_button_panel_->IsHovered() || timeline_->IsHovered();

  return panel_->IsHovered();
}

void MediaControlsImpl::UpdatePlayState() {
  if (is_paused_for_scrubbing_)
    return;

  if (overlay_play_button_)
    overlay_play_button_->UpdateDisplayType();
  play_button_->UpdateDisplayType();
}

HTMLDivElement* MediaControlsImpl::PanelElement() {
  return panel_;
}

HTMLDivElement* MediaControlsImpl::ButtonPanelElement() {
  DCHECK(IsModern());
  return media_button_panel_;
}

void MediaControlsImpl::BeginScrubbing(bool is_touch_event) {
  if (!MediaElement().paused()) {
    is_paused_for_scrubbing_ = true;
    MediaElement().pause();
  }

  if (scrubbing_message_ && is_touch_event) {
    scrubbing_message_->SetIsWanted(true);
    if (scrubbing_message_->DoesFit())
      panel_->setAttribute("class", kScrubbingMessageCSSClass);
  }

  is_scrubbing_ = true;
  UpdateCSSClassFromState();
}

void MediaControlsImpl::EndScrubbing() {
  if (is_paused_for_scrubbing_) {
    is_paused_for_scrubbing_ = false;
    if (MediaElement().paused())
      MediaElement().Play();
  }

  if (scrubbing_message_) {
    scrubbing_message_->SetIsWanted(false);
    panel_->removeAttribute("class");
  }

  is_scrubbing_ = false;
  UpdateCSSClassFromState();
}

void MediaControlsImpl::UpdateCurrentTimeDisplay() {
  if (panel_->IsWanted())
    current_time_display_->SetCurrentValue(MediaElement().currentTime());
}

void MediaControlsImpl::ToggleTextTrackList() {
  if (!MediaElement().HasClosedCaptions()) {
    text_track_list_->SetIsWanted(false);
    return;
  }

  text_track_list_->SetIsWanted(!text_track_list_->IsWanted());
}

bool MediaControlsImpl::TextTrackListIsWanted() {
  return text_track_list_->IsWanted();
}

MediaControlsTextTrackManager& MediaControlsImpl::GetTextTrackManager() {
  return *text_track_manager_;
}

void MediaControlsImpl::RefreshCastButtonVisibility() {
  RefreshCastButtonVisibilityWithoutUpdate();
  BatchedControlUpdate batch(this);
}

void MediaControlsImpl::RefreshCastButtonVisibilityWithoutUpdate() {
  if (!ShouldShowCastButton(MediaElement())) {
    cast_button_->SetIsWanted(false);
    overlay_cast_button_->SetIsWanted(false);
    return;
  }

  // The reason for the autoplay muted test is that some pages (e.g. vimeo.com)
  // have an autoplay background video which has to be muted on Android to play.
  // In such cases we don't want to automatically show the cast button, since
  // it looks strange and is unlikely to correspond with anything the user wants
  // to do.  If a user does want to cast a muted autoplay video then they can
  // still do so by touching or clicking on the video, which will cause the cast
  // button to appear. Note that this concerns various animated images websites
  // too.
  if (!MediaElement().ShouldShowControls() &&
      !MediaElement().GetAutoplayPolicy().IsOrWillBeAutoplayingMuted()) {
    // Note that this is a case where we add the overlay cast button
    // without wanting the panel cast button.  We depend on the fact
    // that computeWhichControlsFit() won't change overlay cast button
    // visibility in the case where the cast button isn't wanted.
    // We don't call compute...() here, but it will be called as
    // non-cast changes (e.g., resize) occur.  If the panel button
    // is shown, however, compute...() will take control of the
    // overlay cast button if it needs to hide it from the panel.
    if (RuntimeEnabledFeatures::MediaCastOverlayButtonEnabled())
      overlay_cast_button_->TryShowOverlay();
    cast_button_->SetIsWanted(false);
  } else if (MediaElement().ShouldShowControls()) {
    overlay_cast_button_->SetIsWanted(false);
    cast_button_->SetIsWanted(true);
  }
}

void MediaControlsImpl::ShowOverlayCastButtonIfNeeded() {
  if (MediaElement().ShouldShowControls() ||
      !ShouldShowCastButton(MediaElement()) ||
      !RuntimeEnabledFeatures::MediaCastOverlayButtonEnabled()) {
    return;
  }

  overlay_cast_button_->TryShowOverlay();
  ResetHideMediaControlsTimer();
}

void MediaControlsImpl::EnterFullscreen() {
  Fullscreen::RequestFullscreen(MediaElement());
}

void MediaControlsImpl::ExitFullscreen() {
  Fullscreen::ExitFullscreen(GetDocument());
}

bool MediaControlsImpl::IsFullscreenEnabled() const {
  return fullscreen_button_->IsWanted() &&
         !fullscreen_button_->hasAttribute(html_names::kDisabledAttr);
}

void MediaControlsImpl::RemotePlaybackStateChanged() {
  cast_button_->UpdateDisplayType();
  overlay_cast_button_->UpdateDisplayType();
}

void MediaControlsImpl::UpdateOverflowMenuWanted() const {
  // If the bool is true then the element is "sticky" this means that we will
  // always try and show it unless there is not room for it.
  std::pair<MediaControlElementBase*, bool> row_elements[] = {
      std::make_pair(play_button_.Get(), true),
      std::make_pair(mute_button_.Get(), true),
      std::make_pair(fullscreen_button_.Get(), true),
      std::make_pair(current_time_display_.Get(), true),
      std::make_pair(duration_display_.Get(), true),
      picture_in_picture_button_.Get()
          ? std::make_pair(picture_in_picture_button_.Get(), false)
          : std::make_pair(nullptr, false),
      std::make_pair(cast_button_.Get(), false),
      std::make_pair(download_button_.Get(), false),
      std::make_pair(toggle_closed_captions_button_.Get(), false),
  };

  // These are the elements in order of priority that take up vertical room.
  MediaControlElementBase* column_elements[] = {
      media_button_panel_.Get(), timeline_.Get(),
  };

  // Current size of the media controls.
  WebSize controls_size = size_;

  // The video controls are more than one row so we need to allocate vertical
  // room and hide the overlay play button if there is not enough room.
  if (ShouldShowVideoControls()) {
    // Allocate vertical room for overlay play button if necessary.
    if (overlay_play_button_) {
      WebSize overlay_play_button_size =
          overlay_play_button_->GetSizeOrDefault();
      if (controls_size.height >= overlay_play_button_size.height &&
          controls_size.width >= kModernMinWidthForOverlayPlayButton) {
        overlay_play_button_->SetDoesFit(true);
        controls_size.height -= overlay_play_button_size.height;
      } else {
        overlay_play_button_->SetDoesFit(false);
      }
    }

    controls_size.width -= kModernControlsVideoButtonPadding;

    // Allocate vertical room for the column elements.
    for (MediaControlElementBase* element : column_elements) {
      WebSize element_size = element->GetSizeOrDefault();
      if (controls_size.height - element_size.height >= 0) {
        element->SetDoesFit(true);
        controls_size.height -= element_size.height;
      } else {
        element->SetDoesFit(false);
      }
    }

    // If we cannot show the overlay play button, show the normal one.
    play_button_->SetIsWanted(!overlay_play_button_ ||
                              !overlay_play_button_->DoesFit());
  } else {
    controls_size.width -= kModernControlsAudioButtonPadding;

    // Undo any IsWanted/DoesFit changes made in the above block if we're
    // switching to act as audio controls.
    if (is_acting_as_audio_controls_) {
      play_button_->SetIsWanted(true);

      for (MediaControlElementBase* element : column_elements)
        element->SetDoesFit(true);
    }
  }

  // Go through the elements and if they are sticky allocate them to the panel
  // if we have enough room. If not (or they are not sticky) then add them to
  // the overflow menu. Once we have run out of room add_elements will be
  // made false and no more elements will be added.
  MediaControlElementBase* last_element = nullptr;
  bool add_elements = true;
  bool overflow_wanted = false;
  for (std::pair<MediaControlElementBase*, bool> pair : row_elements) {
    MediaControlElementBase* element = pair.first;
    if (!element)
      continue;

    // If the element is wanted then it should take up space, otherwise skip it.
    element->SetOverflowElementIsWanted(false);
    if (!element->IsWanted())
      continue;

    // Get the size of the element and see if we should allocate space to it.
    WebSize element_size = element->GetSizeOrDefault();
    bool does_fit = add_elements && pair.second &&
                    ((controls_size.width - element_size.width) >= 0);
    element->SetDoesFit(does_fit);

    if (element == mute_button_.Get() && IsModern())
      volume_control_container_->SetIsWanted(does_fit);

    // The element does fit and is sticky so we should allocate space for it. If
    // we cannot fit this element we should stop allocating space for other
    // elements.
    if (does_fit) {
      controls_size.width -= element_size.width;
      last_element = element;
    } else {
      add_elements = false;
      if (element->HasOverflowButton() && !element->IsDisabled()) {
        overflow_wanted = true;
        element->SetOverflowElementIsWanted(true);
      }
    }
  }

  // The overflow menu is always wanted if it has the "disabled" attr set.
  overflow_wanted = overflow_wanted ||
                    overflow_menu_->hasAttribute(html_names::kDisabledAttr);
  overflow_menu_->SetDoesFit(overflow_wanted);
  overflow_menu_->SetIsWanted(overflow_wanted);

  // If we want to show the overflow button and we do not have any space to show
  // it then we should hide the last shown element.
  int overflow_icon_width = overflow_menu_->GetSizeOrDefault().width;
  if (overflow_wanted && last_element &&
      controls_size.width < overflow_icon_width) {
    last_element->SetDoesFit(false);
    last_element->SetOverflowElementIsWanted(true);

    if (last_element == mute_button_.Get() && IsModern())
      volume_control_container_->SetIsWanted(false);
  }

  MaybeRecordElementsDisplayed();

  UpdateOverflowAndTrackListCSSClassForPip();
  UpdateOverflowMenuItemCSSClass();
}

// This method is responsible for adding css class to overflow menu list
// items to achieve the animation that items appears one after another when
// open the overflow menu.
void MediaControlsImpl::UpdateOverflowMenuItemCSSClass() const {
  unsigned int id = 0;
  for (Element* item = ElementTraversal::LastChild(*overflow_list_); item;
       item = ElementTraversal::PreviousSibling(*item)) {
    const CSSPropertyValueSet* inline_style = item->InlineStyle();
    DOMTokenList& class_list = item->classList();

    // We don't care if the hidden element still have animated-* CSS class
    if (inline_style &&
        inline_style->GetPropertyValue(CSSPropertyID::kDisplay) == "none")
      continue;

    AtomicString css_class =
        AtomicString("animated-") + AtomicString::Number(id++);
    if (!class_list.contains(css_class))
      class_list.setValue(css_class);
  }
}

void MediaControlsImpl::UpdateScrubbingMessageFits() const {
  if (scrubbing_message_)
    scrubbing_message_->SetDoesFit(size_.Width() >= kMinScrubbingMessageWidth);
}

// We want to have wider menu when pip is enabled so that "Exit picture in
// picture" text won't be truncated. When pip is disable (e.g. on mobile
// device), we don't want to enlarged the menu because it would look empty
// when "picture in picture" text is not presented.
void MediaControlsImpl::UpdateOverflowAndTrackListCSSClassForPip() const {
  if (picture_in_picture_button_.Get() &&
      picture_in_picture_button_.Get()->OverflowElementIsWanted()) {
    overflow_list_->classList().Add(kPipPresentedCSSClass);
    text_track_list_->classList().Add(kPipPresentedCSSClass);
  } else {
    overflow_list_->classList().Remove(kPipPresentedCSSClass);
    text_track_list_->classList().Remove(kPipPresentedCSSClass);
  }
}

void MediaControlsImpl::UpdateSizingCSSClass() {
  MediaControlsSizingClass sizing_class =
      MediaControls::GetSizingClass(size_.Width());

  SetClass(kMediaControlsSizingSmallCSSClass,
           ShouldShowVideoControls() &&
               sizing_class == MediaControlsSizingClass::kSmall);
  SetClass(kMediaControlsSizingMediumCSSClass,
           ShouldShowVideoControls() &&
               (sizing_class == MediaControlsSizingClass::kMedium ||
                sizing_class == MediaControlsSizingClass::kLarge));
}

void MediaControlsImpl::MaybeToggleControlsFromTap() {
  if (MediaElement().paused())
    return;

  // If the controls are visible then hide them. If the controls are not visible
  // then show them and start the timer to automatically hide them.
  if (IsVisible()) {
    MakeTransparent();
  } else {
    MakeOpaque();
    // Touch focus shouldn't affect controls visibility.
    if (ShouldHideMediaControls(kIgnoreWaitForTimer | kIgnoreFocus)) {
      keep_showing_until_timer_fires_ = true;
      StartHideMediaControlsTimer();
    }
  }
}

void MediaControlsImpl::OnAccessibleFocus() {
  if (panel_->KeepDisplayedForAccessibility())
    return;

  panel_->SetKeepDisplayedForAccessibility(true);

  if (!MediaElement().ShouldShowControls())
    return;

  OpenVolumeSliderIfNecessary();

  keep_showing_until_timer_fires_ = true;
  StartHideMediaControlsTimer();
  MaybeShow();
}

void MediaControlsImpl::OnAccessibleBlur() {
  panel_->SetKeepDisplayedForAccessibility(false);

  if (MediaElement().ShouldShowControls())
    return;

  CloseVolumeSliderIfNecessary();

  keep_showing_until_timer_fires_ = false;
  ResetHideMediaControlsTimer();
}

void MediaControlsImpl::DefaultEventHandler(Event& event) {
  HTMLDivElement::DefaultEventHandler(event);

  // Do not handle events to not interfere with the rest of the page if no
  // controls should be visible.
  if (!MediaElement().ShouldShowControls())
    return;

  // Add IgnoreControlsHover to m_hideTimerBehaviorFlags when we see a touch
  // event, to allow the hide-timer to do the right thing when it fires.
  // FIXME: Preferably we would only do this when we're actually handling the
  // event here ourselves.
  bool is_touch_event = IsTouchEvent(&event);
  hide_timer_behavior_flags_ |=
      is_touch_event ? kIgnoreControlsHover : kIgnoreNone;

  // Touch events are treated differently to avoid fake mouse events to trigger
  // random behavior. The expect behaviour for touch is that a tap will show the
  // controls and they will hide when the timer to hide fires.
  if (is_touch_event)
    HandleTouchEvent(&event);

  if (event.type() == event_type_names::kMouseover && !is_touch_event)
    is_touch_interaction_ = false;

  if ((event.type() == event_type_names::kPointerover ||
       event.type() == event_type_names::kPointermove ||
       event.type() == event_type_names::kPointerout) &&
      !is_touch_interaction_) {
    HandlePointerEvent(&event);
  }

  if (event.type() == event_type_names::kClick && !is_touch_interaction_)
    HandleClickEvent(&event);

  // If the user is interacting with the controls via the keyboard, don't hide
  // the controls. This will fire when the user tabs between controls (focusin)
  // or when they seek either the timeline or volume sliders (input).
  if (event.type() == event_type_names::kFocusin ||
      event.type() == event_type_names::kInput) {
    ResetHideMediaControlsTimer();
  }

  if (event.IsKeyboardEvent() &&
      !IsSpatialNavigationEnabled(GetDocument().GetFrame())) {
    const String& key = ToKeyboardEvent(event).key();
    if (key == "Enter" || ToKeyboardEvent(event).keyCode() == ' ') {
      if (IsModern() && overlay_play_button_) {
        overlay_play_button_->OnMediaKeyboardEvent(&event);
      } else {
        play_button_->OnMediaKeyboardEvent(&event);
      }
      return;
    }
    if (key == "ArrowLeft" || key == "ArrowRight" || key == "Home" ||
        key == "End") {
      timeline_->OnMediaKeyboardEvent(&event);
      return;
    }
    if (volume_slider_ && (key == "ArrowDown" || key == "ArrowUp")) {
      for (int i = 0; i < 5; i++)
        volume_slider_->OnMediaKeyboardEvent(&event);
      return;
    }
  }
}

void MediaControlsImpl::HandlePointerEvent(Event* event) {
  if (event->type() == event_type_names::kPointerover) {
    if (!ContainsRelatedTarget(event)) {
      is_mouse_over_controls_ = true;
      if (!MediaElement().paused()) {
        MakeOpaqueFromPointerEvent();
        StartHideMediaControlsIfNecessary();
      }
    }
  } else if (event->type() == event_type_names::kPointerout) {
    if (!ContainsRelatedTarget(event)) {
      is_mouse_over_controls_ = false;
      StopHideMediaControlsTimer();

      // When we get a mouse out, if video is playing and control should
      // hide regardless of focus, hide the control.
      // This will fix the issue that when mouse out event happen while video is
      // focused, control never hides.
      if (!MediaElement().paused() && ShouldHideMediaControls(kIgnoreFocus))
        MakeTransparent();
    }
  } else if (event->type() == event_type_names::kPointermove) {
    // When we get a mouse move, show the media controls, and start a timer
    // that will hide the media controls after a 3 seconds without a mouse move.
    is_mouse_over_controls_ = true;
    MakeOpaqueFromPointerEvent();

    // Start the timer regardless of focus state
    if (ShouldHideMediaControls(kIgnoreVideoHover | kIgnoreFocus))
      StartHideMediaControlsTimer();
  }
}

void MediaControlsImpl::HandleClickEvent(Event* event) {
  if (!IsModern() || ContainsRelatedTarget(event) || !IsFullscreenEnabled())
    return;

  if (tap_timer_.IsActive()) {
    tap_timer_.Stop();

    // Toggle fullscreen.
    if (MediaElement().IsFullscreen())
      ExitFullscreen();
    else
      EnterFullscreen();

    // If we paused for the first click of this double-click, then we need to
    // resume playback, since the user was just toggling fullscreen.
    if (is_paused_for_double_tap_) {
      MediaElement().Play();
      is_paused_for_double_tap_ = false;
    }
  } else {
    // If the video is not paused, assume the user is clicking to pause the
    // video. If the user clicks again for a fullscreen-toggling double-tap, we
    // will resume playback.
    if (!MediaElement().paused()) {
      MediaElement().pause();
      is_paused_for_double_tap_ = true;
    }
    tap_timer_.StartOneShot(kDoubleTapDelay, FROM_HERE);
  }
}

void MediaControlsImpl::HandleTouchEvent(Event* event) {
  if (IsModern()) {
    is_mouse_over_controls_ = false;
    is_touch_interaction_ = true;

    if (event->type() == event_type_names::kGesturetap &&
        !ContainsRelatedTarget(event)) {
      event->SetDefaultHandled();

      // Since handling the gesturetap event will prevent the click event from
      // happening, we need to manually hide any popups.
      HidePopupMenu();

      // In immersive mode we don't use double-tap features, so instead of
      // waiting 300 ms for a potential second tap, we just immediately toggle
      // controls visiblity.
      if (GetDocument().GetSettings() &&
          GetDocument().GetSettings()->GetImmersiveModeEnabled()) {
        MaybeToggleControlsFromTap();
        return;
      }

      if (tap_timer_.IsActive()) {
        // Cancel the visibility toggle event.
        tap_timer_.Stop();

        if (IsOnLeftSide(event)) {
          MaybeJump(kNumberOfSecondsToJump * -1);
        } else {
          MaybeJump(kNumberOfSecondsToJump);
        }
      } else {
        tap_timer_.StartOneShot(kDoubleTapDelay, FROM_HERE);
      }
    }
    return;
  }

  if (event->type() == event_type_names::kGesturetap &&
      !ContainsRelatedTarget(event) && !MediaElement().paused()) {
    if (!IsVisible()) {
      MakeOpaque();
      // When the panel switches from invisible to visible, we need to mark
      // the event handled to avoid buttons below the tap to be activated.
      event->SetDefaultHandled();
    }
    if (ShouldHideMediaControls(kIgnoreWaitForTimer)) {
      keep_showing_until_timer_fires_ = true;
      StartHideMediaControlsTimer();
    }
  }
}

void MediaControlsImpl::EnsureAnimatedArrowContainer() {
  if (!animated_arrow_container_element_) {
    animated_arrow_container_element_ =
        new MediaControlAnimatedArrowContainerElement(*this);
    ParserAppendChild(animated_arrow_container_element_);
  }
}

void MediaControlsImpl::MaybeJump(int seconds) {
  // Update the current time.
  double new_time = std::max(0.0, MediaElement().currentTime() + seconds);
  new_time = std::min(new_time, MediaElement().duration());
  MediaElement().setCurrentTime(new_time);

  // Show the arrow animation.
  EnsureAnimatedArrowContainer();
  MediaControlAnimatedArrowContainerElement::ArrowDirection direction =
      (seconds > 0)
          ? MediaControlAnimatedArrowContainerElement::ArrowDirection::kRight
          : MediaControlAnimatedArrowContainerElement::ArrowDirection::kLeft;
  animated_arrow_container_element_->ShowArrowAnimation(direction);
}

bool MediaControlsImpl::IsOnLeftSide(Event* event) {
  if (!event->IsGestureEvent())
    return false;

  float tap_x = ToGestureEvent(event)->NativeEvent().PositionInWidget().x;

  DOMRect* rect = getBoundingClientRect();
  double middle = rect->x() + (rect->width() / 2);
  if (GetDocument().GetFrame())
    middle *= GetDocument().GetFrame()->PageZoomFactor();

  return tap_x < middle;
}

void MediaControlsImpl::TapTimerFired(TimerBase*) {
  if (is_touch_interaction_) {
    MaybeToggleControlsFromTap();
  } else if (MediaElement().paused()) {
    // If this is not a touch interaction and the video is paused, then either
    // the user has just paused via click (in which case we've already paused
    // and there's nothing to do), or the user is playing by click (in which
    // case we need to start playing).
    if (is_paused_for_double_tap_) {
      Platform::Current()->RecordAction(
          UserMetricsAction("Media.Controls.ClickAnywhereToPause"));
      // TODO(https://crbug.com/896252): Show overlay pause animation.
      is_paused_for_double_tap_ = false;
    } else {
      Platform::Current()->RecordAction(
          UserMetricsAction("Media.Controls.ClickAnywhereToPlay"));
      // TODO(https://crbug.com/896252): Show overlay play animation.
      MediaElement().Play();
    }
  }
}

void MediaControlsImpl::HideMediaControlsTimerFired(TimerBase*) {
  unsigned behavior_flags =
      hide_timer_behavior_flags_ | kIgnoreFocus | kIgnoreVideoHover;
  hide_timer_behavior_flags_ = kIgnoreNone;
  keep_showing_until_timer_fires_ = false;

  if (MediaElement().paused())
    return;

  if (!ShouldHideMediaControls(behavior_flags))
    return;

  MakeTransparent();
  overlay_cast_button_->SetIsWanted(false);
}

void MediaControlsImpl::StartHideMediaControlsIfNecessary() {
  if (ShouldHideMediaControls())
    StartHideMediaControlsTimer();
}

void MediaControlsImpl::StartHideMediaControlsTimer() {
  hide_media_controls_timer_.StartOneShot(
      GetTimeWithoutMouseMovementBeforeHidingMediaControls(), FROM_HERE);
}

void MediaControlsImpl::StopHideMediaControlsTimer() {
  keep_showing_until_timer_fires_ = false;
  hide_media_controls_timer_.Stop();
}

void MediaControlsImpl::ResetHideMediaControlsTimer() {
  StopHideMediaControlsTimer();
  if (!MediaElement().paused())
    StartHideMediaControlsTimer();
}

void MediaControlsImpl::HideCursor() {
  SetInlineStyleProperty(CSSPropertyID::kCursor, "none", false);
}

void MediaControlsImpl::ShowCursor() {
  RemoveInlineStyleProperty(CSSPropertyID::kCursor);
}

bool MediaControlsImpl::ContainsRelatedTarget(Event* event) {
  if (!event->IsPointerEvent())
    return false;
  EventTarget* related_target = ToPointerEvent(event)->relatedTarget();
  if (!related_target)
    return false;
  return contains(related_target->ToNode());
}

void MediaControlsImpl::OnVolumeChange() {
  mute_button_->UpdateDisplayType();

  // Update visibility of volume controls.
  // TODO(mlamouri): it should not be part of the volumechange handling because
  // it is using audio availability as input.
  if (volume_slider_) {
    volume_slider_->SetVolume(MediaElement().muted() ? 0
                                                     : MediaElement().volume());
    volume_slider_->SetIsWanted(MediaElement().HasAudio() &&
                                !PreferHiddenVolumeControls(GetDocument()));
  }
  if (IsModern()) {
    mute_button_->SetIsWanted(true);
    mute_button_->setAttribute(
        html_names::kDisabledAttr,
        MediaElement().HasAudio() ? AtomicString() : AtomicString(""));
  } else {
    mute_button_->SetIsWanted(MediaElement().HasAudio());
    mute_button_->removeAttribute(html_names::kDisabledAttr);
  }

  // On modern media controls, if the volume slider is being used we don't want
  // to update controls visiblity, since this can shift the position of the
  // volume slider and make it unusable.
  if (!IsModern() || !volume_slider_ || !volume_slider_->IsHovered())
    BatchedControlUpdate batch(this);
}

void MediaControlsImpl::OnFocusIn() {
  // If the tap timer is active, then we will toggle the controls when the timer
  // completes, so we don't want to start showing here.
  if (!MediaElement().ShouldShowControls() || tap_timer_.IsActive())
    return;

  ResetHideMediaControlsTimer();
  MaybeShow();
}

void MediaControlsImpl::OnTimeUpdate() {
  UpdateTimeIndicators();

  // 'timeupdate' might be called in a paused state. The controls should not
  // become transparent in that case.
  if (MediaElement().paused()) {
    MakeOpaque();
    return;
  }

  if (IsVisible() && ShouldHideMediaControls())
    MakeTransparent();
}

void MediaControlsImpl::OnDurationChange() {
  BatchedControlUpdate batch(this);

  const double duration = MediaElement().duration();
  bool was_finite_duration = std::isfinite(duration_display_->CurrentValue());

  // Update the displayed current time/duration.
  duration_display_->SetCurrentValue(duration);

  // Show the duration display if we have a duration or if we are showing the
  // audio controls without a source.
  duration_display_->SetIsWanted(
      std::isfinite(duration) ||
      (ShouldShowAudioControls() && State() == kNoSource));

  // TODO(crbug.com/756698): Determine if this is still needed since the format
  // of the current time no longer depends on the duration.
  UpdateCurrentTimeDisplay();

  // Update the timeline (the UI with the seek marker).
  timeline_->SetDuration(duration);
  if (!was_finite_duration && std::isfinite(duration)) {
    download_button_->SetIsWanted(
        download_button_->ShouldDisplayDownloadButton());
  }
}

void MediaControlsImpl::OnPlay() {
  UpdatePlayState();
  UpdateTimeIndicators();
  UpdateCSSClassFromState();
}

void MediaControlsImpl::OnPlaying() {
  timeline_->OnPlaying();

  StartHideMediaControlsTimer();
  UpdateCSSClassFromState();
}

void MediaControlsImpl::OnPause() {
  UpdatePlayState();
  UpdateTimeIndicators();
  MakeOpaque();

  StopHideMediaControlsTimer();

  UpdateCSSClassFromState();
}

void MediaControlsImpl::OnSeeking() {
  UpdateTimeIndicators();
  if (!is_scrubbing_) {
    is_scrubbing_ = true;
    UpdateCSSClassFromState();
  }

  // Don't try to show the controls if the seek was caused by the video being
  // looped.
  if (MediaElement().Loop() && MediaElement().currentTime() == 0)
    return;

  if (!MediaElement().ShouldShowControls())
    return;

  MaybeShow();
  StopHideMediaControlsTimer();
}

void MediaControlsImpl::OnSeeked() {
  StartHideMediaControlsIfNecessary();

  is_scrubbing_ = false;
  UpdateCSSClassFromState();
}

void MediaControlsImpl::OnTextTracksAddedOrRemoved() {
  toggle_closed_captions_button_->UpdateDisplayType();
  toggle_closed_captions_button_->SetIsWanted(
      MediaElement().HasClosedCaptions());
  BatchedControlUpdate batch(this);
}

void MediaControlsImpl::OnTextTracksChanged() {
  toggle_closed_captions_button_->UpdateDisplayType();
}

void MediaControlsImpl::OnError() {
  // TODO(mlamouri): we should only change the aspects of the control that need
  // to be changed.
  Reset();
  UpdateCSSClassFromState();
}

void MediaControlsImpl::OnLoadedMetadata() {
  // TODO(mlamouri): we should only change the aspects of the control that need
  // to be changed.
  Reset();
  UpdateCSSClassFromState();
  UpdateActingAsAudioControls();
}

void MediaControlsImpl::OnEnteredFullscreen() {
  fullscreen_button_->SetIsFullscreen(true);
  if (display_cutout_fullscreen_button_)
    display_cutout_fullscreen_button_->SetIsWanted(true);

  StopHideMediaControlsTimer();
  StartHideMediaControlsTimer();
}

void MediaControlsImpl::OnExitedFullscreen() {
  fullscreen_button_->SetIsFullscreen(false);
  if (display_cutout_fullscreen_button_)
    display_cutout_fullscreen_button_->SetIsWanted(false);

  HidePopupMenu();
  StopHideMediaControlsTimer();
  StartHideMediaControlsTimer();
}

void MediaControlsImpl::OnPictureInPictureChanged() {
  // This will only be called if the media controls are listening to the
  // Picture-in-Picture events which only happen when they provide a
  // Picture-in-Picture button.
  DCHECK(picture_in_picture_button_);
  picture_in_picture_button_->UpdateDisplayType();
}

void MediaControlsImpl::OnPanelKeypress() {
  // If the user is interacting with the controls via the keyboard, don't hide
  // the controls. This is called when the user mutes/unmutes, turns CC on/off,
  // etc.
  ResetHideMediaControlsTimer();
}

void MediaControlsImpl::NotifyElementSizeChanged(DOMRectReadOnly* new_size) {
  // Note that this code permits a bad frame on resize, since it is
  // run after the relayout / paint happens.  It would be great to improve
  // this, but it would be even greater to move this code entirely to
  // JS and fix it there.

  IntSize old_size = size_;
  size_.SetWidth(new_size->width());
  size_.SetHeight(new_size->height());

  // Don't bother to do any work if this matches the most recent size.
  if (old_size != size_) {
    // Update the sizing CSS class before computing which controls fit so that
    // the element sizes can update from the CSS class change before we start
    // calculating.
    if (IsModern())
      UpdateSizingCSSClass();
    element_size_changed_timer_.StartOneShot(TimeDelta(), FROM_HERE);
  }
}

void MediaControlsImpl::ElementSizeChangedTimerFired(TimerBase*) {
  ComputeWhichControlsFit();

  // Rerender timeline bar segments when size changed.
  timeline_->RenderBarSegments();
}

void MediaControlsImpl::OnLoadingProgress() {
  timeline_->RenderBarSegments();
}

void MediaControlsImpl::ComputeWhichControlsFit() {
  // Hide all controls that don't fit, and show the ones that do.
  // This might be better suited for a layout, but since JS media controls
  // won't benefit from that anwyay, we just do it here like JS will.
  if (IsModern()) {
    UpdateOverflowMenuWanted();
    UpdateScrubbingMessageFits();
    return;
  }

  // Controls that we'll hide / show, in order of decreasing priority.
  MediaControlElementBase* elements[] = {
      // Exclude m_overflowMenu; we handle it specially.
      play_button_.Get(),
      fullscreen_button_.Get(),
      download_button_.Get(),
      timeline_.Get(),
      mute_button_.Get(),
      volume_slider_.Get(),
      toggle_closed_captions_button_.Get(),
      picture_in_picture_button_.Get() ? picture_in_picture_button_.Get()
                                       : nullptr,
      cast_button_.Get(),
      current_time_display_.Get(),
      duration_display_.Get(),
  };

  // TODO(mlamouri): we need a more dynamic way to find out the width of an
  // element.
  const int kSliderMargin = 36;  // Sliders have 18px margin on each side.

  if (!size_.Width()) {
    // No layout yet -- hide everything, then make them show up later.
    // This prevents the wrong controls from being shown briefly
    // immediately after the first layout and paint, but before we have
    // a chance to revise them.
    for (MediaControlElementBase* element : elements) {
      if (element)
        element->SetDoesFit(false);
    }
    return;
  }

  // Assume that all controls require 48px, unless we can get the computed
  // style for a button. The minimumWidth is recorded and re-use for future
  // MediaControls instances and future calls to this method given that at the
  // moment the controls button width is per plataform.
  // TODO(mlamouri): improve the mechanism without bandaid.
  static int minimum_width = 48;
  if (play_button_->GetLayoutObject() &&
      play_button_->GetLayoutObject()->Style()) {
    const ComputedStyle* style = play_button_->GetLayoutObject()->Style();
    minimum_width = ceil(style->Width().Pixels() / style->EffectiveZoom());
  } else if (overflow_menu_->GetLayoutObject() &&
             overflow_menu_->GetLayoutObject()->Style()) {
    const ComputedStyle* style = overflow_menu_->GetLayoutObject()->Style();
    minimum_width = ceil(style->Width().Pixels() / style->EffectiveZoom());
  }

  // Insert an overflow menu. However, if we see that the overflow menu
  // doesn't end up containing at least two elements, we will not display it
  // but instead make place for the first element that was dropped.
  overflow_menu_->SetDoesFit(true);
  overflow_menu_->SetIsWanted(true);
  int used_width = minimum_width;

  std::list<MediaControlElementBase*> overflow_elements;
  MediaControlElementBase* first_displaced_element = nullptr;
  // For each control that fits, enable it in order of decreasing priority.
  for (MediaControlElementBase* element : elements) {
    if (!element)
      continue;

    int width = minimum_width;
    if ((element == timeline_.Get()) || (element == volume_slider_.Get()))
      width += kSliderMargin;

    element->SetOverflowElementIsWanted(false);
    if (!element->IsWanted())
      continue;

    if (used_width + width <= size_.Width()) {
      element->SetDoesFit(true);
      used_width += width;
    } else {
      element->SetDoesFit(false);
      element->SetOverflowElementIsWanted(true);
      if (element->HasOverflowButton())
        overflow_elements.push_front(element);
      // We want a way to access the first media element that was
      // removed. If we don't end up needing an overflow menu, we can
      // use the space the overflow menu would have taken up to
      // instead display that media element.
      if (!element->HasOverflowButton() && !first_displaced_element)
        first_displaced_element = element;
    }
  }

  // If we don't have at least two overflow elements, we will not show the
  // overflow menu.
  if (overflow_elements.empty()) {
    overflow_menu_->SetIsWanted(false);
    used_width -= minimum_width;
    if (first_displaced_element) {
      int width = minimum_width;
      if ((first_displaced_element == timeline_.Get()) ||
          (first_displaced_element == volume_slider_.Get()))
        width += kSliderMargin;
      if (used_width + width <= size_.Width())
        first_displaced_element->SetDoesFit(true);
    }
  } else if (overflow_elements.size() == 1) {
    overflow_menu_->SetIsWanted(false);
    overflow_elements.front()->SetDoesFit(true);
  }

  // Decide if the overlay play button fits.
  if (overlay_play_button_) {
    bool does_fit = size_.Width() >= kMinWidthForOverlayPlayButton &&
                    size_.Height() >= kMinHeightForOverlayPlayButton;
    overlay_play_button_->SetDoesFit(does_fit);
  }

  MaybeRecordElementsDisplayed();
}

void MediaControlsImpl::MaybeRecordElementsDisplayed() const {
  // Record the display state when needed. It is only recorded when the media
  // element is in a state that allows it in order to reduce noise in the
  // metrics.
  if (!MediaControlInputElement::ShouldRecordDisplayStates(MediaElement()))
    return;

  MediaControlElementBase* elements[] = {
      play_button_.Get(),
      fullscreen_button_.Get(),
      download_button_.Get(),
      timeline_.Get(),
      mute_button_.Get(),
      volume_slider_.Get(),
      toggle_closed_captions_button_.Get(),
      picture_in_picture_button_.Get() ? picture_in_picture_button_.Get()
                                       : nullptr,
      cast_button_.Get(),
      current_time_display_.Get(),
      duration_display_.Get(),
      overlay_play_button_.Get(),
      overlay_cast_button_.Get(),
  };

  // Record which controls are used.
  for (auto* const element : elements) {
    if (element)
      element->MaybeRecordDisplayed();
  }
  overflow_menu_->MaybeRecordDisplayed();
}

const MediaControlCurrentTimeDisplayElement&
MediaControlsImpl::CurrentTimeDisplay() const {
  return *current_time_display_;
}

const MediaControlRemainingTimeDisplayElement&
MediaControlsImpl::RemainingTimeDisplay() const {
  return *duration_display_;
}

MediaControlToggleClosedCaptionsButtonElement&
MediaControlsImpl::ToggleClosedCaptions() {
  return *toggle_closed_captions_button_;
}

bool MediaControlsImpl::ShouldActAsAudioControls() const {
  // A video element should act like an audio element when it has an audio track
  // but no video track.
  return IsModern() && MediaElement().ShouldShowControls() &&
         MediaElement().IsHTMLVideoElement() && MediaElement().HasAudio() &&
         !MediaElement().HasVideo();
}

void MediaControlsImpl::StartActingAsAudioControls() {
  DCHECK(ShouldActAsAudioControls());
  DCHECK(!is_acting_as_audio_controls_);

  is_acting_as_audio_controls_ = true;
  SetClass(kActAsAudioControlsCSSClass, true);
  PopulatePanel();
  Reset();
}

void MediaControlsImpl::StopActingAsAudioControls() {
  DCHECK(!ShouldActAsAudioControls());
  DCHECK(is_acting_as_audio_controls_);

  is_acting_as_audio_controls_ = false;
  SetClass(kActAsAudioControlsCSSClass, false);
  PopulatePanel();
  Reset();
}

void MediaControlsImpl::UpdateActingAsAudioControls() {
  if (ShouldActAsAudioControls() != is_acting_as_audio_controls_) {
    if (is_acting_as_audio_controls_)
      StopActingAsAudioControls();
    else
      StartActingAsAudioControls();
  }
}

bool MediaControlsImpl::ShouldShowAudioControls() const {
  return IsModern() &&
         (MediaElement().IsHTMLAudioElement() || is_acting_as_audio_controls_);
}

bool MediaControlsImpl::ShouldShowVideoControls() const {
  return MediaElement().IsHTMLVideoElement() && !ShouldShowAudioControls();
}

void MediaControlsImpl::NetworkStateChanged() {
  // Update the display state of the download button in case we now have a
  // source or no longer have a source.
  download_button_->SetIsWanted(
      download_button_->ShouldDisplayDownloadButton());

  UpdateCSSClassFromState();
}

void MediaControlsImpl::OpenOverflowMenu() {
  overflow_list_->OpenOverflowMenu();
}

void MediaControlsImpl::CloseOverflowMenu() {
  overflow_list_->CloseOverflowMenu();
}

bool MediaControlsImpl::OverflowMenuIsWanted() {
  return overflow_list_->IsWanted();
}

bool MediaControlsImpl::OverflowMenuVisible() {
  return overflow_list_ ? overflow_list_->IsWanted() : false;
}

void MediaControlsImpl::ToggleOverflowMenu() {
  DCHECK(overflow_list_);

  overflow_list_->SetIsWanted(!overflow_list_->IsWanted());
}

void MediaControlsImpl::HidePopupMenu() {
  if (OverflowMenuVisible())
    ToggleOverflowMenu();

  if (TextTrackListIsWanted())
    ToggleTextTrackList();
}

void MediaControlsImpl::VolumeSliderWantedTimerFired(TimerBase*) {
  volume_slider_->OpenSlider();
  volume_control_container_->OpenContainer();
}

void MediaControlsImpl::OpenVolumeSliderIfNecessary() {
  if (ShouldOpenVolumeSlider()) {
    if (volume_slider_->IsFocused() || mute_button_->IsFocused()) {
      // When we're focusing with the keyboard, we don't need the delay.
      volume_slider_->OpenSlider();
      volume_control_container_->OpenContainer();
    } else {
      volume_slider_wanted_timer_.StartOneShot(
          WebTestSupport::IsRunningWebTest() ? kTimeToShowVolumeSliderTest
                                             : kTimeToShowVolumeSlider,
          FROM_HERE);
    }
  }
}

void MediaControlsImpl::CloseVolumeSliderIfNecessary() {
  if (ShouldCloseVolumeSlider()) {
    volume_slider_->CloseSlider();
    volume_control_container_->CloseContainer();

    if (volume_slider_wanted_timer_.IsActive())
      volume_slider_wanted_timer_.Stop();
  }
}

bool MediaControlsImpl::ShouldOpenVolumeSlider() const {
  if (!volume_slider_ || !IsModern())
    return false;

  return !PreferHiddenVolumeControls(GetDocument());
}

bool MediaControlsImpl::ShouldCloseVolumeSlider() const {
  if (!volume_slider_ || !IsModern())
    return false;

  return !(volume_control_container_->IsHovered() ||
           volume_slider_->IsFocused() || mute_button_->IsFocused());
}

const MediaControlOverflowMenuButtonElement& MediaControlsImpl::OverflowButton()
    const {
  return *overflow_menu_;
}

MediaControlOverflowMenuButtonElement& MediaControlsImpl::OverflowButton() {
  return *overflow_menu_;
}

void MediaControlsImpl::OnWaiting() {
  UpdateCSSClassFromState();
}

void MediaControlsImpl::OnLoadedData() {
  UpdateCSSClassFromState();
}

HTMLVideoElement& MediaControlsImpl::VideoElement() {
  DCHECK(MediaElement().IsHTMLVideoElement());
  return *ToHTMLVideoElement(&MediaElement());
}

void MediaControlsImpl::Trace(blink::Visitor* visitor) {
  visitor->Trace(element_mutation_callback_);
  visitor->Trace(resize_observer_);
  visitor->Trace(panel_);
  visitor->Trace(overlay_play_button_);
  visitor->Trace(overlay_enclosure_);
  visitor->Trace(play_button_);
  visitor->Trace(current_time_display_);
  visitor->Trace(timeline_);
  visitor->Trace(scrubbing_message_);
  visitor->Trace(mute_button_);
  visitor->Trace(volume_slider_);
  visitor->Trace(picture_in_picture_button_);
  visitor->Trace(animated_arrow_container_element_);
  visitor->Trace(toggle_closed_captions_button_);
  visitor->Trace(fullscreen_button_);
  visitor->Trace(download_button_);
  visitor->Trace(duration_display_);
  visitor->Trace(enclosure_);
  visitor->Trace(text_track_list_);
  visitor->Trace(overflow_menu_);
  visitor->Trace(overflow_list_);
  visitor->Trace(cast_button_);
  visitor->Trace(overlay_cast_button_);
  visitor->Trace(media_event_listener_);
  visitor->Trace(orientation_lock_delegate_);
  visitor->Trace(rotate_to_fullscreen_delegate_);
  visitor->Trace(display_cutout_delegate_);
  visitor->Trace(media_button_panel_);
  visitor->Trace(loading_panel_);
  visitor->Trace(display_cutout_fullscreen_button_);
  visitor->Trace(volume_control_container_);
  visitor->Trace(text_track_manager_);
  MediaControls::Trace(visitor);
  HTMLDivElement::Trace(visitor);
}

}  // namespace blink