forked from WebKit/WebKit-http
-
Notifications
You must be signed in to change notification settings - Fork 143
/
Copy pathSourceBuffer.cpp
2040 lines (1678 loc) · 87.8 KB
/
SourceBuffer.cpp
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
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
* Copyright (C) 2013-2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "SourceBuffer.h"
#if ENABLE(MEDIA_SOURCE)
#include "AudioTrackList.h"
#include "Event.h"
#include "ExceptionCodePlaceholder.h"
#include "GenericEventQueue.h"
#include "HTMLMediaElement.h"
#include "InbandTextTrack.h"
#include "Logging.h"
#include "MediaDescription.h"
#include "MediaSample.h"
#include "MediaSource.h"
#include "SampleMap.h"
#include "SourceBufferPrivate.h"
#include "TextTrackList.h"
#include "TimeRanges.h"
#include "VideoTrackList.h"
#include <limits>
#include <map>
#include <runtime/JSCInlines.h>
#include <runtime/JSLock.h>
#include <runtime/VM.h>
#include <wtf/CurrentTime.h>
#include <wtf/NeverDestroyed.h>
#if !LOG_DISABLED
#include <wtf/text/StringBuilder.h>
#endif
namespace WebCore {
static const double ExponentialMovingAverageCoefficient = 0.1;
// Allow hasCurrentTime() to be off by as much as the length of a 24fps video frame
static const MediaTime& currentTimeFudgeFactor()
{
static NeverDestroyed<MediaTime> fudgeFactor(1, 24);
return fudgeFactor;
}
struct SourceBuffer::TrackBuffer {
MediaTime lastDecodeTimestamp;
MediaTime lastFrameDuration;
MediaTime highestPresentationTimestamp;
MediaTime lastEnqueuedPresentationTime;
MediaTime lastEnqueuedDecodeEndTime;
RefPtr<TimeRanges> m_buffered;
bool needRandomAccessFlag;
bool enabled;
bool needsReenqueueing;
SampleMap samples;
DecodeOrderSampleMap::MapType decodeQueue;
RefPtr<MediaDescription> description;
TrackBuffer()
: lastDecodeTimestamp(MediaTime::invalidTime())
, lastFrameDuration(MediaTime::invalidTime())
, highestPresentationTimestamp(MediaTime::invalidTime())
, lastEnqueuedPresentationTime(MediaTime::invalidTime())
, lastEnqueuedDecodeEndTime(MediaTime::invalidTime())
, m_buffered(TimeRanges::create())
, needRandomAccessFlag(true)
, enabled(false)
, needsReenqueueing(false)
{
}
};
Ref<SourceBuffer> SourceBuffer::create(Ref<SourceBufferPrivate>&& sourceBufferPrivate, MediaSource* source)
{
RefPtr<SourceBuffer> sourceBuffer(adoptRef(new SourceBuffer(WTFMove(sourceBufferPrivate), source)));
sourceBuffer->suspendIfNeeded();
return sourceBuffer.releaseNonNull();
}
SourceBuffer::SourceBuffer(Ref<SourceBufferPrivate>&& sourceBufferPrivate, MediaSource* source)
: ActiveDOMObject(source->scriptExecutionContext())
, m_private(WTFMove(sourceBufferPrivate))
, m_source(source)
, m_asyncEventQueue(*this)
, m_appendBufferTimer(*this, &SourceBuffer::appendBufferTimerFired)
#if ENABLE(VIDEO_TRACK)
, m_highestPresentationEndTimestamp(MediaTime::invalidTime())
#endif
, m_buffered(TimeRanges::create())
, m_appendState(WaitingForSegment)
, m_timeOfBufferingMonitor(monotonicallyIncreasingTime())
, m_bufferedSinceLastMonitor(0)
, m_averageBufferRate(0)
, m_reportedExtraMemoryCost(0)
, m_pendingRemoveStart(MediaTime::invalidTime())
, m_pendingRemoveEnd(MediaTime::invalidTime())
, m_removeTimer(*this, &SourceBuffer::removeTimerFired)
, m_updating(false)
, m_receivedFirstInitializationSegment(false)
, m_active(false)
, m_bufferFull(false)
, m_shouldRecalculateBuffered(false)
{
ASSERT(m_source);
m_private->setClient(this);
}
SourceBuffer::~SourceBuffer()
{
ASSERT(isRemoved());
m_private->setClient(nullptr);
}
PassRefPtr<TimeRanges> SourceBuffer::buffered(ExceptionCode& ec) const
{
// Section 3.1 buffered attribute steps.
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#attributes-1
// 1. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an
// INVALID_STATE_ERR exception and abort these steps.
if (isRemoved()) {
ec = INVALID_STATE_ERR;
return nullptr;
}
// Note: Steps 2-4 are handled by recalculateBuffered
if (m_shouldRecalculateBuffered)
recalculateBuffered();
// 5. Return the intersection ranges.
return m_buffered->copy();
}
const RefPtr<TimeRanges>& SourceBuffer::buffered() const
{
if (m_shouldRecalculateBuffered)
recalculateBuffered();
return m_buffered;
}
void SourceBuffer::invalidateBuffered()
{
m_shouldRecalculateBuffered = true;
// FIXME: for caching buffered in MediaSource should add here :
// m_source->invalidateBuffered();
}
void SourceBuffer::recalculateBuffered() const
{
// Section 3.1 buffered attribute steps.
m_shouldRecalculateBuffered = false;
// 2. Let highest end time be the largest track buffer ranges end time across all the track buffers managed by this SourceBuffer object.
MediaTime highestEndTime = MediaTime::zeroTime();
for (HashMap<AtomicString, TrackBuffer>::const_iterator::Values trackBuffer = m_trackBufferMap.values().begin(); trackBuffer != m_trackBufferMap.values().end(); ++trackBuffer) {
PlatformTimeRanges& trackRanges = trackBuffer->m_buffered->ranges();
if (trackRanges.length())
highestEndTime = std::max(highestEndTime, trackRanges.maximumBufferedTime());
}
// Return an empty range if all ranges are empty.
if (!highestEndTime) {
m_buffered = TimeRanges::create();
return;
}
// 3. Let intersection ranges equal a TimeRange object containing a single range from 0 to highest end time.
PlatformTimeRanges intersectionRanges(MediaTime::zeroTime(), highestEndTime);
// 4. For each track buffer managed by this SourceBuffer, run the following steps:
bool ended = m_source->readyState() == MediaSource::endedKeyword();
for (HashMap<AtomicString, TrackBuffer>::const_iterator::Values trackBuffer = m_trackBufferMap.values().begin(); trackBuffer != m_trackBufferMap.values().end(); ++trackBuffer) {
// 4.1 Let track ranges equal the track buffer ranges for the current track buffer.
PlatformTimeRanges trackRanges = trackBuffer->m_buffered->ranges();
// 4.2 If readyState is "ended", then set the end time on the last range in track ranges to highest end time.
if (ended)
trackRanges.add(trackRanges.maximumBufferedTime(), highestEndTime);
// 4.3 Let new intersection ranges equal the intersection between the intersection ranges and the track ranges.
// 4.4 Replace the ranges in intersection ranges with the new intersection ranges.
intersectionRanges.intersectWith(trackRanges);
}
m_buffered = TimeRanges::create(intersectionRanges);
}
double SourceBuffer::timestampOffset() const
{
#if ENABLE(VIDEO_TRACK)
return m_timestampOffset.toDouble();
#else
return m_timestampOffset;
#endif
}
void SourceBuffer::setTimestampOffset(double offset, ExceptionCode& ec)
{
// Section 3.1 timestampOffset attribute setter steps.
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#attributes-1
// 1. Let new timestamp offset equal the new value being assigned to this attribute.
// 2. If this object has been removed from the sourceBuffers attribute of the parent media source, then throw an
// INVALID_STATE_ERR exception and abort these steps.
// 3. If the updating attribute equals true, then throw an INVALID_STATE_ERR exception and abort these steps.
if (isRemoved() || m_updating) {
ec = INVALID_STATE_ERR;
return;
}
// 4. If the readyState attribute of the parent media source is in the "ended" state then run the following steps:
// 4.1 Set the readyState attribute of the parent media source to "open"
// 4.2 Queue a task to fire a simple event named sourceopen at the parent media source.
m_source->openIfInEndedState();
#if ENABLE(VIDEO_TRACK)
// 5. If the append state equals PARSING_MEDIA_SEGMENT, then throw an INVALID_STATE_ERR and abort these steps.
if (m_appendState == ParsingMediaSegment) {
ec = INVALID_STATE_ERR;
return;
}
// FIXME: Add step 6 text when mode attribute is implemented.
// 7. Update the attribute to the new value.
m_timestampOffset = MediaTime::createWithDouble(offset);
#else
// 7. Update the attribute to the new value.
m_timestampOffset = offset;
#endif
}
void SourceBuffer::appendBuffer(PassRefPtr<ArrayBuffer> data, ExceptionCode& ec)
{
// Section 3.2 appendBuffer()
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data
// 1. If data is null then throw an INVALID_ACCESS_ERR exception and abort these steps.
if (!data) {
ec = INVALID_ACCESS_ERR;
return;
}
appendBufferInternal(static_cast<unsigned char*>(data->data()), data->byteLength(), ec);
}
void SourceBuffer::appendBuffer(PassRefPtr<ArrayBufferView> data, ExceptionCode& ec)
{
// Section 3.2 appendBuffer()
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data
// 1. If data is null then throw an INVALID_ACCESS_ERR exception and abort these steps.
if (!data) {
ec = INVALID_ACCESS_ERR;
return;
}
appendBufferInternal(static_cast<unsigned char*>(data->baseAddress()), data->byteLength(), ec);
}
void SourceBuffer::resetParserState()
{
// Section 3.5.2 Reset Parser State algorithm steps.
// http://www.w3.org/TR/2014/CR-media-source-20140717/#sourcebuffer-reset-parser-state
// 1. If the append state equals PARSING_MEDIA_SEGMENT and the input buffer contains some complete coded frames,
// then run the coded frame processing algorithm until all of these complete coded frames have been processed.
// FIXME: If any implementation will work in pulling mode (instead of async push to SourceBufferPrivate, and forget)
// this should be handled somehow either here, or in m_private->abort();
// 2. Unset the last decode timestamp on all track buffers.
// 3. Unset the last frame duration on all track buffers.
// 4. Unset the highest presentation timestamp on all track buffers.
// 5. Set the need random access point flag on all track buffers to true.
for (auto& trackBufferPair : m_trackBufferMap.values()) {
trackBufferPair.lastDecodeTimestamp = MediaTime::invalidTime();
trackBufferPair.lastFrameDuration = MediaTime::invalidTime();
trackBufferPair.highestPresentationTimestamp = MediaTime::invalidTime();
trackBufferPair.needRandomAccessFlag = true;
}
// 6. Remove all bytes from the input buffer.
// Note: this is handled by abortIfUpdating()
// 7. Set append state to WAITING_FOR_SEGMENT.
m_appendState = WaitingForSegment;
m_private->abort();
}
void SourceBuffer::abort(ExceptionCode& ec)
{
// Section 3.2 abort() method steps.
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-abort-void
// 1. If this object has been removed from the sourceBuffers attribute of the parent media source
// then throw an INVALID_STATE_ERR exception and abort these steps.
// 2. If the readyState attribute of the parent media source is not in the "open" state
// then throw an INVALID_STATE_ERR exception and abort these steps.
if (isRemoved() || !m_source->isOpen()) {
ec = INVALID_STATE_ERR;
return;
}
// 3. If the sourceBuffer.updating attribute equals true, then run the following steps: ...
abortIfUpdating();
// 4. Run the reset parser state algorithm.
resetParserState();
// FIXME(229408) Add steps 5-6 update appendWindowStart & appendWindowEnd.
}
void SourceBuffer::remove(double start, double end, ExceptionCode& ec, bool sync)
{
remove(MediaTime::createWithDouble(start), MediaTime::createWithDouble(end), ec, sync);
}
void SourceBuffer::remove(const MediaTime& start, const MediaTime& end, ExceptionCode& ec, bool sync)
{
LOG(MediaSource, "SourceBuffer::remove(%p) - start(%lf), end(%lf)", this, start.toDouble(), end.toDouble());
// Section 3.2 remove() method steps.
// 1. If start is negative or greater than duration, then throw an InvalidAccessError exception and abort these steps.
// 2. If end is less than or equal to start, then throw an InvalidAccessError exception and abort these steps.
if (start < MediaTime::zeroTime() || (m_source && (!m_source->duration().isValid() || start > m_source->duration())) || end <= start) {
ec = INVALID_ACCESS_ERR;
return;
}
// 3. If this object has been removed from the sourceBuffers attribute of the parent media source then throw an
// InvalidStateError exception and abort these steps.
// 4. If the updating attribute equals true, then throw an InvalidStateError exception and abort these steps.
if (isRemoved() || m_updating) {
ec = INVALID_STATE_ERR;
return;
}
// 5. If the readyState attribute of the parent media source is in the "ended" state then run the following steps:
// 5.1. Set the readyState attribute of the parent media source to "open"
// 5.2. Queue a task to fire a simple event named sourceopen at the parent media source .
m_source->openIfInEndedState();
// 6. Set the updating attribute to true.
m_updating = true;
// 7. Queue a task to fire a simple event named updatestart at this SourceBuffer object.
scheduleEvent(eventNames().updatestartEvent);
// 8. Return control to the caller and run the rest of the steps asynchronously.
m_pendingRemoveStart = start;
m_pendingRemoveEnd = end;
if (sync) {
removeTimerFired();
} else {
m_removeTimer.startOneShot(0);
}
}
void SourceBuffer::abortIfUpdating()
{
// Section 3.2 abort() method step 3 substeps.
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-abort-void
if (!m_updating)
return;
// 3.1. Abort the buffer append and stream append loop algorithms if they are running.
m_appendBufferTimer.stop();
m_pendingAppendData.clear();
m_removeTimer.stop();
m_pendingRemoveStart = MediaTime::invalidTime();
m_pendingRemoveEnd = MediaTime::invalidTime();
// 3.2. Set the updating attribute to false.
m_updating = false;
// 3.3. Queue a task to fire a simple event named abort at this SourceBuffer object.
scheduleEvent(eventNames().abortEvent);
// 3.4. Queue a task to fire a simple event named updateend at this SourceBuffer object.
scheduleEvent(eventNames().updateendEvent);
}
void SourceBuffer::removedFromMediaSource()
{
if (isRemoved())
return;
abortIfUpdating();
for (auto& trackBufferPair : m_trackBufferMap.values()) {
trackBufferPair.samples.clear();
trackBufferPair.decodeQueue.clear();
}
m_private->removedFromMediaSource();
m_source = nullptr;
}
void SourceBuffer::seekToTime(const MediaTime& time)
{
LOG(MediaSource, "SourceBuffer::seekToTime(%p) - time(%s)", this, toString(time).utf8().data());
for (auto& trackBufferPair : m_trackBufferMap) {
TrackBuffer& trackBuffer = trackBufferPair.value;
const AtomicString& trackID = trackBufferPair.key;
trackBuffer.needsReenqueueing = true;
reenqueueMediaForTime(trackBuffer, trackID, time);
}
}
MediaTime SourceBuffer::sourceBufferPrivateFastSeekTimeForMediaTime(SourceBufferPrivate*, const MediaTime& targetTime, const MediaTime& negativeThreshold, const MediaTime& positiveThreshold)
{
MediaTime seekTime = targetTime;
MediaTime lowerBoundTime = targetTime - negativeThreshold;
MediaTime upperBoundTime = targetTime + positiveThreshold;
for (auto& trackBuffer : m_trackBufferMap.values()) {
// Find the sample which contains the target time time.
auto futureSyncSampleIterator = trackBuffer.samples.decodeOrder().findSyncSampleAfterPresentationTime(targetTime, positiveThreshold);
auto pastSyncSampleIterator = trackBuffer.samples.decodeOrder().findSyncSamplePriorToPresentationTime(targetTime, negativeThreshold);
auto upperBound = trackBuffer.samples.decodeOrder().end();
auto lowerBound = trackBuffer.samples.decodeOrder().rend();
if (futureSyncSampleIterator == upperBound && pastSyncSampleIterator == lowerBound)
continue;
MediaTime futureSeekTime = MediaTime::positiveInfiniteTime();
if (futureSyncSampleIterator != upperBound) {
RefPtr<MediaSample>& sample = futureSyncSampleIterator->second;
futureSeekTime = sample->presentationTime();
}
MediaTime pastSeekTime = MediaTime::negativeInfiniteTime();
if (pastSyncSampleIterator != lowerBound) {
RefPtr<MediaSample>& sample = pastSyncSampleIterator->second;
pastSeekTime = sample->presentationTime();
}
MediaTime trackSeekTime = abs(targetTime - futureSeekTime) < abs(targetTime - pastSeekTime) ? futureSeekTime : pastSeekTime;
if (abs(targetTime - trackSeekTime) > abs(targetTime - seekTime))
seekTime = trackSeekTime;
}
return seekTime;
}
bool SourceBuffer::hasPendingActivity() const
{
return m_source || m_asyncEventQueue.hasPendingEvents();
}
void SourceBuffer::stop()
{
m_asyncEventQueue.close();
m_appendBufferTimer.stop();
m_removeTimer.stop();
}
bool SourceBuffer::canSuspendForDocumentSuspension() const
{
return !hasPendingActivity();
}
const char* SourceBuffer::activeDOMObjectName() const
{
return "SourceBuffer";
}
bool SourceBuffer::isRemoved() const
{
return !m_source;
}
void SourceBuffer::scheduleEvent(const AtomicString& eventName)
{
RefPtr<Event> event = Event::create(eventName, false, false);
event->setTarget(this);
m_asyncEventQueue.enqueueEvent(event.release());
}
void SourceBuffer::appendBufferInternal(unsigned char* data, unsigned size, ExceptionCode& ec)
{
// Section 3.2 appendBuffer()
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-appendBuffer-void-ArrayBufferView-data
// Step 1 is enforced by the caller.
// 2. Run the prepare append algorithm.
// Section 3.5.4 Prepare AppendAlgorithm
// 1. If the SourceBuffer has been removed from the sourceBuffers attribute of the parent media source
// then throw an INVALID_STATE_ERR exception and abort these steps.
// 2. If the updating attribute equals true, then throw an INVALID_STATE_ERR exception and abort these steps.
if (isRemoved() || m_updating) {
ec = INVALID_STATE_ERR;
return;
}
// 3. If the readyState attribute of the parent media source is in the "ended" state then run the following steps:
// 3.1. Set the readyState attribute of the parent media source to "open"
// 3.2. Queue a task to fire a simple event named sourceopen at the parent media source .
m_source->openIfInEndedState();
// 4. Run the coded frame eviction algorithm.
evictCodedFrames(size);
// 5. If the buffer full flag equals true, then throw a QUOTA_EXCEEDED_ERR exception and abort these step.
if (m_bufferFull) {
LOG(MediaSource, "SourceBuffer::appendBufferInternal(%p) - buffer full, failing with QUOTA_EXCEEDED_ERR error", this);
ec = QUOTA_EXCEEDED_ERR;
scheduleEvent(eventNames().updatestartEvent);
scheduleEvent(eventNames().updateEvent);
scheduleEvent(eventNames().updateendEvent);
return;
}
// NOTE: Return to 3.2 appendBuffer()
// 3. Add data to the end of the input buffer.
m_pendingAppendData.append(data, size);
// 4. Set the updating attribute to true.
m_updating = true;
// 5. Queue a task to fire a simple event named updatestart at this SourceBuffer object.
scheduleEvent(eventNames().updatestartEvent);
// 6. Asynchronously run the buffer append algorithm.
m_appendBufferTimer.startOneShot(0);
reportExtraMemoryAllocated();
}
void SourceBuffer::appendBufferTimerFired()
{
if (isRemoved())
return;
ASSERT(m_updating);
// Section 3.5.5 Buffer Append Algorithm
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-buffer-append
// 1. Run the segment parser loop algorithm.
size_t appendSize = m_pendingAppendData.size();
if (!appendSize) {
// Resize buffer for 0 byte appends so we always have a valid pointer.
// We need to convey all appends, even 0 byte ones to |m_private| so
// that it can clear its end of stream state if necessary.
m_pendingAppendData.resize(1);
}
// Section 3.5.1 Segment Parser Loop
// https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#sourcebuffer-segment-parser-loop
// When the segment parser loop algorithm is invoked, run the following steps:
// 1. Loop Top: If the input buffer is empty, then jump to the need more data step below.
if (!m_pendingAppendData.size()) {
sourceBufferPrivateAppendComplete(&m_private.get(), AppendSucceeded);
return;
}
m_private->append(m_pendingAppendData.data(), appendSize);
m_pendingAppendData.clear();
}
void SourceBuffer::sourceBufferPrivateAppendComplete(SourceBufferPrivate*, AppendResult result)
{
if (isRemoved())
return;
#if USE(GSTREAMER)
// METRO FIXME: Remove some small gaps (less than lastFrameDuration) from reported buffered region.
for (HashMap<AtomicString, TrackBuffer>::iterator
it = m_trackBufferMap.begin(),
itEnd = m_trackBufferMap.end();
it != itEnd; ++it) {
TrackBuffer& trackBuffer = it->value;
const MediaTime& lastFrameDuration = trackBuffer.lastFrameDuration;
if (!lastFrameDuration.isValid())
continue;
PlatformTimeRanges& trackRanges = trackBuffer.m_buffered->ranges();
MediaTime microsecond(1, 1000000);
for (int i = trackRanges.length() - 1; i > 0; --i) {
const MediaTime priorEnd = trackRanges.end(i - 1);
const MediaTime currStart = trackRanges.start(i);
const MediaTime delta = currStart - priorEnd;
if (delta > MediaTime::zeroTime() && delta <= lastFrameDuration) {
trackBuffer.m_buffered->add(priorEnd.toDouble(), (currStart + microsecond).toDouble());
}
}
}
invalidateBuffered();
#endif
// Update buffered cached value
buffered();
// Section 3.5.5 Buffer Append Algorithm, ctd.
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#sourcebuffer-buffer-append
// 2. If the input buffer contains bytes that violate the SourceBuffer byte stream format specification,
// then run the end of stream algorithm with the error parameter set to "decode" and abort this algorithm.
if (result == ParsingFailed) {
LOG(MediaSource, "SourceBuffer::sourceBufferPrivateAppendComplete(%p) - result = ParsingFailed", this);
m_source->streamEndedWithError(decodeError(), IgnorableExceptionCode());
return;
}
// NOTE: Steps 3 - 6 enforced by sourceBufferPrivateDidReceiveInitializationSegment() and
// sourceBufferPrivateDidReceiveSample below.
// 7. Need more data: Return control to the calling algorithm.
invalidateBuffered();
// NOTE: return to Section 3.5.5
// 2.If the segment parser loop algorithm in the previous step was aborted, then abort this algorithm.
if (result != AppendSucceeded)
return;
// 3. Set the updating attribute to false.
m_updating = false;
// 4. Queue a task to fire a simple event named update at this SourceBuffer object.
scheduleEvent(eventNames().updateEvent);
// 5. Queue a task to fire a simple event named updateend at this SourceBuffer object.
scheduleEvent(eventNames().updateendEvent);
if (m_source)
m_source->monitorSourceBuffers();
MediaTime currentMediaTime = m_source->currentTime();
for (auto& trackBufferPair : m_trackBufferMap) {
TrackBuffer& trackBuffer = trackBufferPair.value;
const AtomicString& trackID = trackBufferPair.key;
if (trackBuffer.needsReenqueueing) {
LOG(MediaSource, "SourceBuffer::sourceBufferPrivateAppendComplete(%p) - reenqueuing at time (%s)", this, toString(currentMediaTime).utf8().data());
reenqueueMediaForTime(trackBuffer, trackID, currentMediaTime);
} else
provideMediaData(trackBuffer, trackID);
}
reportExtraMemoryAllocated();
if (extraMemoryCost() > this->maximumBufferSize())
m_bufferFull = true;
LOG(MediaSource, "SourceBuffer::sourceBufferPrivateAppendComplete(%p) - buffered = %s", this, toString(m_buffered->ranges()).utf8().data());
}
void SourceBuffer::sourceBufferPrivateDidReceiveRenderingError(SourceBufferPrivate*, int error)
{
#if LOG_DISABLED
UNUSED_PARAM(error);
#endif
LOG(MediaSource, "SourceBuffer::sourceBufferPrivateDidReceiveRenderingError(%p) - result = %i", this, error);
if (!isRemoved())
m_source->streamEndedWithError(decodeError(), IgnorableExceptionCode());
}
static bool decodeTimeComparator(const PresentationOrderSampleMap::MapType::value_type& a, const PresentationOrderSampleMap::MapType::value_type& b)
{
return a.second->decodeTime() < b.second->decodeTime();
}
static PassRefPtr<TimeRanges> removeSamplesFromTrackBuffer(const DecodeOrderSampleMap::MapType& samples, SourceBuffer::TrackBuffer& trackBuffer, const SourceBuffer* buffer, const char* logPrefix)
{
#if !LOG_DISABLED
double earliestSample = std::numeric_limits<double>::infinity();
double latestSample = 0;
size_t bytesRemoved = 0;
#else
UNUSED_PARAM(logPrefix);
UNUSED_PARAM(buffer);
#endif
RefPtr<TimeRanges> erasedRanges = TimeRanges::create();
MediaTime microsecond(1, 1000000);
for (auto sampleIt : samples) {
const DecodeOrderSampleMap::KeyType& decodeKey = sampleIt.first;
#if !LOG_DISABLED
size_t startBufferSize = trackBuffer.samples.sizeInBytes();
#endif
RefPtr<MediaSample>& sample = sampleIt.second;
LOG(MediaSource, "SourceBuffer::%s(%p) - removing sample(%s)", logPrefix, buffer, toString(*sampleIt.second).utf8().data());
// Remove the erased samples from the TrackBuffer sample map.
trackBuffer.samples.removeSample(sample.get());
// Also remove the erased samples from the TrackBuffer decodeQueue.
trackBuffer.decodeQueue.erase(decodeKey);
double startTime = sample->presentationTime().toDouble();
double endTime = startTime + (sample->duration() + microsecond).toDouble();
erasedRanges->add(startTime, endTime);
#if !LOG_DISABLED
bytesRemoved += startBufferSize - trackBuffer.samples.sizeInBytes();
if (startTime < earliestSample)
earliestSample = startTime;
if (endTime > latestSample)
latestSample = endTime;
#endif
}
#if !LOG_DISABLED
if (bytesRemoved)
LOG(MediaSource, "SourceBuffer::%s(%p) removed %zu bytes, start(%lf), end(%lf)", logPrefix, buffer, bytesRemoved, earliestSample, latestSample);
#endif
return erasedRanges.release();
}
void SourceBuffer::removeCodedFrames(const MediaTime& start, const MediaTime& end)
{
LOG(MediaSource, "SourceBuffer::removeCodedFrames(%p) - start(%s), end(%s)", this, toString(start).utf8().data(), toString(end).utf8().data());
// 3.5.9 Coded Frame Removal Algorithm
// https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#sourcebuffer-coded-frame-removal
// 1. Let start be the starting presentation timestamp for the removal range.
MediaTime durationMediaTime = m_source->duration();
MediaTime currentMediaTime = m_source->currentTime();
// 2. Let end be the end presentation timestamp for the removal range.
// 3. For each track buffer in this source buffer, run the following steps:
for (auto& iter : m_trackBufferMap) {
TrackBuffer& trackBuffer = iter.value;
// 3.1. Let remove end timestamp be the current value of duration
// 3.2 If this track buffer has a random access point timestamp that is greater than or equal to end, then update
// remove end timestamp to that random access point timestamp.
// NOTE: findSyncSampleAfterPresentationTime will return the next sync sample on or after the presentation time
// or decodeOrder().end() if no sync sample exists after that presentation time.
DecodeOrderSampleMap::iterator removeDecodeEnd = trackBuffer.samples.decodeOrder().findSyncSampleAfterPresentationTime(end);
PresentationOrderSampleMap::iterator removePresentationEnd;
if (removeDecodeEnd == trackBuffer.samples.decodeOrder().end())
removePresentationEnd = trackBuffer.samples.presentationOrder().end();
else
removePresentationEnd = trackBuffer.samples.presentationOrder().findSampleWithPresentationTime(removeDecodeEnd->second->presentationTime());
PresentationOrderSampleMap::iterator removePresentationStart = trackBuffer.samples.presentationOrder().findSampleOnOrAfterPresentationTime(start);
if (removePresentationStart == removePresentationEnd)
continue;
// 3.3 Remove all media data, from this track buffer, that contain starting timestamps greater than or equal to
// start and less than the remove end timestamp.
// NOTE: frames must be removed in decode order, so that all dependant frames between the frame to be removed
// and the next sync sample frame are removed. But we must start from the first sample in decode order, not
// presentation order.
PresentationOrderSampleMap::iterator minDecodeTimeIter = std::min_element(removePresentationStart, removePresentationEnd, decodeTimeComparator);
DecodeOrderSampleMap::KeyType decodeKey(minDecodeTimeIter->second->decodeTime(), minDecodeTimeIter->second->presentationTime());
DecodeOrderSampleMap::iterator removeDecodeStart = trackBuffer.samples.decodeOrder().findSampleWithDecodeKey(decodeKey);
DecodeOrderSampleMap::MapType erasedSamples(removeDecodeStart, removeDecodeEnd);
RefPtr<TimeRanges> erasedRanges = removeSamplesFromTrackBuffer(erasedSamples, trackBuffer, this, "removeCodedFrames");
// GStreamer backend doesn't support re-enqueue without preceding flushing seek, so just avoid adding same data to pipeline
#if !USE(GSTREAMER)
// Only force the TrackBuffer to re-enqueue if the removed ranges overlap with enqueued and possibly
// not yet displayed samples.
if (trackBuffer.lastEnqueuedPresentationTime.isValid() && currentMediaTime < trackBuffer.lastEnqueuedPresentationTime) {
PlatformTimeRanges possiblyEnqueuedRanges(currentMediaTime, trackBuffer.lastEnqueuedPresentationTime);
possiblyEnqueuedRanges.intersectWith(erasedRanges->ranges());
if (possiblyEnqueuedRanges.length())
trackBuffer.needsReenqueueing = true;
}
#endif
erasedRanges->invert();
trackBuffer.m_buffered->intersectWith(*erasedRanges);
// 3.4 If this object is in activeSourceBuffers, the current playback position is greater than or equal to start
// and less than the remove end timestamp, and HTMLMediaElement.readyState is greater than HAVE_METADATA, then set
// the HTMLMediaElement.readyState attribute to HAVE_METADATA and stall playback.
if (m_active && currentMediaTime >= start && currentMediaTime < end && m_private->readyState() > MediaPlayer::HaveMetadata)
m_private->setReadyState(MediaPlayer::HaveMetadata);
}
invalidateBuffered();
// 4. If buffer full flag equals true and this object is ready to accept more bytes, then set the buffer full flag to false.
// No-op
LOG(MediaSource, "SourceBuffer::removeCodedFrames(%p) - buffered = %s", this, toString(m_buffered->ranges()).utf8().data());
}
void SourceBuffer::removeTimerFired()
{
ASSERT(m_updating);
ASSERT(m_pendingRemoveStart.isValid());
ASSERT(m_pendingRemoveStart < m_pendingRemoveEnd);
// Section 3.2 remove() method steps
// https://dvcs.w3.org/hg/html-media/raw-file/default/media-source/media-source.html#widl-SourceBuffer-remove-void-double-start-double-end
// 9. Run the coded frame removal algorithm with start and end as the start and end of the removal range.
removeCodedFrames(m_pendingRemoveStart, m_pendingRemoveEnd);
// 10. Set the updating attribute to false.
m_updating = false;
m_pendingRemoveStart = MediaTime::invalidTime();
m_pendingRemoveEnd = MediaTime::invalidTime();
// 11. Queue a task to fire a simple event named update at this SourceBuffer object.
scheduleEvent(eventNames().updateEvent);
// 12. Queue a task to fire a simple event named updateend at this SourceBuffer object.
scheduleEvent(eventNames().updateendEvent);
}
void SourceBuffer::evictCodedFrames(size_t newDataSize)
{
// 3.5.13 Coded Frame Eviction Algorithm
// http://www.w3.org/TR/media-source/#sourcebuffer-coded-frame-eviction
if (isRemoved())
return;
// This algorithm is run to free up space in this source buffer when new data is appended.
// 1. Let new data equal the data that is about to be appended to this SourceBuffer.
// 2. If the buffer full flag equals false, then abort these steps.
if (!m_bufferFull)
return;
size_t maximumBufferSize = this->maximumBufferSize();
// Check if app has removed enough already
if (extraMemoryCost() + newDataSize < maximumBufferSize) {
m_bufferFull = false;
return;
}
// 3. Let removal ranges equal a list of presentation time ranges that can be evicted from
// the presentation to make room for the new data.
// NOTE: begin by removing data from the beginning of the buffered ranges, 30 seconds at
// a time, up to 30 seconds before currentTime.
MediaTime thirtySeconds = MediaTime(30, 1);
MediaTime currentTime = m_source->currentTime();
MediaTime maximumRangeEnd = currentTime - thirtySeconds;
#if !LOG_DISABLED
LOG(MediaSource, "SourceBuffer::evictCodedFrames(%p) - currentTime = %lf, require %zu bytes, maximum buffer size is %zu", this, m_source->currentTime().toDouble(), extraMemoryCost() + newDataSize, maximumBufferSize);
size_t initialBufferedSize = extraMemoryCost();
#endif
MediaTime rangeStart = MediaTime::zeroTime();
MediaTime rangeEnd = rangeStart + thirtySeconds;
while (rangeStart < maximumRangeEnd) {
// 4. For each range in removal ranges, run the coded frame removal algorithm with start and
// end equal to the removal range start and end timestamp respectively.
removeCodedFrames(rangeStart, std::min(rangeEnd, maximumRangeEnd));
if (extraMemoryCost() + newDataSize < maximumBufferSize) {
m_bufferFull = false;
break;
}
rangeStart += thirtySeconds;
rangeEnd += thirtySeconds;
}
if (!m_bufferFull) {
LOG(MediaSource, "SourceBuffer::evictCodedFrames(%p) - evicted %zu bytes", this, initialBufferedSize - extraMemoryCost());
return;
}
// If there still isn't enough free space and there buffers in time ranges after the current range (ie. there is a gap after
// the current buffered range), delete 30 seconds at a time from duration back to the current time range or 30 seconds after
// currenTime whichever we hit first.
auto buffered = m_buffered->ranges();
size_t currentTimeRange = buffered.find(currentTime);
if (currentTimeRange != notFound && currentTimeRange == buffered.length() - 1) {
LOG(MediaSource, "SourceBuffer::evictCodedFrames(%p) - evicted %zu bytes but FAILED to free enough", this, initialBufferedSize - extraMemoryCost());
return;
}
MediaTime minimumRangeStart = currentTime + thirtySeconds;
rangeEnd = m_source->duration().isPositiveInfinite()?buffered.maximumBufferedTime():m_source->duration();
rangeStart = rangeEnd - thirtySeconds;
while (rangeStart > minimumRangeStart) {
if (currentTimeRange != notFound) {
// Do not evict data from the time range that contains currentTime.
size_t startTimeRange = buffered.find(rangeStart);
if (startTimeRange == currentTimeRange) {
size_t endTimeRange = buffered.find(rangeEnd);
if (endTimeRange == currentTimeRange)
break;
rangeEnd = buffered.start(endTimeRange);
}
}
// 4. For each range in removal ranges, run the coded frame removal algorithm with start and
// end equal to the removal range start and end timestamp respectively.
removeCodedFrames(std::max(minimumRangeStart, rangeStart), rangeEnd);
if (extraMemoryCost() + newDataSize < maximumBufferSize) {
m_bufferFull = false;
break;
}
rangeStart -= thirtySeconds;
rangeEnd -= thirtySeconds;
}
LOG(MediaSource, "SourceBuffer::evictCodedFrames(%p) - evicted %zu bytes%s", this, initialBufferedSize - extraMemoryCost(), m_bufferFull ? "" : " but FAILED to free enough");
}
size_t SourceBuffer::maxBufferSizeVideo = 0;
size_t SourceBuffer::maxBufferSizeAudio = 0;
size_t SourceBuffer::maxBufferSizeText = 0;
static void maximumBufferSizeDefaults(size_t& maxBufferSizeVideo, size_t& maxBufferSizeAudio, size_t& maxBufferSizeText)
{
// Syntax: Case insensitive, full type (audio, video, text), compact type (a, v, t),
// wildcard (*), unit multipliers (M=Mb, K=Kb, <empty>=bytes).
// Examples: MSE_MAX_BUFFER_SIZE='V:50M,audio:12k,TeXT:500K'
// MSE_MAX_BUFFER_SIZE='*:100M'
// MSE_MAX_BUFFER_SIZE='video:90M,T:100000'
String s(getenv("MSE_MAX_BUFFER_SIZE"));
if (!s.isEmpty()) {
Vector<String> entries;
s.split(',', false, entries);
for (const String& entry : entries) {
Vector<String> keyvalue;
entry.split(':', false, keyvalue);
if (keyvalue.size() != 2)
continue;
String key = keyvalue[0].stripWhiteSpace().lower();
String value = keyvalue[1].stripWhiteSpace().lower();
size_t units = 1;
if (value.endsWith('k'))
units = 1024;
else if (value.endsWith('m'))
units = 1024 * 1024;
if (units != 1)
value = value.substring(0, value.length()-1);
bool ok = false;
size_t size = size_t(value.toUInt64(&ok));
if (!ok)
continue;
if (key == "a" || key == "audio" || key == "*")
maxBufferSizeAudio = size * units;
if (key == "v" || key == "video" || key == "*")
maxBufferSizeVideo = size * units;
if (key == "t" || key == "text" || key == "*")
maxBufferSizeText = size * units;
}
}
if (maxBufferSizeAudio == 0)
maxBufferSizeAudio = 3 * 1024 * 1024;
if (maxBufferSizeVideo == 0)
maxBufferSizeVideo = 30 * 1024 * 1024;
if (maxBufferSizeText == 0)
maxBufferSizeText = 1 * 1024 * 1024;
}
size_t SourceBuffer::maximumBufferSize() const
{
if (isRemoved())
return 0;
if (!maxBufferSizeVideo)
maximumBufferSizeDefaults(maxBufferSizeVideo, maxBufferSizeAudio, maxBufferSizeText);