-
Notifications
You must be signed in to change notification settings - Fork 7.4k
/
player.js
4245 lines (3710 loc) · 119 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 tsml from 'tsml';
import evented 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 log, { createLogger } from './utils/log.js';
import toTitleCase, { titleCaseEquals } from './utils/to-title-case.js';
import { createTimeRange } from './utils/time-ranges.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 safeParseTuple from 'safe-json-parse/tuple';
import {assign} from './utils/obj';
import mergeOptions from './utils/merge-options.js';
import {silencePromise} 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 {findMimetype} from './utils/mimetypes';
import {IE_VERSION} from './utils/browser';
// 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 Html5 tech, at least for disposing the original video tag.
import './tech/html5.js';
// 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 {EventTarget~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 {EventTarget~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 {EventTarget~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 {EventTarget~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 {EventTarget~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 {EventTarget~Event}
*/
/**
* Retrigger the `stalled` 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 two ways:
* 1. By calling `videojs('example_video_1');`
* 2. By using it directly via `videojs.players.example_video_1;`
*
* @extends Component
*/
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 {Component~ReadyCallback} [ready]
* Ready callback function.
*/
constructor(tag, options, ready) {
// Make sure tag ID exists
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 = 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) {
if (typeof tag.closest === 'function') {
const closest = tag.closest('[lang]');
if (closest && closest.getAttribute) {
options.language = closest.getAttribute('lang');
}
} else {
let element = tag;
while (element && element.nodeType === 1) {
if (Dom.getAttributes(element).hasOwnProperty('lang')) {
options.language = element.getAttribute('lang');
break;
}
element = element.parentNode;
}
}
}
// Run base component initializing with new options
super(null, options, ready);
// create logger
this.log = createLogger(this.id_);
// 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;
// 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;
}
// Cache for video property values.
this.cache_ = {};
// Set poster
this.poster_ = options.poster || '';
// Set controls
this.controls_ = !!options.controls;
// Set default values for lastVolume
this.cache_.lastVolume = 1;
// 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');
// the attribute overrides the option
if (tag.hasAttribute('autoplay')) {
this.options_.autoplay = true;
} else {
// otherwise use the setter to validate and
// set the correct value.
this.autoplay(this.options_.autoplay);
}
/*
* Store the internal state of scrubbing
*
* @private
* @return {Boolean} True if the user is scrubbing
*/
this.scrubbing_ = false;
this.el_ = this.createEl();
// Set default value for lastPlaybackRate
this.cache_.lastPlaybackRate = this.defaultPlaybackRate();
// Make this an evented object and use `el_` as its event bus.
evented(this, {eventBusKey: 'el_'});
// 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 = mergeOptions(this.options_);
// Load plugins
if (options.plugins) {
const plugins = options.plugins;
Object.keys(plugins).forEach(function(name) {
if (typeof this[name] === 'function') {
this[name](plugins[name]);
} else {
throw new Error(`plugin "${name}" does not exist`);
}
}, this);
}
this.options_.playerOptions = playerOptionsCopy;
this.middleware_ = [];
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');
}
if (this.flexNotSupported_()) {
this.addClass('vjs-no-flex');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// 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', this.listenForUserActivity_);
this.on('fullscreenchange', this.handleFullscreenChange_);
this.on('stageclick', this.handleStageClick_);
this.breakpoints(this.options_.breakpoints);
this.responsive(this.options_.responsive);
this.changingSrc_ = false;
this.playWaitingForReady_ = false;
this.playOnLoadstart_ = null;
}
/**
* 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 {EventTarget~Event}
*/
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
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);
// the actual .el_ is removed here
super.dispose();
}
/**
* 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) => {
tag[k] = el[k];
});
}
// set tabindex to -1 to remove the video element from the focus order
tag.setAttribute('tabindex', '-1');
attrs.tabindex = '-1';
// Workaround for #4583 (JAWS+IE doesn't announce BPB or play button)
// 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 IE11 if JAWS is not being used
if (IE_VERSION) {
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');
// 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 overrideable 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);
// 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_ = el;
return el;
}
/**
* A getter/setter for the `Player`'s width. Returns the player's configured value.
* To get the current width use `currentWidth()`.
*
* @param {number} [value]
* The value to set the `Player`'s width to.
*
* @return {number}
* The current width of the `Player` when getting.
*/
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} [value]
* The value to set the `Player`'s heigth to.
*
* @return {number}
* The current height of the `Player` when getting.
*/
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} [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 === '') {
// 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 (bool) {
this.addClass('vjs-fluid');
this.fill(false);
} else {
this.removeClass('vjs-fluid');
}
this.updateStyleEl_();
}
/**
* A getter/setter/toggler for the vjs-fill `className` on the `Player`.
*
* Turning this on will turn off fluid 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.
*/
fill(bool) {
if (bool === undefined) {
return !!this.fill_;
}
this.fill_ = !!bool;
if (bool) {
this.addClass('vjs-fill');
this.fluid(false);
} else {
this.removeClass('vjs-fill');
}
}
/**
* Get/Set the aspect ratio
*
* @param {string} [ratio]
* Aspect ratio for player
*
* @return {string|undefined}
* returns the current aspect ratio when getting
*/
/**
* A getter/setter for the `Player`'s aspect ratio.
*
* @param {string} [ratio]
* The value to set the `Player's aspect ratio to.
*
* @return {string|undefined}
* - The current aspect ratio of the `Player` when getting.
* - undefined when setting
*/
aspectRatio(ratio) {
if (ratio === undefined) {
return this.aspectRatio_;
}
// Check for width:height format
if (!(/^\d+\:\d+$/).test(ratio)) {
throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
}
this.aspectRatio_ = ratio;
// We're assuming if you set an aspect ratio you want fluid mode,
// because in fixed mode you could calculate width and height yourself.
this.fluid(true);
this.updateStyleEl_();
}
/**
* Update styles of the `Player` element (height, width and aspect ratio).
*
* @private
* @listens Tech#loadedmetadata
*/
updateStyleEl_() {
if (window.VIDEOJS_NO_DYNAMIC_STYLE === true) {
const width = typeof this.width_ === 'number' ? this.width_ : this.options_.width;
const height = typeof this.height_ === 'number' ? this.height_ : this.options_.height;
const techEl = this.tech_ && this.tech_.el();
if (techEl) {
if (width >= 0) {
techEl.width = width;
}
if (height >= 0) {
techEl.height = height;
}
}
return;
}
let width;
let height;
let aspectRatio;
let idClass;
// The aspect ratio is either used directly or to calculate width and height.
if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
// Use any aspectRatio that's been specifically set
aspectRatio = this.aspectRatio_;
} else if (this.videoWidth() > 0) {
// Otherwise try to get the aspect ratio from the video metadata
aspectRatio = this.videoWidth() + ':' + this.videoHeight();
} else {
// Or use a default. The video element's is 2:1, but 16:9 is more common.
aspectRatio = '16:9';
}
// Get the ratio as a decimal we can use to calculate dimensions
const ratioParts = aspectRatio.split(':');
const ratioMultiplier = ratioParts[1] / ratioParts[0];
if (this.width_ !== undefined) {
// Use any width that's been specifically set
width = this.width_;
} else if (this.height_ !== undefined) {
// Or calulate the width from the aspect ratio if a height has been set
width = this.height_ / ratioMultiplier;
} else {
// Or use the video's metadata, or use the video el's default of 300
width = this.videoWidth() || 300;
}
if (this.height_ !== undefined) {
// Use any height that's been specifically set
height = this.height_;
} else {
// Otherwise calculate the height from the ratio and the width
height = width * ratioMultiplier;
}
// Ensure the CSS class is valid by starting with an alpha character
if ((/^[^a-zA-Z]/).test(this.id())) {
idClass = 'dimensions-' + this.id();
} else {
idClass = this.id() + '-dimensions';
}
// Ensure the right class is still on the player for the style element
this.addClass(idClass);
stylesheet.setTextContent(this.styleEl_, `
.${idClass} {
width: ${width}px;
height: ${height}px;
}
.${idClass}.vjs-fluid {
padding-top: ${ratioMultiplier * 100}%;
}
`);
}
/**
* Load/Create an instance of playback {@link Tech} including element
* and API methods. Then append the `Tech` element in `Player` as a child.
*
* @param {string} techName
* name of the playback technology
*
* @param {string} source
* video source
*