forked from shaka-project/shaka-player
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1797 lines (1602 loc) · 57.9 KB
/
main.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
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shakaDemo.Main');
goog.require('ShakaDemoAssetInfo');
goog.require('goog.asserts');
goog.require('shakaDemo.CloseButton');
goog.require('shakaDemo.MessageIds');
goog.require('shakaDemo.Utils');
/**
* Shaka Player demo, main section.
* This controls the header and the footer, and contains all methods that should
* be shared by multiple page layouts (loading assets, setting/checking
* configuration, etc).
*/
shakaDemo.Main = class {
/** */
constructor() {
/** @private {HTMLVideoElement} */
this.video_ = null;
/** @private {HTMLElement} */
this.container_ = null;
/** @private {shaka.Player} */
this.player_ = null;
/** @type {?ShakaDemoAssetInfo} */
this.selectedAsset = null;
/** @type {shaka.ui.Localization} */
this.localization_ = null;
/**
* The configuration asked for by the user. I.e., not from the asset.
* @private {shaka.extern.PlayerConfiguration}
*/
this.desiredConfig_;
/** @private {shaka.extern.PlayerConfiguration} */
this.defaultConfig_;
/** @private {boolean} */
this.fullyLoaded_ = false;
/** @private {?shaka.ui.Controls} */
this.controls_ = null;
/** @private {?Array.<shaka.extern.StoredContent>} */
this.initialStoredList_;
/** @private {boolean} */
this.trickPlayControlsEnabled_ = false;
/** @private {boolean} */
this.nativeControlsEnabled_ = false;
/** @private {shaka.extern.SupportType} */
this.support_;
/** @private {string} */
this.uiLocale_ = '';
/** @private {boolean} */
this.noInput_ = false;
/** @private {!HTMLAnchorElement} */
this.errorDisplayLink_ = /** @type {!HTMLAnchorElement} */(
document.getElementById('error-display-link'));
/** @private {?number} */
this.currentErrorSeverity_ = null;
// Override the icon for the MDL library's menu button.
// eslint-disable-next-line no-restricted-syntax
MaterialLayout.prototype.Constant_.MENU_ICON = 'settings';
}
/**
* This function contains the steps of initialization that should be followed
* whether or not the demo successfully set up.
* @private
*/
initCommon_() {
// Display uncaught exceptions. Note that this doesn't seem to work in IE.
// See shakaDemo.Main.initWrapper for a failsafe that works for init-time
// errors on IE.
window.addEventListener('error', (event) => {
const errorEvent = /** @type {!ErrorEvent} */(event);
// Exception to the exceptions we catch: ChromeVox (screenreader) always
// throws an error as of Chrome 73. Screen these out since they are
// unrelated to our application and we can't control them.
if (errorEvent.message.includes('cvox.Api')) {
return;
}
this.onError_(/** @type {!shaka.util.Error} */ (errorEvent.error));
});
// Set up event listeners.
document.getElementById('error-display-close-button').addEventListener(
'click', (event) => this.closeError_());
// Set up version strings in the appropriate divs.
this.setUpVersionStrings_();
}
/**
* Set up the application with errors to show that load failed.
* This does not dispatch the shaka-main-loaded event, so it will not cause
* the nav bar buttons to be set up.
* @param {!shaka.ui.Overlay.FailReasonCode} reasonCode
* @return {!Promise}
*/
async initFailed(reasonCode) {
this.initCommon_();
// Set up version links, so the user can switch to compiled mode if
// necessary.
this.makeVersionLinks_();
const errorCloseButton =
document.getElementById('error-display-close-button');
errorCloseButton.style.display = 'none';
// Update the componentHandler, to account for any new MDL elements added.
componentHandler.upgradeDom();
// Disable elements that should not be used.
const elementsToDisable = [];
const disableClass = 'should-disable-on-fail';
for (const element of document.getElementsByClassName(disableClass)) {
elementsToDisable.push(element);
}
// The hamburger menu close button is added programmatically by MDL, and
// thus isn't given our 'disableonfail' class.
for (const element of document.getElementsByClassName(
'mdl-layout__drawer-button')) {
elementsToDisable.push(element);
}
for (const element of elementsToDisable) {
element.tabIndex = -1;
element.classList.add('disabled-by-fail');
}
// Because the UI did not load, this will need to set up a localization
// object manually.
this.localization_ = new shaka.ui.Localization(/* fallbackLocale= */ 'en');
this.localization_.changeLocale(navigator.languages || []);
await this.setupLocalization_();
// Process a synthetic error about lack of browser support.
const severity = shaka.util.Error.Severity.CRITICAL;
let href = '';
let message = '';
switch (reasonCode) {
case shaka.ui.Overlay.FailReasonCode.NO_BROWSER_SUPPORT:
message = this.getLocalizedString(
shakaDemo.MessageIds.FAILURE_NO_BROWSER_SUPPORT);
href = 'https://github.com/google/shaka-player#' +
'platform-and-browser-support-matrix';
break;
case shaka.ui.Overlay.FailReasonCode.PLAYER_FAILED_TO_LOAD:
message = this.getLocalizedString(shakaDemo.MessageIds.FAILURE_MISC);
break;
}
this.handleError_(severity, message, href);
}
/**
* Initialize the application.
*/
async init() {
this.initCommon_();
this.support_ = await shaka.Player.probeSupport();
this.video_ =
/** @type {!HTMLVideoElement} */(document.getElementById('video'));
this.video_.poster = shakaDemo.Main.mainPoster_;
this.container_ = /** @type {!HTMLElement} */(
document.getElementsByClassName('video-container')[0]);
if (navigator.serviceWorker) {
console.debug('Registering service worker.');
// NOTE: This can sometimes hang on iOS 12, so let's not wait for it to
// complete before setting up the app. We don't even use the Promise
// result or react to the registration failure except to log it.
navigator.serviceWorker.register('service_worker.js');
}
// Optionally enter noinput mode. This has to happen before setting up the
// player.
this.noInput_ = 'noinput' in this.getParams_();
await this.setupPlayer_();
this.readHash_();
window.addEventListener('hashchange', () => this.hashChanged_());
await this.setupStorage_();
this.setupBugButton_();
if (this.noInput_) {
// Set the page to noInput mode, disabling the header and footer.
const hideClass = 'should-hide-in-no-input-mode';
for (const element of document.getElementsByClassName(hideClass)) {
this.hideElement_(element);
}
const showClass = 'should-show-in-no-input-mode';
for (const element of document.getElementsByClassName(showClass)) {
this.showElement_(element);
}
// Also fullscreen the container.
this.container_.classList.add('no-input-sized');
document.getElementById('video-bar').classList.add('no-input-sized');
}
// The main page is loaded. Dispatch an event, so the various
// configurations will load themselves.
this.dispatchEventWithName_('shaka-main-loaded');
// Wait for one interruptor cycle, so that the tabs have time to load.
// This ensures that, for example, if there is an asset playing at page
// load time, the video will scroll into view second, and the page won't
// scroll away from the video.
await Promise.resolve();
// Update the componentHandler, to account for any new MDL elements added.
componentHandler.upgradeDom();
const asset = this.getLastAssetFromHash_();
this.fullyLoaded_ = true;
this.remakeHash();
if (asset && !this.selectedAsset) {
// If an asset has begun loading in the meantime (for example, due to
// re-joining an existing cast session), don't play this.
this.loadAsset(asset);
}
}
/**
* @param {string} url
* @return {!Promise.<string>}
* @private
*/
async loadText_(url) {
const netEngine = new shaka.net.NetworkingEngine();
const retryParams = shaka.net.NetworkingEngine.defaultRetryParameters();
const request = shaka.net.NetworkingEngine.makeRequest([url], retryParams);
const requestType = shaka.net.NetworkingEngine.RequestType.APP;
const operation = netEngine.request(requestType, request);
const response = await operation.promise;
const text = shaka.util.StringUtils.fromUTF8(response.data);
await netEngine.destroy();
return text;
}
/** @private */
async reportBug_() {
// Fetch the special bug template.
let text = await this.loadText_('autoTemplate.txt');
// Fill in what parts of the template we can.
const fillInTemplate = (replaceString, value) => {
text = text.replace(replaceString, value);
};
fillInTemplate('RE:player', shaka.Player.version);
fillInTemplate('RE:link', window.location.href);
fillInTemplate('RE:browser', navigator.userAgent);
if (this.selectedAsset &&
this.selectedAsset.source == shakaAssets.Source.CUSTOM) {
// This is a custom asset, so add a comment warning about custom assets.
const warning = await this.loadText_('customWarning.txt');
fillInTemplate('RE:customwarning', warning);
} else {
// No need for any warnings. So remove it (and the newline after it).
fillInTemplate('RE:customwarning\n', '');
}
// Navigate to the github issue opening interface, with the
// partially-filled template as a preset body.
let url = 'https://github.com/google/shaka-player/issues/new?';
url += 'body=' + encodeURIComponent(text);
// Open in another tab.
window.open(url, '_blank');
}
/** @private */
setupBugButton_() {
const bugButton = document.getElementById('bug-button');
bugButton.addEventListener('click', () => this.reportBug_());
// The button should be disabled when offline, as we can't report bugs in
// that state.
if (!navigator.onLine) {
bugButton.setAttribute('disabled', '');
}
window.addEventListener('online', () => {
bugButton.removeAttribute('disabled');
});
window.addEventListener('offline', () => {
bugButton.setAttribute('disabled', '');
});
}
/** @private */
configureUI_() {
const video = /** @type {!HTMLVideoElement} */ (this.video_);
const ui = video['ui'];
const uiConfig = ui.getConfiguration();
// Remove any trick play configurations from a previous config.
uiConfig.addSeekBar = true;
uiConfig.controlPanelElements =
uiConfig.controlPanelElements.filter((element) => {
return element != 'rewind' && element != 'fast_forward';
});
if (this.trickPlayControlsEnabled_) {
// Trick mode controls don't have a seek bar.
uiConfig.addSeekBar = false;
// Replace the position the play_pause button was at with a full suite of
// trick play controls, including rewind and fast-forward.
const index = uiConfig.controlPanelElements.indexOf('play_pause');
uiConfig.controlPanelElements.splice(
index, 1, 'rewind', 'play_pause', 'fast_forward');
}
if (!uiConfig.controlPanelElements.includes('close')) {
uiConfig.controlPanelElements.push('close');
}
ui.configure(uiConfig);
}
/**
* @return {!Promise}
* @private
*/
async setupPlayer_() {
const video = /** @type {!HTMLVideoElement} */ (this.video_);
const ui = video['ui'];
this.player_ = ui.getControls().getPlayer();
if (!this.noInput_) {
// Don't add the close button if in noInput mode; it doesn't make much
// sense to stop playing a video if you can't start playing other videos.
// Register custom controls to the UI.
const closeFactory = new shakaDemo.CloseButton.Factory();
shaka.ui.Controls.registerElement('close', closeFactory);
// Configure UI.
this.configureUI_();
}
// Add application-level default configs here. These are not the library
// defaults, but they are the application defaults. This will affect the
// default values assigned to UI config elements as well as the decision
// about what values to place in the URL hash.
this.player_.configure(
'manifest.dash.clockSyncUri',
'https://shaka-player-demo.appspot.com/time.txt');
// Get default config.
this.defaultConfig_ = this.player_.getConfiguration();
this.desiredConfig_ = this.player_.getConfiguration();
const languages = navigator.languages || ['en-us'];
this.configure('preferredAudioLanguage', languages[0]);
this.configure('preferredTextLanguage', languages[0]);
this.uiLocale_ = languages[0];
// TODO(#1591): Support multiple language preferences
const onErrorEvent = (event) => this.onErrorEvent_(event);
this.player_.addEventListener('error', onErrorEvent);
// Listen to events on controls.
this.controls_ = ui.getControls();
this.controls_.addEventListener('error', onErrorEvent);
this.controls_.addEventListener('caststatuschanged', (event) => {
this.onCastStatusChange_(event['newStatus']);
});
this.localization_ = this.controls_.getLocalization();
await this.setupLocalization_();
const drawerCloseButton = document.getElementById('drawer-close-button');
drawerCloseButton.addEventListener('click', () => {
const layout = document.getElementById('main-layout');
layout.MaterialLayout.toggleDrawer();
this.dispatchEventWithName_('shaka-main-drawer-state-change');
this.hideElement_(drawerCloseButton);
});
// Dispatch drawer state change events when the drawer button or obfuscator
// are pressed also.
const drawerButton = document.querySelector('.mdl-layout__drawer-button');
goog.asserts.assert(drawerButton, 'There should be a drawer button.');
const openDrawer = () => {
this.dispatchEventWithName_('shaka-main-drawer-state-change');
this.showElement_(drawerCloseButton);
};
// Listen to both the "click" and "keydown" events on the drawer button,
// since the element is actually a div rather than a button, which means
// that it doesn't fire "click" events when activated by keyboard input.
drawerButton.addEventListener('click', openDrawer);
drawerButton.addEventListener('keydown', (event) => {
const key = (/** @type {!KeyboardEvent} */ (event)).key;
// Ignore "keydown" input for keys that won't trigger the button (i.e.
// anything besides spacebar or enter).
if (key == ' ' || key == 'Spacebar' || key == 'Enter') {
openDrawer();
}
});
const obfuscator = document.querySelector('.mdl-layout__obfuscator');
goog.asserts.assert(obfuscator, 'There should be an obfuscator.');
obfuscator.addEventListener('click', () => {
this.dispatchEventWithName_('shaka-main-drawer-state-change');
this.hideElement_(drawerCloseButton);
});
this.hideElement_(drawerCloseButton);
}
/**
* @return {!Promise}
* @private
*/
async setupLocalization_() {
// Set up localization lazy-loading.
const applyNewLocaleIfPossible = () => {
this.localizeHTMLElements_();
this.dispatchEventWithName_('shaka-main-locale-changed');
};
const UNKNOWN_LOCALES = shaka.ui.Localization.UNKNOWN_LOCALES;
this.localization_.addEventListener(UNKNOWN_LOCALES, (event) => {
for (const locale of event['locales']) {
// This will leave promise rejections uncaught; this is acceptable, as
// this function is actually expected to fail fairly often, and has
// built-in fallback behavior (from localization events) without needing
// to catch the promise rejection.
this.loadUILocale_(locale).then(() => {
if (locale == this.uiLocale_) {
applyNewLocaleIfPossible();
}
});
}
});
const LOCALE_CHANGED = shaka.ui.Localization.LOCALE_CHANGED;
this.localization_.addEventListener(LOCALE_CHANGED, (event) => {
applyNewLocaleIfPossible();
});
const initialLocaleLoads = [];
initialLocaleLoads.push(this.loadUILocale_(this.uiLocale_));
if (this.uiLocale_.includes('-')) {
// Also try to load the 'base' localization.
// This is so that, for example, the uiLocale_ is set to 'en-US', it will
// try to load 'en'.
initialLocaleLoads.push(this.loadUILocale_(this.uiLocale_.split('-')[0]));
}
if (!this.uiLocale_.startsWith('en')) {
// Load 'en' as a fallback option, if not already loaded.
initialLocaleLoads.push(this.loadUILocale_('en'));
}
await Promise.all(initialLocaleLoads);
this.localizeHTMLElements_();
}
/** @return {boolean} */
getIsDrawerOpen() {
const drawer = document.querySelector('.mdl-layout__drawer');
goog.asserts.assert(drawer, 'There should be a drawer.');
return drawer.classList.contains('is-visible');
}
/**
* Gets a unique storage identifier for an asset.
* @param {!ShakaDemoAssetInfo} asset
* @return {string}
* @private
*/
getIdentifierFromAsset_(asset) {
// Custom assets can't have special characters like [ or ] in their name,
// and none of the default assets will have that in their name, so we can
// be sure that no asset will have [CUSTOM] in its name.
return asset.name +
(asset.source == shakaAssets.Source.CUSTOM ? ' [CUSTOM]' : '');
}
/**
* Creates a storage instance.
* If and only if storage is not available, this will return null.
* These storage instances are meant to be used once and then destroyed, using
* the |Storage.destroy| method.
* @return {?shaka.offline.Storage}
* @private
*/
makeStorageInstance_() {
if (!shaka.offline.Storage.support()) {
return null;
}
const storage = new shaka.offline.Storage();
// Configure the storage instance.
/**
* @param {string} identifier
* @return {?ShakaDemoAssetInfo}
*/
const getAssetWithIdentifier = (identifier) => {
for (const asset of shakaAssets.testAssets) {
if (this.getIdentifierFromAsset_(asset) == identifier) {
return asset;
}
}
if (shakaDemoCustom) {
for (const asset of shakaDemoCustom.assets()) {
if (this.getIdentifierFromAsset_(asset) == identifier) {
return asset;
}
}
}
return null;
};
/**
* @param {shaka.extern.StoredContent} content
* @param {number} progress
*/
const progressCallback = (content, progress) => {
const identifier = content.appMetadata['identifier'];
const asset = getAssetWithIdentifier(identifier);
if (asset) {
asset.storedProgress = progress;
this.dispatchEventWithName_('shaka-main-offline-progress');
}
};
storage.configure(this.desiredConfig_);
storage.configure('offline.progressCallback', progressCallback);
return storage;
}
/**
* Attaches callbacks to an asset so that it can be downloaded online.
* This method does not verify whether storage is or is not possible.
* Also, if an asset has an associated offline version, load it with that
* info.
* @param {!ShakaDemoAssetInfo} asset
*/
setupOfflineSupport(asset) {
if (!this.initialStoredList_) {
// Storage failed to set up, so nothing happened.
return;
}
// If the list of stored content does not contain this asset, then make sure
// that the asset's |storedContent| value is null. Custom assets that were
// once stored might have that object serialized with their other data.
asset.storedContent = null;
for (const storedContent of this.initialStoredList_) {
const identifier = storedContent.appMetadata['identifier'];
if (this.getIdentifierFromAsset_(asset) == identifier) {
asset.storedContent = storedContent;
}
}
asset.storeCallback = async () => {
const storage = this.makeStorageInstance_();
if (!storage) {
return;
}
try {
await this.drmConfiguration_(asset, storage);
const metadata = {
'identifier': this.getIdentifierFromAsset_(asset),
'downloaded': new Date(),
};
asset.storedProgress = 0;
this.dispatchEventWithName_('shaka-main-offline-progress');
const stored = await storage.store(asset.manifestUri, metadata).promise;
asset.storedContent = stored;
} catch (error) {
this.onError_(/** @type {!shaka.util.Error} */ (error));
asset.storedContent = null;
}
storage.destroy();
asset.storedProgress = 1;
this.dispatchEventWithName_('shaka-main-offline-progress');
};
asset.unstoreCallback = async () => {
if (asset == this.selectedAsset) {
this.unload();
}
if (asset.storedContent && asset.storedContent.offlineUri) {
const storage = this.makeStorageInstance_();
if (!storage) {
return;
}
try {
asset.storedProgress = 0;
this.dispatchEventWithName_('shaka-main-offline-progress');
await storage.remove(asset.storedContent.offlineUri);
asset.storedContent = null;
} catch (error) {
this.onError_(/** @type {!shaka.util.Error} */ (error));
// Presumably, if deleting the asset fails, it still exists?
}
storage.destroy();
asset.storedProgress = 1;
this.dispatchEventWithName_('shaka-main-offline-progress');
}
};
}
/**
* @return {!Promise}
* @private
*/
async setupStorage_() {
// Load stored asset infos.
const storage = this.makeStorageInstance_();
if (!storage) {
return;
}
try {
this.initialStoredList_ = await storage.list();
} catch (error) {
// If this operation errors, it means that storage (while supported) is
// being held up by some kind of error.
// Log that error, and then pretend that storage is unsupported.
console.error(error);
this.initialStoredList_ = null;
} finally {
storage.destroy();
}
// Setup asset callbacks for storage, for the test assets.
for (const asset of shakaAssets.testAssets) {
if (this.getAssetUnsupportedReason(asset, /* needOffline= */ true)) {
// Don't bother setting up the callbacks.
continue;
}
this.setupOfflineSupport(asset);
}
}
/** @private */
hashChanged_() {
this.readHash_();
this.dispatchEventWithName_('shaka-main-config-change');
}
/**
* Get why the asset is unplayable, if it is unplayable.
*
* @param {!ShakaDemoAssetInfo} asset
* @param {boolean} needOffline True if offline support is required.
* @return {?shakaDemo.MessageIds} unsupportedReason
* Null if asset is supported.
*/
getAssetUnsupportedReason(asset, needOffline) {
if (needOffline &&
(!shaka.offline.Storage.support() || !this.initialStoredList_)) {
return shakaDemo.MessageIds.UNSUPPORTED_NO_OFFLINE;
}
if (asset.source == shakaAssets.Source.CUSTOM) {
// We can't be sure if custom assets are supported or not. Just assume
// they are.
return null;
}
// Is the asset disabled?
if (asset.disabled) {
return shakaDemo.MessageIds.UNSUPPORTED_DISABLED;
}
if (needOffline && !asset.features.includes(shakaAssets.Feature.OFFLINE)) {
return shakaDemo.MessageIds.UNSUPPORTED_NO_DOWNLOAD;
}
if (!asset.isClear()) {
const hasSupportedDRM = asset.drm.some((drm) => {
return this.support_.drm[shakaAssets.identifierForKeySystem(drm)];
});
if (!hasSupportedDRM) {
return shakaDemo.MessageIds.UNSUPPORTED_NO_KEY_SUPPORT;
}
if (needOffline) {
const hasSupportedOfflineDRM = asset.drm.some((drm) => {
const identifier = shakaAssets.identifierForKeySystem(drm);
return this.support_.drm[identifier] &&
this.support_.drm[identifier].persistentState;
});
if (!hasSupportedOfflineDRM) {
return shakaDemo.MessageIds.UNSUPPORTED_NO_LICENSE_SUPPORT;
}
}
}
// Does the browser support the asset's manifest type?
if (asset.features.includes(shakaAssets.Feature.DASH) &&
!this.support_.manifest['mpd']) {
return shakaDemo.MessageIds.UNSUPPORTED_NO_DASH_SUPPORT;
}
if (asset.features.includes(shakaAssets.Feature.HLS) &&
!this.support_.manifest['m3u8']) {
return shakaDemo.MessageIds.UNSUPPORTED_NO_HLS_SUPPORT;
}
// Does the asset contain a playable mime type?
const mimeTypes = [];
if (asset.features.includes(shakaAssets.Feature.WEBM)) {
mimeTypes.push('video/webm');
}
if (asset.features.includes(shakaAssets.Feature.MP4)) {
mimeTypes.push('video/mp4');
}
if (asset.features.includes(shakaAssets.Feature.MP2TS)) {
mimeTypes.push('video/mp2t');
}
const hasSupportedMimeType = mimeTypes.some((type) => {
return this.support_.media[type];
});
if (!hasSupportedMimeType) {
return shakaDemo.MessageIds.UNSUPPORTED_NO_FORMAT_SUPPORT;
}
return null;
}
/**
* Enable or disable the UI's trick play controls.
*
* @param {boolean} enabled
*/
setTrickPlayControlsEnabled(enabled) {
this.trickPlayControlsEnabled_ = enabled;
// Configure the UI, to add or remove the controls.
this.configureUI_();
this.remakeHash();
}
/**
* Get if the trick play controls are enabled.
*
* @return {boolean} enabled
*/
getTrickPlayControlsEnabled() {
return this.trickPlayControlsEnabled_;
}
/**
* Enable or disable the native controls.
* Goes into effect during the next load.
*
* @param {boolean} enabled
*/
setNativeControlsEnabled(enabled) {
this.nativeControlsEnabled_ = enabled;
this.remakeHash();
}
/**
* Get if the native controls are enabled.
*
* @return {boolean} enabled
*/
getNativeControlsEnabled() {
return this.nativeControlsEnabled_;
}
/**
* Look through all elements in the DOM, and look for things tagged as having
* a localized string. Then, localize them.
*
* @private
*/
localizeHTMLElements_() {
for (const element of document.querySelectorAll('[localized-string]')) {
const key = element.getAttribute('localized-string');
const value = shakaDemo.MessageIds[key];
if (value) {
element.textContent = this.getLocalizedString(value);
}
}
}
/**
* @param {!shakaDemo.MessageIds} string
* @return {string}
*/
getLocalizedString(string) {
return this.localization_.resolve(string);
}
/**
* @param {string} locale
* @return {!Promise}
* @private
*/
async loadUILocale_(locale) {
if (!locale) {
return;
}
const load = async (urlBase) => {
const url = urlBase + '/locales/' + locale + '.json';
try {
const text = await this.loadText_(url);
const obj = /** @type {!Object.<string, string>} */(JSON.parse(text));
const map = new Map(Object.entries(obj));
this.localization_.insert(locale, map);
} catch (error) {
console.warn('Unable to load locale', locale, 'for url', url);
}
};
await Promise.all([load('../ui'), load('../demo')]);
}
/** @param {string} locale */
setUILocale(locale) {
this.uiLocale_ = locale;
// Fall back to browser languages after the demo page setting.
const preferredLocales = [locale].concat(navigator.languages);
this.localization_.changeLocale(preferredLocales);
}
/** @return {string} */
getUILocale() {
return this.uiLocale_;
}
/**
* @return {?ShakaDemoAssetInfo}
* @private
*/
getLastAssetFromHash_() {
const params = this.getParams_();
const manifest = params['asset'];
const adTagUri = params['adTagUri'];
if (manifest) {
// See if it's a default asset.
for (const asset of shakaAssets.testAssets) {
if (asset.manifestUri == manifest && asset.adTagUri == adTagUri) {
return asset;
}
}
// See if it's a custom asset saved here.
for (const asset of shakaDemoCustom.assets()) {
if (asset.manifestUri == manifest) {
return asset;
}
}
// Construct a new asset.
const asset = new ShakaDemoAssetInfo(
/* name= */ 'loaded asset',
/* iconUri= */ '',
/* manifestUri= */ manifest,
/* source= */ shakaAssets.Source.CUSTOM);
if ('license' in params) {
let drmSystems = shakaDemo.Main.commonDrmSystems;
if ('drmSystem' in params) {
drmSystems = [params['drmSystem']];
}
for (const drmSystem of drmSystems) {
asset.addLicenseServer(drmSystem, params['license']);
}
}
if ('certificate' in params) {
asset.addCertificateUri(params['certificate']);
}
return asset;
}
return null;
}
/** @private */
readHash_() {
const params = this.getParams_();
if (this.player_) {
const readParam = (hashName, configName) => {
if (hashName in params) {
const existing = this.getCurrentConfigValue(configName);
// Translate the param string into a non-string value if appropriate.
// Determine what type the parsed value should be based on the current
// value.
let value = params[hashName];
if (typeof existing == 'boolean') {
value = value == 'true';
} else if (typeof existing == 'number') {
value = parseFloat(value);
}
this.configure(configName, value);
}
};
const config = this.player_.getConfiguration();
shakaDemo.Utils.runThroughHashParams(readParam, config);
const advanced = this.getCurrentConfigValue('drm.advanced');
if (advanced) {
for (const drmSystem of shakaDemo.Main.commonDrmSystems) {
if (!advanced[drmSystem]) {
advanced[drmSystem] = shakaDemo.Main.defaultAdvancedDrmConfig();
}
if ('videoRobustness' in params) {
advanced[drmSystem].videoRobustness = params['videoRobustness'];
}
if ('audioRobustness' in params) {
advanced[drmSystem].audioRobustness = params['audioRobustness'];
}
}
}
}
if ('lang' in params) {
// Load the legacy 'lang' hash value.
const lang = params['lang'];
this.configure('preferredAudioLanguage', lang);
this.configure('preferredTextLanguage', lang);
this.setUILocale(lang);
}
if ('uilang' in params) {
this.setUILocale(params['uilang']);
// TODO(#1591): Support multiple language preferences
}
if ('noadaptation' in params) {
this.configure('abr.enabled', false);
}
if ('jumpLargeGaps' in params) {
this.configure('streaming.jumpLargeGaps', true);
}
// Add compiled/uncompiled links.
this.makeVersionLinks_();
// Disable custom controls.
this.nativeControlsEnabled_ = 'nativecontrols' in params;
// Enable trick play.
if ('trickplay' in params) {
this.trickPlayControlsEnabled_ = true;
this.configureUI_();
}
// Check if uncompiled mode is supported.
if (!shakaDemo.Utils.browserSupportsUncompiledMode()) {
const uncompiledLink = document.getElementById('uncompiled-link');
goog.asserts.assert(
uncompiledLink instanceof HTMLAnchorElement, 'Wrong element type!');
uncompiledLink.setAttribute('disabled', '');
uncompiledLink.removeAttribute('href');
uncompiledLink.title = 'requires a newer browser';
}
if (shaka.log) {
if ('vv' in params) {
shaka.log.setLevel(shaka.log.Level.V2);
} else if ('v' in params) {
shaka.log.setLevel(shaka.log.Level.V1);
} else if ('debug' in params) {
shaka.log.setLevel(shaka.log.Level.DEBUG);
} else if ('info' in params) {
shaka.log.setLevel(shaka.log.Level.INFO);
}
}
}
/** @private */
makeVersionLinks_() {
const params = this.getParams_();
let buildType = 'uncompiled';
if ('build' in params) {
buildType = params['build'];
} else if ('compiled' in params) {
buildType = 'compiled';
}
for (const type of ['compiled', 'debug_compiled', 'uncompiled']) {
const elem = document.getElementById(type.split('_').join('-') + '-link');
goog.asserts.assert(
elem instanceof HTMLAnchorElement, 'Wrong element type!');
if (buildType == type) {
elem.setAttribute('disabled', '');
elem.removeAttribute('href');
elem.title = 'currently selected';
} else {