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
media / filters / chunk_demuxer.cc [blame]
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/filters/chunk_demuxer.h"
#include <algorithm>
#include <limits>
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/not_fatal_until.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/bind_post_task.h"
#include "base/trace_event/trace_event.h"
#include "media/base/audio_decoder_config.h"
#include "media/base/demuxer.h"
#include "media/base/media_tracks.h"
#include "media/base/mime_util.h"
#include "media/base/stream_parser.h"
#include "media/base/stream_parser_buffer.h"
#include "media/base/timestamp_constants.h"
#include "media/base/video_codecs.h"
#include "media/base/video_decoder_config.h"
#include "media/filters/frame_processor.h"
#include "media/filters/source_buffer_stream.h"
#include "media/filters/stream_parser_factory.h"
namespace {
// Helper to attempt construction of a StreamParser specific to |content_type|
// and |codecs|.
// TODO(wolenetz): Consider relocating this to StreamParserFactory in
// conjunction with updating StreamParserFactory's isTypeSupported() to also
// parse codecs, rather than require preparsed vector.
std::unique_ptr<media::StreamParser> CreateParserForTypeAndCodecs(
const std::string& content_type,
const std::string& codecs,
media::MediaLog* media_log) {
std::vector<std::string> parsed_codec_ids;
media::SplitCodecs(codecs, &parsed_codec_ids);
return media::StreamParserFactory::Create(content_type, parsed_codec_ids,
media_log);
}
// Helper to calculate the expected codecs parsed from initialization segments
// for a few mime types that have an implicit codec.
std::string ExpectedCodecs(const std::string& content_type,
const std::string& codecs) {
if (codecs == "" && content_type == "audio/aac")
return "aac";
if (codecs == "" &&
(content_type == "audio/mpeg" || content_type == "audio/mp3"))
return "mp3";
return codecs;
}
} // namespace
namespace media {
ChunkDemuxerStream::ChunkDemuxerStream(Type type, MediaTrack::Id media_track_id)
: type_(type),
liveness_(StreamLiveness::kUnknown),
media_track_id_(media_track_id),
state_(UNINITIALIZED),
is_enabled_(true) {}
void ChunkDemuxerStream::StartReturningData() {
DVLOG(1) << "ChunkDemuxerStream::StartReturningData()";
base::AutoLock auto_lock(lock_);
DCHECK(!read_cb_);
ChangeState_Locked(RETURNING_DATA_FOR_READS);
}
void ChunkDemuxerStream::AbortReads() {
DVLOG(1) << "ChunkDemuxerStream::AbortReads()";
base::AutoLock auto_lock(lock_);
ChangeState_Locked(RETURNING_ABORT_FOR_READS);
if (read_cb_)
std::move(read_cb_).Run(kAborted, {});
}
void ChunkDemuxerStream::CompletePendingReadIfPossible() {
base::AutoLock auto_lock(lock_);
if (!read_cb_)
return;
CompletePendingReadIfPossible_Locked();
}
void ChunkDemuxerStream::Shutdown() {
DVLOG(1) << "ChunkDemuxerStream::Shutdown()";
base::AutoLock auto_lock(lock_);
ChangeState_Locked(SHUTDOWN);
// Pass an end of stream buffer to the pending callback to signal that no more
// data will be sent.
if (read_cb_) {
std::move(read_cb_).Run(DemuxerStream::kOk,
{StreamParserBuffer::CreateEOSBuffer()});
}
}
bool ChunkDemuxerStream::IsSeekWaitingForData() const {
base::AutoLock auto_lock(lock_);
return stream_->IsSeekPending();
}
void ChunkDemuxerStream::Seek(base::TimeDelta time) {
DVLOG(1) << "ChunkDemuxerStream::Seek(" << time.InSecondsF() << ")";
base::AutoLock auto_lock(lock_);
DCHECK(!read_cb_);
DCHECK(state_ == UNINITIALIZED || state_ == RETURNING_ABORT_FOR_READS)
<< state_;
stream_->Seek(time);
}
bool ChunkDemuxerStream::Append(const StreamParser::BufferQueue& buffers) {
if (append_observer_cb_)
append_observer_cb_.Run(&buffers);
if (buffers.empty())
return false;
base::AutoLock auto_lock(lock_);
DCHECK_NE(state_, SHUTDOWN);
stream_->Append(buffers);
if (read_cb_)
CompletePendingReadIfPossible_Locked();
return true;
}
void ChunkDemuxerStream::Remove(base::TimeDelta start,
base::TimeDelta end,
base::TimeDelta duration) {
base::AutoLock auto_lock(lock_);
stream_->Remove(start, end, duration);
}
bool ChunkDemuxerStream::EvictCodedFrames(base::TimeDelta media_time,
size_t newDataSize) {
base::AutoLock auto_lock(lock_);
// If the stream is disabled, then the renderer is not reading from it and
// thus the read position might be stale. MSE GC algorithm uses the read
// position to determine when to stop removing data from the front of buffered
// ranges, so do a Seek in order to update the read position and allow the GC
// to collect unnecessary data that is earlier than the GOP containing
// |media_time|.
if (!is_enabled_)
stream_->Seek(media_time);
// |media_time| is allowed to be a little imprecise here. GC only needs to
// know which GOP currentTime points to.
return stream_->GarbageCollectIfNeeded(media_time, newDataSize);
}
void ChunkDemuxerStream::OnMemoryPressure(
base::TimeDelta media_time,
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level,
bool force_instant_gc) {
// TODO(sebmarchand): Check if MEMORY_PRESSURE_LEVEL_MODERATE should also be
// ignored.
if (memory_pressure_level ==
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) {
return;
}
base::AutoLock auto_lock(lock_);
return stream_->OnMemoryPressure(media_time, memory_pressure_level,
force_instant_gc);
}
void ChunkDemuxerStream::OnSetDuration(base::TimeDelta duration) {
base::AutoLock auto_lock(lock_);
stream_->OnSetDuration(duration);
}
Ranges<base::TimeDelta> ChunkDemuxerStream::GetBufferedRanges(
base::TimeDelta duration) const {
base::AutoLock auto_lock(lock_);
Ranges<base::TimeDelta> range = stream_->GetBufferedTime();
if (range.size() == 0u)
return range;
// Clamp the end of the stream's buffered ranges to fit within the duration.
// This can be done by intersecting the stream's range with the valid time
// range.
Ranges<base::TimeDelta> valid_time_range;
valid_time_range.Add(range.start(0), range.start(0) + duration);
return range.IntersectionWith(valid_time_range);
}
base::TimeDelta ChunkDemuxerStream::GetLowestPresentationTimestamp() const {
base::AutoLock auto_lock(lock_);
return stream_->GetLowestPresentationTimestamp();
}
base::TimeDelta ChunkDemuxerStream::GetHighestPresentationTimestamp() const {
base::AutoLock auto_lock(lock_);
return stream_->GetHighestPresentationTimestamp();
}
base::TimeDelta ChunkDemuxerStream::GetBufferedDuration() const {
base::AutoLock auto_lock(lock_);
return stream_->GetBufferedDuration();
}
size_t ChunkDemuxerStream::GetMemoryUsage() const {
base::AutoLock auto_lock(lock_);
return stream_->GetMemoryUsage();
}
void ChunkDemuxerStream::OnStartOfCodedFrameGroup(DecodeTimestamp start_dts,
base::TimeDelta start_pts) {
DVLOG(2) << "ChunkDemuxerStream::OnStartOfCodedFrameGroup(dts "
<< start_dts.InSecondsF() << ", pts " << start_pts.InSecondsF()
<< ")";
if (group_start_observer_cb_)
group_start_observer_cb_.Run(start_dts, start_pts);
base::AutoLock auto_lock(lock_);
stream_->OnStartOfCodedFrameGroup(start_pts);
}
bool ChunkDemuxerStream::UpdateAudioConfig(const AudioDecoderConfig& config,
bool allow_codec_change,
MediaLog* media_log) {
DCHECK(config.IsValidConfig());
DCHECK_EQ(type_, AUDIO);
base::AutoLock auto_lock(lock_);
if (!stream_) {
DCHECK_EQ(state_, UNINITIALIZED);
stream_ = std::make_unique<SourceBufferStream>(config, media_log);
return true;
}
return stream_->UpdateAudioConfig(config, allow_codec_change);
}
bool ChunkDemuxerStream::UpdateVideoConfig(const VideoDecoderConfig& config,
bool allow_codec_change,
MediaLog* media_log) {
DCHECK(config.IsValidConfig());
DCHECK_EQ(type_, VIDEO);
base::AutoLock auto_lock(lock_);
if (!stream_) {
DCHECK_EQ(state_, UNINITIALIZED);
stream_ = std::make_unique<SourceBufferStream>(config, media_log);
return true;
}
return stream_->UpdateVideoConfig(config, allow_codec_change);
}
void ChunkDemuxerStream::MarkEndOfStream() {
base::AutoLock auto_lock(lock_);
stream_->MarkEndOfStream();
}
void ChunkDemuxerStream::UnmarkEndOfStream() {
base::AutoLock auto_lock(lock_);
stream_->UnmarkEndOfStream();
}
// DemuxerStream methods.
void ChunkDemuxerStream::Read(uint32_t count, ReadCB read_cb) {
base::AutoLock auto_lock(lock_);
DCHECK_NE(state_, UNINITIALIZED);
DCHECK(!read_cb_);
read_cb_ = base::BindPostTaskToCurrentDefault(std::move(read_cb));
requested_buffer_count_ = count;
if (!is_enabled_) {
DVLOG(1) << "Read from disabled stream, returning EOS";
std::move(read_cb_).Run(DemuxerStream::kOk,
{StreamParserBuffer::CreateEOSBuffer()});
return;
}
CompletePendingReadIfPossible_Locked();
}
DemuxerStream::Type ChunkDemuxerStream::type() const { return type_; }
StreamLiveness ChunkDemuxerStream::liveness() const {
base::AutoLock auto_lock(lock_);
return liveness_;
}
AudioDecoderConfig ChunkDemuxerStream::audio_decoder_config() {
CHECK_EQ(type_, AUDIO);
base::AutoLock auto_lock(lock_);
// Trying to track down crash. http://crbug.com/715761
CHECK(stream_);
return stream_->GetCurrentAudioDecoderConfig();
}
VideoDecoderConfig ChunkDemuxerStream::video_decoder_config() {
CHECK_EQ(type_, VIDEO);
base::AutoLock auto_lock(lock_);
// Trying to track down crash. http://crbug.com/715761
CHECK(stream_);
return stream_->GetCurrentVideoDecoderConfig();
}
bool ChunkDemuxerStream::SupportsConfigChanges() { return true; }
bool ChunkDemuxerStream::IsEnabled() const {
base::AutoLock auto_lock(lock_);
return is_enabled_;
}
void ChunkDemuxerStream::SetEnabled(bool enabled, base::TimeDelta timestamp) {
base::AutoLock auto_lock(lock_);
if (enabled == is_enabled_)
return;
is_enabled_ = enabled;
if (enabled) {
DCHECK(stream_);
stream_->Seek(timestamp);
} else if (read_cb_) {
DVLOG(1) << "Read from disabled stream, returning EOS";
std::move(read_cb_).Run(kOk, {StreamParserBuffer::CreateEOSBuffer()});
}
}
void ChunkDemuxerStream::SetStreamMemoryLimit(size_t memory_limit) {
base::AutoLock auto_lock(lock_);
stream_->set_memory_limit(memory_limit);
}
void ChunkDemuxerStream::SetLiveness(StreamLiveness liveness) {
base::AutoLock auto_lock(lock_);
liveness_ = liveness;
}
void ChunkDemuxerStream::ChangeState_Locked(State state) {
lock_.AssertAcquired();
DVLOG(1) << "ChunkDemuxerStream::ChangeState_Locked() : "
<< "type " << type_
<< " - " << state_ << " -> " << state;
state_ = state;
}
ChunkDemuxerStream::~ChunkDemuxerStream() = default;
void ChunkDemuxerStream::CompletePendingReadIfPossible_Locked() {
lock_.AssertAcquired();
DCHECK(read_cb_);
switch (state_) {
case UNINITIALIZED:
NOTREACHED();
case RETURNING_ABORT_FOR_READS:
// Null buffers should be returned in this state since we are waiting
// for a seek. Any buffers in the SourceBuffer should NOT be returned
// because they are associated with the seek.
requested_buffer_count_ = 0;
std::move(read_cb_).Run(kAborted, {});
DVLOG(2) << __func__ << ": returning kAborted, type " << type_;
return;
case SHUTDOWN:
requested_buffer_count_ = 0;
std::move(read_cb_).Run(kOk, {StreamParserBuffer::CreateEOSBuffer()});
DVLOG(2) << __func__ << ": returning kOk with EOS buffer, type " << type_;
return;
case RETURNING_DATA_FOR_READS:
break;
}
DCHECK(state_ == RETURNING_DATA_FOR_READS);
auto [status, buffers] = GetPendingBuffers_Locked();
// If the status from |stream_| is kNeedBuffer and there's no buffers,
// then after ChunkDemuxerStream::Append, try to read data again,
// 'requested_buffer_count_' does not need to be cleared to 0.
if (status == SourceBufferStreamStatus::kNeedBuffer && buffers.empty()) {
return;
}
// If the status from |stream_| is kConfigChange, the vector muse be
// empty, then need to notify new config by running |read_cb_|.
if (status == SourceBufferStreamStatus::kConfigChange) {
DCHECK(buffers.empty());
requested_buffer_count_ = 0;
std::move(read_cb_).Run(kConfigChanged, std::move(buffers));
return;
}
// Other cases are kOk and just return the buffers.
DCHECK(!buffers.empty());
requested_buffer_count_ = 0;
std::move(read_cb_).Run(kOk, std::move(buffers));
}
std::pair<SourceBufferStreamStatus, DemuxerStream::DecoderBufferVector>
ChunkDemuxerStream::GetPendingBuffers_Locked() {
lock_.AssertAcquired();
DemuxerStream::DecoderBufferVector output_buffers;
for (uint32_t i = 0; i < requested_buffer_count_; ++i) {
// This aims to avoid send out buffers with different config. To
// simply the config change handling on renderer(receiver) side, prefer to
// send out buffers before config change happens.
if (stream_->IsNextBufferConfigChanged() && !output_buffers.empty()) {
DVLOG(3) << __func__ << " status=0"
<< ", type=" << type_ << ", req_size=" << requested_buffer_count_
<< ", out_size=" << output_buffers.size();
return {SourceBufferStreamStatus::kSuccess, std::move(output_buffers)};
}
scoped_refptr<StreamParserBuffer> buffer;
SourceBufferStreamStatus status = stream_->GetNextBuffer(&buffer);
switch (status) {
case SourceBufferStreamStatus::kSuccess:
output_buffers.emplace_back(buffer);
break;
case SourceBufferStreamStatus::kNeedBuffer:
// Return early with calling |read_cb_| if output_buffers has buffers
// since there is no more readable data.
DVLOG(3) << __func__ << " status=" << (int)status << ", type=" << type_
<< ", req_size=" << requested_buffer_count_
<< ", out_size=" << output_buffers.size();
return {status, std::move(output_buffers)};
case SourceBufferStreamStatus::kEndOfStream:
output_buffers.emplace_back(StreamParserBuffer::CreateEOSBuffer());
DVLOG(3) << __func__ << " status=" << (int)status << ", type=" << type_
<< ", req_size=" << requested_buffer_count_
<< ", out_size=" << output_buffers.size();
return {status, std::move(output_buffers)};
case SourceBufferStreamStatus::kConfigChange:
// Since IsNextBufferConfigChanged has detected config change happen and
// send out buffers if |output_buffers| has buffer. When confige
// change actually happen it should be the first time run this |for
// loop|, i.e. output_buffers should be empty.
DCHECK(output_buffers.empty());
DVLOG(3) << __func__ << " status=" << (int)status << ", type=" << type_
<< ", req_size=" << requested_buffer_count_
<< ", out_size=" << output_buffers.size();
return {status, std::move(output_buffers)};
}
}
DCHECK_EQ(output_buffers.size(),
static_cast<size_t>(requested_buffer_count_));
DVLOG(3) << __func__ << " status are always kSuccess"
<< ", type=" << type_ << ", req_size=" << requested_buffer_count_
<< ", out_size=" << output_buffers.size();
return {SourceBufferStreamStatus::kSuccess, std::move(output_buffers)};
}
ChunkDemuxer::ChunkDemuxer(
base::OnceClosure open_cb,
base::RepeatingClosure progress_cb,
EncryptedMediaInitDataCB encrypted_media_init_data_cb,
MediaLog* media_log)
: open_cb_(std::move(open_cb)),
progress_cb_(std::move(progress_cb)),
encrypted_media_init_data_cb_(std::move(encrypted_media_init_data_cb)),
media_log_(media_log) {
DCHECK(open_cb_);
DCHECK(encrypted_media_init_data_cb_);
MEDIA_LOG(INFO, media_log_) << GetDisplayName();
}
std::string ChunkDemuxer::GetDisplayName() const {
return "ChunkDemuxer";
}
DemuxerType ChunkDemuxer::GetDemuxerType() const {
return DemuxerType::kChunkDemuxer;
}
void ChunkDemuxer::Initialize(DemuxerHost* host,
PipelineStatusCallback init_cb) {
DVLOG(1) << "Initialize()";
TRACE_EVENT_ASYNC_BEGIN0("media", "ChunkDemuxer::Initialize", this);
base::OnceClosure open_cb;
// Locked scope
{
base::AutoLock auto_lock(lock_);
if (state_ == SHUTDOWN) {
// Init cb must only be run after this method returns, so post.
init_cb_ = base::BindPostTaskToCurrentDefault(std::move(init_cb));
RunInitCB_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
return;
}
DCHECK_EQ(state_, WAITING_FOR_INIT);
host_ = host;
// Do not post init_cb once this function returns because if there is an
// error after initialization, the error might be reported before init_cb
// has a chance to run. This is because ChunkDemuxer::ReportError_Locked
// directly calls DemuxerHost::OnDemuxerError: crbug.com/633016.
init_cb_ = std::move(init_cb);
ChangeState_Locked(INITIALIZING);
open_cb = std::move(open_cb_);
}
std::move(open_cb).Run();
}
void ChunkDemuxer::Stop() {
DVLOG(1) << "Stop()";
Shutdown();
}
void ChunkDemuxer::Seek(base::TimeDelta time, PipelineStatusCallback cb) {
DVLOG(1) << "Seek(" << time.InSecondsF() << ")";
DCHECK(time >= base::TimeDelta());
TRACE_EVENT_ASYNC_BEGIN0("media", "ChunkDemuxer::Seek", this);
base::AutoLock auto_lock(lock_);
DCHECK(!seek_cb_);
seek_cb_ = base::BindPostTaskToCurrentDefault(std::move(cb));
if (state_ != INITIALIZED && state_ != ENDED) {
RunSeekCB_Locked(PIPELINE_ERROR_INVALID_STATE);
return;
}
if (cancel_next_seek_) {
cancel_next_seek_ = false;
RunSeekCB_Locked(PIPELINE_OK);
return;
}
SeekAllSources(time);
StartReturningData();
if (IsSeekWaitingForData_Locked()) {
DVLOG(1) << "Seek() : waiting for more data to arrive.";
return;
}
RunSeekCB_Locked(PIPELINE_OK);
}
bool ChunkDemuxer::IsSeekable() const {
return true;
}
// Demuxer implementation.
base::Time ChunkDemuxer::GetTimelineOffset() const {
return timeline_offset_;
}
std::vector<DemuxerStream*> ChunkDemuxer::GetAllStreams() {
base::AutoLock auto_lock(lock_);
std::vector<DemuxerStream*> result;
// Put enabled streams at the beginning of the list so that
// MediaResource::GetFirstStream returns the enabled stream if there is one.
// TODO(servolk): Revisit this after media track switching is supported.
for (const auto& stream : audio_streams_) {
if (stream->IsEnabled())
result.push_back(stream.get());
}
for (const auto& stream : video_streams_) {
if (stream->IsEnabled())
result.push_back(stream.get());
}
// Put disabled streams at the end of the vector.
for (const auto& stream : audio_streams_) {
if (!stream->IsEnabled())
result.push_back(stream.get());
}
for (const auto& stream : video_streams_) {
if (!stream->IsEnabled())
result.push_back(stream.get());
}
return result;
}
base::TimeDelta ChunkDemuxer::GetStartTime() const {
return base::TimeDelta();
}
int64_t ChunkDemuxer::GetMemoryUsage() const {
base::AutoLock auto_lock(lock_);
int64_t mem = 0;
for (const auto& s : audio_streams_)
mem += s->GetMemoryUsage();
for (const auto& s : video_streams_)
mem += s->GetMemoryUsage();
return mem;
}
std::optional<container_names::MediaContainerName>
ChunkDemuxer::GetContainerForMetrics() const {
return std::nullopt;
}
void ChunkDemuxer::AbortPendingReads() {
base::AutoLock auto_lock(lock_);
DCHECK(state_ == INITIALIZED || state_ == ENDED || state_ == SHUTDOWN ||
state_ == PARSE_ERROR)
<< state_;
if (state_ == SHUTDOWN || state_ == PARSE_ERROR)
return;
AbortPendingReads_Locked();
}
void ChunkDemuxer::StartWaitingForSeek(base::TimeDelta seek_time) {
DVLOG(1) << "StartWaitingForSeek()";
base::AutoLock auto_lock(lock_);
DCHECK(state_ == INITIALIZED || state_ == ENDED || state_ == SHUTDOWN ||
state_ == PARSE_ERROR) << state_;
DCHECK(!seek_cb_);
if (state_ == SHUTDOWN || state_ == PARSE_ERROR)
return;
AbortPendingReads_Locked();
SeekAllSources(seek_time);
// Cancel state set in CancelPendingSeek() since we want to
// accept the next Seek().
cancel_next_seek_ = false;
}
void ChunkDemuxer::CancelPendingSeek(base::TimeDelta seek_time) {
base::AutoLock auto_lock(lock_);
DCHECK_NE(state_, INITIALIZING);
DCHECK(!seek_cb_ || IsSeekWaitingForData_Locked());
if (cancel_next_seek_)
return;
AbortPendingReads_Locked();
SeekAllSources(seek_time);
if (!seek_cb_) {
cancel_next_seek_ = true;
return;
}
RunSeekCB_Locked(PIPELINE_OK);
}
ChunkDemuxer::Status ChunkDemuxer::AddId(
const std::string& id,
std::unique_ptr<AudioDecoderConfig> audio_config) {
DCHECK(audio_config);
DVLOG(1) << __func__ << " id="
<< " audio_config=" << audio_config->AsHumanReadableString();
base::AutoLock auto_lock(lock_);
// Any valid audio config provided by WC is bufferable here, though decode
// error may occur later.
if (!audio_config->IsValidConfig())
return ChunkDemuxer::kNotSupported;
if ((state_ != WAITING_FOR_INIT && state_ != INITIALIZING) ||
IsValidId_Locked(id)) {
return kReachedIdLimit;
}
DCHECK(init_cb_);
std::string expected_codec = GetCodecName(audio_config->codec());
std::unique_ptr<media::StreamParser> stream_parser(
media::StreamParserFactory::Create(std::move(audio_config)));
DCHECK(stream_parser);
return AddIdInternal(id, std::move(stream_parser), expected_codec);
}
ChunkDemuxer::Status ChunkDemuxer::AddId(
const std::string& id,
std::unique_ptr<VideoDecoderConfig> video_config) {
DCHECK(video_config);
DVLOG(1) << __func__ << " id="
<< " video_config=" << video_config->AsHumanReadableString();
base::AutoLock auto_lock(lock_);
// Any valid video config provided by WC is bufferable here, though decode
// error may occur later.
if (!video_config->IsValidConfig())
return ChunkDemuxer::kNotSupported;
if ((state_ != WAITING_FOR_INIT && state_ != INITIALIZING) ||
IsValidId_Locked(id)) {
return kReachedIdLimit;
}
DCHECK(init_cb_);
std::string expected_codec = GetCodecName(video_config->codec());
std::unique_ptr<media::StreamParser> stream_parser(
media::StreamParserFactory::Create(std::move(video_config)));
DCHECK(stream_parser);
return AddIdInternal(id, std::move(stream_parser), expected_codec);
}
ChunkDemuxer::Status ChunkDemuxer::AddId(const std::string& id,
const std::string& content_type,
const std::string& codecs) {
DVLOG(1) << __func__ << " id=" << id << " content_type=" << content_type
<< " codecs=" << codecs;
base::AutoLock auto_lock(lock_);
if ((state_ != WAITING_FOR_INIT && state_ != INITIALIZING) ||
IsValidId_Locked(id)) {
return kReachedIdLimit;
}
// TODO(wolenetz): Change to DCHECK once less verification in release build is
// needed. See https://crbug.com/786975.
CHECK(init_cb_);
std::unique_ptr<media::StreamParser> stream_parser(
CreateParserForTypeAndCodecs(content_type, codecs, media_log_));
if (!stream_parser) {
DVLOG(1) << __func__ << " failed: unsupported content_type=" << content_type
<< " codecs=" << codecs;
return ChunkDemuxer::kNotSupported;
}
return AddIdInternal(id, std::move(stream_parser),
ExpectedCodecs(content_type, codecs));
}
#if BUILDFLAG(ENABLE_HLS_DEMUXER)
ChunkDemuxer::Status ChunkDemuxer::AddAutoDetectedCodecsId(
const std::string& id,
RelaxedParserSupportedType mime_type) {
DVLOG(1) << __func__ << " id=" << id
<< " content_type=" << static_cast<int>(mime_type);
base::AutoLock auto_lock(lock_);
if ((state_ != WAITING_FOR_INIT && state_ != INITIALIZING) ||
IsValidId_Locked(id)) {
return kReachedIdLimit;
}
CHECK(init_cb_);
std::unique_ptr<media::StreamParser> stream_parser =
StreamParserFactory::CreateRelaxedParser(mime_type);
if (!stream_parser) {
DVLOG(1) << __func__ << " failed: unsupported mime type for relaxed parser";
return kNotSupported;
}
return AddIdInternal(id, std::move(stream_parser), std::nullopt);
}
#endif
ChunkDemuxer::Status ChunkDemuxer::AddIdInternal(
const std::string& id,
std::unique_ptr<media::StreamParser> stream_parser,
std::optional<std::string_view> expected_codecs) {
DVLOG(2) << __func__ << " id=" << id
<< " expected_codecs=" << expected_codecs.value_or("None");
lock_.AssertAcquired();
std::unique_ptr<FrameProcessor> frame_processor =
std::make_unique<FrameProcessor>(
base::BindRepeating(&ChunkDemuxer::IncreaseDurationIfNecessary,
base::Unretained(this)),
media_log_);
std::unique_ptr<SourceBufferState> source_state =
std::make_unique<SourceBufferState>(
std::move(stream_parser), std::move(frame_processor),
base::BindRepeating(&ChunkDemuxer::CreateDemuxerStream,
base::Unretained(this), id),
media_log_);
// TODO(wolenetz): Change these to DCHECKs or switch to returning
// kReachedIdLimit once less verification in release build is needed. See
// https://crbug.com/786975.
CHECK(pending_source_init_ids_.find(id) == pending_source_init_ids_.end());
auto insert_result = pending_source_init_ids_.insert(id);
CHECK(insert_result.first != pending_source_init_ids_.end());
CHECK(*insert_result.first == id);
CHECK(insert_result.second); // Only true if insertion succeeded.
source_state->Init(base::BindOnce(&ChunkDemuxer::OnSourceInitDone,
base::Unretained(this), id),
expected_codecs, encrypted_media_init_data_cb_);
// TODO(wolenetz): Change to DCHECKs once less verification in release build
// is needed. See https://crbug.com/786975.
CHECK(!IsValidId_Locked(id));
source_state_map_[id] = std::move(source_state);
CHECK(IsValidId_Locked(id));
return kOk;
}
void ChunkDemuxer::SetTracksWatcher(const std::string& id,
MediaTracksUpdatedCB tracks_updated_cb) {
base::AutoLock auto_lock(lock_);
CHECK(IsValidId_Locked(id));
source_state_map_[id]->SetTracksWatcher(std::move(tracks_updated_cb));
}
void ChunkDemuxer::SetParseWarningCallback(
const std::string& id,
SourceBufferParseWarningCB parse_warning_cb) {
base::AutoLock auto_lock(lock_);
CHECK(IsValidId_Locked(id));
source_state_map_[id]->SetParseWarningCallback(std::move(parse_warning_cb));
}
void ChunkDemuxer::RemoveId(const std::string& id) {
DVLOG(1) << __func__ << " id=" << id;
base::AutoLock auto_lock(lock_);
CHECK(IsValidId_Locked(id));
source_state_map_.erase(id);
pending_source_init_ids_.erase(id);
// Remove demuxer streams created for this id.
for (const ChunkDemuxerStream* s : id_to_streams_map_[id]) {
bool stream_found = false;
for (size_t i = 0; i < audio_streams_.size(); ++i) {
if (audio_streams_[i].get() == s) {
stream_found = true;
removed_streams_.push_back(std::move(audio_streams_[i]));
audio_streams_.erase(audio_streams_.begin() + i);
break;
}
}
if (stream_found)
continue;
for (size_t i = 0; i < video_streams_.size(); ++i) {
if (video_streams_[i].get() == s) {
stream_found = true;
removed_streams_.push_back(std::move(video_streams_[i]));
video_streams_.erase(video_streams_.begin() + i);
break;
}
}
CHECK(stream_found);
}
id_to_streams_map_.erase(id);
}
Ranges<base::TimeDelta> ChunkDemuxer::GetBufferedRanges(
const std::string& id) const {
base::AutoLock auto_lock(lock_);
DCHECK(!id.empty());
auto itr = source_state_map_.find(id);
CHECK(itr != source_state_map_.end(), base::NotFatalUntil::M130);
return itr->second->GetBufferedRanges(duration_, state_ == ENDED);
}
base::TimeDelta ChunkDemuxer::GetLowestPresentationTimestamp(
const std::string& id) const {
base::AutoLock auto_lock(lock_);
DCHECK(!id.empty());
auto itr = source_state_map_.find(id);
CHECK(itr != source_state_map_.end(), base::NotFatalUntil::M130);
return itr->second->GetLowestPresentationTimestamp();
}
base::TimeDelta ChunkDemuxer::GetHighestPresentationTimestamp(
const std::string& id) const {
base::AutoLock auto_lock(lock_);
DCHECK(!id.empty());
auto itr = source_state_map_.find(id);
CHECK(itr != source_state_map_.end(), base::NotFatalUntil::M130);
return itr->second->GetHighestPresentationTimestamp();
}
void ChunkDemuxer::FindAndEnableProperTracks(
const std::vector<MediaTrack::Id>& track_ids,
base::TimeDelta curr_time,
DemuxerStream::Type track_type,
TrackChangeCB change_completed_cb) {
base::AutoLock auto_lock(lock_);
std::set<ChunkDemuxerStream*> enabled_streams;
for (const auto& id : track_ids) {
auto it = track_id_to_demux_stream_map_.find(id);
if (it == track_id_to_demux_stream_map_.end())
continue;
ChunkDemuxerStream* stream = it->second;
DCHECK(stream);
DCHECK_EQ(track_type, stream->type());
// TODO(servolk): Remove after multiple enabled audio tracks are supported
// by the media::RendererImpl.
if (!enabled_streams.empty()) {
MEDIA_LOG(INFO, media_log_)
<< "Only one enabled track is supported, ignoring track " << id;
continue;
}
enabled_streams.insert(stream);
stream->SetEnabled(true, curr_time);
}
bool is_audio = track_type == DemuxerStream::AUDIO;
for (const auto& stream : is_audio ? audio_streams_ : video_streams_) {
if (stream && enabled_streams.find(stream.get()) == enabled_streams.end()) {
DVLOG(1) << __func__ << ": disabling stream " << stream.get();
stream->SetEnabled(false, curr_time);
}
}
std::vector<DemuxerStream*> streams(enabled_streams.begin(),
enabled_streams.end());
std::move(change_completed_cb).Run(streams);
}
void ChunkDemuxer::OnEnabledAudioTracksChanged(
const std::vector<MediaTrack::Id>& track_ids,
base::TimeDelta curr_time,
TrackChangeCB change_completed_cb) {
FindAndEnableProperTracks(track_ids, curr_time, DemuxerStream::AUDIO,
std::move(change_completed_cb));
}
void ChunkDemuxer::OnSelectedVideoTrackChanged(
const std::vector<MediaTrack::Id>& track_ids,
base::TimeDelta curr_time,
TrackChangeCB change_completed_cb) {
FindAndEnableProperTracks(track_ids, curr_time, DemuxerStream::VIDEO,
std::move(change_completed_cb));
}
void ChunkDemuxer::DisableCanChangeType() {
supports_change_type_ = false;
}
void ChunkDemuxer::OnMemoryPressure(
base::TimeDelta currentMediaTime,
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level,
bool force_instant_gc) {
// TODO(sebmarchand): Check if MEMORY_PRESSURE_LEVEL_MODERATE should also be
// ignored.
if (memory_pressure_level ==
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE) {
return;
}
base::AutoLock auto_lock(lock_);
for (const auto& [source, state] : source_state_map_) {
state->OnMemoryPressure(currentMediaTime, memory_pressure_level,
force_instant_gc);
}
}
bool ChunkDemuxer::EvictCodedFrames(const std::string& id,
base::TimeDelta currentMediaTime,
size_t newDataSize) {
DVLOG(1) << __func__ << "(" << id << ")"
<< " media_time=" << currentMediaTime.InSecondsF()
<< " newDataSize=" << newDataSize;
base::AutoLock auto_lock(lock_);
DCHECK(!id.empty());
auto itr = source_state_map_.find(id);
if (itr == source_state_map_.end()) {
LOG(WARNING) << __func__ << " stream " << id << " not found";
return false;
}
return itr->second->EvictCodedFrames(currentMediaTime, newDataSize);
}
bool ChunkDemuxer::AppendToParseBuffer(const std::string& id,
base::span<const uint8_t> data) {
DVLOG(1) << "AppendToParseBuffer(" << id << ", " << data.size() << ")";
DCHECK(!id.empty());
if (data.empty()) {
// We don't DCHECK that |state_| != ENDED here, since |state_| is protected
// by |lock_|. However, transition into ENDED can happen only on
// MarkEndOfStream called by the MediaSource object on parse failure or on
// app calling endOfStream(). In case that contract is violated for
// nonzero-length appends, we still DCHECK within the lock, below.
return true;
}
{
base::AutoLock auto_lock(lock_);
DCHECK_NE(state_, ENDED);
switch (state_) {
case INITIALIZING:
case INITIALIZED:
DCHECK(IsValidId_Locked(id));
if (!source_state_map_[id]->AppendToParseBuffer(data)) {
// Just indicate that the append failed. Let the caller give app an
// error so that it may adapt. This is different from
// RunSegmentParserLoop(), where fatal MediaSource failure should
// occur if the underlying parse fails.
return false;
}
break;
case PARSE_ERROR:
case WAITING_FOR_INIT:
case ENDED:
case SHUTDOWN:
DVLOG(1) << "AppendToParseBuffer(): called in unexpected state "
<< state_;
// To preserve previous app-visible behavior in this hopefully
// never-encountered path, report no failure to caller due to being in
// invalid underlying state. If caller then proceeds with async parse
// (via RunSegmentParserLoop, below), they will get the expected parse
// failure for this set of states. If, instead, we returned false here,
// then caller would instead tell app QuotaExceededErr synchronous with
// the app's appendBuffer() call, instead of async decode error during
// async parse.
// TODO(crbug.com/40244241): Instrument this path to see if it can be
// changed to just NOTREACHED() << state_.
return true;
}
}
return true;
}
StreamParser::ParseStatus ChunkDemuxer::RunSegmentParserLoop(
const std::string& id,
base::TimeDelta append_window_start,
base::TimeDelta append_window_end,
base::TimeDelta* timestamp_offset) {
DVLOG(1) << "RunSegmentParserLoop(" << id << ")";
DCHECK(!id.empty());
DCHECK(timestamp_offset);
Ranges<base::TimeDelta> ranges;
StreamParser::ParseStatus result = StreamParser::ParseStatus::kFailed;
{
base::AutoLock auto_lock(lock_);
DCHECK_NE(state_, ENDED);
// Capture if any of the SourceBuffers are waiting for data before we start
// parsing.
bool old_waiting_for_data = IsSeekWaitingForData_Locked();
switch (state_) {
case INITIALIZING:
case INITIALIZED:
DCHECK(IsValidId_Locked(id));
result = source_state_map_[id]->RunSegmentParserLoop(
append_window_start, append_window_end, timestamp_offset);
if (result == StreamParser::ParseStatus::kFailed) {
ReportError_Locked(CHUNK_DEMUXER_ERROR_APPEND_FAILED);
return result;
}
break;
case PARSE_ERROR:
case WAITING_FOR_INIT:
case ENDED:
case SHUTDOWN:
DVLOG(1) << "RunSegmentParserLoop(): called in unexpected state "
<< state_;
return StreamParser::ParseStatus::kFailed;
}
// Check to see if newly parsed data was at the pending seek point. This
// indicates we have parsed enough data to complete the seek. Work is still
// in progress at this point, but it's okay since |seek_cb_| will post.
if (old_waiting_for_data && !IsSeekWaitingForData_Locked() && seek_cb_) {
RunSeekCB_Locked(PIPELINE_OK);
}
ranges = GetBufferedRanges_Locked();
}
DCHECK_NE(StreamParser::ParseStatus::kFailed, result);
host_->OnBufferedTimeRangesChanged(ranges);
progress_cb_.Run();
return result;
}
bool ChunkDemuxer::AppendChunks(
const std::string& id,
std::unique_ptr<StreamParser::BufferQueue> buffer_queue,
base::TimeDelta append_window_start,
base::TimeDelta append_window_end,
base::TimeDelta* timestamp_offset) {
DCHECK(buffer_queue);
DVLOG(1) << __func__ << ": " << id
<< ", buffer_queue size()=" << buffer_queue->size();
DCHECK(!id.empty());
DCHECK(timestamp_offset);
Ranges<base::TimeDelta> ranges;
{
base::AutoLock auto_lock(lock_);
DCHECK_NE(state_, ENDED);
// Capture if any of the SourceBuffers are waiting for data before we start
// buffering new chunks.
bool old_waiting_for_data = IsSeekWaitingForData_Locked();
if (buffer_queue->size() == 0u)
return true;
switch (state_) {
case INITIALIZING:
case INITIALIZED:
DCHECK(IsValidId_Locked(id));
if (!source_state_map_[id]->AppendChunks(
std::move(buffer_queue), append_window_start, append_window_end,
timestamp_offset)) {
ReportError_Locked(CHUNK_DEMUXER_ERROR_APPEND_FAILED);
return false;
}
break;
case PARSE_ERROR:
case WAITING_FOR_INIT:
case ENDED:
case SHUTDOWN:
DVLOG(1) << "AppendChunks(): called in unexpected state " << state_;
return false;
}
// Check to see if data was appended at the pending seek point. This
// indicates we have parsed enough data to complete the seek. Work is still
// in progress at this point, but it's okay since |seek_cb_| will post.
if (old_waiting_for_data && !IsSeekWaitingForData_Locked() && seek_cb_)
RunSeekCB_Locked(PIPELINE_OK);
ranges = GetBufferedRanges_Locked();
}
host_->OnBufferedTimeRangesChanged(ranges);
progress_cb_.Run();
return true;
}
void ChunkDemuxer::ResetParserState(const std::string& id,
base::TimeDelta append_window_start,
base::TimeDelta append_window_end,
base::TimeDelta* timestamp_offset) {
DVLOG(1) << "ResetParserState(" << id << ")";
base::AutoLock auto_lock(lock_);
DCHECK(!id.empty());
CHECK(IsValidId_Locked(id));
bool old_waiting_for_data = IsSeekWaitingForData_Locked();
source_state_map_[id]->ResetParserState(append_window_start,
append_window_end,
timestamp_offset);
// ResetParserState can possibly emit some buffers.
// Need to check whether seeking can be completed.
if (old_waiting_for_data && !IsSeekWaitingForData_Locked() && seek_cb_)
RunSeekCB_Locked(PIPELINE_OK);
}
void ChunkDemuxer::Remove(const std::string& id,
base::TimeDelta start,
base::TimeDelta end) {
DVLOG(1) << "Remove(" << id << ", " << start.InSecondsF()
<< ", " << end.InSecondsF() << ")";
base::AutoLock auto_lock(lock_);
DCHECK(!id.empty());
CHECK(IsValidId_Locked(id));
DCHECK(start >= base::TimeDelta()) << start.InSecondsF();
DCHECK(start < end) << "start " << start.InSecondsF()
<< " end " << end.InSecondsF();
DCHECK(duration_ != kNoTimestamp);
DCHECK(start <= duration_) << "start " << start.InSecondsF()
<< " duration " << duration_.InSecondsF();
if (start == duration_)
return;
source_state_map_[id]->Remove(start, end, duration_);
host_->OnBufferedTimeRangesChanged(GetBufferedRanges_Locked());
}
bool ChunkDemuxer::CanChangeType(const std::string& id,
const std::string& content_type,
const std::string& codecs) {
// Note, Chromium currently will not compare content_type and codecs, if any,
// with previous content_type and codecs of the SourceBuffer.
// TODO(wolenetz): Consider returning false if the codecs parameters are ever
// made to be precise such that they signal that the number of tracks of
// various media types differ from the first initialization segment (if
// received already). Switching to an audio-only container, when the first
// initialization segment only contained non-audio tracks, is one example we
// could enforce earlier here.
DVLOG(1) << __func__ << " id=" << id << " content_type=" << content_type
<< " codecs=" << codecs;
base::AutoLock auto_lock(lock_);
DCHECK(IsValidId_Locked(id));
if (!supports_change_type_) {
return false;
}
// CanChangeType() doesn't care if there has or hasn't been received a first
// initialization segment for the source buffer corresponding to |id|.
std::unique_ptr<media::StreamParser> stream_parser(
CreateParserForTypeAndCodecs(content_type, codecs, media_log_));
return !!stream_parser;
}
void ChunkDemuxer::ChangeType(const std::string& id,
const std::string& content_type,
const std::string& codecs) {
DVLOG(1) << __func__ << " id=" << id << " content_type=" << content_type
<< " codecs=" << codecs;
base::AutoLock auto_lock(lock_);
DCHECK(state_ == INITIALIZING || state_ == INITIALIZED) << state_;
DCHECK(IsValidId_Locked(id));
std::unique_ptr<media::StreamParser> stream_parser(
CreateParserForTypeAndCodecs(content_type, codecs, media_log_));
// Caller should query CanChangeType() first to protect from failing this.
DCHECK(stream_parser);
source_state_map_[id]->ChangeType(std::move(stream_parser),
ExpectedCodecs(content_type, codecs));
}
double ChunkDemuxer::GetDuration() {
base::AutoLock auto_lock(lock_);
return GetDuration_Locked();
}
double ChunkDemuxer::GetDuration_Locked() {
lock_.AssertAcquired();
if (duration_ == kNoTimestamp)
return std::numeric_limits<double>::quiet_NaN();
// Return positive infinity if the resource is unbounded.
// http://www.whatwg.org/specs/web-apps/current-work/multipage/video.html#dom-media-duration
if (duration_ == kInfiniteDuration)
return std::numeric_limits<double>::infinity();
if (user_specified_duration_ >= 0)
return user_specified_duration_;
return duration_.InSecondsF();
}
void ChunkDemuxer::SetDuration(double duration) {
base::AutoLock auto_lock(lock_);
DVLOG(1) << "SetDuration(" << duration << ")";
DCHECK_GE(duration, 0);
if (duration == GetDuration_Locked())
return;
// Compute & bounds check the base::TimeDelta representation of duration.
// This can be different if the value of |duration| doesn't fit the range or
// precision of base::TimeDelta.
base::TimeDelta min_duration = base::TimeDelta::FromInternalValue(1);
// Don't use base::TimeDelta::Max() here, as we want the largest finite time
// delta.
base::TimeDelta max_duration = base::TimeDelta::FromInternalValue(
std::numeric_limits<int64_t>::max() - 1);
double min_duration_in_seconds = min_duration.InSecondsF();
double max_duration_in_seconds = max_duration.InSecondsF();
base::TimeDelta duration_td;
if (duration == std::numeric_limits<double>::infinity()) {
duration_td = media::kInfiniteDuration;
} else if (duration < min_duration_in_seconds) {
duration_td = min_duration;
} else if (duration > max_duration_in_seconds) {
duration_td = max_duration;
} else {
duration_td =
base::Microseconds(duration * base::Time::kMicrosecondsPerSecond);
}
DCHECK(duration_td.is_positive());
user_specified_duration_ = duration;
duration_ = duration_td;
host_->SetDuration(duration_);
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->OnSetDuration(duration_);
}
}
bool ChunkDemuxer::IsParsingMediaSegment(const std::string& id) {
base::AutoLock auto_lock(lock_);
DVLOG(1) << "IsParsingMediaSegment(" << id << ")";
CHECK(IsValidId_Locked(id));
return source_state_map_[id]->parsing_media_segment();
}
bool ChunkDemuxer::GetGenerateTimestampsFlag(const std::string& id) {
base::AutoLock auto_lock(lock_);
DVLOG(1) << "GetGenerateTimestampsFlag(" << id << ")";
CHECK(IsValidId_Locked(id));
return source_state_map_[id]->generate_timestamps_flag();
}
void ChunkDemuxer::SetSequenceMode(const std::string& id,
bool sequence_mode) {
base::AutoLock auto_lock(lock_);
DVLOG(1) << "SetSequenceMode(" << id << ", " << sequence_mode << ")";
CHECK(IsValidId_Locked(id));
DCHECK_NE(state_, ENDED);
source_state_map_[id]->SetSequenceMode(sequence_mode);
}
void ChunkDemuxer::SetGroupStartTimestampIfInSequenceMode(
const std::string& id,
base::TimeDelta timestamp_offset) {
base::AutoLock auto_lock(lock_);
DVLOG(1) << "SetGroupStartTimestampIfInSequenceMode(" << id << ", "
<< timestamp_offset.InSecondsF() << ")";
CHECK(IsValidId_Locked(id));
DCHECK_NE(state_, ENDED);
source_state_map_[id]->SetGroupStartTimestampIfInSequenceMode(
timestamp_offset);
}
void ChunkDemuxer::MarkEndOfStream(PipelineStatus status) {
DVLOG(1) << "MarkEndOfStream(" << status << ")";
base::AutoLock auto_lock(lock_);
DCHECK_NE(state_, WAITING_FOR_INIT);
DCHECK_NE(state_, ENDED);
if (state_ == SHUTDOWN || state_ == PARSE_ERROR)
return;
if (state_ == INITIALIZING) {
MEDIA_LOG(ERROR, media_log_)
<< "MediaSource endOfStream before demuxer initialization completes "
"(before HAVE_METADATA) is treated as an error. This may also occur "
"as consequence of other MediaSource errors before HAVE_METADATA.";
ReportError_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
return;
}
bool old_waiting_for_data = IsSeekWaitingForData_Locked();
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->MarkEndOfStream();
}
CompletePendingReadsIfPossible();
// Give a chance to resume the pending seek process.
if (status != PIPELINE_OK) {
DCHECK(status == CHUNK_DEMUXER_ERROR_EOS_STATUS_DECODE_ERROR ||
status == CHUNK_DEMUXER_ERROR_EOS_STATUS_NETWORK_ERROR);
ReportError_Locked(status);
return;
}
ChangeState_Locked(ENDED);
DecreaseDurationIfNecessary();
if (old_waiting_for_data && !IsSeekWaitingForData_Locked() && seek_cb_)
RunSeekCB_Locked(PIPELINE_OK);
}
void ChunkDemuxer::UnmarkEndOfStream() {
DVLOG(1) << "UnmarkEndOfStream()";
base::AutoLock auto_lock(lock_);
DCHECK(state_ == ENDED || state_ == SHUTDOWN || state_ == PARSE_ERROR)
<< state_;
// At least ReportError_Locked()'s error reporting to Blink hops threads, so
// SourceBuffer may not be aware of media element error on another operation
// that might race to this point.
if (state_ == PARSE_ERROR || state_ == SHUTDOWN)
return;
ChangeState_Locked(INITIALIZED);
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->UnmarkEndOfStream();
}
}
void ChunkDemuxer::Shutdown() {
DVLOG(1) << "Shutdown()";
base::AutoLock auto_lock(lock_);
if (state_ == SHUTDOWN)
return;
ShutdownAllStreams();
ChangeState_Locked(SHUTDOWN);
if (seek_cb_)
RunSeekCB_Locked(PIPELINE_ERROR_ABORT);
}
void ChunkDemuxer::SetMemoryLimitsForTest(DemuxerStream::Type type,
size_t memory_limit) {
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->SetMemoryLimits(type, memory_limit);
}
}
void ChunkDemuxer::ChangeState_Locked(State new_state) {
lock_.AssertAcquired();
DVLOG(1) << "ChunkDemuxer::ChangeState_Locked() : "
<< state_ << " -> " << new_state;
// TODO(wolenetz): Change to DCHECK once less verification in release build is
// needed. See https://crbug.com/786975.
// Disallow changes from at or beyond PARSE_ERROR to below PARSE_ERROR.
CHECK(!(state_ >= PARSE_ERROR && new_state < PARSE_ERROR));
state_ = new_state;
}
ChunkDemuxer::~ChunkDemuxer() {
DCHECK_NE(state_, INITIALIZED);
}
void ChunkDemuxer::ReportError_Locked(PipelineStatus error) {
DVLOG(1) << "ReportError_Locked(" << error << ")";
lock_.AssertAcquired();
DCHECK(error != PIPELINE_OK);
ChangeState_Locked(PARSE_ERROR);
if (init_cb_) {
RunInitCB_Locked(error);
return;
}
ShutdownAllStreams();
if (seek_cb_) {
RunSeekCB_Locked(error);
return;
}
base::AutoUnlock auto_unlock(lock_);
host_->OnDemuxerError(error);
}
bool ChunkDemuxer::IsSeekWaitingForData_Locked() const {
lock_.AssertAcquired();
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
if (itr->second->IsSeekWaitingForData())
return true;
}
return false;
}
void ChunkDemuxer::OnSourceInitDone(
const std::string& source_id,
const StreamParser::InitParameters& params) {
DVLOG(1) << "OnSourceInitDone source_id=" << source_id
<< " duration=" << params.duration.InSecondsF();
lock_.AssertAcquired();
// TODO(wolenetz): Change these to DCHECKs once less verification in release
// build is needed. See https://crbug.com/786975.
CHECK(!pending_source_init_ids_.empty());
CHECK(IsValidId_Locked(source_id));
CHECK(pending_source_init_ids_.find(source_id) !=
pending_source_init_ids_.end());
CHECK(init_cb_);
CHECK_EQ(state_, INITIALIZING);
if (audio_streams_.empty() && video_streams_.empty()) {
ReportError_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
return;
}
if (!params.duration.is_zero() && duration_ == kNoTimestamp)
UpdateDuration(params.duration);
if (!params.timeline_offset.is_null()) {
if (!timeline_offset_.is_null() &&
params.timeline_offset != timeline_offset_) {
MEDIA_LOG(ERROR, media_log_)
<< "Timeline offset is not the same across all SourceBuffers.";
ReportError_Locked(DEMUXER_ERROR_COULD_NOT_OPEN);
return;
}
timeline_offset_ = params.timeline_offset;
}
if (params.liveness != StreamLiveness::kUnknown) {
for (const auto& s : audio_streams_)
s->SetLiveness(params.liveness);
for (const auto& s : video_streams_)
s->SetLiveness(params.liveness);
}
// Wait until all streams have initialized.
pending_source_init_ids_.erase(source_id);
if (!pending_source_init_ids_.empty())
return;
SeekAllSources(GetStartTime());
StartReturningData();
if (duration_ == kNoTimestamp)
duration_ = kInfiniteDuration;
// The demuxer is now initialized after the |start_timestamp_| was set.
// TODO(wolenetz): Change these to DCHECKs once less verification in release
// build is needed. See https://crbug.com/786975.
CHECK_EQ(state_, INITIALIZING);
ChangeState_Locked(INITIALIZED);
RunInitCB_Locked(PIPELINE_OK);
}
// static
MediaTrack::Id ChunkDemuxer::GenerateMediaTrackId() {
static unsigned g_track_count = 0;
return MediaTrack::Id(base::NumberToString(++g_track_count));
}
ChunkDemuxerStream* ChunkDemuxer::CreateDemuxerStream(
const std::string& source_id,
DemuxerStream::Type type) {
// New ChunkDemuxerStreams can be created only during initialization segment
// processing, which happens when a new chunk of data is appended and the
// lock_ must be held by ChunkDemuxer::RunSegmentParserLoop/AppendChunks.
lock_.AssertAcquired();
MediaTrack::Id media_track_id = GenerateMediaTrackId();
OwnedChunkDemuxerStreamVector* owning_vector = nullptr;
switch (type) {
case DemuxerStream::AUDIO:
owning_vector = &audio_streams_;
break;
case DemuxerStream::VIDEO:
owning_vector = &video_streams_;
break;
case DemuxerStream::UNKNOWN:
NOTREACHED();
}
std::unique_ptr<ChunkDemuxerStream> stream =
std::make_unique<ChunkDemuxerStream>(type, media_track_id);
DCHECK(track_id_to_demux_stream_map_.find(media_track_id) ==
track_id_to_demux_stream_map_.end());
track_id_to_demux_stream_map_[media_track_id] = stream.get();
id_to_streams_map_[source_id].push_back(stream.get());
stream->SetEnabled(owning_vector->empty(), base::TimeDelta());
owning_vector->push_back(std::move(stream));
return owning_vector->back().get();
}
bool ChunkDemuxer::IsValidId_Locked(const std::string& source_id) const {
lock_.AssertAcquired();
return source_state_map_.count(source_id) > 0u;
}
void ChunkDemuxer::UpdateDuration(base::TimeDelta new_duration) {
DCHECK(duration_ != new_duration ||
user_specified_duration_ != new_duration.InSecondsF());
user_specified_duration_ = -1;
duration_ = new_duration;
host_->SetDuration(new_duration);
}
void ChunkDemuxer::IncreaseDurationIfNecessary(base::TimeDelta new_duration) {
DCHECK(new_duration != kNoTimestamp);
DCHECK(new_duration != kInfiniteDuration);
// Per April 1, 2014 MSE spec editor's draft:
// https://dvcs.w3.org/hg/html-media/raw-file/d471a4412040/media-source/
// media-source.html#sourcebuffer-coded-frame-processing
// 5. If the media segment contains data beyond the current duration, then run
// the duration change algorithm with new duration set to the maximum of
// the current duration and the group end timestamp.
if (new_duration <= duration_)
return;
DVLOG(2) << __func__ << ": Increasing duration: " << duration_.InSecondsF()
<< " -> " << new_duration.InSecondsF();
UpdateDuration(new_duration);
}
void ChunkDemuxer::DecreaseDurationIfNecessary() {
lock_.AssertAcquired();
base::TimeDelta max_duration;
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
max_duration = std::max(max_duration,
itr->second->GetMaxBufferedDuration());
}
if (max_duration.is_zero())
return;
// Note: be careful to also check |user_specified_duration_|, which may have
// higher precision than |duration_|.
if (max_duration < duration_ ||
max_duration.InSecondsF() < user_specified_duration_) {
UpdateDuration(max_duration);
}
}
Ranges<base::TimeDelta> ChunkDemuxer::GetBufferedRanges() const {
base::AutoLock auto_lock(lock_);
return GetBufferedRanges_Locked();
}
Ranges<base::TimeDelta> ChunkDemuxer::GetBufferedRanges_Locked() const {
lock_.AssertAcquired();
bool ended = state_ == ENDED;
// TODO(acolwell): When we start allowing SourceBuffers that are not active,
// we'll need to update this loop to only add ranges from active sources.
SourceBufferState::RangesList ranges_list;
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
ranges_list.push_back(itr->second->GetBufferedRanges(duration_, ended));
}
return SourceBufferState::ComputeRangesIntersection(ranges_list, ended);
}
void ChunkDemuxer::StartReturningData() {
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->StartReturningData();
}
}
void ChunkDemuxer::AbortPendingReads_Locked() {
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->AbortReads();
}
}
void ChunkDemuxer::SeekAllSources(base::TimeDelta seek_time) {
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->Seek(seek_time);
}
}
void ChunkDemuxer::CompletePendingReadsIfPossible() {
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->CompletePendingReadIfPossible();
}
}
void ChunkDemuxer::ShutdownAllStreams() {
for (auto itr = source_state_map_.begin(); itr != source_state_map_.end();
++itr) {
itr->second->Shutdown();
}
}
void ChunkDemuxer::RunInitCB_Locked(PipelineStatus status) {
lock_.AssertAcquired();
DCHECK(init_cb_);
TRACE_EVENT_ASYNC_END1("media", "ChunkDemuxer::Initialize", this, "status",
PipelineStatusToString(status));
std::move(init_cb_).Run(status);
}
void ChunkDemuxer::RunSeekCB_Locked(PipelineStatus status) {
lock_.AssertAcquired();
DCHECK(seek_cb_);
TRACE_EVENT_ASYNC_END1("media", "ChunkDemuxer::Seek", this, "status",
PipelineStatusToString(status));
std::move(seek_cb_).Run(status);
}
} // namespace media