forked from shaka-project/shaka-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplayer.js
3733 lines (3127 loc) · 111 KB
/
player.js
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
/**
* @license
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('shaka.Player');
goog.require('goog.asserts');
goog.require('shaka.Deprecate');
goog.require('shaka.log');
goog.require('shaka.media.ActiveStreamMap');
goog.require('shaka.media.AdaptationSetCriteria');
goog.require('shaka.media.BufferingObserver');
goog.require('shaka.media.DrmEngine');
goog.require('shaka.media.ManifestParser');
goog.require('shaka.media.MediaSourceEngine');
goog.require('shaka.media.MuxJSClosedCaptionParser');
goog.require('shaka.media.NoopCaptionParser');
goog.require('shaka.media.PeriodObserver');
goog.require('shaka.media.Playhead');
goog.require('shaka.media.PlayheadObserverManager');
goog.require('shaka.media.PreferenceBasedCriteria');
goog.require('shaka.media.RegionObserver');
goog.require('shaka.media.RegionTimeline');
goog.require('shaka.media.SegmentReference');
goog.require('shaka.media.StreamingEngine');
goog.require('shaka.net.NetworkingEngine');
goog.require('shaka.util.ArrayUtils');
goog.require('shaka.util.Destroyer');
goog.require('shaka.util.Error');
goog.require('shaka.util.EventManager');
goog.require('shaka.util.FakeEvent');
goog.require('shaka.util.FakeEventTarget');
goog.require('shaka.util.IDestroyable');
goog.require('shaka.util.ManifestParserUtils');
goog.require('shaka.util.MimeUtils');
goog.require('shaka.util.MultiMap');
goog.require('shaka.util.PlayerConfiguration');
goog.require('shaka.util.PublicPromise');
goog.require('shaka.util.Stats');
goog.require('shaka.util.StreamUtils');
/**
* Construct a Player.
*
* @param {HTMLMediaElement=} mediaElem If provided, this is equivalent to
* calling attach(mediaElem, true) immediately after construction.
* @param {function(shaka.Player)=} dependencyInjector Optional callback
* which is called to inject mocks into the Player. Used for testing.
*
* @constructor
* @struct
* @implements {shaka.util.IDestroyable}
* @extends {shaka.util.FakeEventTarget}
* @export
*/
shaka.Player = function(mediaElem, dependencyInjector) {
shaka.util.FakeEventTarget.call(this);
/** @private {HTMLMediaElement} */
this.video_ = null;
/**
* Since we may not always have a text displayer created (e.g. before |load|
* is called), we need to track what text visibility SHOULD be so that we can
* ensure that when we create the text displayer. When we create our text
* displayer, we will use this to show (or not show) text as per the user's
* requests.
*
* @private {boolean}
*/
this.textVisibility_ = false;
/** @private {shaka.util.EventManager} */
this.eventManager_ = new shaka.util.EventManager();
/** @private {shaka.net.NetworkingEngine} */
this.networkingEngine_ = null;
/** @private {shaka.media.DrmEngine} */
this.drmEngine_ = null;
/** @private {shaka.media.MediaSourceEngine} */
this.mediaSourceEngine_ = null;
/** @private {shaka.media.Playhead} */
this.playhead_ = null;
/**
* The playhead observers are used to monitor the position of the playhead and
* some other source of data (e.g. buffered content), and raise events.
*
* @private {shaka.media.PlayheadObserverManager}
*/
this.playheadObservers_ = null;
/** @private {shaka.media.RegionTimeline} */
this.regionTimeline_ = null;
/** @private {shaka.media.StreamingEngine} */
this.streamingEngine_ = null;
/** @private {shaka.extern.ManifestParser} */
this.parser_ = null;
/** @private {?shaka.extern.Manifest} */
this.manifest_ = null;
/** @private {?string} */
this.assetUri_ = null;
/** @private {shaka.extern.AbrManager} */
this.abrManager_ = null;
/**
* The factory that was used to create the abrManager_ instance.
* @private {?shaka.extern.AbrManager.Factory}
*/
this.abrManagerFactory_ = null;
/**
* Contains an ID for use with creating streams. The manifest parser should
* start with small IDs, so this starts with a large one.
* @private {number}
*/
this.nextExternalStreamId_ = 1e9;
/** @private {!Set.<shaka.extern.Stream>} */
this.loadingTextStreams_ = new Set();
/** @private {boolean} */
this.buffering_ = false;
/** @private {boolean} */
this.switchingPeriods_ = true;
/** @private {?function()} */
this.onCancelLoad_ = null;
/** @private {Promise} */
this.unloadChain_ = null;
/** @private {?shaka.extern.Variant} */
this.deferredVariant_ = null;
/** @private {boolean} */
this.deferredVariantClearBuffer_ = false;
/** @private {number} */
this.deferredVariantClearBufferSafeMargin_ = 0;
/** @private {?shaka.extern.Stream} */
this.deferredTextStream_ = null;
/**
* A mapping of which streams are/were active in each period. Used when the
* current period (the one containing playhead) differs from the active
* period (the one being streamed in by streaming engine).
*
* @private {!shaka.media.ActiveStreamMap}
*/
this.activeStreams_ = new shaka.media.ActiveStreamMap();
/** @private {?shaka.extern.PlayerConfiguration} */
this.config_ = this.defaultConfig_();
/** @private {{width: number, height: number}} */
this.maxHwRes_ = {width: Infinity, height: Infinity};
/** @private {shaka.util.Stats} */
this.stats_ = null;
/** @private {!shaka.media.AdaptationSetCriteria} */
this.currentAdaptationSetCriteria_ = new shaka.media.PreferenceBasedCriteria(
this.config_.preferredAudioLanguage,
this.config_.preferredVariantRole,
this.config_.preferredAudioChannelCount);
/** @private {string} */
this.currentTextLanguage_ = this.config_.preferredTextLanguage;
/** @private {string} */
this.currentTextRole_ = this.config_.preferredTextRole;
if (dependencyInjector) {
dependencyInjector(this);
}
this.networkingEngine_ = this.createNetworkingEngine();
if (mediaElem) {
this.attach(mediaElem, true /* initializeMediaSource */);
}
/** @private {!shaka.util.Destroyer} */
this.destroyer_ = new shaka.util.Destroyer(() => {
if (this.eventManager_) {
this.eventManager_.release();
this.eventManager_ = null;
}
const waitFor = [];
if (this.networkingEngine_) {
waitFor.push(this.networkingEngine_.destroy());
this.networkingEngine_ = null;
}
this.textVisibility_ = false;
this.eventManager_ = null;
this.abrManager_ = null;
this.abrManagerFactory_ = null;
this.config_ = null;
return Promise.all(waitFor);
});
// If the browser comes back online after being offline, then try to play
// again.
this.eventManager_.listen(window, 'online', () => {
this.retryStreaming();
});
};
goog.inherits(shaka.Player, shaka.util.FakeEventTarget);
/**
* @return {!Promise}
* @private
*/
shaka.Player.prototype.cancelLoad_ = function() {
if (!this.onCancelLoad_) {
return Promise.resolve();
}
let stopParser = Promise.resolve();
if (this.parser_) {
// Stop the parser manually, to ensure that any network calls it may be
// making are stopped in a timely fashion.
// This happens in parallel with cancelling the load chain.
// Otherwise, destroying will wait for any failing network calls to run
// out of retries.
stopParser = this.parser_.stop();
this.parser_ = null;
}
return Promise.all([stopParser, this.onCancelLoad_()]);
};
/**
* After destruction, a Player object cannot be used again.
*
* @override
* @export
*/
shaka.Player.prototype.destroy = async function() {
// First, detach from the media element. This implies unloading content
// and canceling pending loads. This must be called before the destroyer
// as it will indirectly check if the player has already been destroyed and
// won't execute as expected. Calling detach multiple times is safe, so it
// is okay to be outside the protection of the destroyer.
await this.detach();
await this.destroyer_.destroy();
};
/**
* @define {string} A version number taken from git at compile time.
* @export
*/
shaka.Player.version = 'v2.5.0-beta2-master-uncompiled';
// Initialize the deprecation system using the version string we just set
// on the player.
shaka.Deprecate.init(shaka.Player.version);
/**
* @event shaka.Player.ErrorEvent
* @description Fired when a playback error occurs.
* @property {string} type
* 'error'
* @property {!shaka.util.Error} detail
* An object which contains details on the error. The error's 'category' and
* 'code' properties will identify the specific error that occurred. In an
* uncompiled build, you can also use the 'message' and 'stack' properties
* to debug.
* @exportDoc
*/
/**
* @event shaka.Player.EmsgEvent
* @description Fired when a non-typical emsg is found in a segment.
* @property {string} type
* 'emsg'
* @property {shaka.extern.EmsgInfo} detail
* An object which contains the content of the emsg box.
* @exportDoc
*/
/**
* @event shaka.Player.DrmSessionUpdateEvent
* @description Fired when the CDM has accepted the license response.
* @property {string} type
* 'drmsessionupdate'
* @exportDoc
*/
/**
* @event shaka.Player.TimelineRegionAddedEvent
* @description Fired when a media timeline region is added.
* @property {string} type
* 'timelineregionadded'
* @property {shaka.extern.TimelineRegionInfo} detail
* An object which contains a description of the region.
* @exportDoc
*/
/**
* @event shaka.Player.TimelineRegionEnterEvent
* @description Fired when the playhead enters a timeline region.
* @property {string} type
* 'timelineregionenter'
* @property {shaka.extern.TimelineRegionInfo} detail
* An object which contains a description of the region.
* @exportDoc
*/
/**
* @event shaka.Player.TimelineRegionExitEvent
* @description Fired when the playhead exits a timeline region.
* @property {string} type
* 'timelineregionexit'
* @property {shaka.extern.TimelineRegionInfo} detail
* An object which contains a description of the region.
* @exportDoc
*/
/**
* @event shaka.Player.BufferingEvent
* @description Fired when the player's buffering state changes.
* @property {string} type
* 'buffering'
* @property {boolean} buffering
* True when the Player enters the buffering state.
* False when the Player leaves the buffering state.
* @exportDoc
*/
/**
* @event shaka.Player.LoadingEvent
* @description Fired when the player begins loading.
* Used by the Cast receiver to determine idle state.
* @property {string} type
* 'loading'
* @exportDoc
*/
/**
* @event shaka.Player.UnloadingEvent
* @description Fired when the player unloads or fails to load.
* Used by the Cast receiver to determine idle state.
* @property {string} type
* 'unloading'
* @exportDoc
*/
/**
* @event shaka.Player.TextTrackVisibilityEvent
* @description Fired when text track visibility changes.
* @property {string} type
* 'texttrackvisibility'
* @exportDoc
*/
/**
* @event shaka.Player.TracksChangedEvent
* @description Fired when the list of tracks changes. For example, this will
* happen when changing periods or when track restrictions change.
* @property {string} type
* 'trackschanged'
* @exportDoc
*/
/**
* @event shaka.Player.AdaptationEvent
* @description Fired when an automatic adaptation causes the active tracks
* to change. Does not fire when the application calls selectVariantTrack()
* selectTextTrack(), selectAudioLanguage() or selectTextLanguage().
* @property {string} type
* 'adaptation'
* @exportDoc
*/
/**
* @event shaka.Player.VariantChangedEvent
* @description Fired when a call from the application caused a variant change.
* Can be triggered by calls to selectVariantTrack() or selectAudioLanguage().
* Does not fire when an automatic adaptation causes a variant change.
* @property {string} type
* 'variantchanged'
* @exportDoc
*/
/**
* @event shaka.Player.TextChangedEvent
* @description Fired when a call from the application caused a text stream
* change. Can be triggered by calls to selectTextTrack() or
* selectTextLanguage().
* @property {string} type
* 'textchanged'
* @exportDoc
*/
/**
* @event shaka.Player.ExpirationUpdatedEvent
* @description Fired when there is a change in the expiration times of an
* EME session.
* @property {string} type
* 'expirationupdated'
* @exportDoc
*/
/**
* @event shaka.Player.LargeGapEvent
* @description Fired when the playhead enters a large gap. If
* |config.streaming.jumpLargeGaps| is set, the default action of this event
* is to jump the gap; this can be prevented by calling preventDefault() on
* the event object.
* @property {string} type
* 'largegap'
* @property {number} currentTime
* The current time of the playhead.
* @property {number} gapSize
* The size of the gap, in seconds.
* @exportDoc
*/
/**
* @event shaka.Player.StreamingEvent
* @description Fired after the manifest has been parsed and track information
* is available, but before streams have been chosen and before any segments
* have been fetched. You may use this event to configure the player based on
* information found in the manifest.
* @property {string} type
* 'streaming'
* @exportDoc
*/
/**
* These are the EME key statuses that represent restricted playback.
* 'usable', 'released', 'output-downscaled', 'status-pending' are statuses
* of the usable keys. 'expired' status is being handled separately in
* DrmEngine.
*
* @const {!Array.<string>}
* @private
*/
shaka.Player.restrictedStatuses_ = ['output-restricted', 'internal-error'];
/** @private {!Object.<string, function():*>} */
shaka.Player.supportPlugins_ = {};
/**
* Registers a plugin callback that will be called with support(). The
* callback will return the value that will be stored in the return value from
* support().
*
* @param {string} name
* @param {function():*} callback
* @export
*/
shaka.Player.registerSupportPlugin = function(name, callback) {
shaka.Player.supportPlugins_[name] = callback;
};
/**
* Return whether the browser provides basic support. If this returns false,
* Shaka Player cannot be used at all. In this case, do not construct a Player
* instance and do not use the library.
*
* @return {boolean}
* @export
*/
shaka.Player.isBrowserSupported = function() {
// Basic features needed for the library to be usable.
let basic = !!window.Promise && !!window.Uint8Array &&
!!Array.prototype.forEach;
return basic &&
shaka.media.MediaSourceEngine.isBrowserSupported() &&
shaka.media.DrmEngine.isBrowserSupported();
};
/**
* Probes the browser to determine what features are supported. This makes a
* number of requests to EME/MSE/etc which may result in user prompts. This
* should only be used for diagnostics.
*
* NOTE: This may show a request to the user for permission.
*
* @see https://bit.ly/2ywccmH
* @return {!Promise.<shaka.extern.SupportType>}
* @export
*/
shaka.Player.probeSupport = function() {
goog.asserts.assert(shaka.Player.isBrowserSupported(),
'Must have basic support');
return shaka.media.DrmEngine.probeSupport().then(function(drm) {
let manifest = shaka.media.ManifestParser.probeSupport();
let media = shaka.media.MediaSourceEngine.probeSupport();
let ret = {
manifest: manifest,
media: media,
drm: drm,
};
let plugins = shaka.Player.supportPlugins_;
for (let name in plugins) {
ret[name] = plugins[name]();
}
return ret;
});
};
/**
* Attach the Player to a media element (audio or video tag).
*
* If the Player is already attached to a media element, the previous element
* will first be detached.
*
* After calling attach, the media element is owned by the Player and should not
* be used for other purposes until detach or destroy() are called.
*
* @param {!HTMLMediaElement} mediaElem
* @param {boolean=} initializeMediaSource If true, start initializing
* MediaSource right away. This can improve load() latency for
* MediaSource-based playbacks. Defaults to true.
*
* @return {!Promise} If initializeMediaSource is false, the Promise is resolved
* as soon as the Player has released any previous media element and taken
* ownership of the new one. If initializeMediaSource is true, the Promise
* resolves after MediaSource has been subsequently initialized on the new
* media element.
* @export
*/
shaka.Player.prototype.attach =
async function(mediaElem, initializeMediaSource) {
if (initializeMediaSource === undefined) {
initializeMediaSource = true;
}
if (this.video_) {
await this.detach();
}
this.video_ = mediaElem;
goog.asserts.assert(mediaElem, 'Cannot attach to a null media element!');
// Listen for video errors.
this.eventManager_.listen(this.video_, 'error',
this.onVideoError_.bind(this));
if (initializeMediaSource) {
// Start the (potentially slow) process of opening MediaSource now.
this.mediaSourceEngine_ = this.createMediaSourceEngine();
await this.mediaSourceEngine_.open();
}
};
/**
* Detaches the Player from the media element (audio or video tag).
*
* After calling detach and waiting for the Promise to be resolved, the media
* element is no longer owned by the Player and may be used for other purposes.
*
* @return {!Promise} Resolved when the Player has released any previous media
* element.
* @export
*/
shaka.Player.prototype.detach = async function() {
if (!this.video_) {
return;
}
// Unload any loaded content.
await this.unload(false /* reinitializeMediaSource */);
// Stop listening for video errors.
this.eventManager_.unlisten(this.video_, 'error');
this.video_ = null;
};
/**
* Get a parser for the asset located at |assetUri|.
*
* @param {string} assetUri
* @param {?string} mimeType
* When not null, the mimeType will be used to find the best manifest parser
* for the given asset.
* @return {!Promise.<shaka.extern.ManifestParser>}
* @private
*/
shaka.Player.prototype.getParser_ = async function(assetUri, mimeType) {
goog.asserts.assert(
this.networkingEngine_,
'Cannot call |getParser_| after calling |destroy|.');
goog.asserts.assert(
this.config_,
'Cannot call |getParser_| after calling |destroy|');
const Factory = await shaka.media.ManifestParser.getFactory(
assetUri,
this.networkingEngine_,
this.config_.manifest.retryParameters,
mimeType);
return new Factory();
};
/**
* Use the current state of the player and load the asset as a manifest. This
* requires that |this.networkingEngine_|, |this.assetUri_|, and |this.parser_|
* to have already been set.
*
* @return {!Promise.<shaka.extern.Manifest>} Resolves with the manifest.
* @private
*/
shaka.Player.prototype.loadManifest_ = function() {
goog.asserts.assert(
this.networkingEngine_,
'Cannot call |loadManifest_| after calling |destroy|.');
goog.asserts.assert(
this.assetUri_,
'Cannot call |loadManifest_| after calling |destroy|.');
goog.asserts.assert(
this.parser_,
'Cannot call |loadManifest_| after calling |destroy|.');
this.regionTimeline_ = new shaka.media.RegionTimeline();
this.regionTimeline_.setListeners(/* onRegionAdded */ (region) => {
this.onRegionEvent_('timelineregionadded', region);
});
let playerInterface = {
networkingEngine: this.networkingEngine_,
filterNewPeriod: this.filterNewPeriod_.bind(this),
filterAllPeriods: this.filterAllPeriods_.bind(this),
// Called when the parser finds a timeline region. This can be called
// before we start playback or during playback (live/in-progress manifest).
onTimelineRegionAdded: (region) => this.regionTimeline_.addRegion(region),
onEvent: this.onEvent_.bind(this),
onError: this.onError_.bind(this),
};
return this.parser_.start(this.assetUri_, playerInterface);
};
/**
* When there is a variant with video and audio, filter out all variants which
* lack one or the other.
* This is to avoid problems where we choose audio-only variants because they
* have lower bandwidth, when there are variants with video available.
*
* @private
*/
shaka.Player.prototype.filterManifestForAVVariants_ = function() {
const isAVVariant = (variant) => {
// Audio-video variants may include both streams separately or may be single
// multiplexed streams with multiple codecs.
return (variant.video && variant.audio) ||
(variant.video && variant.video.codecs.includes(','));
};
const hasAVVariant = this.manifest_.periods.some((period) => {
return period.variants.some(isAVVariant);
});
if (hasAVVariant) {
shaka.log.debug('Found variant with audio and video content, ' +
'so filtering out audio-only content in all periods.');
this.manifest_.periods.forEach((period) => {
period.variants = period.variants.filter(isAVVariant);
});
}
if (this.manifest_.periods.length == 0) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.MANIFEST,
shaka.util.Error.Code.NO_PERIODS);
}
};
/**
* Load a manifest.
*
* @param {string} assetUri
* @param {?number=} startTime Optional start time, in seconds, to begin
* playback.
* Defaults to 0 for VOD and to the live edge for live.
* Set a positive number to start with a certain offset the beginning.
* Set a negative number to start with a certain offset from the end. This is
* intended for use with live streams, to start at a fixed offset from the
* live edge.
* @param {string|shaka.extern.ManifestParser.Factory=} mimeType
* The mime type for the content |manifestUri| points to or a manifest parser
* factory to override auto-detection or use an unregistered parser. Passing
* a manifest parser factory is deprecated and will be removed.
* @return {!Promise} Resolved when the manifest has been loaded and playback
* has begun; rejected when an error occurs or the call was interrupted by
* destroy(), unload() or another call to load().
* @export
*/
shaka.Player.prototype.load = async function(
assetUri, startTime = null, mimeType) {
if (!this.video_) {
throw new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.PLAYER,
shaka.util.Error.Code.NO_VIDEO_ELEMENT);
}
let cancelValue;
/** @type {!shaka.util.PublicPromise} */
const cancelPromise = new shaka.util.PublicPromise();
const cancelCallback = () => {
cancelValue = new shaka.util.Error(
shaka.util.Error.Severity.CRITICAL,
shaka.util.Error.Category.PLAYER,
shaka.util.Error.Code.LOAD_INTERRUPTED);
return cancelPromise;
};
this.dispatchEvent(new shaka.util.FakeEvent('loading'));
try {
const video = this.video_;
const unloadStart = Date.now();
const unloadPromise = this.unload();
this.onCancelLoad_ = cancelCallback;
await unloadPromise;
const unloadEnd = Date.now();
// Not tracked in stats because it should be insignificant.
// Logged in case it is not.
shaka.log.debug('Unload latency:', (unloadEnd - unloadStart) / 1000);
// We need to wait until we unloaded or else we would clash with a
// previous sessions |stats_|.
this.stats_ = new shaka.util.Stats(video);
this.stats_.markStartOfLoad();
this.eventManager_.listen(video, 'playing', () => {
this.updateStateHistory_();
});
this.eventManager_.listen(video, 'pause', () => {
this.updateStateHistory_();
});
this.eventManager_.listen(video, 'ended', () => {
this.updateStateHistory_();
});
const AbrManagerFactory = this.config_.abrFactory;
if (!this.abrManager_ || this.abrManagerFactory_ != AbrManagerFactory) {
this.abrManagerFactory_ = AbrManagerFactory;
this.abrManager_ = new AbrManagerFactory();
this.abrManager_.configure(this.config_.abr);
}
if (cancelValue) throw cancelValue;
/** @type {?shaka.extern.ManifestParser.Factory} */
let Factory = null;
/** @type {?string} */
let contentMimeType = null;
if (mimeType) {
if (typeof mimeType == 'string') {
contentMimeType = /** @type {string} */(mimeType);
} else {
shaka.Deprecate.deprecateFeature(
2, 6,
'Loading with a manifest parser factory',
'Please register a manifest parser and for the mime-type.');
Factory = /** @type {shaka.extern.ManifestParser.Factory} */(mimeType);
}
}
this.parser_ = Factory ?
new Factory() :
await this.getParser_(assetUri, contentMimeType);
this.parser_.configure(this.config_.manifest);
this.assetUri_ = assetUri;
const manifest = await this.loadManifest_();
this.manifest_ = manifest;
if (cancelValue) throw cancelValue;
this.filterManifestForAVVariants_();
this.drmEngine_ = await this.createDrmEngine(manifest);
if (cancelValue) throw cancelValue;
// Re-filter the manifest after DRM has been initialized.
this.filterAllPeriods_(this.manifest_.periods);
// TODO: When a manifest update adds a new period, that period's closed
// captions should also be turned into text streams. This should be called
// for each new period as well.
this.createTextStreamsForClosedCaptions_(this.manifest_.periods);
// Copy preferred languages from the config again, in case the config was
// changed between construction and playback.
this.currentAdaptationSetCriteria_ =
new shaka.media.PreferenceBasedCriteria(
this.config_.preferredAudioLanguage,
this.config_.preferredVariantRole,
this.config_.preferredAudioChannelCount);
this.currentTextLanguage_ = this.config_.preferredTextLanguage;
shaka.Player.applyPlayRange_(this.manifest_.presentationTimeline,
this.config_.playRangeStart,
this.config_.playRangeEnd);
await this.drmEngine_.attach(video);
if (cancelValue) throw cancelValue;
this.abrManager_.init((variant, clearBuffer, safeMargin) => {
return this.switch_(variant, clearBuffer, safeMargin);
});
if (!this.mediaSourceEngine_) {
this.mediaSourceEngine_ = this.createMediaSourceEngine();
}
// TODO: If there's a default value in the function definition, startTime
// can never be undefined. Even if the caller explicitly passes undefined,
// it will be assigned the default value. So there is no reason for the
// compiler to continue treating startTime as (number|null|undefined) when
// the default value is null. File a bug on the Closure compiler.
goog.asserts.assert(startTime !== undefined, 'Cannot be undefined!');
this.playhead_ = this.createPlayhead(startTime);
this.playheadObservers_ = this.createPlayheadObservers_();
this.streamingEngine_ = this.createStreamingEngine();
this.streamingEngine_.configure(this.config_.streaming);
// If the content is multi-codec and the browser can play more than one of
// them, choose codecs now before we initialize streaming.
this.chooseCodecsAndFilterManifest_();
this.dispatchEvent(new shaka.util.FakeEvent('streaming'));
await this.streamingEngine_.init();
if (cancelValue) throw cancelValue;
if (this.config_.streaming.startAtSegmentBoundary) {
let time = this.adjustStartTime_(this.playhead_.getTime());
this.playhead_.setStartTime(time);
}
// Re-filter the manifest after streams have been chosen.
this.manifest_.periods.forEach(this.filterNewPeriod_.bind(this));
// Dispatch a 'trackschanged' event now that all initial filtering is done.
this.onTracksChanged_();
// Since the first streams just became active, send an adaptation event.
this.onAdaptation_();
// Now that we've filtered out variants that aren't compatible with the
// active one, update abr manager with filtered variants for the current
// period.
const currentPeriod = this.getPresentationPeriod_();
const hasPrimary = currentPeriod.variants.some((v) => v.primary);
if (!this.config_.preferredAudioLanguage && !hasPrimary) {
shaka.log.warning('No preferred audio language set. We will choose an ' +
'arbitrary language initially');
}
this.chooseVariant_(currentPeriod.variants);
// Wait for the 'loadeddata' event to measure load() latency.
this.eventManager_.listenOnce(video, 'loadeddata', () => {
this.stats_.markEndOfLoad();
});
if (cancelValue) throw cancelValue;
this.onCancelLoad_ = null;
} catch (error) {
// |error| will only be null if something returned |Promise.reject()|.
if (error) {
shaka.log.debug('load failed:', error, error.message, error.stack);
} else {
shaka.log.debug('load failed - missing error');
}
goog.asserts.assert(
error instanceof shaka.util.Error,
'Non-shaka error seen. This is an unhandled error.');
// If we haven't started another load, clear the onCancelLoad_.
cancelPromise.resolve();
if (this.onCancelLoad_ == cancelCallback) {
this.onCancelLoad_ = null;
this.dispatchEvent(new shaka.util.FakeEvent('unloading'));
}
// If part of the load chain was aborted, that async call may have thrown.
// In those cases, we want the cancelation error, not the thrown error.
return Promise.reject(cancelValue || error);
}
};
/**
* In case of multiple usable codecs, choose one based on lowest average
* bandwidth and filter out the rest.
* @private
*/
shaka.Player.prototype.chooseCodecsAndFilterManifest_ = function() {
// Collect a list of variants for all periods.
/** @type {!Array.<shaka.extern.Variant>} */
let variants = this.manifest_.periods.reduce(
(variants, period) => variants.concat(period.variants), []);
// To start, consider a subset of variants based on audio channel preferences.
// For some content (#1013), surround-sound variants will use a different
// codec than stereo variants, so it is important to choose codecs **after**
// considering the audio channel config.
variants = shaka.util.StreamUtils.filterVariantsByAudioChannelCount(
variants, this.config_.preferredAudioChannelCount);
function variantCodecs(variant) {
// Only consider the base of the codec string. For example, these should
// both be considered the same codec: avc1.42c01e, avc1.4d401f
let baseVideoCodec = '';
if (variant.video) {
baseVideoCodec = shaka.util.MimeUtils.getCodecBase(variant.video.codecs);
}
let baseAudioCodec = '';
if (variant.audio) {
baseAudioCodec = shaka.util.MimeUtils.getCodecBase(variant.audio.codecs);
}
return baseVideoCodec + '-' + baseAudioCodec;
}