-
Notifications
You must be signed in to change notification settings - Fork 7.5k
/
player.js
5610 lines (4865 loc) · 160 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
/**
* @file player.js
*/
// Subclasses Component
import Component from './component.js';
import {version} from '../../package.json';
import document from 'global/document';
import window from 'global/window';
import evented from './mixins/evented';
import {isEvented, addEventedCallback} from './mixins/evented';
import * as Events from './utils/events.js';
import * as Dom from './utils/dom.js';
import * as Fn from './utils/fn.js';
import * as Guid from './utils/guid.js';
import * as browser from './utils/browser.js';
import {IS_CHROME, IS_WINDOWS} from './utils/browser.js';
import log, { createLogger } from './utils/log.js';
import {toTitleCase, titleCaseEquals} from './utils/str.js';
import { createTimeRange } from './utils/time.js';
import { bufferedPercent } from './utils/buffer.js';
import * as stylesheet from './utils/stylesheet.js';
import FullscreenApi from './fullscreen-api.js';
import MediaError from './media-error.js';
import {merge} from './utils/obj';
import {silencePromise, isPromise} from './utils/promise';
import textTrackConverter from './tracks/text-track-list-converter.js';
import ModalDialog from './modal-dialog';
import Tech from './tech/tech.js';
import * as middleware from './tech/middleware.js';
import {ALL as TRACK_TYPES} from './tracks/track-types';
import filterSource from './utils/filter-source';
import {getMimetype, findMimetype} from './utils/mimetypes';
import {hooks} from './utils/hooks';
import {isObject} from './utils/obj';
import icons from '../images/icons.svg';
import SpatialNavigation from './spatial-navigation.js';
// The following imports are used only to ensure that the corresponding modules
// are always included in the video.js package. Importing the modules will
// execute them and they will register themselves with video.js.
import './tech/loader.js';
import './poster-image.js';
import './tracks/text-track-display.js';
import './loading-spinner.js';
import './big-play-button.js';
import './close-button.js';
import './control-bar/control-bar.js';
import './error-display.js';
import './tracks/text-track-settings.js';
import './resize-manager.js';
import './live-tracker.js';
import './title-bar.js';
import './transient-button.js';
// Import Html5 tech, at least for disposing the original video tag.
import './tech/html5.js';
/** @import { TimeRange } from './utils/time' */
/** @import HtmlTrackElement from './tracks/html-track-element' */
/**
* @callback PlayerReadyCallback
* @this {Player}
* @returns {void}
*/
// The following tech events are simply re-triggered
// on the player when they happen
const TECH_EVENTS_RETRIGGER = [
/**
* Fired while the user agent is downloading media data.
*
* @event Player#progress
* @type {Event}
*/
/**
* Retrigger the `progress` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechProgress_
* @fires Player#progress
* @listens Tech#progress
*/
'progress',
/**
* Fires when the loading of an audio/video is aborted.
*
* @event Player#abort
* @type {Event}
*/
/**
* Retrigger the `abort` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechAbort_
* @fires Player#abort
* @listens Tech#abort
*/
'abort',
/**
* Fires when the browser is intentionally not getting media data.
*
* @event Player#suspend
* @type {Event}
*/
/**
* Retrigger the `suspend` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechSuspend_
* @fires Player#suspend
* @listens Tech#suspend
*/
'suspend',
/**
* Fires when the current playlist is empty.
*
* @event Player#emptied
* @type {Event}
*/
/**
* Retrigger the `emptied` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechEmptied_
* @fires Player#emptied
* @listens Tech#emptied
*/
'emptied',
/**
* Fires when the browser is trying to get media data, but data is not available.
*
* @event Player#stalled
* @type {Event}
*/
/**
* Retrigger the `stalled` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechStalled_
* @fires Player#stalled
* @listens Tech#stalled
*/
'stalled',
/**
* Fires when the browser has loaded meta data for the audio/video.
*
* @event Player#loadedmetadata
* @type {Event}
*/
/**
* Retrigger the `loadedmetadata` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechLoadedmetadata_
* @fires Player#loadedmetadata
* @listens Tech#loadedmetadata
*/
'loadedmetadata',
/**
* Fires when the browser has loaded the current frame of the audio/video.
*
* @event Player#loadeddata
* @type {event}
*/
/**
* Retrigger the `loadeddata` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechLoaddeddata_
* @fires Player#loadeddata
* @listens Tech#loadeddata
*/
'loadeddata',
/**
* Fires when the current playback position has changed.
*
* @event Player#timeupdate
* @type {event}
*/
/**
* Retrigger the `timeupdate` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechTimeUpdate_
* @fires Player#timeupdate
* @listens Tech#timeupdate
*/
'timeupdate',
/**
* Fires when the video's intrinsic dimensions change
*
* @event Player#resize
* @type {event}
*/
/**
* Retrigger the `resize` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechResize_
* @fires Player#resize
* @listens Tech#resize
*/
'resize',
/**
* Fires when the volume has been changed
*
* @event Player#volumechange
* @type {event}
*/
/**
* Retrigger the `volumechange` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechVolumechange_
* @fires Player#volumechange
* @listens Tech#volumechange
*/
'volumechange',
/**
* Fires when the text track has been changed
*
* @event Player#texttrackchange
* @type {event}
*/
/**
* Retrigger the `texttrackchange` event that was triggered by the {@link Tech}.
*
* @private
* @method Player#handleTechTexttrackchange_
* @fires Player#texttrackchange
* @listens Tech#texttrackchange
*/
'texttrackchange'
];
// events to queue when playback rate is zero
// this is a hash for the sole purpose of mapping non-camel-cased event names
// to camel-cased function names
const TECH_EVENTS_QUEUE = {
canplay: 'CanPlay',
canplaythrough: 'CanPlayThrough',
playing: 'Playing',
seeked: 'Seeked'
};
const BREAKPOINT_ORDER = [
'tiny',
'xsmall',
'small',
'medium',
'large',
'xlarge',
'huge'
];
const BREAKPOINT_CLASSES = {};
// grep: vjs-layout-tiny
// grep: vjs-layout-x-small
// grep: vjs-layout-small
// grep: vjs-layout-medium
// grep: vjs-layout-large
// grep: vjs-layout-x-large
// grep: vjs-layout-huge
BREAKPOINT_ORDER.forEach(k => {
const v = k.charAt(0) === 'x' ? `x-${k.substring(1)}` : k;
BREAKPOINT_CLASSES[k] = `vjs-layout-${v}`;
});
const DEFAULT_BREAKPOINTS = {
tiny: 210,
xsmall: 320,
small: 425,
medium: 768,
large: 1440,
xlarge: 2560,
huge: Infinity
};
/**
* An instance of the `Player` class is created when any of the Video.js setup methods
* are used to initialize a video.
*
* After an instance has been created it can be accessed globally in three ways:
* 1. By calling `videojs.getPlayer('example_video_1');`
* 2. By calling `videojs('example_video_1');` (not recommended)
* 2. By using it directly via `videojs.players.example_video_1;`
*
* @extends Component
* @global
*/
class Player extends Component {
/**
* Create an instance of this class.
*
* @param {Element} tag
* The original video DOM element used for configuring options.
*
* @param {Object} [options]
* Object of option names and values.
*
* @param {PlayerReadyCallback} [ready]
* Ready callback function.
*/
constructor(tag, options, ready) {
// Make sure tag ID exists
// also here.. probably better
tag.id = tag.id || options.id || `vjs_video_${Guid.newGUID()}`;
// Set Options
// The options argument overrides options set in the video tag
// which overrides globally set options.
// This latter part coincides with the load order
// (tag must exist before Player)
options = Object.assign(Player.getTagSettings(tag), options);
// Delay the initialization of children because we need to set up
// player properties first, and can't use `this` before `super()`
options.initChildren = false;
// Same with creating the element
options.createEl = false;
// don't auto mixin the evented mixin
options.evented = false;
// we don't want the player to report touch activity on itself
// see enableTouchActivity in Component
options.reportTouchActivity = false;
// If language is not set, get the closest lang attribute
if (!options.language) {
const closest = tag.closest('[lang]');
if (closest) {
options.language = closest.getAttribute('lang');
}
}
// Run base component initializing with new options
super(null, options, ready);
// Create bound methods for document listeners.
this.boundDocumentFullscreenChange_ = (e) => this.documentFullscreenChange_(e);
this.boundFullWindowOnEscKey_ = (e) => this.fullWindowOnEscKey(e);
this.boundUpdateStyleEl_ = (e) => this.updateStyleEl_(e);
this.boundApplyInitTime_ = (e) => this.applyInitTime_(e);
this.boundUpdateCurrentBreakpoint_ = (e) => this.updateCurrentBreakpoint_(e);
this.boundHandleTechClick_ = (e) => this.handleTechClick_(e);
this.boundHandleTechDoubleClick_ = (e) => this.handleTechDoubleClick_(e);
this.boundHandleTechTouchStart_ = (e) => this.handleTechTouchStart_(e);
this.boundHandleTechTouchMove_ = (e) => this.handleTechTouchMove_(e);
this.boundHandleTechTouchEnd_ = (e) => this.handleTechTouchEnd_(e);
this.boundHandleTechTap_ = (e) => this.handleTechTap_(e);
this.boundUpdatePlayerHeightOnAudioOnlyMode_ = (e) => this.updatePlayerHeightOnAudioOnlyMode_(e);
// default isFullscreen_ to false
this.isFullscreen_ = false;
// create logger
this.log = createLogger(this.id_);
// Hold our own reference to fullscreen api so it can be mocked in tests
this.fsApi_ = FullscreenApi;
// Tracks when a tech changes the poster
this.isPosterFromTech_ = false;
// Holds callback info that gets queued when playback rate is zero
// and a seek is happening
this.queuedCallbacks_ = [];
// Turn off API access because we're loading a new tech that might load asynchronously
this.isReady_ = false;
// Init state hasStarted_
this.hasStarted_ = false;
// Init state userActive_
this.userActive_ = false;
// Init debugEnabled_
this.debugEnabled_ = false;
// Init state audioOnlyMode_
this.audioOnlyMode_ = false;
// Init state audioPosterMode_
this.audioPosterMode_ = false;
// Init state audioOnlyCache_
this.audioOnlyCache_ = {
controlBarHeight: null,
playerHeight: null,
hiddenChildren: []
};
// if the global option object was accidentally blown away by
// someone, bail early with an informative error
if (!this.options_ ||
!this.options_.techOrder ||
!this.options_.techOrder.length) {
throw new Error('No techOrder specified. Did you overwrite ' +
'videojs.options instead of just changing the ' +
'properties you want to override?');
}
// Store the original tag used to set options
this.tag = tag;
// Store the tag attributes used to restore html5 element
this.tagAttributes = tag && Dom.getAttributes(tag);
// Update current language
this.language(this.options_.language);
// Update Supported Languages
if (options.languages) {
// Normalise player option languages to lowercase
const languagesToLower = {};
Object.getOwnPropertyNames(options.languages).forEach(function(name) {
languagesToLower[name.toLowerCase()] = options.languages[name];
});
this.languages_ = languagesToLower;
} else {
this.languages_ = Player.prototype.options_.languages;
}
this.resetCache_();
// Set poster
/** @type string */
this.poster_ = options.poster || '';
// Set controls
/** @type {boolean} */
this.controls_ = !!options.controls;
// Original tag settings stored in options
// now remove immediately so native controls don't flash.
// May be turned back on by HTML5 tech if nativeControlsForTouch is true
tag.controls = false;
tag.removeAttribute('controls');
this.changingSrc_ = false;
this.playCallbacks_ = [];
this.playTerminatedQueue_ = [];
// the attribute overrides the option
if (tag.hasAttribute('autoplay')) {
this.autoplay(true);
} else {
// otherwise use the setter to validate and
// set the correct value.
this.autoplay(this.options_.autoplay);
}
// check plugins
if (options.plugins) {
Object.keys(options.plugins).forEach((name) => {
if (typeof this[name] !== 'function') {
throw new Error(`plugin "${name}" does not exist`);
}
});
}
/*
* Store the internal state of scrubbing
*
* @private
* @return {Boolean} True if the user is scrubbing
*/
this.scrubbing_ = false;
this.el_ = this.createEl();
// Make this an evented object and use `el_` as its event bus.
evented(this, {eventBusKey: 'el_'});
// listen to document and player fullscreenchange handlers so we receive those events
// before a user can receive them so we can update isFullscreen appropriately.
// make sure that we listen to fullscreenchange events before everything else to make sure that
// our isFullscreen method is updated properly for internal components as well as external.
if (this.fsApi_.requestFullscreen) {
Events.on(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
this.on(this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
}
if (this.fluid_) {
this.on(['playerreset', 'resize'], this.boundUpdateStyleEl_);
}
// We also want to pass the original player options to each component and plugin
// as well so they don't need to reach back into the player for options later.
// We also need to do another copy of this.options_ so we don't end up with
// an infinite loop.
const playerOptionsCopy = merge(this.options_);
// Load plugins
if (options.plugins) {
Object.keys(options.plugins).forEach((name) => {
this[name](options.plugins[name]);
});
}
// Enable debug mode to fire debugon event for all plugins.
if (options.debug) {
this.debug(true);
}
this.options_.playerOptions = playerOptionsCopy;
this.middleware_ = [];
this.playbackRates(options.playbackRates);
if (options.experimentalSvgIcons) {
// Add SVG Sprite to the DOM
const parser = new window.DOMParser();
const parsedSVG = parser.parseFromString(icons, 'image/svg+xml');
const errorNode = parsedSVG.querySelector('parsererror');
if (errorNode) {
log.warn('Failed to load SVG Icons. Falling back to Font Icons.');
this.options_.experimentalSvgIcons = null;
} else {
const sprite = parsedSVG.documentElement;
sprite.style.display = 'none';
this.el_.appendChild(sprite);
this.addClass('vjs-svg-icons-enabled');
}
}
this.initChildren();
// Set isAudio based on whether or not an audio tag was used
this.isAudio(tag.nodeName.toLowerCase() === 'audio');
// Update controls className. Can't do this when the controls are initially
// set because the element doesn't exist yet.
if (this.controls()) {
this.addClass('vjs-controls-enabled');
} else {
this.addClass('vjs-controls-disabled');
}
// Set ARIA label and region role depending on player type
this.el_.setAttribute('role', 'region');
if (this.isAudio()) {
this.el_.setAttribute('aria-label', this.localize('Audio Player'));
} else {
this.el_.setAttribute('aria-label', this.localize('Video Player'));
}
if (this.isAudio()) {
this.addClass('vjs-audio');
}
// Check if spatial navigation is enabled in the options.
// If enabled, instantiate the SpatialNavigation class.
if (options.spatialNavigation && options.spatialNavigation.enabled) {
this.spatialNavigation = new SpatialNavigation(this);
this.addClass('vjs-spatial-navigation-enabled');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// TODO: Make this check be performed again when the window switches between monitors
// (See https://github.com/videojs/video.js/issues/5683)
if (browser.TOUCH_ENABLED) {
this.addClass('vjs-touch-enabled');
}
// iOS Safari has broken hover handling
if (!browser.IS_IOS) {
this.addClass('vjs-workinghover');
}
// Make player easily findable by ID
Player.players[this.id_] = this;
// Add a major version class to aid css in plugins
const majorVersion = version.split('.')[0];
this.addClass(`vjs-v${majorVersion}`);
// When the player is first initialized, trigger activity so components
// like the control bar show themselves if needed
this.userActive(true);
this.reportUserActivity();
this.one('play', (e) => this.listenForUserActivity_(e));
this.on('keydown', (e) => this.handleKeyDown(e));
this.on('languagechange', (e) => this.handleLanguagechange(e));
this.breakpoints(this.options_.breakpoints);
this.responsive(this.options_.responsive);
// Calling both the audio mode methods after the player is fully
// setup to be able to listen to the events triggered by them
this.on('ready', () => {
// Calling the audioPosterMode method first so that
// the audioOnlyMode can take precedence when both options are set to true
this.audioPosterMode(this.options_.audioPosterMode);
this.audioOnlyMode(this.options_.audioOnlyMode);
});
}
/**
* Destroys the video player and does any necessary cleanup.
*
* This is especially helpful if you are dynamically adding and removing videos
* to/from the DOM.
*
* @fires Player#dispose
*/
dispose() {
/**
* Called when the player is being disposed of.
*
* @event Player#dispose
* @type {Event}
*/
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
// Make sure all player-specific document listeners are unbound. This is
Events.off(document, this.fsApi_.fullscreenchange, this.boundDocumentFullscreenChange_);
Events.off(document, 'keydown', this.boundFullWindowOnEscKey_);
if (this.styleEl_ && this.styleEl_.parentNode) {
this.styleEl_.parentNode.removeChild(this.styleEl_);
this.styleEl_ = null;
}
// Kill reference to this player
Player.players[this.id_] = null;
if (this.tag && this.tag.player) {
this.tag.player = null;
}
if (this.el_ && this.el_.player) {
this.el_.player = null;
}
if (this.tech_) {
this.tech_.dispose();
this.isPosterFromTech_ = false;
this.poster_ = '';
}
if (this.playerElIngest_) {
this.playerElIngest_ = null;
}
if (this.tag) {
this.tag = null;
}
middleware.clearCacheForPlayer(this);
// remove all event handlers for track lists
// all tracks and track listeners are removed on
// tech dispose
TRACK_TYPES.names.forEach((name) => {
const props = TRACK_TYPES[name];
const list = this[props.getterName]();
// if it is not a native list
// we have to manually remove event listeners
if (list && list.off) {
list.off();
}
});
// the actual .el_ is removed here, or replaced if
super.dispose({restoreEl: this.options_.restoreEl});
}
/**
* Create the `Player`'s DOM element.
*
* @return {Element}
* The DOM element that gets created.
*/
createEl() {
let tag = this.tag;
let el;
let playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player');
const divEmbed = this.tag.tagName.toLowerCase() === 'video-js';
if (playerElIngest) {
el = this.el_ = tag.parentNode;
} else if (!divEmbed) {
el = this.el_ = super.createEl('div');
}
// Copy over all the attributes from the tag, including ID and class
// ID will now reference player box, not the video tag
const attrs = Dom.getAttributes(tag);
if (divEmbed) {
el = this.el_ = tag;
tag = this.tag = document.createElement('video');
while (el.children.length) {
tag.appendChild(el.firstChild);
}
if (!Dom.hasClass(el, 'video-js')) {
Dom.addClass(el, 'video-js');
}
el.appendChild(tag);
playerElIngest = this.playerElIngest_ = el;
// move properties over from our custom `video-js` element
// to our new `video` element. This will move things like
// `src` or `controls` that were set via js before the player
// was initialized.
Object.keys(el).forEach((k) => {
try {
tag[k] = el[k];
} catch (e) {
// we got a a property like outerHTML which we can't actually copy, ignore it
}
});
}
// set tabindex to -1 to remove the video element from the focus order
tag.setAttribute('tabindex', '-1');
attrs.tabindex = '-1';
// Workaround for #4583 on Chrome (on Windows) with JAWS.
// See https://github.com/FreedomScientific/VFO-standards-support/issues/78
// Note that we can't detect if JAWS is being used, but this ARIA attribute
// doesn't change behavior of Chrome if JAWS is not being used
if (IS_CHROME && IS_WINDOWS) {
tag.setAttribute('role', 'application');
attrs.role = 'application';
}
// Remove width/height attrs from tag so CSS can make it 100% width/height
tag.removeAttribute('width');
tag.removeAttribute('height');
if ('width' in attrs) {
delete attrs.width;
}
if ('height' in attrs) {
delete attrs.height;
}
Object.getOwnPropertyNames(attrs).forEach(function(attr) {
// don't copy over the class attribute to the player element when we're in a div embed
// the class is already set up properly in the divEmbed case
// and we want to make sure that the `video-js` class doesn't get lost
if (!(divEmbed && attr === 'class')) {
el.setAttribute(attr, attrs[attr]);
}
if (divEmbed) {
tag.setAttribute(attr, attrs[attr]);
}
});
// Update tag id/class for use as HTML5 playback tech
// Might think we should do this after embedding in container so .vjs-tech class
// doesn't flash 100% width/height, but class only applies with .video-js parent
tag.playerId = tag.id;
tag.id += '_html5_api';
tag.className = 'vjs-tech';
// Make player findable on elements
tag.player = el.player = this;
// Default state of video is paused
this.addClass('vjs-paused');
const deviceClassNames = [
'IS_SMART_TV',
'IS_TIZEN',
'IS_WEBOS',
'IS_ANDROID',
'IS_IPAD',
'IS_IPHONE',
'IS_CHROMECAST_RECEIVER'
].filter(key => browser[key]).map(key => {
return 'vjs-device-' + key.substring(3).toLowerCase().replace(/\_/g, '-');
});
this.addClass(...deviceClassNames);
// Add a style element in the player that we'll use to set the width/height
// of the player in a way that's still overridable by CSS, just like the
// video element
if (window.VIDEOJS_NO_DYNAMIC_STYLE !== true) {
this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions');
const defaultsStyleEl = Dom.$('.vjs-styles-defaults');
const head = Dom.$('head');
head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
}
this.fill_ = false;
this.fluid_ = false;
// Pass in the width/height/aspectRatio options which will update the style el
this.width(this.options_.width);
this.height(this.options_.height);
this.fill(this.options_.fill);
this.fluid(this.options_.fluid);
this.aspectRatio(this.options_.aspectRatio);
// support both crossOrigin and crossorigin to reduce confusion and issues around the name
this.crossOrigin(this.options_.crossOrigin || this.options_.crossorigin);
// Hide any links within the video/audio tag,
// because IE doesn't hide them completely from screen readers.
const links = tag.getElementsByTagName('a');
for (let i = 0; i < links.length; i++) {
const linkEl = links.item(i);
Dom.addClass(linkEl, 'vjs-hidden');
linkEl.setAttribute('hidden', 'hidden');
}
// insertElFirst seems to cause the networkState to flicker from 3 to 2, so
// keep track of the original for later so we can know if the source originally failed
tag.initNetworkState_ = tag.networkState;
// Wrap video tag in div (el/box) container
if (tag.parentNode && !playerElIngest) {
tag.parentNode.insertBefore(el, tag);
}
// insert the tag as the first child of the player element
// then manually add it to the children array so that this.addChild
// will work properly for other components
//
// Breaks iPhone, fixed in HTML5 setup.
Dom.prependTo(tag, el);
this.children_.unshift(tag);
// Set lang attr on player to ensure CSS :lang() in consistent with player
// if it's been set to something different to the doc
this.el_.setAttribute('lang', this.language_);
this.el_.setAttribute('translate', 'no');
this.el_ = el;
return el;
}
/**
* Get or set the `Player`'s crossOrigin option. For the HTML5 player, this
* sets the `crossOrigin` property on the `<video>` tag to control the CORS
* behavior.
*
* @see [Video Element Attributes]{@link https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video#attr-crossorigin}
*
* @param {string|null} [value]
* The value to set the `Player`'s crossOrigin to. If an argument is
* given, must be one of `'anonymous'` or `'use-credentials'`, or 'null'.
*
* @return {string|null|undefined}
* - The current crossOrigin value of the `Player` when getting.
* - undefined when setting
*/
crossOrigin(value) {
// `null` can be set to unset a value
if (typeof value === 'undefined') {
return this.techGet_('crossOrigin');
}
if (value !== null && value !== 'anonymous' && value !== 'use-credentials') {
log.warn(`crossOrigin must be null, "anonymous" or "use-credentials", given "${value}"`);
return;
}
this.techCall_('setCrossOrigin', value);
if (this.posterImage) {
this.posterImage.crossOrigin(value);
}
return;
}
/**
* A getter/setter for the `Player`'s width. Returns the player's configured value.
* To get the current width use `currentWidth()`.
*
* @param {number|string} [value]
* CSS value to set the `Player`'s width to.
*
* @return {number|undefined}
* - The current width of the `Player` when getting.
* - Nothing when setting
*/
width(value) {
return this.dimension('width', value);
}
/**
* A getter/setter for the `Player`'s height. Returns the player's configured value.
* To get the current height use `currentheight()`.
*
* @param {number|string} [value]
* CSS value to set the `Player`'s height to.
*
* @return {number|undefined}
* - The current height of the `Player` when getting.
* - Nothing when setting
*/
height(value) {
return this.dimension('height', value);
}
/**
* A getter/setter for the `Player`'s width & height.
*
* @param {string} dimension
* This string can be:
* - 'width'
* - 'height'
*
* @param {number|string} [value]
* Value for dimension specified in the first argument.
*
* @return {number}
* The dimension arguments value when getting (width/height).
*/
dimension(dimension, value) {
const privDimension = dimension + '_';
if (value === undefined) {
return this[privDimension] || 0;
}
if (value === '' || value === 'auto') {
// If an empty string is given, reset the dimension to be automatic
this[privDimension] = undefined;
this.updateStyleEl_();
return;
}
const parsedVal = parseFloat(value);
if (isNaN(parsedVal)) {
log.error(`Improper value "${value}" supplied for for ${dimension}`);
return;
}
this[privDimension] = parsedVal;
this.updateStyleEl_();
}
/**
* A getter/setter/toggler for the vjs-fluid `className` on the `Player`.
*
* Turning this on will turn off fill mode.
*
* @param {boolean} [bool]
* - A value of true adds the class.
* - A value of false removes the class.
* - No value will be a getter.
*
* @return {boolean|undefined}
* - The value of fluid when getting.
* - `undefined` when setting.
*/
fluid(bool) {
if (bool === undefined) {
return !!this.fluid_;
}
this.fluid_ = !!bool;
if (isEvented(this)) {
this.off(['playerreset', 'resize'], this.boundUpdateStyleEl_);
}