-
Notifications
You must be signed in to change notification settings - Fork 437
Expand file tree
/
Copy pathmaster-playlist-controller.js
More file actions
1995 lines (1665 loc) · 65.1 KB
/
master-playlist-controller.js
File metadata and controls
1995 lines (1665 loc) · 65.1 KB
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
/**
* @file master-playlist-controller.js
*/
import window from 'global/window';
import PlaylistLoader from './playlist-loader';
import DashPlaylistLoader from './dash-playlist-loader';
import { isEnabled, isLowestEnabledRendition } from './playlist.js';
import SegmentLoader from './segment-loader';
import SourceUpdater from './source-updater';
import VTTSegmentLoader from './vtt-segment-loader';
import * as Ranges from './ranges';
import videojs from 'video.js';
import { updateAdCues } from './ad-cue-tags';
import SyncController from './sync-controller';
import TimelineChangeController from './timeline-change-controller';
import Decrypter from 'worker!./decrypter-worker.js';
import Config from './config';
import {
parseCodecs,
browserSupportsCodec,
muxerSupportsCodec,
DEFAULT_AUDIO_CODEC,
DEFAULT_VIDEO_CODEC
} from '@videojs/vhs-utils/es/codecs.js';
import { codecsForPlaylist, unwrapCodecList, codecCount } from './util/codecs.js';
import { createMediaTypes, setupMediaGroups } from './media-groups';
import logger from './util/logger';
import MediaGroupController from './media-group-controller.js';
const ABORT_EARLY_BLACKLIST_SECONDS = 60 * 2;
let Vhs;
// SegmentLoader stats that need to have each loader's
// values summed to calculate the final value
const loaderStats = [
'mediaRequests',
'mediaRequestsAborted',
'mediaRequestsTimedout',
'mediaRequestsErrored',
'mediaTransferDuration',
'mediaBytesTransferred',
'mediaAppends'
];
const sumLoaderStat = function(stat) {
return this.audioSegmentLoader_[stat] +
this.mainSegmentLoader_[stat];
};
const shouldSwitchToMedia = function({
currentPlaylist,
buffered,
currentTime,
nextPlaylist,
bufferLowWaterLine,
bufferHighWaterLine,
duration,
experimentalBufferBasedABR,
log
}) {
// we have no other playlist to switch to
if (!nextPlaylist) {
videojs.log.warn('We received no playlist to switch to. Please check your stream.');
return false;
}
const sharedLogLine = `allowing switch ${currentPlaylist && currentPlaylist.id || 'null'} -> ${nextPlaylist.id}`;
if (!currentPlaylist) {
log(`${sharedLogLine} as current playlist is not set`);
return true;
}
// no need to switch if playlist is the same
if (nextPlaylist.id === currentPlaylist.id) {
return false;
}
// determine if current time is in a buffered range.
const isBuffered = Boolean(Ranges.findRange(buffered, currentTime).length);
// If the playlist is live, then we want to not take low water line into account.
// This is because in LIVE, the player plays 3 segments from the end of the
// playlist, and if `BUFFER_LOW_WATER_LINE` is greater than the duration availble
// in those segments, a viewer will never experience a rendition upswitch.
if (!currentPlaylist.endList) {
// For LLHLS live streams, don't switch renditions before playback has started, as it almost
// doubles the time to first playback.
if (!isBuffered && typeof currentPlaylist.partTargetDuration === 'number') {
log(`not ${sharedLogLine} as current playlist is live llhls, but currentTime isn't in buffered.`);
return false;
}
log(`${sharedLogLine} as current playlist is live`);
return true;
}
const forwardBuffer = Ranges.timeAheadOf(buffered, currentTime);
const maxBufferLowWaterLine = experimentalBufferBasedABR ?
Config.EXPERIMENTAL_MAX_BUFFER_LOW_WATER_LINE : Config.MAX_BUFFER_LOW_WATER_LINE;
// For the same reason as LIVE, we ignore the low water line when the VOD
// duration is below the max potential low water line
if (duration < maxBufferLowWaterLine) {
log(`${sharedLogLine} as duration < max low water line (${duration} < ${maxBufferLowWaterLine})`);
return true;
}
const nextBandwidth = nextPlaylist.attributes.BANDWIDTH;
const currBandwidth = currentPlaylist.attributes.BANDWIDTH;
// when switching down, if our buffer is lower than the high water line,
// we can switch down
if (nextBandwidth < currBandwidth && (!experimentalBufferBasedABR || forwardBuffer < bufferHighWaterLine)) {
let logLine = `${sharedLogLine} as next bandwidth < current bandwidth (${nextBandwidth} < ${currBandwidth})`;
if (experimentalBufferBasedABR) {
logLine += ` and forwardBuffer < bufferHighWaterLine (${forwardBuffer} < ${bufferHighWaterLine})`;
}
log(logLine);
return true;
}
// and if our buffer is higher than the low water line,
// we can switch up
if ((!experimentalBufferBasedABR || nextBandwidth > currBandwidth) && forwardBuffer >= bufferLowWaterLine) {
let logLine = `${sharedLogLine} as forwardBuffer >= bufferLowWaterLine (${forwardBuffer} >= ${bufferLowWaterLine})`;
if (experimentalBufferBasedABR) {
logLine += ` and next bandwidth > current bandwidth (${nextBandwidth} > ${currBandwidth})`;
}
log(logLine);
return true;
}
log(`not ${sharedLogLine} as no switching criteria met`);
return false;
};
/**
* the master playlist controller controller all interactons
* between playlists and segmentloaders. At this time this mainly
* involves a master playlist and a series of audio playlists
* if they are available
*
* @class MasterPlaylistController
* @extends videojs.EventTarget
*/
export class MasterPlaylistController extends videojs.EventTarget {
constructor(options) {
super();
const {
src,
handleManifestRedirects,
withCredentials,
tech,
bandwidth,
externVhs,
useCueTags,
blacklistDuration,
enableLowInitialPlaylist,
sourceType,
cacheEncryptionKeys,
experimentalBufferBasedABR,
experimentalLeastPixelDiffSelector,
captionServices
} = options;
if (!src) {
throw new Error('A non-empty playlist URL or JSON manifest string is required');
}
let { maxPlaylistRetries } = options;
if (maxPlaylistRetries === null || typeof maxPlaylistRetries === 'undefined') {
maxPlaylistRetries = Infinity;
}
Vhs = externVhs;
this.experimentalBufferBasedABR = Boolean(experimentalBufferBasedABR);
this.experimentalLeastPixelDiffSelector = Boolean(experimentalLeastPixelDiffSelector);
this.withCredentials = withCredentials;
this.tech_ = tech;
this.vhs_ = tech.vhs;
this.sourceType_ = sourceType;
this.useCueTags_ = useCueTags;
this.blacklistDuration = blacklistDuration;
this.maxPlaylistRetries = maxPlaylistRetries;
this.enableLowInitialPlaylist = enableLowInitialPlaylist;
if (this.useCueTags_) {
this.cueTagsTrack_ = this.tech_.addTextTrack(
'metadata',
'ad-cues'
);
this.cueTagsTrack_.inBandMetadataTrackDispatchType = '';
}
this.requestOptions_ = {
withCredentials,
handleManifestRedirects,
maxPlaylistRetries,
timeout: null
};
this.on('error', this.pauseLoading);
this.mediaTypes_ = createMediaTypes();
this.mediaSource = new window.MediaSource();
this.handleDurationChange_ = this.handleDurationChange_.bind(this);
this.handleSourceOpen_ = this.handleSourceOpen_.bind(this);
this.handleSourceEnded_ = this.handleSourceEnded_.bind(this);
this.mediaSource.addEventListener('durationchange', this.handleDurationChange_);
// load the media source into the player
this.mediaSource.addEventListener('sourceopen', this.handleSourceOpen_);
this.mediaSource.addEventListener('sourceended', this.handleSourceEnded_);
// we don't have to handle sourceclose since dispose will handle termination of
// everything, and the MediaSource should not be detached without a proper disposal
this.seekable_ = videojs.createTimeRanges();
this.hasPlayed_ = false;
this.syncController_ = new SyncController(options);
this.segmentMetadataTrack_ = tech.addRemoteTextTrack({
kind: 'metadata',
label: 'segment-metadata'
}, false).track;
this.decrypter_ = new Decrypter();
this.sourceUpdater_ = new SourceUpdater(this.mediaSource);
this.inbandTextTracks_ = {};
this.timelineChangeController_ = new TimelineChangeController();
const segmentLoaderSettings = {
vhs: this.vhs_,
parse708captions: options.parse708captions,
captionServices,
mediaSource: this.mediaSource,
currentTime: this.tech_.currentTime.bind(this.tech_),
seekable: () => this.seekable(),
seeking: () => this.tech_.seeking(),
duration: () => this.duration(),
hasPlayed: () => this.hasPlayed_,
goalBufferLength: () => this.goalBufferLength(),
bandwidth,
syncController: this.syncController_,
decrypter: this.decrypter_,
sourceType: this.sourceType_,
inbandTextTracks: this.inbandTextTracks_,
cacheEncryptionKeys,
sourceUpdater: this.sourceUpdater_,
timelineChangeController: this.timelineChangeController_,
experimentalExactManifestTimings: options.experimentalExactManifestTimings
};
// The source type check not only determines whether a special DASH playlist loader
// should be used, but also covers the case where the provided src is a vhs-json
// manifest object (instead of a URL). In the case of vhs-json, the default
// PlaylistLoader should be used.
this.masterPlaylistLoader_ = this.sourceType_ === 'dash' ?
new DashPlaylistLoader(src, this.vhs_, this.requestOptions_) :
new PlaylistLoader(src, this.vhs_, this.requestOptions_);
this.setupMasterPlaylistLoaderListeners_();
this.mediaGroupController_ = new MediaGroupController({
tech,
mainPlaylistLoader: this.masterPlaylistLoader_
});
// setup segment loaders
// combined audio/video or just video when alternate audio track is selected
this.mainSegmentLoader_ =
new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
segmentMetadataTrack: this.segmentMetadataTrack_,
loaderType: 'main'
}), options);
// alternate audio track
this.audioSegmentLoader_ =
new SegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
loaderType: 'audio'
}), options);
this.subtitleSegmentLoader_ =
new VTTSegmentLoader(videojs.mergeOptions(segmentLoaderSettings, {
loaderType: 'vtt',
featuresNativeTextTracks: this.tech_.featuresNativeTextTracks
}), options);
this.setupSegmentLoaderListeners_();
if (this.experimentalBufferBasedABR) {
this.masterPlaylistLoader_.one('loadedplaylist', () => this.startABRTimer_());
this.tech_.on('pause', () => this.stopABRTimer_());
this.tech_.on('play', () => this.startABRTimer_());
}
// Create SegmentLoader stat-getters
// mediaRequests_
// mediaRequestsAborted_
// mediaRequestsTimedout_
// mediaRequestsErrored_
// mediaTransferDuration_
// mediaBytesTransferred_
// mediaAppends_
loaderStats.forEach((stat) => {
this[stat + '_'] = sumLoaderStat.bind(this, stat);
});
this.logger_ = logger('MPC');
this.triggeredFmp4Usage = false;
if (this.tech_.preload() === 'none') {
this.loadOnPlay_ = () => {
this.loadOnPlay_ = null;
this.masterPlaylistLoader_.load();
};
this.tech_.one('play', this.loadOnPlay_);
} else {
this.masterPlaylistLoader_.load();
}
this.timeToLoadedData__ = -1;
this.mainAppendsToLoadedData__ = -1;
this.audioAppendsToLoadedData__ = -1;
const event = this.tech_.preload() === 'none' ? 'play' : 'loadstart';
// start the first frame timer on loadstart or play (for preload none)
this.tech_.one(event, () => {
const timeToLoadedDataStart = Date.now();
this.tech_.one('loadeddata', () => {
this.timeToLoadedData__ = Date.now() - timeToLoadedDataStart;
this.mainAppendsToLoadedData__ = this.mainSegmentLoader_.mediaAppends;
this.audioAppendsToLoadedData__ = this.audioSegmentLoader_.mediaAppends;
});
});
}
mainAppendsToLoadedData_() {
return this.mainAppendsToLoadedData__;
}
audioAppendsToLoadedData_() {
return this.audioAppendsToLoadedData__;
}
appendsToLoadedData_() {
const main = this.mainAppendsToLoadedData_();
const audio = this.audioAppendsToLoadedData_();
if (main === -1 || audio === -1) {
return -1;
}
return main + audio;
}
timeToLoadedData_() {
return this.timeToLoadedData__;
}
/**
* Run selectPlaylist and switch to the new playlist if we should
*
* @private
*
*/
checkABR_() {
const nextPlaylist = this.selectPlaylist();
if (nextPlaylist && this.shouldSwitchToMedia_(nextPlaylist)) {
this.switchMedia_(nextPlaylist, 'abr');
}
}
switchMedia_(playlist, cause, delay) {
const oldMedia = this.media();
const oldId = oldMedia && (oldMedia.id || oldMedia.uri);
const newId = playlist.id || playlist.uri;
if (oldId && oldId !== newId) {
this.logger_(`switch media ${oldId} -> ${newId} from ${cause}`);
this.tech_.trigger({type: 'usage', name: `vhs-rendition-change-${cause}`});
}
this.masterPlaylistLoader_.media(playlist, delay);
}
/**
* Start a timer that periodically calls checkABR_
*
* @private
*/
startABRTimer_() {
this.stopABRTimer_();
this.abrTimer_ = window.setInterval(() => this.checkABR_(), 250);
}
/**
* Stop the timer that periodically calls checkABR_
*
* @private
*/
stopABRTimer_() {
// if we're scrubbing, we don't need to pause.
// This getter will be added to Video.js in version 7.11.
if (this.tech_.scrubbing && this.tech_.scrubbing()) {
return;
}
window.clearInterval(this.abrTimer_);
this.abrTimer_ = null;
}
/**
* Get a list of playlists for the currently selected audio playlist
*
* @return {Array} the array of audio playlists
*/
getAudioTrackPlaylists_() {
const master = this.master();
const defaultPlaylists = master && master.playlists || [];
// if we don't have any audio groups then we can only
// assume that the audio tracks are contained in masters
// playlist array, use that or an empty array.
if (!master || !master.mediaGroups || !master.mediaGroups.AUDIO) {
return defaultPlaylists;
}
const AUDIO = master.mediaGroups.AUDIO;
const groupKeys = Object.keys(AUDIO);
let track;
// get the current active track
if (Object.keys(this.mediaTypes_.AUDIO.groups).length) {
track = this.mediaTypes_.AUDIO.activeTrack();
// or get the default track from master if mediaTypes_ isn't setup yet
} else {
// default group is `main` or just the first group.
const defaultGroup = AUDIO.main || groupKeys.length && AUDIO[groupKeys[0]];
for (const label in defaultGroup) {
if (defaultGroup[label].default) {
track = {label};
break;
}
}
}
// no active track no playlists.
if (!track) {
return defaultPlaylists;
}
const playlists = [];
// get all of the playlists that are possible for the
// active track.
for (const group in AUDIO) {
if (AUDIO[group][track.label]) {
const properties = AUDIO[group][track.label];
if (properties.playlists && properties.playlists.length) {
playlists.push.apply(playlists, properties.playlists);
} else if (properties.uri) {
playlists.push(properties);
} else if (master.playlists.length) {
// if an audio group does not have a uri
// see if we have main playlists that use it as a group.
// if we do then add those to the playlists list.
for (let i = 0; i < master.playlists.length; i++) {
const playlist = master.playlists[i];
if (playlist.attributes && playlist.attributes.AUDIO && playlist.attributes.AUDIO === group) {
playlists.push(playlist);
}
}
}
}
}
if (!playlists.length) {
return defaultPlaylists;
}
return playlists;
}
/**
* Register event handlers on the master playlist loader. A helper
* function for construction time.
*
* @private
*/
setupMasterPlaylistLoaderListeners_() {
this.masterPlaylistLoader_.on('loadedmetadata', () => {
const media = this.masterPlaylistLoader_.media();
const requestTimeout = (media.targetDuration * 1.5) * 1000;
// If we don't have any more available playlists, we don't want to
// timeout the request.
if (isLowestEnabledRendition(this.masterPlaylistLoader_.master, this.masterPlaylistLoader_.media())) {
this.requestOptions_.timeout = 0;
} else {
this.requestOptions_.timeout = requestTimeout;
}
// if this isn't a live video and preload permits, start
// downloading segments
if (media.endList && this.tech_.preload() !== 'none') {
this.mainSegmentLoader_.playlist(media, this.requestOptions_);
this.mainSegmentLoader_.load();
}
setupMediaGroups({
sourceType: this.sourceType_,
segmentLoaders: {
AUDIO: this.audioSegmentLoader_,
SUBTITLES: this.subtitleSegmentLoader_,
main: this.mainSegmentLoader_
},
tech: this.tech_,
requestOptions: this.requestOptions_,
masterPlaylistLoader: this.masterPlaylistLoader_,
vhs: this.vhs_,
master: this.master(),
mediaTypes: this.mediaTypes_,
blacklistCurrentPlaylist: this.blacklistCurrentPlaylist.bind(this)
});
this.triggerPresenceUsage_(this.master(), media);
this.setupFirstPlay();
if (!this.mediaTypes_.AUDIO.activePlaylistLoader ||
this.mediaTypes_.AUDIO.activePlaylistLoader.media()) {
this.trigger('selectedinitialmedia');
} else {
// We must wait for the active audio playlist loader to
// finish setting up before triggering this event so the
// representations API and EME setup is correct
this.mediaTypes_.AUDIO.activePlaylistLoader.one('loadedmetadata', () => {
this.trigger('selectedinitialmedia');
});
}
});
this.masterPlaylistLoader_.on('loadedplaylist', () => {
if (this.loadOnPlay_) {
this.tech_.off('play', this.loadOnPlay_);
}
let updatedPlaylist = this.masterPlaylistLoader_.media();
if (!updatedPlaylist) {
// exclude any variants that are not supported by the browser before selecting
// an initial media as the playlist selectors do not consider browser support
this.excludeUnsupportedVariants_();
let selectedMedia;
if (this.enableLowInitialPlaylist) {
selectedMedia = this.selectInitialPlaylist();
}
if (!selectedMedia) {
selectedMedia = this.selectPlaylist();
}
if (!selectedMedia || !this.shouldSwitchToMedia_(selectedMedia)) {
return;
}
this.initialMedia_ = selectedMedia;
this.switchMedia_(this.initialMedia_, 'initial');
// Under the standard case where a source URL is provided, loadedplaylist will
// fire again since the playlist will be requested. In the case of vhs-json
// (where the manifest object is provided as the source), when the media
// playlist's `segments` list is already available, a media playlist won't be
// requested, and loadedplaylist won't fire again, so the playlist handler must be
// called on its own here.
const haveJsonSource = this.sourceType_ === 'vhs-json' && this.initialMedia_.segments;
if (!haveJsonSource) {
return;
}
updatedPlaylist = this.initialMedia_;
}
this.handleUpdatedMediaPlaylist(updatedPlaylist);
});
this.masterPlaylistLoader_.on('error', () => {
this.blacklistCurrentPlaylist(this.masterPlaylistLoader_.error);
});
this.masterPlaylistLoader_.on('mediachanging', () => {
this.mainSegmentLoader_.abort();
this.mainSegmentLoader_.pause();
});
this.masterPlaylistLoader_.on('mediachange', () => {
const media = this.masterPlaylistLoader_.media();
const requestTimeout = (media.targetDuration * 1.5) * 1000;
// If we don't have any more available playlists, we don't want to
// timeout the request.
if (isLowestEnabledRendition(this.masterPlaylistLoader_.master, this.masterPlaylistLoader_.media())) {
this.requestOptions_.timeout = 0;
} else {
this.requestOptions_.timeout = requestTimeout;
}
// TODO: Create a new event on the PlaylistLoader that signals
// that the segments have changed in some way and use that to
// update the SegmentLoader instead of doing it twice here and
// on `loadedplaylist`
this.mainSegmentLoader_.playlist(media, this.requestOptions_);
this.mainSegmentLoader_.load();
this.tech_.trigger({
type: 'mediachange',
bubbles: true
});
});
this.masterPlaylistLoader_.on('playlistunchanged', () => {
const updatedPlaylist = this.masterPlaylistLoader_.media();
// ignore unchanged playlists that have already been
// excluded for not-changing. We likely just have a really slowly updating
// playlist.
if (updatedPlaylist.lastExcludeReason_ === 'playlist-unchanged') {
return;
}
const playlistOutdated = this.stuckAtPlaylistEnd_(updatedPlaylist);
if (playlistOutdated) {
// Playlist has stopped updating and we're stuck at its end. Try to
// blacklist it and switch to another playlist in the hope that that
// one is updating (and give the player a chance to re-adjust to the
// safe live point).
this.blacklistCurrentPlaylist({
message: 'Playlist no longer updating.',
reason: 'playlist-unchanged'
});
// useful for monitoring QoS
this.tech_.trigger('playliststuck');
}
});
this.masterPlaylistLoader_.on('renditiondisabled', () => {
this.tech_.trigger({type: 'usage', name: 'vhs-rendition-disabled'});
this.tech_.trigger({type: 'usage', name: 'hls-rendition-disabled'});
});
this.masterPlaylistLoader_.on('renditionenabled', () => {
this.tech_.trigger({type: 'usage', name: 'vhs-rendition-enabled'});
this.tech_.trigger({type: 'usage', name: 'hls-rendition-enabled'});
});
}
/**
* Given an updated media playlist (whether it was loaded for the first time, or
* refreshed for live playlists), update any relevant properties and state to reflect
* changes in the media that should be accounted for (e.g., cues and duration).
*
* @param {Object} updatedPlaylist the updated media playlist object
*
* @private
*/
handleUpdatedMediaPlaylist(updatedPlaylist) {
if (this.useCueTags_) {
this.updateAdCues_(updatedPlaylist);
}
// TODO: Create a new event on the PlaylistLoader that signals
// that the segments have changed in some way and use that to
// update the SegmentLoader instead of doing it twice here and
// on `mediachange`
this.mainSegmentLoader_.playlist(updatedPlaylist, this.requestOptions_);
this.updateDuration(!updatedPlaylist.endList);
// If the player isn't paused, ensure that the segment loader is running,
// as it is possible that it was temporarily stopped while waiting for
// a playlist (e.g., in case the playlist errored and we re-requested it).
if (!this.tech_.paused()) {
this.mainSegmentLoader_.load();
if (this.audioSegmentLoader_) {
this.audioSegmentLoader_.load();
}
}
}
/**
* A helper function for triggerring presence usage events once per source
*
* @private
*/
triggerPresenceUsage_(master, media) {
const mediaGroups = master.mediaGroups || {};
let defaultDemuxed = true;
const audioGroupKeys = Object.keys(mediaGroups.AUDIO);
for (const mediaGroup in mediaGroups.AUDIO) {
for (const label in mediaGroups.AUDIO[mediaGroup]) {
const properties = mediaGroups.AUDIO[mediaGroup][label];
if (!properties.uri) {
defaultDemuxed = false;
}
}
}
if (defaultDemuxed) {
this.tech_.trigger({type: 'usage', name: 'vhs-demuxed'});
this.tech_.trigger({type: 'usage', name: 'hls-demuxed'});
}
if (Object.keys(mediaGroups.SUBTITLES).length) {
this.tech_.trigger({type: 'usage', name: 'vhs-webvtt'});
this.tech_.trigger({type: 'usage', name: 'hls-webvtt'});
}
if (Vhs.Playlist.isAes(media)) {
this.tech_.trigger({type: 'usage', name: 'vhs-aes'});
this.tech_.trigger({type: 'usage', name: 'hls-aes'});
}
if (audioGroupKeys.length &&
Object.keys(mediaGroups.AUDIO[audioGroupKeys[0]]).length > 1) {
this.tech_.trigger({type: 'usage', name: 'vhs-alternate-audio'});
this.tech_.trigger({type: 'usage', name: 'hls-alternate-audio'});
}
if (this.useCueTags_) {
this.tech_.trigger({type: 'usage', name: 'vhs-playlist-cue-tags'});
this.tech_.trigger({type: 'usage', name: 'hls-playlist-cue-tags'});
}
}
shouldSwitchToMedia_(nextPlaylist) {
const currentPlaylist = this.masterPlaylistLoader_.media() ||
this.masterPlaylistLoader_.pendingMedia_;
const currentTime = this.tech_.currentTime();
const bufferLowWaterLine = this.bufferLowWaterLine();
const bufferHighWaterLine = this.bufferHighWaterLine();
const buffered = this.tech_.buffered();
return shouldSwitchToMedia({
buffered,
currentTime,
currentPlaylist,
nextPlaylist,
bufferLowWaterLine,
bufferHighWaterLine,
duration: this.duration(),
experimentalBufferBasedABR: this.experimentalBufferBasedABR,
log: this.logger_
});
}
/**
* Register event handlers on the segment loaders. A helper function
* for construction time.
*
* @private
*/
setupSegmentLoaderListeners_() {
if (!this.experimentalBufferBasedABR) {
this.mainSegmentLoader_.on('bandwidthupdate', () => {
const nextPlaylist = this.selectPlaylist();
if (this.shouldSwitchToMedia_(nextPlaylist)) {
this.switchMedia_(nextPlaylist, 'bandwidthupdate');
}
this.tech_.trigger('bandwidthupdate');
});
this.mainSegmentLoader_.on('progress', () => {
this.trigger('progress');
});
}
this.mainSegmentLoader_.on('error', () => {
this.blacklistCurrentPlaylist(this.mainSegmentLoader_.error());
});
this.mainSegmentLoader_.on('appenderror', () => {
this.error = this.mainSegmentLoader_.error_;
this.trigger('error');
});
this.mainSegmentLoader_.on('syncinfoupdate', () => {
this.onSyncInfoUpdate_();
});
this.mainSegmentLoader_.on('timestampoffset', () => {
this.tech_.trigger({type: 'usage', name: 'vhs-timestamp-offset'});
this.tech_.trigger({type: 'usage', name: 'hls-timestamp-offset'});
});
this.audioSegmentLoader_.on('syncinfoupdate', () => {
this.onSyncInfoUpdate_();
});
this.audioSegmentLoader_.on('appenderror', () => {
this.error = this.audioSegmentLoader_.error_;
this.trigger('error');
});
this.mainSegmentLoader_.on('ended', () => {
this.logger_('main segment loader ended');
this.onEndOfStream();
});
this.mainSegmentLoader_.on('earlyabort', (event) => {
// never try to early abort with the new ABR algorithm
if (this.experimentalBufferBasedABR) {
return;
}
this.delegateLoaders_('all', ['abort']);
this.blacklistCurrentPlaylist({
message: 'Aborted early because there isn\'t enough bandwidth to complete the ' +
'request without rebuffering.'
}, ABORT_EARLY_BLACKLIST_SECONDS);
});
const updateCodecs = () => {
if (!this.sourceUpdater_.hasCreatedSourceBuffers()) {
return this.tryToCreateSourceBuffers_();
}
const codecs = this.getCodecsOrExclude_();
// no codecs means that the playlist was excluded
if (!codecs) {
return;
}
this.sourceUpdater_.addOrChangeSourceBuffers(codecs);
};
this.mainSegmentLoader_.on('trackinfo', updateCodecs);
this.audioSegmentLoader_.on('trackinfo', updateCodecs);
this.mainSegmentLoader_.on('fmp4', () => {
if (!this.triggeredFmp4Usage) {
this.tech_.trigger({type: 'usage', name: 'vhs-fmp4'});
this.tech_.trigger({type: 'usage', name: 'hls-fmp4'});
this.triggeredFmp4Usage = true;
}
});
this.audioSegmentLoader_.on('fmp4', () => {
if (!this.triggeredFmp4Usage) {
this.tech_.trigger({type: 'usage', name: 'vhs-fmp4'});
this.tech_.trigger({type: 'usage', name: 'hls-fmp4'});
this.triggeredFmp4Usage = true;
}
});
this.audioSegmentLoader_.on('ended', () => {
this.logger_('audioSegmentLoader ended');
this.onEndOfStream();
});
}
mediaSecondsLoaded_() {
return Math.max(this.audioSegmentLoader_.mediaSecondsLoaded +
this.mainSegmentLoader_.mediaSecondsLoaded);
}
/**
* Call load on our SegmentLoaders
*/
load() {
this.mainSegmentLoader_.load();
if (this.mediaTypes_.AUDIO.activePlaylistLoader) {
this.audioSegmentLoader_.load();
}
if (this.mediaTypes_.SUBTITLES.activePlaylistLoader) {
this.subtitleSegmentLoader_.load();
}
}
/**
* Re-tune playback quality level for the current player
* conditions without performing destructive actions, like
* removing already buffered content
*
* @private
* @deprecated
*/
smoothQualityChange_(media = this.selectPlaylist()) {
this.fastQualityChange_(media);
}
/**
* Re-tune playback quality level for the current player
* conditions. This method will perform destructive actions like removing
* already buffered content in order to readjust the currently active
* playlist quickly. This is good for manual quality changes
*
* @private
*/
fastQualityChange_(media = this.selectPlaylist()) {
if (media === this.masterPlaylistLoader_.media()) {
this.logger_('skipping fastQualityChange because new media is same as old');
return;
}
this.switchMedia_(media, 'fast-quality');
// Delete all buffered data to allow an immediate quality switch, then seek to give
// the browser a kick to remove any cached frames from the previous rendtion (.04 seconds
// ahead is roughly the minimum that will accomplish this across a variety of content
// in IE and Edge, but seeking in place is sufficient on all other browsers)
// Edge/IE bug: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/14600375/
// Chrome bug: https://bugs.chromium.org/p/chromium/issues/detail?id=651904
this.mainSegmentLoader_.resetEverything(() => {
// Since this is not a typical seek, we avoid the seekTo method which can cause segments
// from the previously enabled rendition to load before the new playlist has finished loading
if (videojs.browser.IE_VERSION || videojs.browser.IS_EDGE) {
this.tech_.setCurrentTime(this.tech_.currentTime() + 0.04);
} else {
this.tech_.setCurrentTime(this.tech_.currentTime());
}
});
// don't need to reset audio as it is reset when media changes
}
/**
* Begin playback.
*/
play() {
if (this.setupFirstPlay()) {
return;
}
if (this.tech_.ended()) {
this.tech_.setCurrentTime(0);
}
if (this.hasPlayed_) {
this.load();
}
const seekable = this.tech_.seekable();
// if the viewer has paused and we fell out of the live window,
// seek forward to the live point
if (this.tech_.duration() === Infinity) {
if (this.tech_.currentTime() < seekable.start(0)) {
return this.tech_.setCurrentTime(seekable.end(seekable.length - 1));
}
}
}
/**
* Seek to the latest media position if this is a live video and the
* player and video are loaded and initialized.
*/
setupFirstPlay() {
const media = this.masterPlaylistLoader_.media();
// Check that everything is ready to begin buffering for the first call to play
// If 1) there is no active media
// 2) the player is paused
// 3) the first play has already been setup
// then exit early
if (!media || this.tech_.paused() || this.hasPlayed_) {
return false;
}
// when the video is a live stream
if (!media.endList) {
const seekable = this.seekable();
if (!seekable.length) {
// without a seekable range, the player cannot seek to begin buffering at the live
// point
return false;
}
if (videojs.browser.IE_VERSION &&
this.tech_.readyState() === 0) {
// IE11 throws an InvalidStateError if you try to set currentTime while the
// readyState is 0, so it must be delayed until the tech fires loadedmetadata.