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

#include <string>

#include "base/basictypes.h"
#include "base/logging.h"
#include "base/memory/scoped_ptr.h"
#include "base/strings/stringprintf.h"
#include "media/base/android/audio_decoder_job.h"
#include "media/base/android/media_codec_bridge.h"
#include "media/base/android/media_drm_bridge.h"
#include "media/base/android/media_player_manager.h"
#include "media/base/android/media_source_player.h"
#include "media/base/android/media_url_interceptor.h"
#include "media/base/android/video_decoder_job.h"
#include "media/base/bind_to_current_loop.h"
#include "media/base/decoder_buffer.h"
#include "media/base/test_data_util.h"
#include "media/base/timestamp_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/gl/android/surface_texture.h"

namespace media {

// Helper macro to skip the test if MediaCodecBridge isn't available.
#define SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE()        \
  do {                                                            \
    if (!MediaCodecBridge::IsAvailable()) {                       \
      VLOG(0) << "Could not run test - not supported on device."; \
      return;                                                     \
    }                                                             \
  } while (0)

const base::TimeDelta kDefaultDuration =
    base::TimeDelta::FromMilliseconds(10000);

// TODO(wolenetz/qinmin): Simplify tests with more effective mock usage, and
// fix flaky pointer-based MDJ inequality testing. See http://crbug.com/327839.

// Mock of MediaPlayerManager for testing purpose.
class MockMediaPlayerManager : public MediaPlayerManager {
 public:
  explicit MockMediaPlayerManager(base::MessageLoop* message_loop)
      : message_loop_(message_loop),
        playback_completed_(false),
        num_metadata_changes_(0),
        timestamp_updated_(false),
        allow_play_(true) {}
  ~MockMediaPlayerManager() override {}

  // MediaPlayerManager implementation.
  MediaResourceGetter* GetMediaResourceGetter() override { return NULL; }
  MediaUrlInterceptor* GetMediaUrlInterceptor() override { return NULL; }
  void OnTimeUpdate(int player_id,
                    base::TimeDelta current_time,
                    base::TimeTicks current_time_ticks) override {
    timestamp_updated_ = true;
  }
  void OnMediaMetadataChanged(int player_id,
                              base::TimeDelta duration,
                              int width,
                              int height,
                              bool success) override {
    num_metadata_changes_++;
  }
  void OnPlaybackComplete(int player_id) override {
    playback_completed_ = true;
    if (message_loop_->is_running())
      message_loop_->Quit();
  }
  void OnMediaInterrupted(int player_id) override {}
  void OnBufferingUpdate(int player_id, int percentage) override {}
  void OnSeekComplete(int player_id,
                      const base::TimeDelta& current_time) override {}
  void OnError(int player_id, int error) override {}
  void OnVideoSizeChanged(int player_id, int width, int height) override {}
  void OnWaitingForDecryptionKey(int player_id) override {}
  MediaPlayerAndroid* GetFullscreenPlayer() override { return NULL; }
  MediaPlayerAndroid* GetPlayer(int player_id) override { return NULL; }
  void OnDecorderResourcesReleased(int player_id) {}

  bool RequestPlay(int player_id, base::TimeDelta duration) override {
    return allow_play_;
  }

  bool playback_completed() const {
    return playback_completed_;
  }

  int num_metadata_changes() const {
    return num_metadata_changes_;
  }

  bool timestamp_updated() const {
    return timestamp_updated_;
  }

  void ResetTimestampUpdated() {
    timestamp_updated_ = false;
  }

  void set_allow_play(bool value) {
    allow_play_ = value;
  }

 private:
  base::MessageLoop* message_loop_;
  bool playback_completed_;
  // The number of metadata changes reported by the player.
  int num_metadata_changes_;
  // Playback timestamp was updated.
  bool timestamp_updated_;
  // Whether the manager will allow players that request playing.
  bool allow_play_;

  DISALLOW_COPY_AND_ASSIGN(MockMediaPlayerManager);
};

class MockDemuxerAndroid : public DemuxerAndroid {
 public:
  explicit MockDemuxerAndroid(base::MessageLoop* message_loop)
      : message_loop_(message_loop),
        num_data_requests_(0),
        num_seek_requests_(0),
        num_browser_seek_requests_(0) {}
  ~MockDemuxerAndroid() override {}

  void Initialize(DemuxerAndroidClient* client) override {}
  void RequestDemuxerData(DemuxerStream::Type type) override {
    num_data_requests_++;
    if (message_loop_->is_running())
      message_loop_->Quit();
  }
  void RequestDemuxerSeek(const base::TimeDelta& time_to_seek,
                          bool is_browser_seek) override {
    num_seek_requests_++;
    if (is_browser_seek)
      num_browser_seek_requests_++;
  }

  int num_data_requests() const { return num_data_requests_; }
  int num_seek_requests() const { return num_seek_requests_; }
  int num_browser_seek_requests() const { return num_browser_seek_requests_; }

 private:
  base::MessageLoop* message_loop_;

  // The number of encoded data requests this object has seen.
  int num_data_requests_;

  // The number of regular and browser seek requests this object has seen.
  int num_seek_requests_;

  // The number of browser seek requests this object has seen.
  int num_browser_seek_requests_;

  DISALLOW_COPY_AND_ASSIGN(MockDemuxerAndroid);
};

class MediaSourcePlayerTest : public testing::Test {
 public:
  MediaSourcePlayerTest()
      : manager_(&message_loop_),
        demuxer_(new MockDemuxerAndroid(&message_loop_)),
        player_(0, &manager_,
                base::Bind(&MockMediaPlayerManager::OnDecorderResourcesReleased,
                           base::Unretained(&manager_)),
                scoped_ptr<DemuxerAndroid>(demuxer_),
                GURL()),
        decoder_callback_hook_executed_(false),
        surface_texture_a_is_next_(true) {}

  ~MediaSourcePlayerTest() override {}

 protected:
  // Get the decoder job from the MediaSourcePlayer. The return value must not
  // be NULL.
  MediaDecoderJob* GetMediaDecoderJob(bool is_audio) {
    if (is_audio) {
      return reinterpret_cast<MediaDecoderJob*>(
          player_.audio_decoder_job_.get());
    }
    return reinterpret_cast<MediaDecoderJob*>(
        player_.video_decoder_job_.get());
  }

  // Get the MediaCodecBridge from the decoder job. The return value could be
  // NULL if the decoder is not yet created.
  MediaCodecBridge* GetMediaCodecBridge(bool is_audio) {
    if (is_audio)
      return player_.audio_decoder_job_->media_codec_bridge_.get();
    return player_.video_decoder_job_->media_codec_bridge_.get();
  }

  // Get the per-job prerolling status from the MediaSourcePlayer's job matching
  // |is_audio|. Caller must guard against NPE if the player's job is NULL.
  bool IsPrerolling(bool is_audio) {
    return GetMediaDecoderJob(is_audio)->prerolling_;
  }

  // Get the preroll timestamp from the MediaSourcePlayer.
  base::TimeDelta GetPrerollTimestamp() {
    return player_.preroll_timestamp_;
  }

  // Simulate player has reached starvation timeout.
  void TriggerPlayerStarvation() {
    player_.decoder_starvation_callback_.Cancel();
    player_.OnDecoderStarved();
  }

  // Release() the player.
  void ReleasePlayer() {
    EXPECT_TRUE(player_.IsPlaying());
    player_.Release();
    EXPECT_FALSE(player_.IsPlaying());
  }

  // Upon the next successful decode callback, post a task to call Release()
  // on the |player_|. TEST_F's do not have access to the private player
  // members, hence this helper method.
  // Prevent usage creep of MSP::set_decode_callback_for_testing() by
  // only using it for the ReleaseWithOnPrefetchDoneAlreadyPosted test.
  void OnNextTestDecodeCallbackPostTaskToReleasePlayer() {
    DCHECK_EQ(&message_loop_, base::MessageLoop::current());
    player_.set_decode_callback_for_testing(media::BindToCurrentLoop(
      base::Bind(
          &MediaSourcePlayerTest::ReleaseWithPendingPrefetchDoneVerification,
          base::Unretained(this))));
  }

  // Asynch test callback posted upon decode completion to verify that a pending
  // prefetch done event is not cleared across |player_|'s Release(). This helps
  // ensure the ReleaseWithOnPrefetchDoneAlreadyPosted test scenario is met.
  void ReleaseWithPendingPrefetchDoneVerification() {
    EXPECT_TRUE(player_.IsEventPending(player_.PREFETCH_DONE_EVENT_PENDING));
    ReleasePlayer();
    EXPECT_TRUE(player_.IsEventPending(player_.PREFETCH_DONE_EVENT_PENDING));
    EXPECT_FALSE(decoder_callback_hook_executed_);
    EXPECT_FALSE(GetMediaCodecBridge(true));
    decoder_callback_hook_executed_ = true;
  }

  DemuxerConfigs CreateAudioDemuxerConfigs(AudioCodec audio_codec,
                                           bool use_low_sample_rate) {
    DemuxerConfigs configs;
    configs.audio_codec = audio_codec;
    configs.audio_channels = 2;
    configs.is_audio_encrypted = false;
    configs.duration = kDefaultDuration;

    if (audio_codec == kCodecVorbis) {
      configs.audio_sampling_rate = use_low_sample_rate ? 11025 : 44100;
      scoped_refptr<DecoderBuffer> buffer = ReadTestDataFile(
          "vorbis-extradata");
      configs.audio_extra_data = std::vector<uint8>(
          buffer->data(),
          buffer->data() + buffer->data_size());
      return configs;
    }

    // Other codecs are not yet supported by this helper.
    EXPECT_EQ(audio_codec, kCodecAAC);

    configs.audio_sampling_rate = 48000;
    uint8 aac_extra_data[] = { 0x13, 0x10 };
    configs.audio_extra_data = std::vector<uint8>(
        aac_extra_data,
        aac_extra_data + 2);
    return configs;
  }

  DemuxerConfigs CreateVideoDemuxerConfigs(bool use_larger_size) {
    DemuxerConfigs configs;
    configs.video_codec = kCodecVP8;
    configs.video_size =
        use_larger_size ? gfx::Size(640, 240) : gfx::Size(320, 240);
    configs.is_video_encrypted = false;
    configs.duration = kDefaultDuration;
    return configs;
  }

  DemuxerConfigs CreateAudioVideoDemuxerConfigs() {
    DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);
    configs.video_codec = kCodecVP8;
    configs.video_size = gfx::Size(320, 240);
    configs.is_video_encrypted = false;
    return configs;
  }

  DemuxerConfigs CreateDemuxerConfigs(bool have_audio, bool have_video) {
    DCHECK(have_audio || have_video);

    if (have_audio && !have_video)
      return CreateAudioDemuxerConfigs(kCodecVorbis, false);

    if (have_video && !have_audio)
      return CreateVideoDemuxerConfigs(false);

    return CreateAudioVideoDemuxerConfigs();
  }

  // Starts an audio decoder job.
  void StartAudioDecoderJob() {
    Start(CreateAudioDemuxerConfigs(kCodecVorbis, false));
  }

  // Starts a video decoder job.
  void StartVideoDecoderJob() {
    Start(CreateVideoDemuxerConfigs(false));
  }

  // Starts decoding the data.
  void Start(const DemuxerConfigs& configs) {
    EXPECT_EQ(demuxer_->num_data_requests(), 0);
    player_.OnDemuxerConfigsAvailable(configs);
    player_.Start();

    EXPECT_TRUE(player_.IsPlaying());
    int expected_num_requests = (player_.HasAudio() ? 1 : 0) +
        (player_.HasVideo() ? 1 : 0);
    EXPECT_EQ(expected_num_requests, demuxer_->num_data_requests());
  }

  // Resumes decoding the data. Verifies player behavior relative to
  // |expect_player_requests_audio_data| and
  // |expect_player_requests_video_data|.
  void Resume(bool expect_player_requests_audio_data,
              bool expect_player_requests_video_data) {
    EXPECT_FALSE(player_.IsPlaying());
    EXPECT_TRUE(player_.HasVideo() || player_.HasAudio());
    int original_num_data_requests = demuxer_->num_data_requests();
    int expected_request_delta =
        (expect_player_requests_audio_data ? 1 : 0) +
        (expect_player_requests_video_data ? 1 : 0);

    player_.Start();

    EXPECT_TRUE(player_.IsPlaying());
    EXPECT_EQ(original_num_data_requests + expected_request_delta,
              demuxer_->num_data_requests());
  }

  // Keeps decoding audio data until the decoder starts to output samples.
  // Gives up if no audio output after decoding 10 frames.
  void DecodeAudioDataUntilOutputBecomesAvailable() {
    EXPECT_TRUE(player_.IsPlaying());
    base::TimeDelta current_time = player_.GetCurrentTime();
    base::TimeDelta start_timestamp = current_time;
    for (int i = 0; i < 10; ++i) {
      manager_.ResetTimestampUpdated();
      player_.OnDemuxerDataAvailable(
          CreateReadFromDemuxerAckForAudio(i > 3 ? 3 : i));
      WaitForAudioDecodeDone();
      base::TimeDelta new_current_time = player_.GetCurrentTime();
      EXPECT_LE(current_time.InMilliseconds(),
                new_current_time.InMilliseconds());
      current_time = new_current_time;
      if (manager_.timestamp_updated()) {
        // TODO(qinmin): the current time is from the decoder thread and it does
        // not take the delay from posting the task into consideration.
        // http://crbug.com/421616.
        EXPECT_LE(start_timestamp.InMillisecondsF(),
                  new_current_time.InMillisecondsF());
        return;
      }
    }
    EXPECT_TRUE(false);
  }

  AccessUnit CreateAccessUnitWithData(bool is_audio, int audio_packet_id,
                                      bool use_large_size_video) {
    AccessUnit unit;

    unit.status = DemuxerStream::kOk;
    scoped_refptr<DecoderBuffer> buffer;
    if (is_audio) {
      buffer = ReadTestDataFile(
          base::StringPrintf("vorbis-packet-%d", audio_packet_id));
    } else {
      buffer = ReadTestDataFile(
          use_large_size_video ? "vp8-I-frame-640x240" : "vp8-I-frame-320x240");
    }
    unit.data = std::vector<uint8>(
        buffer->data(), buffer->data() + buffer->data_size());

    if (is_audio) {
      // Vorbis needs 4 extra bytes padding on Android to decode properly. Check
      // NuMediaExtractor.cpp in Android source code.
      uint8 padding[4] = { 0xff , 0xff , 0xff , 0xff };
      unit.data.insert(unit.data.end(), padding, padding + 4);
    }

    return unit;
  }

  DemuxerData CreateReadFromDemuxerAckForAudio(int packet_id) {
    DemuxerData data;
    data.type = DemuxerStream::AUDIO;
    data.access_units.resize(1);
    data.access_units[0] = CreateAccessUnitWithData(true, packet_id, false);

    return data;
  }

  DemuxerData CreateReadFromDemuxerAckForVideo(bool use_large_size) {
    DemuxerData data;
    data.type = DemuxerStream::VIDEO;
    data.access_units.resize(1);
    data.access_units[0] = CreateAccessUnitWithData(false, 0, use_large_size);
    return data;
  }

  DemuxerData CreateEOSAck(bool is_audio) {
    DemuxerData data;
    data.type = is_audio ? DemuxerStream::AUDIO : DemuxerStream::VIDEO;
    data.access_units.resize(1);
    data.access_units[0].status = DemuxerStream::kOk;
    data.access_units[0].is_end_of_stream = true;
    return data;
  }

  DemuxerData CreateAbortedAck(bool is_audio) {
    DemuxerData data;
    data.type = is_audio ? DemuxerStream::AUDIO : DemuxerStream::VIDEO;
    data.access_units.resize(1);
    data.access_units[0].status = DemuxerStream::kAborted;
    return data;
  }

  bool HasData(bool is_audio) {
    return GetMediaDecoderJob(is_audio)->HasData();
  }

  // Helper method for use at test start. It starts an audio decoder job and
  // immediately feeds it some data to decode. Then, without letting the decoder
  // job complete a decode cycle, it also starts player SeekTo(). Upon return,
  // the player should not yet have sent the DemuxerSeek IPC request, though
  // seek event should be pending. The audio decoder job will also still be
  // decoding.
  void StartAudioDecoderJobAndSeekToWhileDecoding(
      const base::TimeDelta& seek_time) {
    EXPECT_FALSE(GetMediaCodecBridge(true));
    EXPECT_FALSE(player_.IsPlaying());
    EXPECT_EQ(0, demuxer_->num_data_requests());
    EXPECT_EQ(0.0, GetPrerollTimestamp().InMillisecondsF());
    EXPECT_EQ(player_.GetCurrentTime(), GetPrerollTimestamp());
    StartAudioDecoderJob();
    EXPECT_FALSE(GetMediaDecoderJob(true)->is_decoding());
    player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
    EXPECT_EQ(2, demuxer_->num_data_requests());
    EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
    player_.SeekTo(seek_time);
    EXPECT_EQ(0.0, GetPrerollTimestamp().InMillisecondsF());
    EXPECT_EQ(0, demuxer_->num_seek_requests());
    player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  }

  // Seek, including simulated receipt of |kAborted| read between SeekTo() and
  // OnDemuxerSeekDone(). Use this helper method only when the player already
  // has created the media codec bridge. Exactly one request for more data is
  // expected following the seek, so use this helper for players with only audio
  // or only video.
  void SeekPlayerWithAbort(bool is_audio, const base::TimeDelta& seek_time) {
    int original_num_seeks = demuxer_->num_seek_requests();
    int original_num_data_requests = demuxer_->num_data_requests();

    // Initiate a seek. Skip the round-trip of requesting seek from renderer.
    // Instead behave as if the renderer has asked us to seek.
    player_.SeekTo(seek_time);

    // Verify that the seek does not occur until previously outstanding data
    // request is satisfied.
    EXPECT_EQ(original_num_seeks, demuxer_->num_seek_requests());

    // Simulate seeking causes the demuxer to abort the outstanding read
    // caused by the seek.
    player_.OnDemuxerDataAvailable(CreateAbortedAck(is_audio));

    // Wait for the decode job to finish so we can process the seek request.
    WaitForDecodeDone(is_audio, !is_audio);

    // Verify that the seek is requested.
    EXPECT_EQ(original_num_seeks + 1, demuxer_->num_seek_requests());

    // Send back the seek done notification. This should trigger the player to
    // call OnReadFromDemuxer() again.
    EXPECT_EQ(original_num_data_requests, demuxer_->num_data_requests());
    player_.OnDemuxerSeekDone(kNoTimestamp());
    EXPECT_EQ(original_num_data_requests + 1, demuxer_->num_data_requests());

    // No other seek should have been requested.
    EXPECT_EQ(original_num_seeks + 1, demuxer_->num_seek_requests());
  }

  // Preroll the decoder job to |target_timestamp|. The first access unit
  // to decode will have a timestamp equal to |start_timestamp|.
  // |is_clock_manager| indicates whether the decoder serves as the clock
  // manager for the player.
  // TODO(qinmin): Add additional test cases for out-of-order decodes.
  // See http://crbug.com/331421.
  void PrerollDecoderToTime(bool is_audio,
                            const base::TimeDelta& start_timestamp,
                            const base::TimeDelta& target_timestamp,
                            bool is_clock_manager) {
    // For streams with both audio and video, it is possible that audio rolls
    // past the |target_timestamp|. As a result, the current time may be larger
    // than the |target_timestamp| for video as it may not be the clock manager.
    EXPECT_TRUE(!is_clock_manager ||
                target_timestamp == player_.GetCurrentTime());
    // |start_timestamp| must be smaller than |target_timestamp|.
    EXPECT_LE(start_timestamp, target_timestamp);
    DemuxerData data = is_audio ? CreateReadFromDemuxerAckForAudio(1) :
        CreateReadFromDemuxerAckForVideo(false);
    int current_timestamp = start_timestamp.InMilliseconds();

    // Send some data with access unit timestamps before the |target_timestamp|,
    // and continue sending the data until preroll finishes.
    // This simulates the common condition that AUs received after browser
    // seek begin with timestamps before the seek target, and don't
    // immediately complete preroll.
    while (IsPrerolling(is_audio)) {
      data.access_units[0].timestamp =
          base::TimeDelta::FromMilliseconds(current_timestamp);
      player_.OnDemuxerDataAvailable(data);
      EXPECT_TRUE(GetMediaDecoderJob(is_audio)->is_decoding());
      EXPECT_TRUE(GetMediaCodecBridge(is_audio));
      EXPECT_TRUE(!is_clock_manager ||
                  target_timestamp == player_.GetCurrentTime());
      current_timestamp += 30;
      WaitForDecodeDone(is_audio, !is_audio);
    }
    EXPECT_LE(target_timestamp, player_.GetCurrentTime());
  }

  DemuxerData CreateReadFromDemuxerAckWithConfigChanged(
      bool is_audio,
      int config_unit_index,
      const DemuxerConfigs& configs) {
    DemuxerData data;
    data.type = is_audio ? DemuxerStream::AUDIO : DemuxerStream::VIDEO;
    data.access_units.resize(config_unit_index + 1);

    for (int i = 0; i < config_unit_index; ++i)
      data.access_units[i] = CreateAccessUnitWithData(is_audio, i, false);

    data.access_units[config_unit_index].status = DemuxerStream::kConfigChanged;
    data.demuxer_configs.resize(1);
    data.demuxer_configs[0] = configs;
    return data;
  }

  // Valid only for video-only player tests. If |trigger_with_release_start| is
  // true, triggers the browser seek with a Release() + video data received +
  // Start() with a new surface. If false, triggers the browser seek by
  // setting a new video surface after beginning decode of received video data.
  // Such data receipt causes possibility that an I-frame is not next, and
  // browser seek results once decode completes and surface change processing
  // begins.
  void BrowserSeekPlayer(bool trigger_with_release_start) {
    int expected_num_data_requests = demuxer_->num_data_requests() + 2;
    int expected_num_seek_requests = demuxer_->num_seek_requests();
    int expected_num_browser_seek_requests =
        demuxer_->num_browser_seek_requests();

    CreateNextTextureAndSetVideoSurface();
    StartVideoDecoderJob();
    if (trigger_with_release_start) {
      // Consume the first frame, so that the next VideoDecoderJob will not
      // inherit the I-frame from the previous decoder.
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
      ReleasePlayer();
      WaitForVideoDecodeDone();

      // Simulate demuxer's response to the video data request. The data will be
      // passed to the next MediaCodecBridge.
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
      EXPECT_FALSE(GetMediaCodecBridge(false));
      EXPECT_FALSE(player_.IsPlaying());
      EXPECT_EQ(expected_num_seek_requests, demuxer_->num_seek_requests());

      CreateNextTextureAndSetVideoSurface();
      Resume(false, false);
      EXPECT_FALSE(GetMediaCodecBridge(false));

      // Run the message loop so that prefetch will complete.
      while (expected_num_seek_requests == demuxer_->num_seek_requests())
        message_loop_.RunUntilIdle();
    } else {
      // Simulate demuxer's response to the video data request.
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));

      // While the decoder is decoding, trigger a browser seek by changing
      // surface. Demuxer does not know of browser seek in advance, so no
      // |kAborted| data is required (though |kAborted| can certainly occur for
      // any pending read in reality due to renderer preparing for a regular
      // seek).
      CreateNextTextureAndSetVideoSurface();

      // Browser seek should not begin until decoding has completed.
      EXPECT_TRUE(GetMediaCodecBridge(false));
      EXPECT_EQ(expected_num_seek_requests, demuxer_->num_seek_requests());

      // Wait for the media codec bridge to finish decoding and be reset pending
      // the browser seek.
      WaitForVideoDecodeDone();
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
    }

    // Only one browser seek should have been initiated, and no further data
    // should have been requested.
    expected_num_seek_requests++;
    expected_num_browser_seek_requests++;
    EXPECT_EQ(expected_num_seek_requests, demuxer_->num_seek_requests());
    EXPECT_EQ(expected_num_browser_seek_requests,
              demuxer_->num_browser_seek_requests());
    EXPECT_EQ(expected_num_data_requests, demuxer_->num_data_requests());
  }

  // Creates a new media codec bridge and feeds it data ending with a
  // |kConfigChanged| access unit. If |config_unit_in_prefetch| is true, sends
  // feeds the config change AU in response to the job's first read request
  // (prefetch). If false, regular data is fed and decoded prior to feeding the
  // config change AU in response to the second data request (after prefetch
  // completed). |config_unit_index| controls which access unit is
  // |kConfigChanged|. If |enable_adaptive_playback| is true, config change will
  // not cause the decoder to recreate the media codec bridge. Otherwise, the
  // decoder has to drain all its data before recreating the new codec.
  void SendConfigChangeToDecoder(bool is_audio,
                                 bool config_unit_in_prefetch,
                                 int config_unit_index,
                                 bool enable_adaptive_playback) {
    EXPECT_FALSE(GetMediaCodecBridge(is_audio));
    if (is_audio) {
      StartAudioDecoderJob();
    } else {
      CreateNextTextureAndSetVideoSurface();
      StartVideoDecoderJob();
    }

    int expected_num_data_requests = demuxer_->num_data_requests();
    // Feed and decode a standalone access unit so the player exits prefetch.
    if (!config_unit_in_prefetch) {
      if (is_audio) {
        player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
      } else {
        player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
        EnableAdaptiveVideoPlayback(enable_adaptive_playback);
      }

      WaitForDecodeDone(is_audio, !is_audio);

      // We should have completed the prefetch phase at this point.
      expected_num_data_requests++;
      EXPECT_EQ(expected_num_data_requests, demuxer_->num_data_requests());
    }

    DemuxerConfigs configs = is_audio ?
        CreateAudioDemuxerConfigs(kCodecVorbis, true) :
        CreateVideoDemuxerConfigs(true);
    // Feed and decode access units with data for any units prior to
    // |config_unit_index|, and a |kConfigChanged| unit at that index.
    // Player should prepare to reconfigure the decoder job, and should request
    // new demuxer configs.
    player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckWithConfigChanged(
        is_audio, config_unit_index, configs));

    expected_num_data_requests++;
    EXPECT_EQ(expected_num_data_requests, demuxer_->num_data_requests());
    if (is_audio)
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
    else
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(true));

    // If the adaptive playback setting was not passed to the MediaCodecBridge
    // earlier, do it here.
    if (config_unit_in_prefetch && !is_audio)
      EnableAdaptiveVideoPlayback(enable_adaptive_playback);
  }

  // Send a config change to the decoder job and drain the decoder so that the
  // config change is processed.
  void StartConfigChange(bool is_audio,
                         bool config_unit_in_prefetch,
                         int config_unit_index,
                         bool enable_adaptive_playback) {
    SendConfigChangeToDecoder(is_audio, config_unit_in_prefetch,
                              config_unit_index, enable_adaptive_playback);

    EXPECT_EQ(!config_unit_in_prefetch && !enable_adaptive_playback &&
              config_unit_index == 0, IsDrainingDecoder(is_audio));
    int expected_num_data_requests = demuxer_->num_data_requests();
    // Run until decoder starts to request new data.
    while (demuxer_->num_data_requests() == expected_num_data_requests)
      message_loop_.RunUntilIdle();
    EXPECT_FALSE(IsDrainingDecoder(is_audio));
  }

  void EnableAdaptiveVideoPlayback(bool enable) {
    EXPECT_TRUE(GetMediaCodecBridge(false));
    static_cast<VideoCodecBridge*>(GetMediaCodecBridge(false))->
        set_adaptive_playback_supported_for_testing(
            enable ? 1 : 0);
  }

  void CreateNextTextureAndSetVideoSurface() {
    gfx::SurfaceTexture* surface_texture;
    if (surface_texture_a_is_next_) {
      surface_texture_a_ = gfx::SurfaceTexture::Create(next_texture_id_++);
      surface_texture = surface_texture_a_.get();
    } else {
      surface_texture_b_ = gfx::SurfaceTexture::Create(next_texture_id_++);
      surface_texture = surface_texture_b_.get();
    }

    surface_texture_a_is_next_ = !surface_texture_a_is_next_;
    gfx::ScopedJavaSurface surface = gfx::ScopedJavaSurface(surface_texture);
    player_.SetVideoSurface(surface.Pass());
  }

  // Wait for one or both of the jobs to complete decoding. Media codec bridges
  // are assumed to exist for any stream whose decode completion is awaited.
  void WaitForDecodeDone(bool wait_for_audio, bool wait_for_video) {
    DCHECK(wait_for_audio || wait_for_video);
    while ((wait_for_audio && GetMediaCodecBridge(true) &&
               GetMediaDecoderJob(true)->HasData() &&
               GetMediaDecoderJob(true)->is_decoding()) ||
           (wait_for_video && GetMediaCodecBridge(false) &&
               GetMediaDecoderJob(false)->HasData() &&
               GetMediaDecoderJob(false)->is_decoding())) {
      message_loop_.RunUntilIdle();
    }
  }

  void WaitForAudioDecodeDone() {
    WaitForDecodeDone(true, false);
  }

  void WaitForVideoDecodeDone() {
    WaitForDecodeDone(false, true);
  }

  void WaitForAudioVideoDecodeDone() {
    WaitForDecodeDone(true, true);
  }

  // If |send_eos| is true, generates EOS for the stream corresponding to
  // |eos_for_audio|. Verifies that playback completes and no further data
  // is requested.
  // If |send_eos| is false, then it is assumed that caller previously arranged
  // for player to receive EOS for each stream, but the player has not yet
  // decoded all of them. In this case, |eos_for_audio| is ignored.
  void VerifyPlaybackCompletesOnEOSDecode(bool send_eos, bool eos_for_audio) {
    int original_num_data_requests = demuxer_->num_data_requests();
    if (send_eos)
      player_.OnDemuxerDataAvailable(CreateEOSAck(eos_for_audio));
    EXPECT_FALSE(manager_.playback_completed());
    message_loop_.Run();
    EXPECT_TRUE(manager_.playback_completed());
    EXPECT_EQ(original_num_data_requests, demuxer_->num_data_requests());
  }

  void VerifyCompletedPlaybackResumesOnSeekPlusStart(bool have_audio,
                                                     bool have_video) {
    DCHECK(have_audio || have_video);

    EXPECT_TRUE(manager_.playback_completed());

    player_.SeekTo(base::TimeDelta());
    player_.OnDemuxerSeekDone(kNoTimestamp());
    Resume(have_audio, have_video);
  }

  // Starts the appropriate decoder jobs according to |have_audio| and
  // |have_video|. Then starts seek during decode of EOS or non-EOS according to
  // |eos_audio| and |eos_video|. Simulates seek completion and verifies that
  // playback never completed. |eos_{audio,video}| is ignored if the
  // corresponding |have_{audio,video}| is false.
  void VerifySeekDuringEOSDecodePreventsPlaybackCompletion(bool have_audio,
                                                           bool have_video,
                                                           bool eos_audio,
                                                           bool eos_video) {
    DCHECK(have_audio || have_video);

    if (have_video)
      CreateNextTextureAndSetVideoSurface();

    Start(CreateDemuxerConfigs(have_audio, have_video));

    if (have_audio)
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));

    if (have_video)
      player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));

    // Run until more data is requested a number of times equal to the number of
    // media types configured. Since prefetching may be in progress, we cannot
    // reliably expect Run() to complete until we have sent demuxer data for all
    // configured media types, above.
    WaitForDecodeDone(have_audio, have_video);

    // Simulate seek while decoding EOS or non-EOS for the appropriate
    // stream(s).
    if (have_audio) {
      if (eos_audio)
        player_.OnDemuxerDataAvailable(CreateEOSAck(true));
      else
        player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(1));
    }

    if (have_video) {
      if (eos_video)
        player_.OnDemuxerDataAvailable(CreateEOSAck(false));
      else
        player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
    }

    player_.SeekTo(base::TimeDelta());
    EXPECT_EQ(0, demuxer_->num_seek_requests());
    WaitForDecodeDone(have_audio, have_video);
    EXPECT_EQ(1, demuxer_->num_seek_requests());

    player_.OnDemuxerSeekDone(kNoTimestamp());
    EXPECT_FALSE(manager_.playback_completed());
  }

  base::TimeTicks StartTimeTicks() {
    return player_.start_time_ticks_;
  }

  bool IsRequestingDemuxerData(bool is_audio) {
    return GetMediaDecoderJob(is_audio)->is_requesting_demuxer_data_;
  }

  bool IsDrainingDecoder(bool is_audio) {
    return GetMediaDecoderJob(is_audio)->drain_decoder_;
  }

 protected:
  base::MessageLoop message_loop_;
  MockMediaPlayerManager manager_;
  MockDemuxerAndroid* demuxer_;  // Owned by |player_|.
  MediaSourcePlayer player_;

  // Track whether a possibly async decoder callback test hook has run.
  bool decoder_callback_hook_executed_;

  // We need to keep the surface texture while the decoder is actively decoding.
  // Otherwise, it may trigger unexpected crashes on some devices. To switch
  // surfaces, tests need to create a new surface texture without releasing
  // their previous one. In CreateNextTextureAndSetVideoSurface(), we toggle
  // between two surface textures, only replacing the N-2 texture. Assumption is
  // that no more than N-1 texture is in use by decoder when
  // CreateNextTextureAndSetVideoSurface() is called.
  scoped_refptr<gfx::SurfaceTexture> surface_texture_a_;
  scoped_refptr<gfx::SurfaceTexture> surface_texture_b_;
  bool surface_texture_a_is_next_;
  int next_texture_id_;

  DISALLOW_COPY_AND_ASSIGN(MediaSourcePlayerTest);
};

TEST_F(MediaSourcePlayerTest, StartAudioDecoderWithValidConfig) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test audio codec will be created when valid configs and data are passed to
  // the audio decoder job.
  StartAudioDecoderJob();
  EXPECT_EQ(0, demuxer_->num_seek_requests());
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  EXPECT_TRUE(GetMediaCodecBridge(true));
}

TEST_F(MediaSourcePlayerTest, StartAudioDecoderWithInvalidConfig) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test audio decoder job will not be created when failed to start the codec.
  DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);
  // Replace with invalid |audio_extra_data|
  configs.audio_extra_data.clear();
  uint8 invalid_codec_data[] = { 0x00, 0xff, 0xff, 0xff, 0xff };
  configs.audio_extra_data.insert(configs.audio_extra_data.begin(),
                                 invalid_codec_data, invalid_codec_data + 4);
  Start(configs);

  // Decoder is not created after data is received.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  EXPECT_FALSE(GetMediaCodecBridge(true));
}

TEST_F(MediaSourcePlayerTest, StartVideoCodecWithValidSurface) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test video codec will not be created until data is received.
  StartVideoDecoderJob();

  // Set both an initial and a later video surface without receiving any
  // demuxed data yet.
  CreateNextTextureAndSetVideoSurface();
  EXPECT_FALSE(GetMediaCodecBridge(false));
  CreateNextTextureAndSetVideoSurface();
  EXPECT_FALSE(GetMediaCodecBridge(false));

  // No seeks, even on setting surface, should have occurred. (Browser seeks can
  // occur on setting surface, but only after previously receiving video data.)
  EXPECT_EQ(0, demuxer_->num_seek_requests());

  // Send the first input chunk and verify that decoder will be created.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_TRUE(GetMediaCodecBridge(false));
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, StartVideoCodecWithInvalidSurface) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test video codec will not be created when surface is invalid.
  scoped_refptr<gfx::SurfaceTexture> surface_texture(
      gfx::SurfaceTexture::Create(0));
  gfx::ScopedJavaSurface surface(surface_texture.get());
  StartVideoDecoderJob();

  // Release the surface texture.
  surface_texture = NULL;
  player_.SetVideoSurface(surface.Pass());

  // Player should not seek the demuxer on setting initial surface.
  EXPECT_EQ(0, demuxer_->num_seek_requests());
  EXPECT_EQ(1, demuxer_->num_data_requests());

  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_FALSE(GetMediaCodecBridge(false));
}

TEST_F(MediaSourcePlayerTest, ReadFromDemuxerAfterSeek) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will resend a ReadFromDemuxer request after seek.
  StartAudioDecoderJob();
  SeekPlayerWithAbort(true, base::TimeDelta());
}

TEST_F(MediaSourcePlayerTest, SetSurfaceWhileSeeking) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test SetVideoSurface() will not cause an extra seek while the player is
  // waiting for demuxer to indicate seek is done.
  player_.OnDemuxerConfigsAvailable(
      CreateVideoDemuxerConfigs(false));

  // Initiate a seek. Skip requesting element seek of renderer.
  // Instead behave as if the renderer has asked us to seek.
  player_.SeekTo(base::TimeDelta());
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  CreateNextTextureAndSetVideoSurface();
  EXPECT_EQ(1, demuxer_->num_seek_requests());
  player_.Start();

  // Send the seek done notification. The player should start requesting data.
  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_FALSE(GetMediaCodecBridge(false));
  EXPECT_EQ(1, demuxer_->num_data_requests());
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_TRUE(GetMediaCodecBridge(false));

  // Reconfirm exactly 1 seek request has been made of demuxer, and that it
  // was not a browser seek request.
  EXPECT_EQ(1, demuxer_->num_seek_requests());
  EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, ChangeMultipleSurfaceWhileDecoding) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test MediaSourcePlayer can switch multiple surfaces during decoding.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  EXPECT_EQ(0, demuxer_->num_seek_requests());

  // Send the first input chunk.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));

  // While the decoder is decoding, change multiple surfaces. Pass an empty
  // surface first.
  gfx::ScopedJavaSurface empty_surface;
  player_.SetVideoSurface(empty_surface.Pass());
  // Next, pass a new non-empty surface.
  CreateNextTextureAndSetVideoSurface();

  // Wait for the media codec bridge to finish decoding and be reset pending a
  // browser seek.
  WaitForVideoDecodeDone();
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));

  // Only one browser seek should have been initiated. No further data request
  // should have been processed on |message_loop_| before surface change event
  // became pending, above.
  EXPECT_EQ(1, demuxer_->num_browser_seek_requests());
  EXPECT_EQ(2, demuxer_->num_data_requests());

  // Simulate browser seek is done and confirm player requests more data for new
  // video codec.
  player_.OnDemuxerSeekDone(player_.GetCurrentTime());
  EXPECT_FALSE(GetMediaCodecBridge(false));
  EXPECT_EQ(3, demuxer_->num_data_requests());
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_TRUE(GetMediaCodecBridge(false));
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, SetEmptySurfaceAndStarveWhileDecoding) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test player pauses if an empty surface is passed.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  EXPECT_EQ(1, demuxer_->num_data_requests());

  // Send the first input chunk.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));

  // While the decoder is decoding, pass an empty surface.
  gfx::ScopedJavaSurface empty_surface;
  player_.SetVideoSurface(empty_surface.Pass());
  // Let the player starve. However, it should not issue any new data request in
  // this case.
  TriggerPlayerStarvation();
  // Wait for the media codec bridge to finish decoding and be reset.
  while (GetMediaDecoderJob(false)->is_decoding())
    message_loop_.RunUntilIdle();

  // No further seek or data requests should have been received since the
  // surface is empty.
  EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
  EXPECT_EQ(2, demuxer_->num_data_requests());
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));

  // Playback resumes once a non-empty surface is passed.
  CreateNextTextureAndSetVideoSurface();
  EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
  while(demuxer_->num_browser_seek_requests() != 1)
    message_loop_.RunUntilIdle();
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, ReleaseVideoDecoderResourcesWhileDecoding) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that if video decoder is released while decoding, the resources will
  // not be immediately released.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  ReleasePlayer();
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));

  // Recreate the video decoder.
  CreateNextTextureAndSetVideoSurface();
  player_.Start();
  while (!GetMediaDecoderJob(false)->is_decoding())
    message_loop_.RunUntilIdle();
  EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
  ReleasePlayer();
  // Wait for the media codec bridge to finish decoding and be reset.
  while (GetMediaDecoderJob(false)->is_decoding())
    message_loop_.RunUntilIdle();
}

TEST_F(MediaSourcePlayerTest, AudioOnlyStartAfterSeekFinish) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test audio decoder job will not start until pending seek event is handled.
  DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);
  player_.OnDemuxerConfigsAvailable(configs);

  // Initiate a seek. Skip requesting element seek of renderer.
  // Instead behave as if the renderer has asked us to seek.
  player_.SeekTo(base::TimeDelta());
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  player_.Start();
  EXPECT_EQ(0, demuxer_->num_data_requests());

  // Sending back the seek done notification.
  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_FALSE(GetMediaCodecBridge(true));
  EXPECT_EQ(1, demuxer_->num_data_requests());

  // Reconfirm exactly 1 seek request has been made of demuxer.
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  // Decoder is created after data is received.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  EXPECT_TRUE(GetMediaCodecBridge(true));
}

TEST_F(MediaSourcePlayerTest, VideoOnlyStartAfterSeekFinish) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test video decoder job will not start until pending seek event is handled.
  CreateNextTextureAndSetVideoSurface();
  DemuxerConfigs configs = CreateVideoDemuxerConfigs(false);
  player_.OnDemuxerConfigsAvailable(configs);

  // Initiate a seek. Skip requesting element seek of renderer.
  // Instead behave as if the renderer has asked us to seek.
  player_.SeekTo(base::TimeDelta());
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  player_.Start();
  EXPECT_EQ(0, demuxer_->num_data_requests());

  // Sending back the seek done notification.
  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_FALSE(GetMediaCodecBridge(false));
  EXPECT_EQ(1, demuxer_->num_data_requests());

  // Reconfirm exactly 1 seek request has been made of demuxer.
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  // Decoder is created after data is received.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_TRUE(GetMediaCodecBridge(false));
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, StartImmediatelyAfterPause) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that if the decoding job is not fully stopped after Pause(),
  // calling Start() will be a noop.
  StartAudioDecoderJob();

  MediaDecoderJob* decoder_job = GetMediaDecoderJob(true);
  EXPECT_FALSE(GetMediaDecoderJob(true)->is_decoding());

  // Sending data to player.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
  EXPECT_EQ(2, demuxer_->num_data_requests());

  // Decoder job will not immediately stop after Pause() since it is
  // running on another thread.
  player_.Pause(true);
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());

  // Nothing happens when calling Start() again.
  player_.Start();
  // Verify that Start() will not destroy and recreate the media codec bridge.
  EXPECT_EQ(decoder_job, GetMediaDecoderJob(true));

  while (GetMediaDecoderJob(true)->is_decoding())
    message_loop_.RunUntilIdle();
  // The decoder job should finish and wait for data.
  EXPECT_EQ(2, demuxer_->num_data_requests());
  EXPECT_TRUE(IsRequestingDemuxerData(true));
}

TEST_F(MediaSourcePlayerTest, DecoderJobsCannotStartWithoutAudio) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that when Start() is called, video decoder job will wait for audio
  // decoder job before start decoding the data.
  CreateNextTextureAndSetVideoSurface();
  Start(CreateAudioVideoDemuxerConfigs());
  MediaDecoderJob* audio_decoder_job = GetMediaDecoderJob(true);
  MediaDecoderJob* video_decoder_job = GetMediaDecoderJob(false);

  EXPECT_FALSE(audio_decoder_job->is_decoding());
  EXPECT_FALSE(video_decoder_job->is_decoding());

  // Sending video data to player, video decoder should not start.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_FALSE(video_decoder_job->is_decoding());

  // Sending audio data to player, both decoders should start now.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  EXPECT_TRUE(audio_decoder_job->is_decoding());
  EXPECT_TRUE(video_decoder_job->is_decoding());

  // No seeks should have occurred.
  EXPECT_EQ(0, demuxer_->num_seek_requests());
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, StartTimeTicksResetAfterDecoderUnderruns) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test start time ticks will reset after decoder job underruns.
  StartAudioDecoderJob();

  DecodeAudioDataUntilOutputBecomesAvailable();

  // The decoder job should finish prerolling and start prefetching.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(3));
  base::TimeTicks previous = StartTimeTicks();

  // Let the decoder starve.
  TriggerPlayerStarvation();
  WaitForAudioDecodeDone();
  EXPECT_TRUE(StartTimeTicks() == previous);

  // Send new data to the decoder so it can finish prefetching. This should
  // reset the start time ticks.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(3));
  EXPECT_TRUE(StartTimeTicks() != previous);

  base::TimeTicks current = StartTimeTicks();
  EXPECT_LE(0, (current - previous).InMillisecondsF());
}

TEST_F(MediaSourcePlayerTest, V_SecondAccessUnitIsEOSAndResumePlayAfterSeek) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test MediaSourcePlayer can replay video after input EOS is reached.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();

  // Send the first input chunk.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  WaitForVideoDecodeDone();

  VerifyPlaybackCompletesOnEOSDecode(true, false);
  VerifyCompletedPlaybackResumesOnSeekPlusStart(false, true);
}

TEST_F(MediaSourcePlayerTest, A_FirstAccessUnitIsEOSAndResumePlayAfterSeek) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decode of audio EOS buffer without any prior decode. See also
  // http://b/11696552.
  // Also tests that seeking+Start() after completing audio playback resumes
  // playback.
  Start(CreateAudioDemuxerConfigs(kCodecAAC, false));
  VerifyPlaybackCompletesOnEOSDecode(true, true);
  VerifyCompletedPlaybackResumesOnSeekPlusStart(true, false);
}

TEST_F(MediaSourcePlayerTest, V_FirstAccessUnitAfterSeekIsEOS) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decode of video EOS buffer, just after seeking, without any prior
  // decode (other than the simulated |kAborted| resulting from the seek
  // process.)
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  SeekPlayerWithAbort(false, base::TimeDelta());
  VerifyPlaybackCompletesOnEOSDecode(true, false);
}

TEST_F(MediaSourcePlayerTest, A_FirstAccessUnitAfterSeekIsEOS) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decode of audio EOS buffer, just after seeking, without any prior
  // decode (other than the simulated |kAborted| resulting from the seek
  // process.) See also http://b/11696552.
  Start(CreateAudioDemuxerConfigs(kCodecAAC, false));
  SeekPlayerWithAbort(true, base::TimeDelta());
  VerifyPlaybackCompletesOnEOSDecode(true, true);
}

TEST_F(MediaSourcePlayerTest, AV_PlaybackCompletionAcrossConfigChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that if one stream (audio) has completed decode of EOS and the other
  // stream (video) processes config change, that subsequent video EOS completes
  // A/V playback.
  // Also tests that seeking+Start() after completing playback resumes playback.
  CreateNextTextureAndSetVideoSurface();
  Start(CreateAudioVideoDemuxerConfigs());

  player_.OnDemuxerDataAvailable(CreateEOSAck(true));  // Audio EOS
  DemuxerConfigs configs = CreateVideoDemuxerConfigs(true);
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckWithConfigChanged(
      false, 0, configs));  // Video |kConfigChanged| as first unit.

  WaitForAudioVideoDecodeDone();

  EXPECT_EQ(3, demuxer_->num_data_requests());

  // At no time after completing audio EOS decode, above, should the
  // audio decoder job resume decoding. Send and decode video EOS.
  VerifyPlaybackCompletesOnEOSDecode(true, false);
  VerifyCompletedPlaybackResumesOnSeekPlusStart(true, true);
}

TEST_F(MediaSourcePlayerTest, VA_PlaybackCompletionAcrossConfigChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that if one stream (video) has completed decode of EOS and the other
  // stream (audio) processes config change, that subsequent audio EOS completes
  // A/V playback.
  // Also tests that seeking+Start() after completing playback resumes playback.
  CreateNextTextureAndSetVideoSurface();
  Start(CreateAudioVideoDemuxerConfigs());

  player_.OnDemuxerDataAvailable(CreateEOSAck(false));  // Video EOS
  // Audio |kConfigChanged| as first unit.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckWithConfigChanged(
      true, 0, CreateAudioDemuxerConfigs(kCodecVorbis, false)));

  WaitForAudioVideoDecodeDone();

  EXPECT_EQ(3, demuxer_->num_data_requests());

  // At no time after completing video EOS decode, above, should the
  // video decoder job resume decoding. Send and decode audio EOS.
  VerifyPlaybackCompletesOnEOSDecode(true, true);
  VerifyCompletedPlaybackResumesOnSeekPlusStart(true, true);
}

TEST_F(MediaSourcePlayerTest, AV_NoPrefetchForFinishedVideoOnAudioStarvation) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that if one stream (video) has completed decode of EOS, prefetch
  // resulting from player starvation occurs only for the other stream (audio),
  // and responding to that prefetch with EOS completes A/V playback, even if
  // another starvation occurs during the latter EOS's decode.
  CreateNextTextureAndSetVideoSurface();
  Start(CreateAudioVideoDemuxerConfigs());

  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  player_.OnDemuxerDataAvailable(CreateEOSAck(false));  // Video EOS

  // Wait until video EOS is processed and more data (assumed to be audio) is
  // requested.
  WaitForAudioVideoDecodeDone();
  EXPECT_EQ(3, demuxer_->num_data_requests());

  // Simulate decoder underrun to trigger prefetch while still decoding audio.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(1));
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding() &&
              !GetMediaDecoderJob(false)->is_decoding());
  TriggerPlayerStarvation();

  // Complete the audio decode that was in progress when simulated player
  // starvation was triggered.
  WaitForAudioDecodeDone();
  EXPECT_EQ(4, demuxer_->num_data_requests());
  player_.OnDemuxerDataAvailable(CreateEOSAck(true));  // Audio EOS
  EXPECT_FALSE(GetMediaDecoderJob(false)->is_decoding());
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());

  // Simulate another decoder underrun to trigger prefetch while decoding EOS.
  TriggerPlayerStarvation();
  VerifyPlaybackCompletesOnEOSDecode(false, true /* ignored */);
}

TEST_F(MediaSourcePlayerTest, V_StarvationDuringEOSDecode) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that video-only playback completes without further data requested when
  // starvation occurs during EOS decode.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  WaitForVideoDecodeDone();

  // Simulate decoder underrun to trigger prefetch while decoding EOS.
  player_.OnDemuxerDataAvailable(CreateEOSAck(false));  // Video EOS
  EXPECT_TRUE(GetMediaDecoderJob(false)->is_decoding());
  TriggerPlayerStarvation();
  VerifyPlaybackCompletesOnEOSDecode(false, false /* ignored */);
}

TEST_F(MediaSourcePlayerTest, A_StarvationDuringEOSDecode) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that audio-only playback completes without further data requested when
  // starvation occurs during EOS decode.
  StartAudioDecoderJob();
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  WaitForAudioDecodeDone();

  // Simulate decoder underrun to trigger prefetch while decoding EOS.
  player_.OnDemuxerDataAvailable(CreateEOSAck(true));  // Audio EOS
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
  TriggerPlayerStarvation();
  VerifyPlaybackCompletesOnEOSDecode(false, true /* ignored */);
}

TEST_F(MediaSourcePlayerTest, AV_SeekDuringEOSDecodePreventsCompletion) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that seek supercedes audio+video playback completion on simultaneous
  // audio and video EOS decode, if SeekTo() occurs during these EOS decodes.
  VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, true, true, true);
}

TEST_F(MediaSourcePlayerTest, AV_SeekDuringAudioEOSDecodePreventsCompletion) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that seek supercedes audio+video playback completion on simultaneous
  // audio EOS and video non-EOS decode, if SeekTo() occurs during these
  // decodes.
  VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, true, true, false);
}

TEST_F(MediaSourcePlayerTest, AV_SeekDuringVideoEOSDecodePreventsCompletion) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that seek supercedes audio+video playback completion on simultaneous
  // audio non-EOS and video EOS decode, if SeekTo() occurs during these
  // decodes.
  VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, true, false, true);
}

TEST_F(MediaSourcePlayerTest, V_SeekDuringEOSDecodePreventsCompletion) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that seek supercedes video-only playback completion on EOS decode, if
  // SeekTo() occurs during EOS decode.
  VerifySeekDuringEOSDecodePreventsPlaybackCompletion(false, true, false, true);
}

TEST_F(MediaSourcePlayerTest, A_SeekDuringEOSDecodePreventsCompletion) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that seek supercedes audio-only playback completion on EOS decode, if
  // SeekTo() occurs during EOS decode.
  VerifySeekDuringEOSDecodePreventsPlaybackCompletion(true, false, true, false);
}

TEST_F(MediaSourcePlayerTest, NoRequestForDataAfterAbort) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the decoder will not request new data after receiving an aborted
  // access unit.
  StartAudioDecoderJob();

  // Send an aborted access unit.
  player_.OnDemuxerDataAvailable(CreateAbortedAck(true));
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
  WaitForAudioDecodeDone();

  // No request will be sent for new data.
  EXPECT_EQ(1, demuxer_->num_data_requests());

  // No seek requests should have occurred.
  EXPECT_EQ(0, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, DemuxerDataArrivesAfterRelease) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the decoder should not crash if demuxer data arrives after
  // Release().
  StartAudioDecoderJob();

  ReleasePlayer();
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));

  // The media codec bridge should have been released.
  EXPECT_FALSE(player_.IsPlaying());

  // No further data should have been requested.
  EXPECT_EQ(1, demuxer_->num_data_requests());

  // No seek requests should have occurred.
  EXPECT_EQ(0, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, BrowserSeek_RegularSeekPendsBrowserSeekDone) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that a browser seek, once started, delays a newly arrived regular
  // SeekTo() request's demuxer seek until the browser seek is done.
  BrowserSeekPlayer(false);

  // Simulate renderer requesting a regular seek while browser seek in progress.
  player_.SeekTo(base::TimeDelta());

  // Simulate browser seek is done. Confirm player requests the regular seek,
  // still has no video codec configured, and has not requested any
  // further data since the surface change event became pending in
  // BrowserSeekPlayer().
  EXPECT_EQ(1, demuxer_->num_seek_requests());
  player_.OnDemuxerSeekDone(base::TimeDelta());
  EXPECT_EQ(2, demuxer_->num_seek_requests());
  EXPECT_EQ(1, demuxer_->num_browser_seek_requests());

  // Simulate regular seek is done and confirm player requests more data for
  // new video codec.
  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_FALSE(GetMediaCodecBridge(false));
  EXPECT_EQ(3, demuxer_->num_data_requests());
  EXPECT_EQ(2, demuxer_->num_seek_requests());
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_TRUE(GetMediaCodecBridge(false));
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, BrowserSeek_InitialReleaseAndStart) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that no browser seek is requested if player Release() + Start() occurs
  // prior to receiving any data.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  ReleasePlayer();

  // Pass a new non-empty surface.
  CreateNextTextureAndSetVideoSurface();

  player_.Start();

  // No data request is issued since there is still one pending.
  EXPECT_EQ(1, demuxer_->num_data_requests());
  EXPECT_FALSE(GetMediaCodecBridge(false));

  // No browser seek is needed.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
  EXPECT_EQ(2, demuxer_->num_data_requests());
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, BrowserSeek_MidStreamReleaseAndStart) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that one browser seek is requested if player Release() + Start(), with
  // video data received between Release() and Start().
  BrowserSeekPlayer(true);

  // Simulate browser seek is done and confirm player requests more data.
  player_.OnDemuxerSeekDone(base::TimeDelta());
  EXPECT_EQ(3, demuxer_->num_data_requests());
  EXPECT_EQ(1, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, NoBrowserSeekWithKeyFrameInCache) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that browser seek is not needed if a key frame is found in data
  // cache.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  DemuxerData data = CreateReadFromDemuxerAckForVideo(false);
  data.access_units[0].is_key_frame = true;

  // Simulate demuxer's response to the video data request.
  player_.OnDemuxerDataAvailable(data);

  // Trigger decoder recreation later by changing surfaces.
  CreateNextTextureAndSetVideoSurface();

  // Wait for the media codec bridge to finish decoding and be reset.
  WaitForVideoDecodeDone();
  EXPECT_FALSE(HasData(false));

  // Send a non key frame to decoder so that decoder can continue. This will
  // not trigger any browser seeks as the previous key frame is still in the
  // buffer.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  WaitForVideoDecodeDone();
  EXPECT_EQ(0, demuxer_->num_browser_seek_requests());
}

TEST_F(MediaSourcePlayerTest, PrerollAudioAfterSeek) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will preroll the media to the seek position.
  StartAudioDecoderJob();

  SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(100));
  EXPECT_TRUE(IsPrerolling(true));
  PrerollDecoderToTime(
      true, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100), true);
}

TEST_F(MediaSourcePlayerTest, PrerollVideoAfterSeek) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will preroll the media to the seek position.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();

  SeekPlayerWithAbort(false, base::TimeDelta::FromMilliseconds(100));
  EXPECT_TRUE(IsPrerolling(false));
  PrerollDecoderToTime(
      false, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100), true);
}

TEST_F(MediaSourcePlayerTest, SeekingAfterCompletingPrerollRestartsPreroll) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will begin prerolling upon seek, when it was not
  // prerolling prior to the seek.
  StartAudioDecoderJob();
  MediaDecoderJob* decoder_job = GetMediaDecoderJob(true);
  EXPECT_TRUE(IsPrerolling(true));

  // Complete the initial preroll by feeding data to the decoder.
  DecodeAudioDataUntilOutputBecomesAvailable();
  EXPECT_FALSE(IsPrerolling(true));

  SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(500));

  // Prerolling should have begun again.
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(500.0, GetPrerollTimestamp().InMillisecondsF());

  // Send data at and after the seek position. Prerolling should complete.
  for (int i = 0; i < 4; ++i) {
    DemuxerData data = CreateReadFromDemuxerAckForAudio(i);
    data.access_units[0].timestamp = base::TimeDelta::FromMilliseconds(
        500 + 30 * (i - 1));
    player_.OnDemuxerDataAvailable(data);
    EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
    WaitForAudioDecodeDone();
  }
  EXPECT_LT(500.0, player_.GetCurrentTime().InMillisecondsF());
  EXPECT_FALSE(IsPrerolling(true));

  // Throughout this test, we should have not re-created the media codec bridge,
  // so IsPrerolling() transition from false to true was not due to constructor
  // initialization. It was due to BeginPrerolling().
  EXPECT_EQ(decoder_job, GetMediaDecoderJob(true));
}

TEST_F(MediaSourcePlayerTest, PrerollContinuesAcrossReleaseAndStart) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will resume media prerolling if interrupted by Release()
  // and Start().
  StartAudioDecoderJob();

  base::TimeDelta target_timestamp = base::TimeDelta::FromMilliseconds(100);
  SeekPlayerWithAbort(true, target_timestamp);
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());

  // Send some data before the seek position.
  // Test uses 'large' number of iterations because decoder job may not get
  // MEDIA_CODEC_OK output status until after a few dequeue output attempts.
  // This allows decoder status to stabilize prior to AU timestamp reaching
  // the preroll target.
  DemuxerData data;
  for (int i = 0; i < 10; ++i) {
    data = CreateReadFromDemuxerAckForAudio(3);
    data.access_units[0].timestamp = base::TimeDelta::FromMilliseconds(i * 10);
    if (i == 1) {
      // While still prerolling, Release() and Start() the player.
      ReleasePlayer();
      // The decoder is still decoding and will not be immediately released.
      EXPECT_TRUE(GetMediaCodecBridge(true));
      Resume(false, false);
    } else {
      player_.OnDemuxerDataAvailable(data);
      EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
      WaitForAudioDecodeDone();
    }
    EXPECT_TRUE(IsPrerolling(true));
  }
  EXPECT_EQ(100.0, player_.GetCurrentTime().InMillisecondsF());
  EXPECT_TRUE(IsPrerolling(true));

  // Send data after the seek position.
  PrerollDecoderToTime(true, target_timestamp, target_timestamp, true);
}

// Flaky on Android: crbug.com/419122.
#if defined(OS_ANDROID)
#define MAYBE_PrerollContinuesAcrossConfigChange \
        DISABLED_PrerollContinuesAcrossConfigChange
#else
#define MAYBE_PrerollContinuesAcrossConfigChange \
        PrerollContinuesAcrossConfigChange
#endif
TEST_F(MediaSourcePlayerTest, MAYBE_PrerollContinuesAcrossConfigChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will resume media prerolling if interrupted by
  // |kConfigChanged| and OnDemuxerConfigsAvailable().
  StartAudioDecoderJob();

  SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(100));
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());

  DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);

  // In response to data request, simulate that demuxer signals config change by
  // sending an AU with |kConfigChanged|.
  DemuxerData data = CreateReadFromDemuxerAckWithConfigChanged(
      true, 0, configs);
  player_.OnDemuxerDataAvailable(data);

  PrerollDecoderToTime(
      true, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100), true);
}

TEST_F(MediaSourcePlayerTest, PrerollContinuesAfterUnchangedConfigs) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will resume media prerolling if interrupted by a config
  // change access unit with unchanged configs.
  StartAudioDecoderJob();

  SeekPlayerWithAbort(true, base::TimeDelta::FromMilliseconds(100));
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());

  DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, false);

  // In response to data request, simulate that demuxer signals config change by
  // sending an AU with |kConfigChanged|.
  DemuxerData data = CreateReadFromDemuxerAckWithConfigChanged(
      true, 0, configs);
  player_.OnDemuxerDataAvailable(data);
  PrerollDecoderToTime(
      true, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100), true);
}

TEST_F(MediaSourcePlayerTest, AudioPrerollFinishesBeforeVideo) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that after audio finishes prerolling, it will wait for video to finish
  // prerolling before advancing together.
  CreateNextTextureAndSetVideoSurface();
  Start(CreateAudioVideoDemuxerConfigs());

  // Initiate a seek.
  base::TimeDelta seek_position = base::TimeDelta::FromMilliseconds(100);
  player_.SeekTo(seek_position);
  player_.OnDemuxerDataAvailable(CreateAbortedAck(true));
  player_.OnDemuxerDataAvailable(CreateAbortedAck(false));
  WaitForDecodeDone(true, true);

  // Verify that the seek is requested.
  EXPECT_EQ(1, demuxer_->num_seek_requests());
  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_EQ(4, demuxer_->num_data_requests());
  EXPECT_EQ(player_.GetCurrentTime().InMillisecondsF(), 100.0);
  EXPECT_EQ(GetPrerollTimestamp().InMillisecondsF(), 100.0);

  // Send both audio and video data to finish prefetching.
  base::TimeDelta seek_ack_position = base::TimeDelta::FromMilliseconds(70);
  DemuxerData audio_data = CreateReadFromDemuxerAckForAudio(0);
  audio_data.access_units[0].timestamp = seek_ack_position;
  DemuxerData video_data = CreateReadFromDemuxerAckForVideo(false);
  video_data.access_units[0].timestamp = seek_ack_position;
  player_.OnDemuxerDataAvailable(audio_data);
  player_.OnDemuxerDataAvailable(video_data);
  WaitForAudioDecodeDone();
  WaitForVideoDecodeDone();

  // Send audio data at and after the seek position. Audio should finish
  // prerolling and stop decoding.
  EXPECT_EQ(6, demuxer_->num_data_requests());
  PrerollDecoderToTime(true, seek_position, seek_position, true);
  EXPECT_FALSE(GetMediaDecoderJob(true)->is_decoding());
  EXPECT_FALSE(IsPrerolling(true));
  EXPECT_TRUE(IsPrerolling(false));

  // Send video data to let video finish prerolling.
  PrerollDecoderToTime(false, seek_position, seek_position, false);
  EXPECT_FALSE(IsPrerolling(false));

  // Both audio and video decoders should start decoding again.
  player_.OnDemuxerDataAvailable(audio_data);
  player_.OnDemuxerDataAvailable(video_data);
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());
  EXPECT_TRUE(GetMediaDecoderJob(false)->is_decoding());
}

TEST_F(MediaSourcePlayerTest, SimultaneousAudioVideoConfigChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the player allows simultaneous audio and video config change,
  // such as might occur during OnPrefetchDone() if next access unit for both
  // audio and video jobs is |kConfigChanged|.
  CreateNextTextureAndSetVideoSurface();
  Start(CreateAudioVideoDemuxerConfigs());
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_TRUE(GetMediaCodecBridge(true));
  EXPECT_TRUE(GetMediaCodecBridge(false));
  EnableAdaptiveVideoPlayback(false);
  WaitForAudioVideoDecodeDone();

  // If audio or video hasn't finished prerolling, let them finish it.
  if (IsPrerolling(true))
    PrerollDecoderToTime(true, base::TimeDelta(), base::TimeDelta(), true);
  if (IsPrerolling(false))
    PrerollDecoderToTime(false, base::TimeDelta(), base::TimeDelta(), false);
  int expected_num_data_requests = demuxer_->num_data_requests();

  // Simulate audio |kConfigChanged| prefetched as standalone access unit.
  DemuxerConfigs audio_configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);
  player_.OnDemuxerDataAvailable(
      CreateReadFromDemuxerAckWithConfigChanged(true, 0, audio_configs));

  // Simulate video |kConfigChanged| prefetched as standalone access unit.
  player_.OnDemuxerDataAvailable(
      CreateReadFromDemuxerAckWithConfigChanged(
          false, 0, CreateVideoDemuxerConfigs(true)));
  EXPECT_EQ(expected_num_data_requests + 2, demuxer_->num_data_requests());
  EXPECT_TRUE(IsDrainingDecoder(true));
  EXPECT_TRUE(IsDrainingDecoder(false));

  // Waiting for decoder to finish draining.
  while (IsDrainingDecoder(true) || IsDrainingDecoder(false))
    message_loop_.RunUntilIdle();
}

TEST_F(MediaSourcePlayerTest,
       SimultaneousAudioVideoConfigChangeWithAdaptivePlayback) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the player allows simultaneous audio and video config change with
  // adaptive video playback enabled.
  CreateNextTextureAndSetVideoSurface();
  Start(CreateAudioVideoDemuxerConfigs());
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_EQ(4, demuxer_->num_data_requests());
  EXPECT_TRUE(GetMediaCodecBridge(true));
  EXPECT_TRUE(GetMediaCodecBridge(false));
  EnableAdaptiveVideoPlayback(true);
  WaitForAudioVideoDecodeDone();

  // If audio or video hasn't finished prerolling, let them finish it.
  if (IsPrerolling(true))
    PrerollDecoderToTime(true, base::TimeDelta(), base::TimeDelta(), true);
  if (IsPrerolling(false))
    PrerollDecoderToTime(false, base::TimeDelta(), base::TimeDelta(), false);
  int expected_num_data_requests = demuxer_->num_data_requests();

  // Simulate audio |kConfigChanged| prefetched as standalone access unit.
  DemuxerConfigs audio_configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);
  player_.OnDemuxerDataAvailable(
      CreateReadFromDemuxerAckWithConfigChanged(true, 0, audio_configs));

  // Simulate video |kConfigChanged| prefetched as standalone access unit.
  player_.OnDemuxerDataAvailable(
      CreateReadFromDemuxerAckWithConfigChanged(
          false, 0, CreateVideoDemuxerConfigs(true)));
  EXPECT_EQ(expected_num_data_requests + 2, demuxer_->num_data_requests());
  EXPECT_TRUE(IsDrainingDecoder(true));
  EXPECT_FALSE(IsDrainingDecoder(false));

  // Waiting for audio decoder to finish draining.
  while (IsDrainingDecoder(true))
    message_loop_.RunUntilIdle();
}

TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInPrefetchUnit0) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the player detects need for and requests demuxer configs if
  // the |kConfigChanged| unit is the very first unit in the set of units
  // received in OnDemuxerDataAvailable() ostensibly while
  // |PREFETCH_DONE_EVENT_PENDING|.
  StartConfigChange(true, true, 0, false);
  WaitForAudioDecodeDone();
}

TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInPrefetchUnit1) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the player detects need for and requests demuxer configs if
  // the |kConfigChanged| unit is not the first unit in the set of units
  // received in OnDemuxerDataAvailable() ostensibly while
  // |PREFETCH_DONE_EVENT_PENDING|.
  StartConfigChange(true, true, 1, false);
  WaitForAudioDecodeDone();
}

TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInUnit0AfterPrefetch) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the player detects need for and requests demuxer configs if
  // the |kConfigChanged| unit is the very first unit in the set of units
  // received in OnDemuxerDataAvailable() from data requested ostensibly while
  // not prefetching.
  StartConfigChange(true, false, 0, false);
  WaitForAudioDecodeDone();
}

TEST_F(MediaSourcePlayerTest, DemuxerConfigRequestedIfInUnit1AfterPrefetch) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that the player detects need for and requests demuxer configs if
  // the |kConfigChanged| unit is not the first unit in the set of units
  // received in OnDemuxerDataAvailable() from data requested ostensibly while
  // not prefetching.
  StartConfigChange(true, false, 1, false);
  WaitForAudioDecodeDone();
}

TEST_F(MediaSourcePlayerTest, BrowserSeek_PrerollAfterBrowserSeek) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test decoder job will preroll the media to the actual seek position
  // resulting from a browser seek.
  BrowserSeekPlayer(false);

  // Simulate browser seek is done, but to a later time than was requested.
  EXPECT_LT(player_.GetCurrentTime().InMillisecondsF(), 100);
  player_.OnDemuxerSeekDone(base::TimeDelta::FromMilliseconds(100));
  // Because next AU is not I-frame, MediaCodecBridge will not be recreated.
  EXPECT_FALSE(GetMediaCodecBridge(false));
  EXPECT_EQ(100.0, player_.GetCurrentTime().InMillisecondsF());
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
  EXPECT_EQ(3, demuxer_->num_data_requests());

  PrerollDecoderToTime(
      false, base::TimeDelta(), base::TimeDelta::FromMilliseconds(100), true);
}

TEST_F(MediaSourcePlayerTest, VideoDemuxerConfigChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that video config change notification results in creating a new
  // video codec without any browser seek.
  StartConfigChange(false, true, 1, false);

  // New video codec should have been created and configured, without any
  // browser seek.
  EXPECT_TRUE(GetMediaCodecBridge(false));
  EXPECT_EQ(3, demuxer_->num_data_requests());
  EXPECT_EQ(0, demuxer_->num_seek_requests());
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, VideoDemuxerConfigChangeWithAdaptivePlayback) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that if codec supports adaptive playback, no new codec should be
  // created beyond the one used to decode the prefetch media data prior to
  // the kConfigChanged.
  StartConfigChange(false, true, 1, true);

  // No browser seek should be needed.
  EXPECT_TRUE(GetMediaCodecBridge(false));
  EXPECT_EQ(3, demuxer_->num_data_requests());
  EXPECT_EQ(0, demuxer_->num_seek_requests());
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, DecoderDrainInterruptedBySeek) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if a decoder is being drained while receiving a seek request, draining
  // is canceled.
  SendConfigChangeToDecoder(true, false, 0, false);
  EXPECT_TRUE(IsDrainingDecoder(true));

  player_.SeekTo(base::TimeDelta::FromMilliseconds(100));
  WaitForAudioDecodeDone();
  EXPECT_FALSE(IsDrainingDecoder(true));
  player_.OnDemuxerSeekDone(kNoTimestamp());

  EXPECT_EQ(1, demuxer_->num_seek_requests());
  EXPECT_EQ(4, demuxer_->num_data_requests());
}

TEST_F(MediaSourcePlayerTest, DecoderDrainInterruptedByRelease) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if a decoder is being drained while receiving a release request,
  // draining is canceled.
  SendConfigChangeToDecoder(true, false, 0, false);
  EXPECT_TRUE(IsDrainingDecoder(true));

  ReleasePlayer();
  WaitForAudioDecodeDone();
  EXPECT_EQ(3, demuxer_->num_data_requests());
  EXPECT_FALSE(IsDrainingDecoder(true));

  EXPECT_FALSE(GetMediaCodecBridge(true));
  EXPECT_FALSE(player_.IsPlaying());

  player_.Start();
  EXPECT_TRUE(player_.IsPlaying());
  EXPECT_EQ(3, demuxer_->num_data_requests());
}

TEST_F(MediaSourcePlayerTest, DecoderDrainInterruptedBySurfaceChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if a video decoder is being drained while surface changes, draining
  // is canceled.
  SendConfigChangeToDecoder(false, false, 0, false);
  EXPECT_TRUE(IsDrainingDecoder(false));

  CreateNextTextureAndSetVideoSurface();
  WaitForVideoDecodeDone();

  EXPECT_FALSE(IsDrainingDecoder(false));
  EXPECT_TRUE(player_.IsPlaying());

  // The frame after the config change should always be an iframe, so no browser
  // seek is needed when recreating the video decoder due to surface change.
  EXPECT_TRUE(GetMediaCodecBridge(false));
  EXPECT_EQ(4, demuxer_->num_data_requests());
  EXPECT_EQ(0, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest,
       BrowserSeek_DecoderStarvationWhilePendingSurfaceChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test video decoder starvation while handling a pending surface change
  // should not cause any crashes.
  CreateNextTextureAndSetVideoSurface();
  StartVideoDecoderJob();
  DemuxerData data = CreateReadFromDemuxerAckForVideo(false);
  player_.OnDemuxerDataAvailable(data);

  // Trigger a surface change and decoder starvation.
  CreateNextTextureAndSetVideoSurface();
  TriggerPlayerStarvation();
  WaitForVideoDecodeDone();
  EXPECT_EQ(0, demuxer_->num_browser_seek_requests());

  // Surface change should trigger a seek.
  player_.OnDemuxerDataAvailable(data);
  EXPECT_EQ(1, demuxer_->num_browser_seek_requests());
  player_.OnDemuxerSeekDone(base::TimeDelta());
  // After seek is done, prefetch is handled first. MediaCodecBridge is not
  // created at this moment.
  EXPECT_FALSE(GetMediaCodecBridge(false));

  // A new data request should be sent.
  EXPECT_EQ(3, demuxer_->num_data_requests());
}

TEST_F(MediaSourcePlayerTest, ReleaseWithOnPrefetchDoneAlreadyPosted) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if OnPrefetchDone() had already been posted before and is executed
  // after Release(), then player does not DCHECK. This test is fragile to
  // change to MediaDecoderJob::Prefetch() implementation; it assumes task
  // is posted to run |prefetch_cb| if the job already HasData().
  // TODO(wolenetz): Remove MSP::set_decode_callback_for_testing() if this test
  // becomes obsolete. See http://crbug.com/304234.
  StartAudioDecoderJob();

  // Escape the original prefetch by decoding a single access unit.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(0));
  WaitForAudioDecodeDone();

  // Prime the job with a few more access units, so that a later prefetch,
  // triggered by starvation to simulate decoder underrun, can trivially
  // post task to run OnPrefetchDone().
  player_.OnDemuxerDataAvailable(
      CreateReadFromDemuxerAckWithConfigChanged(
          true, 4, CreateAudioDemuxerConfigs(kCodecVorbis, false)));
  EXPECT_TRUE(GetMediaDecoderJob(true)->is_decoding());

  // Simulate decoder underrun, so trivial prefetch starts while still decoding.
  // The prefetch and posting of OnPrefetchDone() will not occur until next
  // MediaDecoderCallBack() occurs.
  TriggerPlayerStarvation();

  // Upon the next successful decode callback, post a task to call Release() on
  // the |player_|, such that the trivial OnPrefetchDone() task posting also
  // occurs and should execute after the Release().
  OnNextTestDecodeCallbackPostTaskToReleasePlayer();

  WaitForAudioDecodeDone();
  EXPECT_TRUE(decoder_callback_hook_executed_);

  EXPECT_EQ(3, demuxer_->num_data_requests());

  // Player should not request any new data since the access units haven't
  // been fully decoded yet.
  Resume(false, false);
}

TEST_F(MediaSourcePlayerTest, SeekToThenReleaseThenDemuxerSeekAndDone) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if Release() occurs after SeekTo(), but the DemuxerSeek IPC request
  // has not yet been sent, then the seek request is sent after Release(). Also,
  // test if OnDemuxerSeekDone() occurs prior to next Start(), then the player
  // will resume correct post-seek preroll upon Start().
  StartAudioDecoderJobAndSeekToWhileDecoding(
      base::TimeDelta::FromMilliseconds(100));
  ReleasePlayer();
  EXPECT_EQ(0, demuxer_->num_seek_requests());
  WaitForAudioDecodeDone();
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
  EXPECT_FALSE(GetMediaCodecBridge(true));
  EXPECT_FALSE(player_.IsPlaying());

  // Player should begin prefetch and resume preroll upon Start().
  EXPECT_EQ(2, demuxer_->num_data_requests());
  Resume(true, false);
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());

  // No further seek should have been requested since Release(), above.
  EXPECT_EQ(1, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, SeekToThenReleaseThenDemuxerSeekThenStart) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if Release() occurs after SeekTo(), but the DemuxerSeek IPC request
  // has not yet been sent, then the seek request is sent after Release(). Also,
  // test if OnDemuxerSeekDone() does not occur until after the next Start(),
  // then the player remains pending seek done until (and resumes correct
  // post-seek preroll after) OnDemuxerSeekDone().
  StartAudioDecoderJobAndSeekToWhileDecoding(
      base::TimeDelta::FromMilliseconds(100));
  ReleasePlayer();
  EXPECT_EQ(0, demuxer_->num_seek_requests());

  // Player should not prefetch upon Start() nor create the media codec bridge,
  // due to awaiting DemuxerSeekDone.
  EXPECT_EQ(2, demuxer_->num_data_requests());
  Resume(false, false);

  WaitForAudioDecodeDone();
  EXPECT_EQ(1, demuxer_->num_seek_requests());
  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_TRUE(GetMediaDecoderJob(true));
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
  EXPECT_EQ(3, demuxer_->num_data_requests());

  // No further seek should have been requested since Release(), above.
  EXPECT_EQ(1, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, SeekToThenDemuxerSeekThenReleaseThenSeekDone) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if Release() occurs after a SeekTo()'s subsequent DemuxerSeek IPC
  // request and OnDemuxerSeekDone() arrives prior to the next Start(), then the
  // player will resume correct post-seek preroll upon Start().
  StartAudioDecoderJobAndSeekToWhileDecoding(
      base::TimeDelta::FromMilliseconds(100));
  WaitForAudioDecodeDone();
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  ReleasePlayer();
  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_FALSE(player_.IsPlaying());
  EXPECT_FALSE(GetMediaCodecBridge(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());

  // Player should begin prefetch and resume preroll upon Start().
  EXPECT_EQ(2, demuxer_->num_data_requests());
  Resume(true, false);
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());

  // No further seek should have been requested since before Release(), above.
  EXPECT_EQ(1, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, SeekToThenReleaseThenStart) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if Release() occurs after a SeekTo()'s subsequent DemuxerSeeK IPC
  // request and OnDemuxerSeekDone() does not occur until after the next
  // Start(), then the player remains pending seek done until (and resumes
  // correct post-seek preroll after) OnDemuxerSeekDone().
  StartAudioDecoderJobAndSeekToWhileDecoding(
      base::TimeDelta::FromMilliseconds(100));
  WaitForAudioDecodeDone();
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  ReleasePlayer();
  EXPECT_EQ(2, demuxer_->num_data_requests());
  Resume(false, false);

  player_.OnDemuxerSeekDone(kNoTimestamp());
  EXPECT_FALSE(GetMediaCodecBridge(true));
  EXPECT_TRUE(IsPrerolling(true));
  EXPECT_EQ(100.0, GetPrerollTimestamp().InMillisecondsF());
  EXPECT_EQ(3, demuxer_->num_data_requests());

  // No further seek should have been requested since before Release(), above.
  EXPECT_EQ(1, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, ConfigChangedThenReleaseThenStart) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test if Release() occurs after |kConfigChanged| is processed, new data
  // requested of demuxer, and the requested data arrive before the next
  // Start(), then the player starts to decode the new data without any seek.
  StartConfigChange(true, true, 0, false);
  ReleasePlayer();

  EXPECT_TRUE(GetMediaCodecBridge(true));
  EXPECT_FALSE(player_.IsPlaying());
  EXPECT_EQ(3, demuxer_->num_data_requests());
  player_.OnDemuxerDataAvailable(
        CreateReadFromDemuxerAckWithConfigChanged(
            true, 4, CreateAudioDemuxerConfigs(kCodecVorbis, false)));
  WaitForAudioDecodeDone();
  EXPECT_FALSE(GetMediaCodecBridge(true));

  // Player should resume upon Start(), even without further configs supplied.
  player_.Start();
  EXPECT_TRUE(player_.IsPlaying());
  EXPECT_EQ(3, demuxer_->num_data_requests());
  EXPECT_EQ(0, demuxer_->num_seek_requests());
  WaitForAudioDecodeDone();
}

TEST_F(MediaSourcePlayerTest, BrowserSeek_ThenReleaseThenDemuxerSeekDone) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that Release() after a browser seek's DemuxerSeek IPC request has been
  // sent behaves similar to a regular seek: if OnDemuxerSeekDone() occurs
  // before the next Start()+SetVideoSurface(), then the player will resume
  // correct post-seek preroll upon Start()+SetVideoSurface().
  BrowserSeekPlayer(false);
  base::TimeDelta expected_preroll_timestamp = player_.GetCurrentTime();
  ReleasePlayer();

  player_.OnDemuxerSeekDone(expected_preroll_timestamp);
  EXPECT_FALSE(player_.IsPlaying());
  EXPECT_FALSE(GetMediaCodecBridge(false));
  EXPECT_EQ(expected_preroll_timestamp, GetPrerollTimestamp());

  // Player should begin prefetch and resume preroll upon Start().
  EXPECT_EQ(2, demuxer_->num_data_requests());
  CreateNextTextureAndSetVideoSurface();
  Resume(false, true);
  EXPECT_TRUE(IsPrerolling(false));
  EXPECT_EQ(expected_preroll_timestamp, GetPrerollTimestamp());
  EXPECT_EQ(expected_preroll_timestamp, player_.GetCurrentTime());

  // No further seek should have been requested since BrowserSeekPlayer().
  EXPECT_EQ(1, demuxer_->num_seek_requests());
}

TEST_F(MediaSourcePlayerTest, BrowserSeek_ThenReleaseThenStart) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that Release() after a browser seek's DemuxerSeek IPC request has been
  // sent behaves similar to a regular seek: if OnDemuxerSeekDone() does not
  // occur until after the next Start()+SetVideoSurface(), then the player
  // remains pending seek done until (and resumes correct post-seek preroll
  // after) OnDemuxerSeekDone().
  BrowserSeekPlayer(false);
  base::TimeDelta expected_preroll_timestamp = player_.GetCurrentTime();
  ReleasePlayer();

  EXPECT_EQ(2, demuxer_->num_data_requests());
  CreateNextTextureAndSetVideoSurface();
  Resume(false, false);

  player_.OnDemuxerSeekDone(expected_preroll_timestamp);
  // Prefetch takes place first, and the decoder is not created yet.
  EXPECT_FALSE(GetMediaCodecBridge(false));
  EXPECT_TRUE(IsPrerolling(false));
  EXPECT_EQ(expected_preroll_timestamp, GetPrerollTimestamp());
  EXPECT_EQ(expected_preroll_timestamp, player_.GetCurrentTime());
  EXPECT_EQ(3, demuxer_->num_data_requests());

  // No further seek should have been requested since BrowserSeekPlayer().
  EXPECT_EQ(1, demuxer_->num_seek_requests());

  // Decoder will be created once data is received.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForVideo(false));
  EXPECT_TRUE(GetMediaCodecBridge(false));
  WaitForVideoDecodeDone();
}

// TODO(xhwang): Once we add tests to cover DrmBridge, update this test to
// also verify that the job is successfully created if SetDrmBridge(), Start()
// and eventually OnMediaCrypto() occur. This would increase test coverage of
// http://crbug.com/313470 and allow us to remove inspection of internal player
// pending event state. See http://crbug.com/313860.
TEST_F(MediaSourcePlayerTest, SurfaceChangeClearedEvenIfMediaCryptoAbsent) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that |SURFACE_CHANGE_EVENT_PENDING| is not pending after
  // SetVideoSurface() for a player configured for encrypted video, when the
  // player has not yet received media crypto.
  DemuxerConfigs configs = CreateVideoDemuxerConfigs(false);
  configs.is_video_encrypted = true;

  player_.OnDemuxerConfigsAvailable(configs);
  CreateNextTextureAndSetVideoSurface();
  EXPECT_FALSE(GetMediaCodecBridge(false));
}

TEST_F(MediaSourcePlayerTest, CurrentTimeUpdatedWhileDecoderStarved) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that current time is updated while decoder is starved.
  StartAudioDecoderJob();
  DecodeAudioDataUntilOutputBecomesAvailable();

  // Trigger starvation while the decoder is decoding.
  player_.OnDemuxerDataAvailable(CreateReadFromDemuxerAckForAudio(3));
  manager_.ResetTimestampUpdated();
  TriggerPlayerStarvation();
  WaitForAudioDecodeDone();

  // Current time should be updated.
  EXPECT_TRUE(manager_.timestamp_updated());
}

TEST_F(MediaSourcePlayerTest, CurrentTimeKeepsIncreasingAfterConfigChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test current time keep on increasing after audio config change.
  // Test that current time is updated while decoder is starved.
  StartAudioDecoderJob();

  DecodeAudioDataUntilOutputBecomesAvailable();

  DemuxerConfigs configs = CreateAudioDemuxerConfigs(kCodecVorbis, true);
  DemuxerData data = CreateReadFromDemuxerAckWithConfigChanged(
      true, 0, configs);
  player_.OnDemuxerDataAvailable(data);
  WaitForAudioDecodeDone();
  DecodeAudioDataUntilOutputBecomesAvailable();
}

TEST_F(MediaSourcePlayerTest, VideoMetadataChangeAfterConfigChange) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  // Test that after a config change, metadata change will be happen
  // after decoder is drained.
  StartConfigChange(false, true, 2, false);
  EXPECT_EQ(1, manager_.num_metadata_changes());
  EXPECT_FALSE(IsDrainingDecoder(false));

  // Create video data with new resolutions.
  DemuxerData data = CreateReadFromDemuxerAckForVideo(true);

  // Wait for the metadata change.
  while(manager_.num_metadata_changes() == 1) {
    player_.OnDemuxerDataAvailable(data);
    WaitForVideoDecodeDone();
  }
  EXPECT_EQ(2, manager_.num_metadata_changes());
  WaitForVideoDecodeDone();
}

TEST_F(MediaSourcePlayerTest, RequestPlayDeniedDontPlay_Audio) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  EXPECT_EQ(demuxer_->num_data_requests(), 0);
  player_.OnDemuxerConfigsAvailable(CreateDemuxerConfigs(true, false));

  manager_.set_allow_play(false);
  player_.Start();
  EXPECT_FALSE(player_.IsPlaying());
}

TEST_F(MediaSourcePlayerTest, RequestPlayDeniedDontPlay_Video) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  EXPECT_EQ(demuxer_->num_data_requests(), 0);
  player_.OnDemuxerConfigsAvailable(CreateDemuxerConfigs(false, true));

  manager_.set_allow_play(false);
  player_.Start();
  EXPECT_FALSE(player_.IsPlaying());
}

TEST_F(MediaSourcePlayerTest, RequestPlayDeniedDontPlay_AV) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  EXPECT_EQ(demuxer_->num_data_requests(), 0);
  player_.OnDemuxerConfigsAvailable(CreateDemuxerConfigs(true, true));

  manager_.set_allow_play(false);
  player_.Start();
  EXPECT_FALSE(player_.IsPlaying());
}

TEST_F(MediaSourcePlayerTest, RequestPlayGrantedPlays) {
  SKIP_TEST_IF_MEDIA_CODEC_BRIDGE_IS_NOT_AVAILABLE();

  EXPECT_EQ(demuxer_->num_data_requests(), 0);
  player_.OnDemuxerConfigsAvailable(CreateDemuxerConfigs(true, true));

  manager_.set_allow_play(true);
  player_.Start();
  EXPECT_TRUE(player_.IsPlaying());
}

}  // namespace media