/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { /* eslint-disable no-var */ /* eslint-env qunit */ var mediaSources = __webpack_require__(1); var q = window.QUnit; q.module('Webpack Require'); q.test('mediaSources should be requirable and bundled via webpack', function(assert) { assert.ok(mediaSources, 'videojs-contrib-media-sources is required properly'); }); /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { /** * @file videojs-contrib-media-sources.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalWindow = __webpack_require__(2); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _flashMediaSource = __webpack_require__(3); var _flashMediaSource2 = _interopRequireDefault(_flashMediaSource); var _htmlMediaSource = __webpack_require__(137); var _htmlMediaSource2 = _interopRequireDefault(_htmlMediaSource); var _videoJs = __webpack_require__(6); var _videoJs2 = _interopRequireDefault(_videoJs); var urlCount = 0; // ------------ // Media Source // ------------ var defaults = { // how to determine the MediaSource implementation to use. There // are three available modes: // - auto: use native MediaSources where available and Flash // everywhere else // - html5: always use native MediaSources // - flash: always use the Flash MediaSource polyfill mode: 'auto' }; // store references to the media sources so they can be connected // to a video element (a swf object) // TODO: can we store this somewhere local to this module? _videoJs2['default'].mediaSources = {}; /** * Provide a method for a swf object to notify JS that a * media source is now open. * * @param {String} msObjectURL string referencing the MSE Object URL * @param {String} swfId the swf id */ var open = function open(msObjectURL, swfId) { var mediaSource = _videoJs2['default'].mediaSources[msObjectURL]; if (mediaSource) { mediaSource.trigger({ type: 'sourceopen', swfId: swfId }); } else { throw new Error('Media Source not found (Video.js)'); } }; /** * Check to see if the native MediaSource object exists and supports * an MP4 container with both H.264 video and AAC-LC audio. * * @return {Boolean} if native media sources are supported */ var supportsNativeMediaSources = function supportsNativeMediaSources() { return !!_globalWindow2['default'].MediaSource && !!_globalWindow2['default'].MediaSource.isTypeSupported && _globalWindow2['default'].MediaSource.isTypeSupported('video/mp4;codecs="avc1.4d400d,mp4a.40.2"'); }; /** * An emulation of the MediaSource API so that we can support * native and non-native functionality such as flash and * video/mp2t videos. returns an instance of HtmlMediaSource or * FlashMediaSource depending on what is supported and what options * are passed in. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/MediaSource * @param {Object} options options to use during setup. */ var MediaSource = function MediaSource(options) { var settings = _videoJs2['default'].mergeOptions(defaults, options); this.MediaSource = { open: open, supportsNativeMediaSources: supportsNativeMediaSources }; // determine whether HTML MediaSources should be used if (settings.mode === 'html5' || settings.mode === 'auto' && supportsNativeMediaSources()) { return new _htmlMediaSource2['default'](); } else if (_videoJs2['default'].getTech('Flash')) { return new _flashMediaSource2['default'](); } throw new Error('Cannot use Flash or Html5 to create a MediaSource for this video'); }; exports.MediaSource = MediaSource; MediaSource.open = open; MediaSource.supportsNativeMediaSources = supportsNativeMediaSources; /** * A wrapper around the native URL for our MSE object * implementation, this object is exposed under videojs.URL * * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/URL */ var URL = { /** * A wrapper around the native createObjectURL for our objects. * This function maps a native or emulated mediaSource to a blob * url so that it can be loaded into video.js * * @link https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL * @param {MediaSource} object the object to create a blob url to */ createObjectURL: function createObjectURL(object) { var objectUrlPrefix = 'blob:vjs-media-source/'; var url = undefined; // use the native MediaSource to generate an object URL if (object instanceof _htmlMediaSource2['default']) { url = _globalWindow2['default'].URL.createObjectURL(object.nativeMediaSource_); object.url_ = url; return url; } // if the object isn't an emulated MediaSource, delegate to the // native implementation if (!(object instanceof _flashMediaSource2['default'])) { url = _globalWindow2['default'].URL.createObjectURL(object); object.url_ = url; return url; } // build a URL that can be used to map back to the emulated // MediaSource url = objectUrlPrefix + urlCount; urlCount++; // setup the mapping back to object _videoJs2['default'].mediaSources[url] = object; return url; } }; exports.URL = URL; _videoJs2['default'].MediaSource = MediaSource; _videoJs2['default'].URL = URL; /***/ }), /* 2 */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {var win; if (typeof window !== "undefined") { win = window; } else if (typeof global !== "undefined") { win = global; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } module.exports = win; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { /** * @file flash-media-source.js */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _globalDocument = __webpack_require__(4); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _videoJs = __webpack_require__(6); var _videoJs2 = _interopRequireDefault(_videoJs); var _flashSourceBuffer = __webpack_require__(114); var _flashSourceBuffer2 = _interopRequireDefault(_flashSourceBuffer); var _flashConstants = __webpack_require__(135); var _flashConstants2 = _interopRequireDefault(_flashConstants); var _codecUtils = __webpack_require__(136); /** * A flash implmentation of HTML MediaSources and a polyfill * for browsers that don't support native or HTML MediaSources.. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource * @class FlashMediaSource * @extends videojs.EventTarget */ var FlashMediaSource = (function (_videojs$EventTarget) { _inherits(FlashMediaSource, _videojs$EventTarget); function FlashMediaSource() { var _this = this; _classCallCheck(this, FlashMediaSource); _get(Object.getPrototypeOf(FlashMediaSource.prototype), 'constructor', this).call(this); this.sourceBuffers = []; this.readyState = 'closed'; this.on(['sourceopen', 'webkitsourceopen'], function (event) { // find the swf where we will push media data _this.swfObj = _globalDocument2['default'].getElementById(event.swfId); _this.player_ = (0, _videoJs2['default'])(_this.swfObj.parentNode); _this.tech_ = _this.swfObj.tech; _this.readyState = 'open'; _this.tech_.on('seeking', function () { var i = _this.sourceBuffers.length; while (i--) { _this.sourceBuffers[i].abort(); } }); // trigger load events if (_this.swfObj) { _this.swfObj.vjs_load(); } }); } /** * Set or return the presentation duration. * * @param {Double} value the duration of the media in seconds * @param {Double} the current presentation duration * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration */ /** * We have this function so that the html and flash interfaces * are the same. * * @private */ _createClass(FlashMediaSource, [{ key: 'addSeekableRange_', value: function addSeekableRange_() {} // intentional no-op /** * Create a new flash source buffer and add it to our flash media source. * * @link https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/addSourceBuffer * @param {String} type the content-type of the source * @return {Object} the flash source buffer */ }, { key: 'addSourceBuffer', value: function addSourceBuffer(type) { var parsedType = (0, _codecUtils.parseContentType)(type); var sourceBuffer = undefined; // if this is an FLV type, we'll push data to flash if (parsedType.type === 'video/mp2t' || parsedType.type === 'audio/mp2t') { // Flash source buffers sourceBuffer = new _flashSourceBuffer2['default'](this); } else { throw new Error('NotSupportedError (Video.js)'); } this.sourceBuffers.push(sourceBuffer); return sourceBuffer; } /** * Signals the end of the stream. * * @link https://w3c.github.io/media-source/#widl-MediaSource-endOfStream-void-EndOfStreamError-error * @param {String=} error Signals that a playback error * has occurred. If specified, it must be either "network" or * "decode". */ }, { key: 'endOfStream', value: function endOfStream(error) { if (error === 'network') { // MEDIA_ERR_NETWORK this.tech_.error(2); } else if (error === 'decode') { // MEDIA_ERR_DECODE this.tech_.error(3); } if (this.readyState !== 'ended') { this.readyState = 'ended'; this.swfObj.vjs_endOfStream(); } } }]); return FlashMediaSource; })(_videoJs2['default'].EventTarget); exports['default'] = FlashMediaSource; try { Object.defineProperty(FlashMediaSource.prototype, 'duration', { /** * Return the presentation duration. * * @return {Double} the duration of the media in seconds * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration */ get: function get() { if (!this.swfObj) { return NaN; } // get the current duration from the SWF return this.swfObj.vjs_getProperty('duration'); }, /** * Set the presentation duration. * * @param {Double} value the duration of the media in seconds * @return {Double} the duration of the media in seconds * @link http://www.w3.org/TR/media-source/#widl-MediaSource-duration */ set: function set(value) { var i = undefined; var oldDuration = this.swfObj.vjs_getProperty('duration'); this.swfObj.vjs_setProperty('duration', value); if (value < oldDuration) { // In MSE, this triggers the range removal algorithm which causes // an update to occur for (i = 0; i < this.sourceBuffers.length; i++) { this.sourceBuffers[i].remove(value, oldDuration); } } return value; } }); } catch (e) { // IE8 throws if defineProperty is called on a non-DOM node. We // don't support IE8 but we shouldn't throw an error if loaded // there. FlashMediaSource.prototype.duration = NaN; } for (var property in _flashConstants2['default']) { FlashMediaSource[property] = _flashConstants2['default'][property]; } module.exports = exports['default']; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = __webpack_require__(5); var doccy; if (typeof document !== 'undefined') { doccy = document; } else { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } } module.exports = doccy; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }), /* 5 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; /** * @file video.js * @module videojs */ /* global define */ // Include the built-in techs var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); var _browser = __webpack_require__(10); var browser = _interopRequireWildcard(_browser); var _dom = __webpack_require__(11); var Dom = _interopRequireWildcard(_dom); var _setup = __webpack_require__(16); var setup = _interopRequireWildcard(_setup); var _stylesheet = __webpack_require__(18); var stylesheet = _interopRequireWildcard(_stylesheet); var _component = __webpack_require__(19); var _component2 = _interopRequireDefault(_component); var _eventTarget = __webpack_require__(23); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _events = __webpack_require__(17); var Events = _interopRequireWildcard(_events); var _player = __webpack_require__(24); var _player2 = _interopRequireDefault(_player); var _plugins = __webpack_require__(110); var _plugins2 = _interopRequireDefault(_plugins); var _mergeOptions2 = __webpack_require__(22); var _mergeOptions3 = _interopRequireDefault(_mergeOptions2); var _fn = __webpack_require__(20); var Fn = _interopRequireWildcard(_fn); var _textTrack = __webpack_require__(34); var _textTrack2 = _interopRequireDefault(_textTrack); var _audioTrack = __webpack_require__(111); var _audioTrack2 = _interopRequireDefault(_audioTrack); var _videoTrack = __webpack_require__(112); var _videoTrack2 = _interopRequireDefault(_videoTrack); var _timeRanges = __webpack_require__(25); var _formatTime = __webpack_require__(67); var _formatTime2 = _interopRequireDefault(_formatTime); var _log = __webpack_require__(13); var _log2 = _interopRequireDefault(_log); var _url = __webpack_require__(38); var Url = _interopRequireWildcard(_url); var _obj = __webpack_require__(14); var _computedStyle = __webpack_require__(75); var _computedStyle2 = _interopRequireDefault(_computedStyle); var _extend = __webpack_require__(113); var _extend2 = _interopRequireDefault(_extend); var _xhr = __webpack_require__(39); var _xhr2 = _interopRequireDefault(_xhr); var _tech = __webpack_require__(32); var _tech2 = _interopRequireDefault(_tech); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined' && Dom.isReal()) { _document2['default'].createElement('video'); _document2['default'].createElement('audio'); _document2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * * @param {string|Element} id * Video element or video element ID * * @param {Object} [options] * Optional options object for config/settings * * @param {Component~ReadyCallback} [ready] * Optional ready callback * * @return {Player} * A player instance * * @mixes videojs */ function videojs(id, options, ready) { var tag = void 0; // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (videojs.getPlayers()[id]) { // If options or ready funtion are passed, warn if (options) { _log2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { videojs.getPlayers()[id].ready(ready); } return videojs.getPlayers()[id]; } // Otherwise get element for ID tag = Dom.getEl(id); // ID is a media element } else { tag = id; } // Check for a useable element // re: nodeName, could be a box div also if (!tag || !tag.nodeName) { throw new TypeError('The element or ID supplied is not valid. (videojs)'); } // Element may have a player attr referring to an already created player instance. // If so return that otherwise set up a new player below if (tag.player || _player2['default'].players[tag.playerId]) { return tag.player || _player2['default'].players[tag.playerId]; } options = options || {}; videojs.hooks('beforesetup').forEach(function (hookFunction) { var opts = hookFunction(tag, (0, _mergeOptions3['default'])(options)); if (!(0, _obj.isObject)(opts) || Array.isArray(opts)) { _log2['default'].error('please return an object in beforesetup hooks'); return; } options = (0, _mergeOptions3['default'])(options, opts); }); var PlayerComponent = _component2['default'].getComponent('Player'); // If not, set up a new player var player = new PlayerComponent(tag, options, ready); videojs.hooks('setup').forEach(function (hookFunction) { return hookFunction(player); }); return player; } /** * An Object that contains lifecycle hooks as keys which point to an array * of functions that are run when a lifecycle is triggered */ videojs.hooks_ = {}; /** * Get a list of hooks for a specific lifecycle * * @param {string} type * the lifecyle to get hooks from * * @param {Function} [fn] * Optionally add a hook to the lifecycle that your are getting. * * @return {Array} * an array of hooks, or an empty array if there are none. */ videojs.hooks = function (type, fn) { videojs.hooks_[type] = videojs.hooks_[type] || []; if (fn) { videojs.hooks_[type] = videojs.hooks_[type].concat(fn); } return videojs.hooks_[type]; }; /** * Add a function hook to a specific videojs lifecycle. * * @param {string} type * the lifecycle to hook the function to. * * @param {Function|Function[]} * The function or array of functions to attach. */ videojs.hook = function (type, fn) { videojs.hooks(type, fn); }; /** * Remove a hook from a specific videojs lifecycle. * * @param {string} type * the lifecycle that the function hooked to * * @param {Function} fn * The hooked function to remove * * @return {boolean} * The function that was removed or undef */ videojs.removeHook = function (type, fn) { var index = videojs.hooks(type).indexOf(fn); if (index <= -1) { return false; } videojs.hooks_[type] = videojs.hooks_[type].slice(); videojs.hooks_[type].splice(index, 1); return true; }; // Add default styles if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true && Dom.isReal()) { var style = Dom.$('.vjs-styles-defaults'); if (!style) { style = stylesheet.createStyleElement('vjs-styles-defaults'); var head = Dom.$('head'); if (head) { head.insertBefore(style, head.firstChild); } stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n '); } } // Run Auto-load players // You have to wait at least once in case this script is loaded after your // video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /** * Current software version. Follows semver. * * @type {string} */ videojs.VERSION = '5.20.3'; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * @type {Object} */ videojs.options = _player2['default'].prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} * The created players */ videojs.getPlayers = function () { return _player2['default'].players; }; /** * Expose players object. * * @memberOf videojs * @property {Object} players */ videojs.players = _player2['default'].players; /** * Get a component class object by name * * @borrows Component.getComponent as videojs.getComponent */ videojs.getComponent = _component2['default'].getComponent; /** * Register a component so it can referred to by name. Used when adding to other * components, either through addChild `component.addChild('myComponent')` or through * default children options `{ children: ['myComponent'] }`. * * > NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {string} name * The class name of the component * * @param {Component} comp * The component class * * @return {Component} * The newly registered component */ videojs.registerComponent = function (name, comp) { if (_tech2['default'].isTech(comp)) { _log2['default'].warn('The ' + name + ' tech was registered as a component. It should instead be registered using videojs.registerTech(name, tech)'); } _component2['default'].registerComponent.call(_component2['default'], name, comp); }; /** * Get a Tech class object by name * * @borrows Tech.getTech as videojs.getTech */ videojs.getTech = _tech2['default'].getTech; /** * Register a Tech so it can referred to by name. * This is used in the tech order for the player. * * @borrows Tech.registerTech as videojs.registerTech */ videojs.registerTech = _tech2['default'].registerTech; /** * A suite of browser and device tests from {@link browser}. * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated since version 5.0 * @type {boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extend` keyword * * @borrows extend:extendFn as videojs.extend */ videojs.extend = _extend2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * * @borrows merge-options:mergeOptions as videojs.mergeOptions */ videojs.mergeOptions = _mergeOptions3['default']; /** * Change the context (this) of a function * * > NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function() {}.bind(newContext);` instead of this. * * @borrows fn:bind as videojs.bind */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin. * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * * @borrows plugin:plugin as videojs.plugin */ videojs.plugin = _plugins2['default']; /** * Adding languages so that they're available to all players. * Example: `videojs.addLanguage('es', { 'Hello': 'Hola' });` * * @param {string} code * The language code or dictionary property * * @param {Object} data * The data values to be translated * * @return {Object} * The resulting language dictionary object */ videojs.addLanguage = function (code, data) { var _mergeOptions; code = ('' + code).toLowerCase(); videojs.options.languages = (0, _mergeOptions3['default'])(videojs.options.languages, (_mergeOptions = {}, _mergeOptions[code] = data, _mergeOptions)); return videojs.options.languages[code]; }; /** * Log messages * * @borrows log:log as videojs.log */ videojs.log = _log2['default']; /** * Creates an emulated TimeRange object. * * @borrows time-ranges:createTimeRanges as videojs.createTimeRange */ /** * @borrows time-ranges:createTimeRanges as videojs.createTimeRanges */ videojs.createTimeRange = videojs.createTimeRanges = _timeRanges.createTimeRanges; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @borrows format-time:formatTime as videojs.formatTime */ videojs.formatTime = _formatTime2['default']; /** * Resolve and parse the elements of a URL * * @borrows url:parseUrl as videojs.parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Returns whether the url passed is a cross domain request or not. * * @borrows url:isCrossOrigin as videojs.isCrossOrigin */ videojs.isCrossOrigin = Url.isCrossOrigin; /** * Event target class. * * @borrows EventTarget as videojs.EventTarget */ videojs.EventTarget = _eventTarget2['default']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @borrows events:on as videojs.on */ videojs.on = Events.on; /** * Trigger a listener only once for an event * * @borrows events:one as videojs.one */ videojs.one = Events.one; /** * Removes event listeners from an element * * @borrows events:off as videojs.off */ videojs.off = Events.off; /** * Trigger an event for an element * * @borrows events:trigger as videojs.trigger */ videojs.trigger = Events.trigger; /** * A cross-browser XMLHttpRequest wrapper. Here's a simple example: * * @param {Object} options * settings for the request. * * @return {XMLHttpRequest|XDomainRequest} * The request object. * * @see https://github.com/Raynos/xhr */ videojs.xhr = _xhr2['default']; /** * TextTrack class * * @borrows TextTrack as videojs.TextTrack */ videojs.TextTrack = _textTrack2['default']; /** * export the AudioTrack class so that source handlers can create * AudioTracks and then add them to the players AudioTrackList * * @borrows AudioTrack as videojs.AudioTrack */ videojs.AudioTrack = _audioTrack2['default']; /** * export the VideoTrack class so that source handlers can create * VideoTracks and then add them to the players VideoTrackList * * @borrows VideoTrack as videojs.VideoTrack */ videojs.VideoTrack = _videoTrack2['default']; /** * Determines, via duck typing, whether or not a value is a DOM element. * * @borrows dom:isEl as videojs.isEl */ videojs.isEl = Dom.isEl; /** * Determines, via duck typing, whether or not a value is a text node. * * @borrows dom:isTextNode as videojs.isTextNode */ videojs.isTextNode = Dom.isTextNode; /** * Creates an element and applies properties. * * @borrows dom:createEl as videojs.createEl */ videojs.createEl = Dom.createEl; /** * Check if an element has a CSS class * * @borrows dom:hasElClass as videojs.hasClass */ videojs.hasClass = Dom.hasElClass; /** * Add a CSS class name to an element * * @borrows dom:addElClass as videojs.addClass */ videojs.addClass = Dom.addElClass; /** * Remove a CSS class name from an element * * @borrows dom:removeElClass as videojs.removeClass */ videojs.removeClass = Dom.removeElClass; /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @borrows dom:toggleElClass as videojs.toggleClass */ videojs.toggleClass = Dom.toggleElClass; /** * Apply attributes to an HTML element. * * @borrows dom:setElAttributes as videojs.setAttribute */ videojs.setAttributes = Dom.setElAttributes; /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @borrows dom:getElAttributes as videojs.getAttributes */ videojs.getAttributes = Dom.getElAttributes; /** * Empties the contents of an element. * * @borrows dom:emptyEl as videojs.emptyEl */ videojs.emptyEl = Dom.emptyEl; /** * Normalizes and appends content to an element. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @borrows dom:appendContents as videojs.appendContet */ videojs.appendContent = Dom.appendContent; /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * - String * Normalized into a text node. * * - Element, TextNode * Passed through. * * - Array * A one-dimensional array of strings, elements, nodes, or functions (which * return single strings, elements, or nodes). * * - Function * If the sole argument, is expected to produce a string, element, * node, or array. * * @borrows dom:insertContent as videojs.insertContent */ videojs.insertContent = Dom.insertContent; /** * A safe getComputedStyle with an IE8 fallback. * * This is because in Firefox, if the player is loaded in an iframe with `display:none`, * then `getComputedStyle` returns `null`, so, we do a null-check to make sure * that the player doesn't break in these cases. * See https://bugzilla.mozilla.org/show_bug.cgi?id=548397 for more details. * * @borrows computed-style:computedStyle as videojs.computedStyle */ videojs.computedStyle = _computedStyle2['default']; /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return videojs; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); // checking that module is an object too because of umdjs/umd#35 } else if ((typeof exports === 'undefined' ? 'undefined' : _typeof(exports)) === 'object' && (typeof module === 'undefined' ? 'undefined' : _typeof(module)) === 'object') { module.exports = videojs; } exports['default'] = videojs; /***/ }), /* 7 */ /***/ (function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = __webpack_require__(9); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }), /* 9 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.BACKGROUND_SIZE_SUPPORTED = exports.TOUCH_ENABLED = exports.IS_ANY_SAFARI = exports.IS_SAFARI = exports.IE_VERSION = exports.IS_IE8 = exports.CHROME_VERSION = exports.IS_CHROME = exports.IS_EDGE = exports.IS_FIREFOX = exports.IS_NATIVE_ANDROID = exports.IS_OLD_ANDROID = exports.ANDROID_VERSION = exports.IS_ANDROID = exports.IOS_VERSION = exports.IS_IOS = exports.IS_IPOD = exports.IS_IPHONE = exports.IS_IPAD = undefined; var _dom = __webpack_require__(11); var Dom = _interopRequireWildcard(_dom); var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * @file browser.js * @module browser */ var USER_AGENT = _window2['default'].navigator && _window2['default'].navigator.userAgent || ''; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPAD = exports.IS_IPAD = /iPad/i.test(USER_AGENT); // The Facebook app's UIWebView identifies as both an iPhone and iPad, so // to identify iPhones, we need to exclude iPads. // http://artsy.github.io/blog/2012/10/18/the-perils-of-ios-user-agent-sniffing/ var IS_IPHONE = exports.IS_IPHONE = /iPhone/i.test(USER_AGENT) && !IS_IPAD; var IS_IPOD = exports.IS_IPOD = /iPod/i.test(USER_AGENT); var IS_IOS = exports.IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; var IOS_VERSION = exports.IOS_VERSION = function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } return null; }(); var IS_ANDROID = exports.IS_ANDROID = /Android/i.test(USER_AGENT); var ANDROID_VERSION = exports.ANDROID_VERSION = function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i); if (!match) { return null; } var major = match[1] && parseFloat(match[1]); var minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } return null; }(); // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = exports.IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; var IS_NATIVE_ANDROID = exports.IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; var IS_FIREFOX = exports.IS_FIREFOX = /Firefox/i.test(USER_AGENT); var IS_EDGE = exports.IS_EDGE = /Edge/i.test(USER_AGENT); var IS_CHROME = exports.IS_CHROME = !IS_EDGE && /Chrome/i.test(USER_AGENT); var CHROME_VERSION = exports.CHROME_VERSION = function () { var match = USER_AGENT.match(/Chrome\/(\d+)/); if (match && match[1]) { return parseFloat(match[1]); } return null; }(); var IS_IE8 = exports.IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); var IE_VERSION = exports.IE_VERSION = function () { var result = /MSIE\s(\d+)\.\d/.exec(USER_AGENT); var version = result && parseFloat(result[1]); if (!version && /Trident\/7.0/i.test(USER_AGENT) && /rv:11.0/.test(USER_AGENT)) { // IE 11 has a different user agent string than other IE versions version = 11.0; } return version; }(); var IS_SAFARI = exports.IS_SAFARI = /Safari/i.test(USER_AGENT) && !IS_CHROME && !IS_ANDROID && !IS_EDGE; var IS_ANY_SAFARI = exports.IS_ANY_SAFARI = IS_SAFARI || IS_IOS; var TOUCH_ENABLED = exports.TOUCH_ENABLED = Dom.isReal() && ('ontouchstart' in _window2['default'] || _window2['default'].DocumentTouch && _window2['default'].document instanceof _window2['default'].DocumentTouch); var BACKGROUND_SIZE_SUPPORTED = exports.BACKGROUND_SIZE_SUPPORTED = Dom.isReal() && 'backgroundSize' in _window2['default'].document.createElement('video').style; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.$$ = exports.$ = undefined; var _templateObject = _taggedTemplateLiteralLoose(['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.'], ['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.']); exports.isReal = isReal; exports.isEl = isEl; exports.getEl = getEl; exports.createEl = createEl; exports.textContent = textContent; exports.insertElFirst = insertElFirst; exports.getElData = getElData; exports.hasElData = hasElData; exports.removeElData = removeElData; exports.hasElClass = hasElClass; exports.addElClass = addElClass; exports.removeElClass = removeElClass; exports.toggleElClass = toggleElClass; exports.setElAttributes = setElAttributes; exports.getElAttributes = getElAttributes; exports.getAttribute = getAttribute; exports.setAttribute = setAttribute; exports.removeAttribute = removeAttribute; exports.blockTextSelection = blockTextSelection; exports.unblockTextSelection = unblockTextSelection; exports.findElPosition = findElPosition; exports.getPointerPosition = getPointerPosition; exports.isTextNode = isTextNode; exports.emptyEl = emptyEl; exports.normalizeContent = normalizeContent; exports.appendContent = appendContent; exports.insertContent = insertContent; var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); var _guid = __webpack_require__(12); var Guid = _interopRequireWildcard(_guid); var _log = __webpack_require__(13); var _log2 = _interopRequireDefault(_log); var _tsml = __webpack_require__(15); var _tsml2 = _interopRequireDefault(_tsml); var _obj = __webpack_require__(14); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } /** * @file dom.js * @module dom */ /** * Detect if a value is a string with any non-whitespace characters. * * @param {string} str * The string to check * * @return {boolean} * - True if the string is non-blank * - False otherwise * */ function isNonBlankString(str) { return typeof str === 'string' && /\S/.test(str); } /** * Throws an error if the passed string has whitespace. This is used by * class methods to be relatively consistent with the classList API. * * @param {string} str * The string to check for whitespace. * * @throws {Error} * Throws an error if there is whitespace in the string. * */ function throwIfWhitespace(str) { if (/\s/.test(str)) { throw new Error('class has illegal whitespace characters'); } } /** * Produce a regular expression for matching a className within an elements className. * * @param {string} className * The className to generate the RegExp for. * * @return {RegExp} * The RegExp that will check for a specific `className` in an elements * className. */ function classRegExp(className) { return new RegExp('(^|\\s)' + className + '($|\\s)'); } /** * Whether the current DOM interface appears to be real. * * @return {Boolean} */ function isReal() { return ( // Both document and window will never be undefined thanks to `global`. _document2['default'] === _window2['default'].document && // In IE < 9, DOM methods return "object" as their type, so all we can // confidently check is that it exists. typeof _document2['default'].createElement !== 'undefined' ); } /** * Determines, via duck typing, whether or not a value is a DOM element. * * @param {Mixed} value * The thing to check * * @return {boolean} * - True if it is a DOM element * - False otherwise */ function isEl(value) { return (0, _obj.isObject)(value) && value.nodeType === 1; } /** * Creates functions to query the DOM using a given method. * * @param {string} method * The method to create the query with. * * @return {Function} * The query method */ function createQuerier(method) { return function (selector, context) { if (!isNonBlankString(selector)) { return _document2['default'][method](null); } if (isNonBlankString(context)) { context = _document2['default'].querySelector(context); } var ctx = isEl(context) ? context : _document2['default']; return ctx[method] && ctx[method](selector); }; } /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {string} id * The id of the element to get * * @return {Element|null} * Element with supplied ID or null if there wasn't one. */ function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _document2['default'].getElementById(id); } /** * Creates an element and applies properties. * * @param {string} [tagName='div'] * Name of tag to be created. * * @param {Object} [properties={}] * Element properties to be applied. * * @param {Object} [attributes={}] * Element attributes to be applied. * * @param {String|Element|TextNode|Array|Function} [content] * Contents for the element (see: {@link dom:normalizeContent}) * * @return {Element} * The element that was created. */ function createEl() { var tagName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'div'; var properties = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var attributes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var content = arguments[3]; var el = _document2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { _log2['default'].warn((0, _tsml2['default'])(_templateObject, propName, val)); el.setAttribute(propName, val); // Handle textContent since it's not supported everywhere and we have a // method for it. } else if (propName === 'textContent') { textContent(el, val); } else { el[propName] = val; } }); Object.getOwnPropertyNames(attributes).forEach(function (attrName) { el.setAttribute(attrName, attributes[attrName]); }); if (content) { appendContent(el, content); } return el; } /** * Injects text into an element, replacing any existing contents entirely. * * @param {Element} el * The element to add text content into * * @param {string} text * The text content to add. * * @return {Element} * The element with added text content. */ function textContent(el, text) { if (typeof el.textContent === 'undefined') { el.innerText = text; } else { el.textContent = text; } return el; } /** * Insert an element as the first child node of another * * @param {Element} child * Element to insert * * @param {Element} parent * Element to insert child into * */ function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {string} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); /** * Returns the cache object where data for an element is stored * * @param {Element} el * Element to store data for. * * @return {Object} * The cache object for that el that was passed in. */ function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } /** * Returns whether or not an element has cached data * * @param {Element} el * Check if this element has cached data. * * @return {boolean} * - True if the DOM element has cached data. * - False otherwise. */ function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el * Remove cached data for this element. */ function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } /** * Check if an element has a CSS class * * @param {Element} element * Element to check * * @param {string} classToCheck * Class name to check for * * @return {boolean} * - True if the element had the class * - False otherwise. * * @throws {Error} * Throws an error if `classToCheck` has white space. */ function hasElClass(element, classToCheck) { throwIfWhitespace(classToCheck); if (element.classList) { return element.classList.contains(classToCheck); } return classRegExp(classToCheck).test(element.className); } /** * Add a CSS class name to an element * * @param {Element} element * Element to add class name to. * * @param {string} classToAdd * Class name to add. * * @return {Element} * The dom element with the added class name. */ function addElClass(element, classToAdd) { if (element.classList) { element.classList.add(classToAdd); // Don't need to `throwIfWhitespace` here because `hasElClass` will do it // in the case of classList not being supported. } else if (!hasElClass(element, classToAdd)) { element.className = (element.className + ' ' + classToAdd).trim(); } return element; } /** * Remove a CSS class name from an element * * @param {Element} element * Element to remove a class name from. * * @param {string} classToRemove * Class name to remove * * @return {Element} * The dom element with class name removed. */ function removeElClass(element, classToRemove) { if (element.classList) { element.classList.remove(classToRemove); } else { throwIfWhitespace(classToRemove); element.className = element.className.split(/\s+/).filter(function (c) { return c !== classToRemove; }).join(' '); } return element; } /** * The callback definition for toggleElClass. * * @callback Dom~PredicateCallback * @param {Element} element * The DOM element of the Component. * * @param {string} classToToggle * The `className` that wants to be toggled * * @return {boolean|undefined} * - If true the `classToToggle` will get added to `element`. * - If false the `classToToggle` will get removed from `element`. * - If undefined this callback will be ignored */ /** * Adds or removes a CSS class name on an element depending on an optional * condition or the presence/absence of the class name. * * @param {Element} element * The element to toggle a class name on. * * @param {string} classToToggle * The class that should be toggled * * @param {boolean|PredicateCallback} [predicate] * See the return value for {@link Dom~PredicateCallback} * * @return {Element} * The element with a class that has been toggled. */ function toggleElClass(element, classToToggle, predicate) { // This CANNOT use `classList` internally because IE does not support the // second parameter to the `classList.toggle()` method! Which is fine because // `classList` will be used by the add/remove functions. var has = hasElClass(element, classToToggle); if (typeof predicate === 'function') { predicate = predicate(element, classToToggle); } if (typeof predicate !== 'boolean') { predicate = !has; } // If the necessary class operation matches the current state of the // element, no action is required. if (predicate === has) { return; } if (predicate) { addElClass(element, classToToggle); } else { removeElClass(element, classToToggle); } return element; } /** * Apply attributes to an HTML element. * * @param {Element} el * Element to add attributes to. * * @param {Object} [attributes] * Attributes to be applied. */ function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag * Element from which to get tag attributes. * * @return {Object} * All attributes of the element. */ function getElAttributes(tag) { var obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from var knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { var attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { var attrName = attrs[i].name; var attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Get the value of an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to get the value of * * @return {string} * value of the attribute */ function getAttribute(el, attribute) { return el.getAttribute(attribute); } /** * Set the value of an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to set * * @param {string} value * Value to set the attribute to */ function setAttribute(el, attribute, value) { el.setAttribute(attribute, value); } /** * Remove an element's attribute * * @param {Element} el * A DOM element * * @param {string} attribute * Attribute to remove */ function removeAttribute(el, attribute) { el.removeAttribute(attribute); } /** * Attempt to block the ability to select text while dragging controls */ function blockTextSelection() { _document2['default'].body.focus(); _document2['default'].onselectstart = function () { return false; }; } /** * Turn off text selection blocking */ function unblockTextSelection() { _document2['default'].onselectstart = function () { return true; }; } /** * The postion of a DOM element on the page. * * @typedef {Object} Dom~Position * * @property {number} left * Pixels to the left * * @property {number} top * Pixels on top */ /** * Offset Left. * getBoundingClientRect technique from * John Resig * * @see http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el * Element from which to get offset * * @return {Dom~Position} * The position of the element that was passed in. */ function findElPosition(el) { var box = void 0; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _document2['default'].documentElement; var body = _document2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _window2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _window2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } /** * x and y coordinates for a dom element or mouse pointer * * @typedef {Object} Dom~Coordinates * * @property {number} x * x coordinate in pixels * * @property {number} y * y coordinate in pixels */ /** * Get pointer position in element * Returns an object with x and y coordinates. * The base on the coordinates are the bottom left of the element. * * @param {Element} el * Element on which to get the pointer position on * * @param {EventTarget~Event} event * Event object * * @return {Dom~Coordinates} * A Coordinates object corresponding to the mouse position. * */ function getPointerPosition(el, event) { var position = {}; var box = findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var boxY = box.top; var boxX = box.left; var pageY = event.pageY; var pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; } /** * Determines, via duck typing, whether or not a value is a text node. * * @param {Mixed} value * Check if this value is a text node. * * @return {boolean} * - True if it is a text node * - False otherwise */ function isTextNode(value) { return (0, _obj.isObject)(value) && value.nodeType === 3; } /** * Empties the contents of an element. * * @param {Element} el * The element to empty children from * * @return {Element} * The element with no children */ function emptyEl(el) { while (el.firstChild) { el.removeChild(el.firstChild); } return el; } /** * Normalizes content for eventual insertion into the DOM. * * This allows a wide range of content definition methods, but protects * from falling into the trap of simply writing to `innerHTML`, which is * an XSS concern. * * The content for an element can be passed in multiple types and * combinations, whose behavior is as follows: * * @param {String|Element|TextNode|Array|Function} content * - String: Normalized into a text node. * - Element/TextNode: Passed through. * - Array: A one-dimensional array of strings, elements, nodes, or functions * (which return single strings, elements, or nodes). * - Function: If the sole argument, is expected to produce a string, element, * node, or array as defined above. * * @return {Array} * All of the content that was passed in normalized. */ function normalizeContent(content) { // First, invoke content if it is a function. If it produces an array, // that needs to happen before normalization. if (typeof content === 'function') { content = content(); } // Next up, normalize to an array, so one or many items can be normalized, // filtered, and returned. return (Array.isArray(content) ? content : [content]).map(function (value) { // First, invoke value if it is a function to produce a new value, // which will be subsequently normalized to a Node of some kind. if (typeof value === 'function') { value = value(); } if (isEl(value) || isTextNode(value)) { return value; } if (typeof value === 'string' && /\S/.test(value)) { return _document2['default'].createTextNode(value); } }).filter(function (value) { return value; }); } /** * Normalizes and appends content to an element. * * @param {Element} el * Element to append normalized content to. * * * @param {String|Element|TextNode|Array|Function} content * See the `content` argument of {@link dom:normalizeContent} * * @return {Element} * The element with appended normalized content. */ function appendContent(el, content) { normalizeContent(content).forEach(function (node) { return el.appendChild(node); }); return el; } /** * Normalizes and inserts content into an element; this is identical to * `appendContent()`, except it empties the element first. * * @param {Element} el * Element to insert normalized content into. * * @param {String|Element|TextNode|Array|Function} content * See the `content` argument of {@link dom:normalizeContent} * * @return {Element} * The element with inserted normalized content. * */ function insertContent(el, content) { return appendContent(emptyEl(el), content); } /** * Finds a single DOM element matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {Element|null} * The element that was found or null. */ var $ = exports.$ = createQuerier('querySelector'); /** * Finds a all DOM elements matching `selector` within the optional * `context` of another DOM element (defaulting to `document`). * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|String} [context=document] * A DOM element within which to query. Can also be a selector * string in which case the first matching element will be used * as context. If missing (or no element matches selector), falls * back to `document`. * * @return {NodeList} * A element list of elements that were found. Will be empty if none were found. * */ var $$ = exports.$$ = createQuerier('querySelectorAll'); /***/ }), /* 12 */ /***/ (function(module, exports) { "use strict"; exports.__esModule = true; exports.newGUID = newGUID; /** * @file guid.js * @module guid */ /** * Unique ID for an element or function * @type {Number} */ var _guid = 1; /** * Get a unique auto-incrementing ID by number that has not been returned before. * * @return {number} * A new unique ID. */ function newGUID() { return _guid++; } /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.logByType = undefined; var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); var _browser = __webpack_require__(10); var _obj = __webpack_require__(14); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var log = void 0; /** * Log messages to the console and history based on the type of message * * @param {string} type * The name of the console method to use. * * @param {Array} args * The arguments to be passed to the matching console method. * * @param {boolean} [stringify] * By default, only old IEs should get console argument stringification, * but this is exposed as a parameter to facilitate testing. */ /** * @file log.js * @module log */ var logByType = exports.logByType = function logByType(type, args) { var stringify = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : !!_browser.IE_VERSION && _browser.IE_VERSION < 11; if (type !== 'log') { // add the type to the front of the message when it's not "log" args.unshift(type.toUpperCase() + ':'); } // add to history log.history.push(args); // add console prefix after adding to history args.unshift('VIDEOJS:'); // If there's no console then don't try to output messages, but they will // still be stored in `log.history`. // // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist // when the module is executed. var fn = _window2['default'].console && _window2['default'].console[type]; // Bail out if there's no console. if (!fn) { return; } // IEs previous to 11 log objects uselessly as "[object Object]"; so, JSONify // objects and arrays for those less-capable browsers. if (stringify) { args = args.map(function (a) { if ((0, _obj.isObject)(a) || Array.isArray(a)) { try { return JSON.stringify(a); } catch (x) { return String(a); } } // Cast to string before joining, so we get null and undefined explicitly // included in output (as we would in a modern console). return String(a); }).join(' '); } // Old IE versions do not allow .apply() for console methods (they are // reported as objects rather than functions). if (!fn.apply) { fn(args); } else { fn[Array.isArray(args) ? 'apply' : 'call'](_window2['default'].console, args); } }; /** * Log plain debug messages * * @param {Mixed[]} args * One or more messages or objects that should be logged. */ log = function log() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } logByType('log', args); }; /** * Keep a history of log messages * * @type {Array} */ log.history = []; /** * Log error messages * * @param {Mixed[]} args * One or more messages or objects that should be logged as an error */ log.error = function () { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } return logByType('error', args); }; /** * Log warning messages * * @param {Mixed[]} args * One or more messages or objects that should be logged as a warning. */ log.warn = function () { for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } return logByType('warn', args); }; exports['default'] = log; /***/ }), /* 14 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; exports.each = each; exports.reduce = reduce; exports.assign = assign; exports.isObject = isObject; exports.isPlain = isPlain; /** * @file obj.js * @module obj */ /** * @callback obj:EachCallback * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over */ /** * @callback obj:ReduceCallback * * @param {Mixed} accum * The value that is accumulating over the reduce loop. * * @param {Mixed} value * The current key for the object that is being iterated over. * * @param {string} key * The current key-value for object that is being iterated over * * @return {Mixed} * The new accumulated value. */ var toString = Object.prototype.toString; /** * Get the keys of an Object * * @param {Object} * The Object to get the keys from * * @return {string[]} * An array of the keys from the object. Returns an empty array if the * object passed in was invalid or had no keys. * * @private */ var keys = function keys(object) { return isObject(object) ? Object.keys(object) : []; }; /** * Array-like iteration for objects. * * @param {Object} object * The object to iterate over * * @param {obj:EachCallback} fn * The callback function which is called for each key in the object. */ function each(object, fn) { keys(object).forEach(function (key) { return fn(object[key], key); }); } /** * Array-like reduce for objects. * * @param {Object} object * The Object that you want to reduce. * * @param {Function} fn * A callback function which is called for each key in the object. It * receives the accumulated value and the per-iteration value and key * as arguments. * * @param {Mixed} [initial = 0] * Starting value * * @return {Mixed} * The final accumulated value. */ function reduce(object, fn) { var initial = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; return keys(object).reduce(function (accum, key) { return fn(accum, object[key], key); }, initial); } /** * Object.assign-style object shallow merge/extend. * * @param {Object} target * @param {Object} ...sources * @return {Object} */ function assign(target) { for (var _len = arguments.length, sources = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { sources[_key - 1] = arguments[_key]; } if (Object.assign) { return Object.assign.apply(Object, [target].concat(sources)); } sources.forEach(function (source) { if (!source) { return; } each(source, function (value, key) { target[key] = value; }); }); return target; } /** * Returns whether a value is an object of any kind - including DOM nodes, * arrays, regular expressions, etc. Not functions, though. * * This avoids the gotcha where using `typeof` on a `null` value * results in `'object'`. * * @param {Object} value * @return {Boolean} */ function isObject(value) { return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object'; } /** * Returns whether an object appears to be a "plain" object - that is, a * direct instance of `Object`. * * @param {Object} value * @return {Boolean} */ function isPlain(value) { return isObject(value) && toString.call(value) === '[object Object]' && value.constructor === Object; } /***/ }), /* 15 */ /***/ (function(module, exports) { function clean (s) { return s.replace(/\n\r?\s*/g, '') } module.exports = function tsml (sa) { var s = '' , i = 0 for (; i < arguments.length; i++) s += clean(sa[i]) + (arguments[i + 1] || '') return s } /***/ }), /* 16 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.hasLoaded = exports.autoSetupTimeout = exports.autoSetup = undefined; var _dom = __webpack_require__(11); var Dom = _interopRequireWildcard(_dom); var _events = __webpack_require__(17); var Events = _interopRequireWildcard(_events); var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * @file setup.js - Functions for setting up a player without * user interaction based on the data-setup `attribute` of the video tag. * * @module setup */ var _windowLoaded = false; var videojs = void 0; /** * Set up any tags that have a data-setup `attribute` when the player is started. */ var autoSetup = function autoSetup() { // Protect against breakage in non-browser environments. if (!Dom.isReal()) { return; } // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop // through each list of elements to build up a new, combined list of elements. var vids = _document2['default'].getElementsByTagName('video'); var audios = _document2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var _i = 0, _e = audios.length; _i < _e; _i++) { mediaEls.push(audios[_i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var _i2 = 0, _e2 = mediaEls.length; _i2 < _e2; _i2++) { var mediaEl = mediaEls[_i2]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of // 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl.player === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; /** * Wait until the page is loaded before running autoSetup. This will be called in * autoSetup if `hasLoaded` returns false. * * @param {number} wait * How long to wait in ms * * @param {videojs} [vjs] * The videojs library function */ function autoSetupTimeout(wait, vjs) { if (vjs) { videojs = vjs; } _window2['default'].setTimeout(autoSetup, wait); } if (Dom.isReal() && _document2['default'].readyState === 'complete') { _windowLoaded = true; } else { /** * Listen for the load event on window, and set _windowLoaded to true. * * @listens load */ Events.one(_window2['default'], 'load', function () { _windowLoaded = true; }); } /** * check if the document has been loaded */ var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.fixEvent = fixEvent; exports.on = on; exports.off = off; exports.trigger = trigger; exports.one = one; var _dom = __webpack_require__(11); var Dom = _interopRequireWildcard(_dom); var _guid = __webpack_require__(12); var Guid = _interopRequireWildcard(_guid); var _log = __webpack_require__(13); var _log2 = _interopRequireDefault(_log); var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem * Element to clean up * * @param {string} type * Type of event to clean up */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn * The event method we want to use. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string} type * Type of event to bind to. * * @param {EventTarget~EventListener} callback * Event listener. */ /** * @file events.js. An Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. * * @module events */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { // Call the event method for each one of the types fn(elem, type, callback); }); } /** * Fix a native event to have standard property values * * @param {Object} event * Event object to fix. * * @return {Object} * Fixed event object. */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _window2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation // and webkitMovementX/Y if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _document2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX !== null && event.clientX !== undefined) { var doc = _document2['default'].documentElement; var body = _document2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button !== null && event.button !== undefined) { // The following is disabled because it does not pass videojs-standard // and... yikes. /* eslint-disable */ event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; /* eslint-enable */ } } // Returns fixed-up instance return event; } /** * Whether passive event listeners are supported */ var _supportsPassive = false; (function () { try { var opts = Object.defineProperty({}, 'passive', { get: function get() { _supportsPassive = true; } }); _window2['default'].addEventListener('test', null, opts); } catch (e) { // disregard } })(); /** * Touch events Chrome expects to be passive */ var passiveEvents = ['touchstart', 'touchmove']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem * Element or object to bind listeners to * * @param {string|string[]} type * Type of event to bind to. * * @param {EventTarget~EventListener} fn * Event listener. */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) { data.handlers = {}; } if (!data.handlers[type]) { data.handlers[type] = []; } if (!fn.guid) { fn.guid = Guid.newGUID(); } data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) { return; } event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { try { handlersCopy[m].call(elem, event, hash); } catch (e) { _log2['default'].error(e); } } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { var options = false; if (_supportsPassive && passiveEvents.indexOf(type) > -1) { options = { passive: true }; } elem.addEventListener(type, data.dispatcher, options); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem * Object to remove listeners from. * * @param {string|string[]} [type] * Type of listener to remove. Don't include to remove all events from element. * * @param {EventTarget~EventListener} [fn] * Specific listener to remove. Don't include to remove listeners for an event * type. */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) { return; } var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); } return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) { return; } // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem * Element to trigger an event on * * @param {EventTarget~Event|string} event * A string (the type) or an event object with a type attribute * * @param {Object} [hash] * data hash to pass along with the event * * @return {boolean|undefined} * - Returns the opposite of `defaultPrevented` if default was prevented * - Otherwise returns undefined */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event * * @param {Element|Object} elem * Element or object to bind to. * * @param {string|string[]} type * Name/type of event * * @param {Event~EventListener} fn * Event Listener function */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.setTextContent = exports.createStyleElement = undefined; var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Create a DOM syle element given a className for it. * * @param {string} className * The className to add to the created style element. * * @return {Element} * The element that was created. */ var createStyleElement = exports.createStyleElement = function createStyleElement(className) { var style = _document2['default'].createElement('style'); style.className = className; return style; }; /** * Add text to a DOM element. * * @param {Element} el * The Element to add text content to. * * @param {string} content * The text to add to the element. */ /** * @file stylesheet.js * @module stylesheet */ var setTextContent = exports.setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; /***/ }), /* 19 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); var _dom = __webpack_require__(11); var Dom = _interopRequireWildcard(_dom); var _fn = __webpack_require__(20); var Fn = _interopRequireWildcard(_fn); var _guid = __webpack_require__(12); var Guid = _interopRequireWildcard(_guid); var _events = __webpack_require__(17); var Events = _interopRequireWildcard(_events); var _log = __webpack_require__(13); var _log2 = _interopRequireDefault(_log); var _toTitleCase = __webpack_require__(21); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); var _mergeOptions = __webpack_require__(22); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Player Component - Base class for all UI objects * * @file component.js */ /** * Base class for all UI Components. * Components are UI objects which represent both a javascript object and an element * in the DOM. They can be children of other components, and can have * children themselves. * * Components can also use methods from {@link EventTarget} */ var Component = function () { /** * A callback that is called when a component is ready. Does not have any * paramters and any callback value will be ignored. * * @callback Component~ReadyCallback * @this Component */ /** * Creates an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. # * @param {Object[]} [options.children] * An array of children objects to intialize this component with. Children objects have * a name property that will be used if more than one component of the same type needs to be * added. * * @param {Component~ReadyCallback} [ready] * Function that gets called when the `Component` is ready. */ function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = (0, _mergeOptions2['default'])({}, this.options_); // Updated options with supplied options options = this.options_ = (0, _mergeOptions2['default'])(this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the `Component` and all child components. * * @fires Component#dispose */ Component.prototype.dispose = function dispose() { /** * Triggered when a `Component` is disposed. * * @event Component#dispose * @type {EventTarget~Event} * * @property {boolean} [bubbles=false] * set to false so that the close event does not * bubble up */ this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the {@link Player} that the `Component` has attached to. * * @return {Player} * The player that this `Component` has attached to. */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects with new options. * > Note: When both `obj` and `options` contain properties whose values are objects. * The two properties get merged using {@link module:mergeOptions} * * @param {Object} obj * The object that contains new options. * * @return {Object} * A new object of `this.options_` and `obj` merged together. * * @deprecated since version 5 */ Component.prototype.options = function options(obj) { _log2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = (0, _mergeOptions2['default'])(this.options_, obj); return this.options_; }; /** * Get the `Component`s DOM element * * @return {Element} * The DOM element for this `Component`. */ Component.prototype.el = function el() { return this.el_; }; /** * Create the `Component`s DOM element. * * @param {string} [tagName] * Element's DOM node type. e.g. 'div' * * @param {Object} [properties] * An object of properties that should be set. * * @param {Object} [attributes] * An object of attributes that should be set. * * @return {Element} * The element that gets created. */ Component.prototype.createEl = function createEl(tagName, properties, attributes) { return Dom.createEl(tagName, properties, attributes); }; /** * Localize a string given the string in english. * * @param {string} string * The string to localize. * * @return {string} * The localized string or if no localization exists the english string. */ Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the `Component`s DOM element. This is where children get inserted. * This will usually be the the same as the element returned in {@link Component#el}. * * @return {Element} * The content element for this `Component`. */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get this `Component`s ID * * @return {string} * The id of this `Component` */ Component.prototype.id = function id() { return this.id_; }; /** * Get the `Component`s name. The name gets used to reference the `Component` * and is set during registration. * * @return {string} * The name of this `Component`. */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * * @return {Array} * The children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns the child `Component` with the given `id`. * * @param {string} id * The id of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `id` or undefined. */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns the child `Component` with the given `name`. * * @param {string} name * The name of the child `Component` to get. * * @return {Component|undefined} * The child `Component` with the given `name` or undefined. */ Component.prototype.getChild = function getChild(name) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); return this.childNameIndex_[name]; }; /** * Add a child `Component` inside the current `Component`. * * * @param {string|Component} child * The name or instance of a child to add. * * @param {Object} [options={}] * The key/value store of options that will get passed to children of * the child. * * @param {number} [index=this.children_.length] * The index to attempt to add a child into. * * @return {Component} * The `Component` that gets added as a child. When using a string the * `Component` will get created by this process. */ Component.prototype.addChild = function addChild(child) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.children_.length; var component = void 0; var componentName = void 0; // If child is a string, create component with options if (typeof child === 'string') { componentName = (0, _toTitleCase2['default'])(child); // Options can also be specified as a boolean, // so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _log2['default'].warn('Initializing a child component with `true` is deprecated.' + 'Children should be defined in an array when possible, ' + 'but if necessary use an object instead of `true`.'); options = {}; } var componentClassName = options.componentClass || componentName; // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); if (!ComponentClass) { throw new Error('Component ' + componentClassName + ' does not exist'); } // data stored directly on the videojs object may be // misidentified as a component to retain // backwards-compatibility with 4.x. check to make sure the // component class can be instantiated. if (typeof ComponentClass !== 'function') { return null; } component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.splice(index, 0, component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && (0, _toTitleCase2['default'])(component.name()); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { var childNodes = this.contentEl().children; var refNode = childNodes[index] || null; this.contentEl().insertBefore(component.el(), refNode); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child `Component` from this `Component`s list of children. Also removes * the child `Component`s element from this `Component`s element. * * @param {Component} component * The child `Component` to remove. */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child `Component`s based upon options. */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { // `this` is `parent` var parentOptions = this.options_; var handleAdd = function handleAdd(child) { var name = child.name; var opts = child.opts; // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options // to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each var newChild = _this.addChild(name, opts); if (newChild) { _this[name] = newChild; } }; // Allow for an array of children details to passed in the options var workingChildren = void 0; var Tech = Component.getComponent('Tech'); if (Array.isArray(children)) { workingChildren = children; } else { workingChildren = Object.keys(children); } workingChildren // children that are in this.options_ but also in workingChildren would // give us extra children we do not want. So, we want to filter them out. .concat(Object.keys(this.options_).filter(function (child) { return !workingChildren.some(function (wchild) { if (typeof wchild === 'string') { return child === wchild; } return child === wchild.name; }); })).map(function (child) { var name = void 0; var opts = void 0; if (typeof child === 'string') { name = child; opts = children[name] || _this.options_[name] || {}; } else { name = child.name; opts = child; } return { name: name, opts: opts }; }).filter(function (child) { // we have to make sure that child.name isn't in the techOrder since // techs are registerd as Components but can't aren't compatible // See https://github.com/videojs/video.js/issues/2772 var c = Component.getComponent(child.opts.componentClass || (0, _toTitleCase2['default'])(child.name)); return c && !Tech.isTech(c); }).forEach(handleAdd); } }; /** * Builds the default DOM class name. Should be overriden by sub-components. * * @return {string} * The DOM class name for this object. * * @abstract */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an `event listener` to this `Component`s element. * * The benefit of using this over the following: * - `VjsEvents.on(otherElement, 'eventName', myFunc)` * - `otherComponent.on('eventName', myFunc)` * * 1. Is that the listeners will get cleaned up when either component gets disposed. * 1. It will also bind `myComponent` as the context of `myFunc`. * > NOTE: If you remove the element from the DOM that has used `on` you need to * clean up references using: `myComponent.trigger(el, 'dispose')` * This will also allow the browser to garbage collect it. In special * cases such as with `window` and `document`, which are both permanent, * this is not necessary. * * @param {string|Component|string[]} [first] * The event name, and array of event names, or another `Component`. * * @param {EventTarget~EventListener|string|string[]} [second] * The listener function, an event name, or an Array of events names. * * @param {EventTarget~EventListener} [third] * The event handler if `first` is a `Component` and `second` is an event name * or an Array of event names. * * @return {Component} * Returns itself; method can be chained. * * @listens Component#dispose */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { var target = first; var type = second; var fn = Fn.bind(this, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; this.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } } return this; }; /** * Remove an event listener from this `Component`s element. If the second argument is * exluded all listeners for the type passed in as the first argument will be removed. * * @param {string|Component|string[]} [first] * The event name, and array of event names, or another `Component`. * * @param {EventTarget~EventListener|string|string[]} [second] * The listener function, an event name, or an Array of events names. * * @param {EventTarget~EventListener} [third] * The event handler if `first` is a `Component` and `second` is an event name * or an Array of event names. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener that gets triggered only once and then gets removed. * * @param {string|Component|string[]} [first] * The event name, and array of event names, or another `Component`. * * @param {EventTarget~EventListener|string|string[]} [second] * The listener function, an event name, or an Array of events names. * * @param {EventTarget~EventListener} [third] * The event handler if `first` is a `Component` and `second` is an event name * or an Array of event names. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.one = function one(first, second, third) { var _this3 = this, _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { var target = first; var type = second; var fn = Fn.bind(this, third); var newFunc = function newFunc() { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; this.on(target, type, newFunc); } return this; }; /** * Trigger an event on an element. * * @param {EventTarget~Event|Object|string} event * The event name, and Event, or an event-like object with a type attribute * set to the event name. * * @param {Object} [hash] * Data hash to pass along with the event * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. If the ready event has already * happened it will trigger the function immediately. * * @param {Component~ReadyCallback} fn * A function to call when ready is triggered. * * @param {boolean} [sync=false] * Execute the listener synchronously if `Component` is ready. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.ready = function ready(fn) { var sync = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (fn) { if (this.isReady_) { if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger all the ready listeners for this `Component`. * * @fires Component#ready */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; // Reset Ready Queue this.readyQueue_ = []; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); } // Allow for using event listeners also /** * Triggered when a `Component` is ready. * * @event Component#ready * @type {EventTarget~Event} */ this.trigger('ready'); }, 1); }; /** * Find a single DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelector`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {Element|null} * the dom element that was found, or null * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ Component.prototype.$ = function $(selector, context) { return Dom.$(selector, context || this.contentEl()); }; /** * Finds all DOM element matching a `selector`. This can be within the `Component`s * `contentEl()` or another custom context. * * @param {string} selector * A valid CSS selector, which will be passed to `querySelectorAll`. * * @param {Element|string} [context=this.contentEl()] * A DOM element within which to query. Can also be a selector string in * which case the first matching element will get used as context. If * missing `this.contentEl()` gets used. If `this.contentEl()` returns * nothing it falls back to `document`. * * @return {NodeList} * a list of dom elements that were found * * @see [Information on CSS Selectors](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_Started/Selectors) */ Component.prototype.$$ = function $$(selector, context) { return Dom.$$(selector, context || this.contentEl()); }; /** * Check if a component's element has a CSS class name. * * @param {string} classToCheck * CSS class name to check. * * @return {boolean} * - True if the `Component` has the class. * - False if the `Component` does not have the class` */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the `Component`s element. * * @param {string} classToAdd * CSS class name to add * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove a CSS class name from the `Component`s element. * * @param {string} classToRemove * CSS class name to remove * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Add or remove a CSS class name from the component's element. * - `classToToggle` gets added when {@link Component#hasClass} would return false. * - `classToToggle` gets removed when {@link Component#hasClass} would return true. * * @param {string} classToToggle * The class to add or remove based on (@link Component#hasClass} * * @param {boolean|Dom~predicate} [predicate] * An {@link Dom~predicate} function or a boolean * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.toggleClass = function toggleClass(classToToggle, predicate) { Dom.toggleElClass(this.el_, classToToggle, predicate); return this; }; /** * Show the `Component`s element if it is hidden by removing the * 'vjs-hidden' class name from it. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the `Component`s element if it is currently showing by adding the * 'vjs-hidden` class name to it. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock a `Component`s element in its visible state by adding the 'vjs-lock-showing' * class name to it. Used during fadeIn/fadeOut. * * @return {Component} * Returns itself; method can be chained. * * @private */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock a `Component`s element from its visible state by removing the 'vjs-lock-showing' * class name from it. Used during fadeIn/fadeOut. * * @return {Component} * Returns itself; method can be chained. * * @private */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Get the value of an attribute on the `Component`s element. * * @param {string} attribute * Name of the attribute to get the value from. * * @return {string|null} * - The value of the attribute that was asked for. * - Can be an empty string on some browsers if the attribute does not exist * or has no value * - Most browsers will return null if the attibute does not exist or has * no value. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute} */ Component.prototype.getAttribute = function getAttribute(attribute) { return Dom.getAttribute(this.el_, attribute); }; /** * Set the value of an attribute on the `Component`'s element * * @param {string} attribute * Name of the attribute to set. * * @param {string} value * Value to set the attribute to. * * @return {Component} * Returns itself; method can be chained. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute} */ Component.prototype.setAttribute = function setAttribute(attribute, value) { Dom.setAttribute(this.el_, attribute, value); return this; }; /** * Remove an attribute from the `Component`s element. * * @param {string} attribute * Name of the attribute to remove. * * @return {Component} * Returns itself; method can be chained. * * @see [DOM API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Element/removeAttribute} */ Component.prototype.removeAttribute = function removeAttribute(attribute) { Dom.removeAttribute(this.el_, attribute); return this; }; /** * Get or set the width of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The width that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the resize event trigger * * @return {Component|number|string} * - The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. * - Returns itself when setting; method can be chained. */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component based upon the CSS styles. * See {@link Component#dimension} for more detailed information. * * @param {number|string} [num] * The height that you want to set postfixed with '%', 'px' or nothing. * * @param {boolean} [skipListeners] * Skip the resize event trigger * * @return {Component|number|string} * - The width when getting, zero if there is no width. Can be a string * postpixed with '%' or 'px'. * - Returns itself when setting; method can be chained. */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both the width and height of the `Component` element at the same time. * * @param {number|string} width * Width to set the `Component`s element to. * * @param {number|string} height * Height to set the `Component`s element to. * * @return {Component} * Returns itself; method can be chained. */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height of the `Component` element. This is the shared code * for the {@link Component#width} and {@link Component#height}. * * Things to know: * - If the width or height in an number this will return the number postfixed with 'px'. * - If the width/height is a percent this will return the percent postfixed with '%' * - Hidden elements have a width of 0 with `window.getComputedStyle`. This function * defaults to the `Component`s `style.width` and falls back to `window.getComputedStyle`. * See [this]{@link http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/} * for more information * - If you want the computed style of the component, use {@link Component#currentWidth} * and {@link {Component#currentHeight} * * @fires Component#resize * * @param {string} widthOrHeight 8 'width' or 'height' * * @param {number|string} [num] 8 New dimension * * @param {boolean} [skipListeners] * Skip resize event trigger * * @return {Component} * - the dimension when getting or 0 if unset * - Returns itself when setting; method can be chained. */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { /** * Triggered when a component is resized. * * @event Component#resize * @type {EventTarget~Event} */ this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + (0, _toTitleCase2['default'])(widthOrHeight)], 10); }; /** * Get the width or the height of the `Component` elements computed style. Uses * `window.getComputedStyle`. * * @param {string} widthOrHeight * A string containing 'width' or 'height'. Whichever one you want to get. * * @return {number} * The dimension that gets asked for or 0 if nothing was set * for that dimension. */ Component.prototype.currentDimension = function currentDimension(widthOrHeight) { var computedWidthOrHeight = 0; if (widthOrHeight !== 'width' && widthOrHeight !== 'height') { throw new Error('currentDimension only accepts width or height value'); } if (typeof _window2['default'].getComputedStyle === 'function') { var computedStyle = _window2['default'].getComputedStyle(this.el_); computedWidthOrHeight = computedStyle.getPropertyValue(widthOrHeight) || computedStyle[widthOrHeight]; } // remove 'px' from variable and parse as integer computedWidthOrHeight = parseFloat(computedWidthOrHeight); // if the computed value is still 0, it's possible that the browser is lying // and we want to check the offset values. // This code also runs on IE8 and wherever getComputedStyle doesn't exist. if (computedWidthOrHeight === 0) { var rule = 'offset' + (0, _toTitleCase2['default'])(widthOrHeight); computedWidthOrHeight = this.el_[rule]; } return computedWidthOrHeight; }; /** * An object that contains width and height values of the `Component`s * computed style. Uses `window.getComputedStyle`. * * @typedef {Object} Component~DimensionObject * * @property {number} width * The width of the `Component`s computed style. * * @property {number} height * The height of the `Component`s computed style. */ /** * Get an object that contains width and height values of the `Component`s * computed style. * * @return {Component~DimensionObject} * The dimensions of the components element */ Component.prototype.currentDimensions = function currentDimensions() { return { width: this.currentDimension('width'), height: this.currentDimension('height') }; }; /** * Get the width of the `Component`s computed style. Uses `window.getComputedStyle`. * * @return {number} width * The width of the `Component`s computed style. */ Component.prototype.currentWidth = function currentWidth() { return this.currentDimension('width'); }; /** * Get the height of the `Component`s computed style. Uses `window.getComputedStyle`. * * @return {number} height * The height of the `Component`s computed style. */ Component.prototype.currentHeight = function currentHeight() { return this.currentDimension('height'); }; /** * Set the focus to this component */ Component.prototype.focus = function focus() { this.el_.focus(); }; /** * Remove the focus from this component */ Component.prototype.blur = function blur() { this.el_.blur(); }; /** * Emit a 'tap' events when touch event support gets detected. This gets used to * support toggling the controls through a tap on the video. They get enabled * because every sub-component would have extra overhead otherwise. * * @private * @fires Component#tap * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchleave * @listens Component#touchcancel * @listens Component#touchend */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, // so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = void 0; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy pageX/pageY from the object firstTouch = { pageX: event.touches[0].pageX, pageY: event.touches[0].pageY }; // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); /** * Triggered when a `Component` is tapped. * * @event Component#tap * @type {EventTarget~Event} */ this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * This function reports user activity whenever touch events happen. This can get * turned off by any sub-components that wants touch events to act another way. * * Report user touch activity when touch events occur. User activity gets used to * determine when controls should show/hide. It is simple when it comes to mouse * events, because any mouse event should show the controls. So we capture mouse * events that bubble up to the player and report activity when that happens. * With touch events it isn't as easy as `touchstart` and `touchend` toggle player * controls. So touch events can't help us at the player level either. * * User activity gets checked asynchronously. So what could happen is a tap event * on the video turns the controls off. Then the `touchend` event bubbles up to * the player. Which, if it reported user activity, would turn the controls right * back on. We also don't want to completely block touch events from bubbling up. * Furthermore a `touchmove` event and anything other than a tap, should not turn * controls back on. * * @listens Component#touchstart * @listens Component#touchmove * @listens Component#touchend * @listens Component#touchcancel */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = void 0; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * A callback that has no parameters and is bound into `Component`s context. * * @callback Component~GenericCallback * @this Component */ /** * Creates a function that runs after an `x` millisecond timeout. This function is a * wrapper around `window.setTimeout`. There are a few reasons to use this one * instead though: * 1. It gets cleared via {@link Component#clearTimeout} when * {@link Component#dispose} gets called. * 2. The function callback will gets turned into a {@link Component~GenericCallback} * * > Note: You can use `window.clearTimeout` on the id returned by this function. This * will cause its dispose listener not to get cleaned up! Please use * {@link Component#clearTimeout} or {@link Component#dispose}. * * @param {Component~GenericCallback} fn * The function that will be run after `timeout`. * * @param {number} timeout * Timeout in milliseconds to delay before executing the specified function. * * @return {number} * Returns a timeout ID that gets used to identify the timeout. It can also * get used in {@link Component#clearTimeout} to clear the timeout that * was set. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout} */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); var timeoutId = _window2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout that gets created via `window.setTimeout` or * {@link Component#setTimeout}. If you set a timeout via {@link Component#setTimeout} * use this function instead of `window.clearTimout`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} timeoutId * The id of the timeout to clear. The return value of * {@link Component#setTimeout} or `window.setTimeout`. * * @return {number} * Returns the timeout id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearTimeout} */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _window2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates a function that gets run every `x` milliseconds. This function is a wrapper * around `window.setInterval`. There are a few reasons to use this one instead though. * 1. It gets cleared via {@link Component#clearInterval} when * {@link Component#dispose} gets called. * 2. The function callback will be a {@link Component~GenericCallback} * * @param {Component~GenericCallback} fn * The function to run every `x` seconds. * * @param {number} interval * Execute the specified function every `x` milliseconds. * * @return {number} * Returns an id that can be used to identify the interval. It can also be be used in * {@link Component#clearInterval} to clear the interval. * * @listens Component#dispose * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval} */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _window2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval that gets created via `window.setInterval` or * {@link Component#setInterval}. If you set an inteval via {@link Component#setInterval} * use this function instead of `window.clearInterval`. If you don't your dispose * listener will not get cleaned up until {@link Component#dispose}! * * @param {number} intervalId * The id of the interval to clear. The return value of * {@link Component#setInterval} or `window.setInterval`. * * @return {number} * Returns the interval id that was cleared. * * @see [Similar to]{@link https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/clearInterval} */ Component.prototype.clearInterval = function clearInterval(intervalId) { _window2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Register a `Component` with `videojs` given the name and the component. * * > NOTE: {@link Tech}s should not be registered as a `Component`. {@link Tech}s * should be registered using {@link Tech.registerTech} or * {@link videojs:videojs.registerTech}. * * > NOTE: This function can also be seen on videojs as * {@link videojs:videojs.registerComponent}. * * @param {string} name * The name of the `Component` to register. * * @param {Component} comp * The `Component` class to register. * * @return {Component} * The `Component` that was registered. */ Component.registerComponent = function registerComponent(name, comp) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); if (!Component.components_) { Component.components_ = {}; } if (name === 'Player' && Component.components_[name]) { var Player = Component.components_[name]; // If we have players that were disposed, then their name will still be // in Players.players. So, we must loop through and verify that the value // for each item is not null. This allows registration of the Player component // after all players have been disposed or before any were created. if (Player.players && Object.keys(Player.players).length > 0 && Object.keys(Player.players).map(function (playerName) { return Player.players[playerName]; }).every(Boolean)) { throw new Error('Can not register Player component after player has been created'); } } Component.components_[name] = comp; return comp; }; /** * Get a `Component` based on the name it was registered with. * * @param {string} name * The Name of the component to get. * * @return {Component} * The `Component` that got registered under the given name. * * @deprecated In `videojs` 6 this will not return `Component`s that were not * registered using {@link Component.registerComponent}. Currently we * check the global `videojs` object for a `Component` name and * return that if it exists. */ Component.getComponent = function getComponent(name) { if (!name) { return; } name = (0, _toTitleCase2['default'])(name); if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_window2['default'] && _window2['default'].videojs && _window2['default'].videojs[name]) { _log2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _window2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method or uses the init of the * parent object. * * @param {Object} [props={}] * An object of properties. * * @return {Object} * the extended object. * * @deprecated since version 5 */ Component.extend = function extend(props) { props = props || {}; _log2['default'].warn('Component.extend({}) has been deprecated, ' + ' use videojs.extend(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var name in props) { if (props.hasOwnProperty(name)) { subObj.prototype[name] = props[name]; } } return subObj; }; return Component; }(); Component.registerComponent('Component', Component); exports['default'] = Component; /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.throttle = exports.bind = undefined; var _guid = __webpack_require__(12); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events. * * @param {Mixed} context * The object to bind as scope. * * @param {Function} fn * The function to be bound to a scope. * * @param {number} [uid] * An optional unique ID for the function to be set * * @return {Function} * The new function that will be bound into the context given */ var bind = exports.bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = (0, _guid.newGUID)(); } // Create the new function that changes the context var bound = function bound() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks bound.guid = uid ? uid + '_' + fn.guid : fn.guid; return bound; }; /** * Wraps the given function, `fn`, with a new function that only invokes `fn` * at most once per every `wait` milliseconds. * * @param {Function} fn * The function to be throttled. * * @param {Number} wait * The number of milliseconds by which to throttle. * * @return {Function} */ /** * @file fn.js * @module fn */ var throttle = exports.throttle = function throttle(fn, wait) { var last = Date.now(); var throttled = function throttled() { var now = Date.now(); if (now - last >= wait) { fn.apply(undefined, arguments); last = now; } }; return throttled; }; /***/ }), /* 21 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; /** * @file to-title-case.js * @module to-title-case */ /** * Uppercase the first letter of a string. * * @param {string} string * String to be uppercased * * @return {string} * The string with an uppercased first letter */ function toTitleCase(string) { if (typeof string !== 'string') { return string; } return string.charAt(0).toUpperCase() + string.slice(1); } exports['default'] = toTitleCase; /***/ }), /* 22 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = mergeOptions; var _obj = __webpack_require__(14); /** * Deep-merge one or more options objects, recursively merging **only** plain * object properties. * * @param {Object[]} sources * One or more objects to merge into a new object. * * @returns {Object} * A new object that is the merged result of all sources. */ function mergeOptions() { var result = {}; for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) { sources[_key] = arguments[_key]; } sources.forEach(function (source) { if (!source) { return; } (0, _obj.each)(source, function (value, key) { if (!(0, _obj.isPlain)(value)) { result[key] = value; return; } if (!(0, _obj.isPlain)(result[key])) { result[key] = {}; } result[key] = mergeOptions(result[key], value); }); }); return result; } /** * @file merge-options.js * @module merge-options */ /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _events = __webpack_require__(17); var Events = _interopRequireWildcard(_events); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } /** * `EventTarget` is a class that can have the same API as the DOM `EventTarget`. It * adds shorthand functions that wrap around lengthy functions. For example: * the `on` function is a wrapper around `addEventListener`. * * @see [EventTarget Spec]{@link https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventTarget} * @class EventTarget */ var EventTarget = function EventTarget() {}; /** * A Custom DOM event. * * @typedef {Object} EventTarget~Event * @see [Properties]{@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent} */ /** * All event listeners should follow the following format. * * @callback EventTarget~EventListener * @this {EventTarget} * * @param {EventTarget~Event} event * the event that triggered this function * * @param {Object} [hash] * hash of data sent during the event */ /** * An object containing event names as keys and booleans as values. * * > NOTE: If an event name is set to a true value here {@link EventTarget#trigger} * will have extra functionality. See that function for more information. * * @property EventTarget.prototype.allowedEvents_ * @private */ /** * @file src/js/event-target.js */ EventTarget.prototype.allowedEvents_ = {}; /** * Adds an `event listener` to an instance of an `EventTarget`. An `event listener` is a * function that will get called when an event with a certain name gets triggered. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to call with `EventTarget`s */ EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; Events.on(this, type, fn); this.addEventListener = ael; }; /** * An alias of {@link EventTarget#on}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#on} */ EventTarget.prototype.addEventListener = EventTarget.prototype.on; /** * Removes an `event listener` for a specific event from an instance of `EventTarget`. * This makes it so that the `event listener` will no longer get called when the * named event happens. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to remove. */ EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; /** * An alias of {@link EventTarget#off}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#off} */ EventTarget.prototype.removeEventListener = EventTarget.prototype.off; /** * This function will add an `event listener` that gets triggered only once. After the * first trigger it will get removed. This is like adding an `event listener` * with {@link EventTarget#on} that calls {@link EventTarget#off} on itself. * * @param {string|string[]} type * An event name or an array of event names. * * @param {EventTarget~EventListener} fn * The function to be called once for each event name. */ EventTarget.prototype.one = function (type, fn) { // Remove the addEventListener alialing Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = function () {}; Events.one(this, type, fn); this.addEventListener = ael; }; /** * This function causes an event to happen. This will then cause any `event listeners` * that are waiting for that event, to get called. If there are no `event listeners` * for an event then nothing will happen. * * If the name of the `Event` that is being triggered is in `EventTarget.allowedEvents_`. * Trigger will also call the `on` + `uppercaseEventName` function. * * Example: * 'click' is in `EventTarget.allowedEvents_`, so, trigger will attempt to call * `onClick` if it exists. * * @param {string|EventTarget~Event|Object} event * The name of the event, an `Event`, or an object with a key of type set to * an event name. */ EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; /** * An alias of {@link EventTarget#trigger}. Allows `EventTarget` to mimic * the standard DOM API. * * @function * @see {@link EventTarget#trigger} */ EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _component = __webpack_require__(19); var _component2 = _interopRequireDefault(_component); var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); var _events = __webpack_require__(17); var Events = _interopRequireWildcard(_events); var _dom = __webpack_require__(11); var Dom = _interopRequireWildcard(_dom); var _fn = __webpack_require__(20); var Fn = _interopRequireWildcard(_fn); var _guid = __webpack_require__(12); var Guid = _interopRequireWildcard(_guid); var _browser = __webpack_require__(10); var browser = _interopRequireWildcard(_browser); var _log = __webpack_require__(13); var _log2 = _interopRequireDefault(_log); var _toTitleCase = __webpack_require__(21); var _toTitleCase2 = _interopRequireDefault(_toTitleCase); var _timeRanges = __webpack_require__(25); var _buffer = __webpack_require__(26); var _stylesheet = __webpack_require__(18); var stylesheet = _interopRequireWildcard(_stylesheet); var _fullscreenApi = __webpack_require__(27); var _fullscreenApi2 = _interopRequireDefault(_fullscreenApi); var _mediaError = __webpack_require__(28); var _mediaError2 = _interopRequireDefault(_mediaError); var _tuple = __webpack_require__(29); var _tuple2 = _interopRequireDefault(_tuple); var _obj = __webpack_require__(14); var _mergeOptions = __webpack_require__(22); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _textTrackListConverter = __webpack_require__(30); var _textTrackListConverter2 = _interopRequireDefault(_textTrackListConverter); var _modalDialog = __webpack_require__(31); var _modalDialog2 = _interopRequireDefault(_modalDialog); var _tech = __webpack_require__(32); var _tech2 = _interopRequireDefault(_tech); var _audioTrackList = __webpack_require__(49); var _audioTrackList2 = _interopRequireDefault(_audioTrackList); var _videoTrackList = __webpack_require__(48); var _videoTrackList2 = _interopRequireDefault(_videoTrackList); __webpack_require__(54); __webpack_require__(55); __webpack_require__(57); __webpack_require__(59); __webpack_require__(60); __webpack_require__(61); __webpack_require__(63); __webpack_require__(64); __webpack_require__(107); __webpack_require__(108); __webpack_require__(109); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file player.js */ // Subclasses Component // 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 Html5 tech, at least for disposing the original video tag. // The following tech events are simply re-triggered // on the player when they happen var 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 playing speed of the audio/video is changed * * @event player#ratechange * @type {event} */ /** * Retrigger the `ratechange` event that was triggered by the {@link Tech}. * * @private * @method Player#handleTechRatechange_ * @fires Player#ratechange * @listens Tech#ratechange */ 'ratechange', /** * 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']; /** * 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 */ var Player = function (_Component) { _inherits(Player, _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. */ function Player(tag, options, ready) { _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.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 = (0, _obj.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; // 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') { var closest = tag.closest('[lang]'); if (closest) { options.language = closest.getAttribute('lang'); } } else { var element = tag; while (element && element.nodeType === 1) { if (Dom.getElAttributes(element).hasOwnProperty('lang')) { options.language = element.getAttribute('lang'); break; } element = element.parentNode; } } } // Run base component initializing with new options // if the global option object was accidentally blown away by // someone, bail early with an informative error var _this = _possibleConstructorReturn(this, _Component.call(this, null, options, ready)); 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.getElAttributes(tag); // Update current language _this.language(_this.options_.language); // Update Supported Languages if (options.languages) { // Normalise player option languages to lowercase var 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; // 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; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ _this.scrubbing_ = false; _this.el_ = _this.createEl(); // 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. var playerOptionsCopy = (0, _mergeOptions2['default'])(_this.options_); // Load plugins if (options.plugins) { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _log2['default'].error('Unable to find plugin:', name); } }, _this); } _this.options_.playerOptions = playerOptionsCopy; _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', 'audio player'); } else { _this.el_.setAttribute('aria-label', '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 var majorVersion = '5.20.3'.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.listenForUserActivity_(); _this.on('fullscreenchange', _this.handleFullscreenChange_); _this.on('stageclick', _this.handleStageClick_); return _this; } /** * 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 */ Player.prototype.dispose = function 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_); } // 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(); } _Component.prototype.dispose.call(this); }; /** * Create the `Player`'s DOM element. * * @return {Element} * The DOM element that gets created. */ Player.prototype.createEl = function createEl() { var tag = this.tag; var el = void 0; var playerElIngest = this.playerElIngest_ = tag.parentNode && tag.parentNode.hasAttribute && tag.parentNode.hasAttribute('data-vjs-player'); if (playerElIngest) { el = this.el_ = tag.parentNode; } else { el = this.el_ = _Component.prototype.createEl.call(this, 'div'); } // set tabindex to -1 so we could focus on the player element tag.setAttribute('tabindex', '-1'); // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className += ' ' + attrs[attr]; } else { el.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 (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE !== true) { this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = Dom.$('.vjs-styles-defaults'); var head = Dom.$('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); } // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); 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. var links = tag.getElementsByTagName('a'); for (var i = 0; i < links.length; i++) { var linkEl = links.item(i); Dom.addElClass(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.insertElFirst(tag, el); this.children_.unshift(tag); this.el_ = el; return el; }; /** * A getter/setter for the `Player`'s width. * * @param {number} [value] * The value to set the `Player's width to. * * @return {number} * The current width of the `Player`. */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * A getter/setter for the `Player`'s height. * * @param {number} [value] * The value to set the `Player's heigth to. * * @return {number} * The current heigth of the `Player`. */ Player.prototype.height = function 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 {Player|number} * - Returns itself when setting; method can be chained. * - The dimension arguments value when getting (width/height). */ Player.prototype.dimension = function dimension(_dimension, value) { var 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; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _log2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }; /** * A getter/setter/toggler for the vjs-fluid `className` on the `Player`. * * @param {boolean} [bool] * - A value of true adds the class. * - A value of false removes the class. * - No value will toggle the fluid class. * * @return {boolean|undefined} * - The value of fluid when getting. * - `undefined` when setting. */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } this.updateStyleEl_(); }; /** * 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 */ Player.prototype.aspectRatio = function 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 */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { if (_window2['default'].VIDEOJS_NO_DYNAMIC_STYLE === true) { var _width = typeof this.width_ === 'number' ? this.width_ : this.options_.width; var _height = typeof this.height_ === 'number' ? this.height_ : this.options_.height; var techEl = this.tech_ && this.tech_.el(); if (techEl) { if (_width >= 0) { techEl.width = _width; } if (_height >= 0) { techEl.height = _height; } } return; } var width = void 0; var height = void 0; var aspectRatio = void 0; var idClass = void 0; // 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 var ratioParts = aspectRatio.split(':'); var 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_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n '); }; /** * 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 * * @private */ Player.prototype.loadTech_ = function loadTech_(techName, source) { var _this2 = this; // Pause and remove current playback technology if (this.tech_) { this.unloadTech_(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _tech2['default'].getTech('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName_ = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = (0, _obj.assign)({ source: source, 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'playerId': this.id(), 'techId': this.id() + '_' + techName + '_api', 'videoTracks': this.videoTracks_, 'textTracks': this.textTracks_, 'audioTracks': this.audioTracks_, 'autoplay': this.options_.autoplay, 'playsinline': this.options_.playsinline, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'playerElIngest': this.playerElIngest_ || false, 'vtt.js': this.options_['vtt.js'] }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.sources = null; this.cache_.source = source; this.cache_.src = source.src; } // Initialize tech instance var TechComponent = _tech2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!TechComponent) { TechComponent = _component2['default'].getComponent(techName); } this.tech_ = new TechComponent(techOptions); // player.triggerReady is always async, so don't need this to be async this.tech_.ready(Fn.bind(this, this.handleTechReady_), true); _textTrackListConverter2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player TECH_EVENTS_RETRIGGER.forEach(function (event) { _this2.on(_this2.tech_, event, _this2['handleTech' + (0, _toTitleCase2['default'])(event) + '_']); }); this.on(this.tech_, 'loadstart', this.handleTechLoadStart_); this.on(this.tech_, 'waiting', this.handleTechWaiting_); this.on(this.tech_, 'canplay', this.handleTechCanPlay_); this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_); this.on(this.tech_, 'playing', this.handleTechPlaying_); this.on(this.tech_, 'ended', this.handleTechEnded_); this.on(this.tech_, 'seeking', this.handleTechSeeking_); this.on(this.tech_, 'seeked', this.handleTechSeeked_); this.on(this.tech_, 'play', this.handleTechPlay_); this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_); this.on(this.tech_, 'pause', this.handleTechPause_); this.on(this.tech_, 'durationchange', this.handleTechDurationChange_); this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_); this.on(this.tech_, 'error', this.handleTechError_); this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_); this.on(this.tech_, 'posterchange', this.handleTechPosterChange_); this.on(this.tech_, 'textdata', this.handleTechTextData_); this.usingNativeControls(this.techGet_('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners_(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech_.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech_.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } }; /** * Unload and dispose of the current playback {@link Tech}. * * @private */ Player.prototype.unloadTech_ = function unloadTech_() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.videoTracks_ = this.videoTracks(); this.textTracks_ = this.textTracks(); this.audioTracks_ = this.audioTracks(); this.textTracksJson_ = _textTrackListConverter2['default'].textTracksToJson(this.tech_); this.isReady_ = false; this.tech_.dispose(); this.tech_ = false; }; /** * Return a reference to the current {@link Tech}, but only if given an object with the * `IWillNotUseThisInPlugins` property having a true value. This is try and prevent misuse * of techs by plugins. * * @param {Object} safety * An object that must contain `{IWillNotUseThisInPlugins: true}` * * @param {boolean} safety.IWillNotUseThisInPlugins * Must be set to true or else this function will throw an error. * * @return {Tech} * The Tech */ Player.prototype.tech = function tech(safety) { if (safety && safety.IWillNotUseThisInPlugins) { return this.tech_; } var errorText = '\n Please make sure that you are not using this inside of a plugin.\n To disable this alert and error, please pass in an object with\n `IWillNotUseThisInPlugins` to the `tech` method. See\n https://github.com/videojs/video.js/issues/2617 for more info.\n '; _window2['default'].alert(errorText); throw new Error(errorText); }; /** * Set up click and touch listeners for the playback element * * - On desktops: a click on the video itself will toggle playback * - On mobile devices: a click on the video toggles controls * which is done by toggling the user state between active and * inactive * - A tap can signal that a user has become active or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * - In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * * > Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold * on any controls will still keep the user active * * @private */ Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners_(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech_, 'mousedown', this.handleTechClick_); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech_, 'touchstart', this.handleTechTouchStart_); this.on(this.tech_, 'touchmove', this.handleTechTouchMove_); this.on(this.tech_, 'touchend', this.handleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech_, 'tap', this.handleTechTap_); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @private */ Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech_, 'tap', this.handleTechTap_); this.off(this.tech_, 'touchstart', this.handleTechTouchStart_); this.off(this.tech_, 'touchmove', this.handleTechTouchMove_); this.off(this.tech_, 'touchend', this.handleTechTouchEnd_); this.off(this.tech_, 'mousedown', this.handleTechClick_); }; /** * Player waits for the tech to be ready * * @private */ Player.prototype.handleTechReady_ = function handleTechReady_() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall_('setVolume', this.cache_.volume); } // Look if the tech found a higher resolution poster while loading this.handleTechPosterChange_(); // Update the duration if available this.handleTechDurationChange_(); // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if ((this.src() || this.currentSrc()) && this.tag && this.options_.autoplay && this.paused()) { try { // Chrome Fix. Fixed in Chrome v16. delete this.tag.poster; } catch (e) { (0, _log2['default'])('deleting tag.poster throws in some browsers', e); } this.play(); } }; /** * Retrigger the `loadstart` event that was triggered by the {@link Tech}. This * function will also trigger {@link Player#firstplay} if it is the first loadstart * for a video. * * @fires Player#loadstart * @fires Player#firstplay * @listens Tech#loadstart * @private */ Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); this.removeClass('vjs-seeking'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { /** * Fired when the user agent begins looking for media data * * @event Player#loadstart * @type {EventTarget~Event} */ this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @fires Player#firstplay * * @param {boolean} hasStarted * - true: adds the class * - false: remove the class * * @return {boolean} * the boolean value of hasStarted */ Player.prototype.hasStarted = function hasStarted(_hasStarted) { if (_hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== _hasStarted) { this.hasStarted_ = _hasStarted; if (_hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }; /** * Fired whenever the media begins or resumes playback * * @see [Spec]{@link https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play} * @fires Player#play * @listens Tech#play * @private */ Player.prototype.handleTechPlay_ = function handleTechPlay_() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play this.hasStarted(true); /** * Triggered whenever an {@link Tech#play} event happens. Indicates that * playback has started or resumed. * * @event Player#play * @type {EventTarget~Event} */ this.trigger('play'); }; /** * Retrigger the `waiting` event that was triggered by the {@link Tech}. * * @fires Player#waiting * @listens Tech#waiting * @private */ Player.prototype.handleTechWaiting_ = function handleTechWaiting_() { var _this3 = this; this.addClass('vjs-waiting'); /** * A readyState change on the DOM element has caused playback to stop. * * @event Player#waiting * @type {EventTarget~Event} */ this.trigger('waiting'); this.one('timeupdate', function () { return _this3.removeClass('vjs-waiting'); }); }; /** * Retrigger the `canplay` event that was triggered by the {@link Tech}. * > Note: This is not consistent between browsers. See #1351 * * @fires Player#canplay * @listens Tech#canplay * @private */ Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_FUTURE_DATA or greater. * * @event Player#canplay * @type {EventTarget~Event} */ this.trigger('canplay'); }; /** * Retrigger the `canplaythrough` event that was triggered by the {@link Tech}. * * @fires Player#canplaythrough * @listens Tech#canplaythrough * @private */ Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() { this.removeClass('vjs-waiting'); /** * The media has a readyState of HAVE_ENOUGH_DATA or greater. This means that the * entire media file can be played without buffering. * * @event Player#canplaythrough * @type {EventTarget~Event} */ this.trigger('canplaythrough'); }; /** * Retrigger the `playing` event that was triggered by the {@link Tech}. * * @fires Player#playing * @listens Tech#playing * @private */ Player.prototype.handleTechPlaying_ = function handleTechPlaying_() { this.removeClass('vjs-waiting'); /** * The media is no longer blocked from playback, and has started playing. * * @event Player#playing * @type {EventTarget~Event} */ this.trigger('playing'); }; /** * Retrigger the `seeking` event that was triggered by the {@link Tech}. * * @fires Player#seeking * @listens Tech#seeking * @private */ Player.prototype.handleTechSeeking_ = function handleTechSeeking_() { this.addClass('vjs-seeking'); /** * Fired whenever the player is jumping to a new time * * @event Player#seeking * @type {EventTarget~Event} */ this.trigger('seeking'); }; /** * Retrigger the `seeked` event that was triggered by the {@link Tech}. * * @fires Player#seeked * @listens Tech#seeked * @private */ Player.prototype.handleTechSeeked_ = function handleTechSeeked_() { this.removeClass('vjs-seeking'); /** * Fired when the player has finished jumping to a new time * * @event Player#seeked * @type {EventTarget~Event} */ this.trigger('seeked'); }; /** * Retrigger the `firstplay` event that was triggered by the {@link Tech}. * * @fires Player#firstplay * @listens Tech#firstplay * @deprecated As of 6.0 passing the `starttime` option to the player will be deprecated * @private */ Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() { // If the first starttime attribute is specified // then we will start at the given offset in seconds if (this.options_.starttime) { _log2['default'].warn('Passing the `starttime` option to the player will be deprecated in 6.0'); this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); /** * Fired the first time a video is played. Not part of the HLS spec, and this is * probably not the best implementation yet, so use sparingly. If you don't have a * reason to prevent playback, use `myPlayer.one('play');` instead. * * @event Player#firstplay * @type {EventTarget~Event} */ this.trigger('firstplay'); }; /** * Retrigger the `pause` event that was triggered by the {@link Tech}. * * @fires Player#pause * @listens Tech#pause * @private */ Player.prototype.handleTechPause_ = function handleTechPause_() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); /** * Fired whenever the media has been paused * * @event Player#pause * @type {EventTarget~Event} */ this.trigger('pause'); }; /** * Retrigger the `ended` event that was triggered by the {@link Tech}. * * @fires Player#ended * @listens Tech#ended * @private */ Player.prototype.handleTechEnded_ = function handleTechEnded_() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event Player#ended * @type {EventTarget~Event} */ this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @listens Tech#durationchange * @private */ Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() { this.duration(this.techGet_('duration')); }; /** * Handle a click on the media element to play/pause * * @param {EventTarget~Event} event * the event that caused this function to trigger * * @listens Tech#mousedown * @private */ Player.prototype.handleTechClick_ = function handleTechClick_(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) { return; } // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @listens Tech#tap * @private */ Player.prototype.handleTechTap_ = function handleTechTap_() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @listens Tech#touchstart * @private */ Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @listens Tech#touchmove * @private */ Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @param {EventTarget~Event} event * the touchend event that triggered * this function * * @listens Tech#touchend * @private */ Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Fired when the player switches in or out of fullscreen mode * * @private * @listens Player#fullscreenchange */ Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @listens stageclick */ Player.prototype.handleStageClick_ = function handleStageClick_() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @param {EventTarget~Event} event * the fullscreenchange event that triggered this function * * @param {Object} data * the data that was sent with the event * * @private * @listens Tech#fullscreenchange * @fires Player#fullscreenchange */ Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } /** * Fired when going in and out of fullscreen. * * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video. * * @private * @listens Tech#error */ Player.prototype.handleTechError_ = function handleTechError_() { var error = this.tech_.error(); this.error(error); }; /** * Retrigger the `textdata` event that was triggered by the {@link Tech}. * * @fires Player#textdata * @listens Tech#textdata * @private */ Player.prototype.handleTechTextData_ = function handleTechTextData_() { var data = null; if (arguments.length > 1) { data = arguments[1]; } /** * Fires when we get a textdata event from tech * * @event Player#textdata * @type {EventTarget~Event} */ this.trigger('textdata', data); }; /** * Get object for cached values. * * @return {Object} * get the current object cache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {string} [method] * the method to call * * @param {Object} arg * the argument to pass * * @private */ Player.prototype.techCall_ = function techCall_(method, arg) { // If it's not ready yet, call method when it is if (this.tech_ && !this.tech_.isReady_) { this.tech_.ready(function () { this[method](arg); }, true); // Otherwise call method now } else { try { if (this.tech_) { this.tech_[method](arg); } } catch (e) { (0, _log2['default'])(e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {string} method * Tech method * * @return {Function|undefined} * the method or undefined * * @private */ Player.prototype.techGet_ = function techGet_(method) { if (this.tech_ && this.tech_.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech_[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech_[method] === undefined) { (0, _log2['default'])('Video.js: ' + method + ' method not defined for ' + this.techName_ + ' playback technology.', e); // When a method isn't available on the object it throws a TypeError } else if (e.name === 'TypeError') { (0, _log2['default'])('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e); this.tech_.isReady_ = false; } else { (0, _log2['default'])(e); } throw e; } } return; }; /** * start media playback * * @return {Player} * A reference to the player object this function was called on */ Player.prototype.play = function play() { // Only calls the tech's play if we already have a src loaded if (this.src() || this.currentSrc()) { this.techCall_('play'); } else { this.tech_.one('loadstart', function () { this.play(); }); } return this; }; /** * Pause the video playback * * @return {Player} * A reference to the player object this function was called on */ Player.prototype.pause = function pause() { this.techCall_('pause'); return this; }; /** * Check if the player is paused or has yet to play * * @return {boolean} * - false: if the media is currently playing * - true: if media is not currently playing */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet_('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is * when the user has clicked the progress bar handle and is * dragging it along the progress bar. * * @param {boolean} [isScrubbing] * wether the user is or is not scrubbing * * @return {boolean|Player} * A instance of the player that called this function when setting, * and the value of scrubbing when getting */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * * @param {number|string} [seconds] * The time to seek to in seconds * * @return {Player|number} * - the current time in seconds when getting * - a reference to the current player object when setting */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall_('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. this.cache_.currentTime = this.techGet_('currentTime') || 0; return this.cache_.currentTime; }; /** * Normally gets the length in time of the video in seconds; * in all but the rarest use cases an argument will NOT be passed to the method * * > **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @fires Player#durationchange * * @param {number} [seconds] * The duration of the video to set in seconds * * @return {number|Player} * - The duration of the video in seconds when getting * - A reference to the player that called this function * when setting */ Player.prototype.duration = function duration(seconds) { if (seconds === undefined) { // return NaN if the duration is not known return this.cache_.duration !== undefined ? this.cache_.duration : NaN; } seconds = parseFloat(seconds); // Standardize on Inifity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } /** * @event Player#durationchange * @type {EventTarget~Event} */ this.trigger('durationchange'); } return this; }; /** * Calculates how much time is left in the video. Not part * of the native video API. * * @return {number} * The time remaining in seconds */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with an array of the times of the video * that have been downloaded. If you just want the percent of the * video that's been downloaded, use bufferedPercent. * * @see [Buffered Spec]{@link http://dev.w3.org/html5/spec/video.html#dom-media-buffered} * * @return {TimeRange} * A mock TimeRange object (following HTML spec) */ Player.prototype.buffered = function buffered() { var buffered = this.techGet_('buffered'); if (!buffered || !buffered.length) { buffered = (0, _timeRanges.createTimeRange)(0, 0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded. * This method is not a part of the native HTML video API. * * @return {number} * A decimal between 0 and 1 representing the percent * that is bufferred 0 being 0% and 1 being 100% */ Player.prototype.bufferedPercent = function bufferedPercent() { return (0, _buffer.bufferedPercent)(this.buffered(), this.duration()); }; /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {number} * The end of the last buffered time range */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(); var duration = this.duration(); var end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * * @param {number} [percentAsDecimal] * The new volume as a decimal percent: * - 0 is muted/0%/off * - 1.0 is 100%/full * - 0.5 is half volume or 50% * * @return {Player|number} * a reference to the calling player when setting and the * current volume as a percent when getting */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = void 0; if (percentAsDecimal !== undefined) { // Force value to between 0 and 1 vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); this.cache_.volume = vol; this.techCall_('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet_('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * * @param {boolean} [muted] * - true to mute * - false to unmute * * @return {boolean|Player} * - true if mute is on and getting * - false if mute is off and getting * - A reference to the current player when setting */ Player.prototype.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall_('setMuted', _muted); return this; } return this.techGet_('muted') || false; }; /** * Check if current tech can support native fullscreen * (e.g. with built in controls like iOS, so not our flash swf) * * @return {boolean} * if native fullscreen is supported */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet_('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode or tell the player that it * is or is not in fullscreen mode. * * > NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {boolean} [isFS] * Set the players current fullscreen state * * @return {boolean|Player} * - true if fullscreen is on and getting * - false if fullscreen is off and getting * - A reference to the current player when setting */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @fires Player#fullscreenchange * @return {Player} * A reference to the current player */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _fullscreenApi2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_document2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_document2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_document2['default'], fsApi.fullscreenchange, documentFullscreenChange); } /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech_.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall_('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * * @fires Player#fullscreenchange * * @return {Player} * A reference to the current player */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _fullscreenApi2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _document2['default'][fsApi.exitFullscreen](); } else if (this.tech_.supportsFullScreen()) { this.techCall_('exitFullScreen'); } else { this.exitFullWindow(); /** * @event Player#fullscreenchange * @type {EventTarget~Event} */ this.trigger('fullscreenchange'); } return this; }; /** * When fullscreen isn't supported we can stretch the * video container to as wide as the browser will let us. * * @fires Player#enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _document2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_document2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _document2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_document2['default'].body, 'vjs-full-window'); /** * @event Player#enterFullWindow * @type {EventTarget~Event} */ this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or * full screen on ESC key * * @param {string} event * Event to check for key press */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @fires Player#exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_document2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _document2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_document2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); /** * @event Player#exitFullWindow * @type {EventTarget~Event} */ this.trigger('exitFullWindow'); }; /** * Check whether the player can play a given mimetype * * @see https://www.w3.org/TR/2011/WD-html5-20110113/video.html#dom-navigator-canplaytype * * @param {string} type * The mimetype to check * * @return {string} * 'probably', 'maybe', or '' (empty string) */ Player.prototype.canPlayType = function canPlayType(type) { var can = void 0; // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = (0, _toTitleCase2['default'])(j[i]); var tech = _tech2['default'].getTech(techName); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!tech) { tech = _component2['default'].getComponent(techName); } // Check if the current tech is defined before continuing if (!tech) { _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { can = tech.canPlayType(type); if (can) { return can; } } } return ''; }; /** * Select source based on tech-order or source-order * Uses source-order selection if `options.sourceOrder` is truthy. Otherwise, * defaults to tech-order selection * * @param {Array} sources * The sources for a media asset * * @return {Object|boolean} * Object of source and tech order or false */ Player.prototype.selectSource = function selectSource(sources) { var _this4 = this; // Get only the techs specified in `techOrder` that exist and are supported by the // current platform var techs = this.options_.techOrder.map(_toTitleCase2['default']).map(function (techName) { // `Component.getComponent(...)` is for support of old behavior of techs // being registered as components. // Remove once that deprecated behavior is removed. return [techName, _tech2['default'].getTech(techName) || _component2['default'].getComponent(techName)]; }).filter(function (_ref) { var techName = _ref[0], tech = _ref[1]; // Check if the current tech is defined before continuing if (tech) { // Check if the browser supports this technology return tech.isSupported(); } _log2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); return false; }); // Iterate over each `innerArray` element once per `outerArray` element and execute // `tester` with both. If `tester` returns a non-falsy value, exit early and return // that value. var findFirstPassingTechSourcePair = function findFirstPassingTechSourcePair(outerArray, innerArray, tester) { var found = void 0; outerArray.some(function (outerChoice) { return innerArray.some(function (innerChoice) { found = tester(outerChoice, innerChoice); if (found) { return true; } }); }); return found; }; var foundSourceAndTech = void 0; var flip = function flip(fn) { return function (a, b) { return fn(b, a); }; }; var finder = function finder(_ref2, source) { var techName = _ref2[0], tech = _ref2[1]; if (tech.canPlaySource(source, _this4.options_[techName.toLowerCase()])) { return { source: source, tech: techName }; } }; // Depending on the truthiness of `options.sourceOrder`, we swap the order of techs and sources // to select from them based on their priority. if (this.options_.sourceOrder) { // Source-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(sources, techs, flip(finder)); } else { // Tech-first ordering foundSourceAndTech = findFirstPassingTechSourcePair(techs, sources, finder); } return foundSourceAndTech || false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL string**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * * @param {Tech~SourceObject|Tech~SourceObject[]} [source] * One SourceObject or an array of SourceObjects * * @return {string|Player} * - The current video source when getting * - The player when setting */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet_('src'); } var currentTech = _tech2['default'].getTech(this.techName_); // Support old behavior of techs being registered as components. // Remove once that deprecated behavior is removed. if (!currentTech) { currentTech = _component2['default'].getComponent(this.techName_); } // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source, this.options_[this.techName_.toLowerCase()])) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.sources = null; this.cache_.source = source; this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall_('setSource', source); } else { this.techCall_('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } // Set the source synchronously if possible (#2326) }, true); } } return this; }; /** * Handle an array of source objects * * @param {Tech~SourceObject[]} sources * Array of source objects * * @private */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName_) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech_(sourceTech.tech, sourceTech.source); } this.cache_.sources = sources; } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} * A reference to the player */ Player.prototype.load = function load() { this.techCall_('load'); return this; }; /** * Reset the player. Loads the first tech in the techOrder, * and calls `reset` on the tech`. * * @return {Player} * A reference to the player */ Player.prototype.reset = function reset() { this.loadTech_((0, _toTitleCase2['default'])(this.options_.techOrder[0]), null); this.techCall_('reset'); return this; }; /** * Returns all of the current source objects. * * @return {Tech~SourceObject[]} * The current source objects */ Player.prototype.currentSources = function currentSources() { var source = this.currentSource(); var sources = []; // assume `{}` or `{ src }` if (Object.keys(source).length !== 0) { sources.push(source); } return this.cache_.sources || sources; }; /** * Returns the current source object. * * @return {Tech~SourceObject} * The current source object */ Player.prototype.currentSource = function currentSource() { var source = {}; var src = this.currentSrc(); if (src) { source.src = src; } return this.cache_.source || source; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {string} * The current source */ Player.prototype.currentSrc = function currentSrc() { return this.techGet_('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {string} * The source MIME type */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {boolean} [value] * - true means that we should preload * - false maens that we should not preload * * @return {string|Player} * - the preload attribute value when getting * - the player when setting */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall_('setPreload', value); this.options_.preload = value; return this; } return this.techGet_('preload'); }; /** * Get or set the autoplay attribute. * * @param {boolean} [value] * - true means that we should autoplay * - false maens that we should not autoplay * * @return {string|Player} * - the current value of autoplay * - the player when setting */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall_('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet_('autoplay', value); }; /** * Set or unset the playsinline attribute. * Playsinline tells the browser that non-fullscreen playback is preferred. * * @param {boolean} [value] * - true means that we should try to play inline by default * - false means that we should use the browser's default playback mode, * which in most cases is inline. iOS Safari is a notable exception * and plays fullscreen by default. * * @return {string|Player} * - the current value of playsinline * - the player when setting * * @see [Spec]{@link https://html.spec.whatwg.org/#attr-video-playsinline} */ Player.prototype.playsinline = function playsinline(value) { if (value !== undefined) { this.techCall_('setPlaysinline', value); this.options_.playsinline = value; return this; } return this.techGet_('playsinline'); }; /** * Get or set the loop attribute on the video element. * * @param {boolean} [value] * - true means that we should loop the video * - false means that we should not loop the video * * @return {string|Player} * - the current value of loop when getting * - the player when setting */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall_('setLoop', value); this.options_.loop = value; return this; } return this.techGet_('loop'); }; /** * Get or set the poster image source url * * @fires Player#posterchange * * @param {string} [src] * Poster image source URL * * @return {string|Player} * - the current value of poster when getting * - the player when setting */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall_('setPoster', src); // alert components that the poster has been set /** * This event fires when the poster image is changed on the player. * * @event Player#posterchange * @type {EventTarget~Event} */ this.trigger('posterchange'); return this; }; /** * Some techs (e.g. YouTube) can provide a poster source in an * asynchronous way. We want the poster component to use this * poster source so that it covers up the tech's controls. * (YouTube's play button). However we only want to use this * soruce if the player user hasn't set a poster through * the normal APIs. * * @fires Player#posterchange * @listens Tech#posterchange * @private */ Player.prototype.handleTechPosterChange_ = function handleTechPosterChange_() { if (!this.poster_ && this.tech_ && this.tech_.poster) { this.poster_ = this.tech_.poster() || ''; // Let components know the poster has changed this.trigger('posterchange'); } }; /** * Get or set whether or not the controls are showing. * * @fires Player#controlsenabled * * @param {boolean} [bool] * - true to turn controls on * - false to turn controls off * * @return {boolean|Player} * - the current value of controls when getting * - the player when setting */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall_('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); /** * @event Player#controlsenabled * @type {EventTarget~Event} */ this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners_(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); /** * @event Player#controlsdisabled * @type {EventTarget~Event} */ this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners_(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @fires Player#usingnativecontrols * @fires Player#usingcustomcontrols * * @param {boolean} [bool] * - true to turn native controls on * - false to turn native controls off * * @return {boolean|Player} * - the current value of native controls when getting * - the player when setting */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event Player#usingnativecontrols * @type {EventTarget~Event} */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event Player#usingcustomcontrols * @type {EventTarget~Event} */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @fires Player#error * * @param {MediaError|string|number} [err] * A MediaError or a string/number to be turned * into a MediaError * * @return {MediaError|null|Player} * - The current MediaError when getting (or null) * - The player when setting */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); if (this.errorDisplay) { this.errorDisplay.close(); } return this; } this.error_ = new _mediaError2['default'](err); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _log2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaError2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); /** * @event Player#error * @type {EventTarget~Event} */ this.trigger('error'); return this; }; /** * Report user activity * * @param {Object} event * Event object */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @fires Player#useractive * @fires Player#userinactive * * @param {boolean} [bool] * - true if the user is active * - false if the user is inactive * @return {boolean|Player} * - the current value of userActive when getting * - the player when setting */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); /** * @event Player#useractive * @type {EventTarget~Event} */ this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech_) { this.tech_.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); /** * @event Player#userinactive * @type {EventTarget~Event} */ this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @private */ Player.prototype.listenForUserActivity_ = function listenForUserActivity_() { var mouseInProgress = void 0; var lastMoveX = void 0; var lastMoveY = void 0; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = void 0; this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_.inactivityTimeout; if (timeout > 0) { // In milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activity check loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {number} [rate] * New playback rate to set. * * @return {number|Player} * - The current playback rate when getting or 1.0 * - the player when setting */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall_('setPlaybackRate', rate); return this; } if (this.tech_ && this.tech_.featuresPlaybackRate) { return this.techGet_('playbackRate'); } return 1.0; }; /** * Gets or sets the audio flag * * @param {boolean} bool * - true signals that this is an audio player * - false signals that this is not an audio player * * @return {Player|boolean} * - the current value of isAudio when getting * - the player if setting */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Get the {@link VideoTrackList} * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#videotracklist * * @return {VideoTrackList} * the current video track list */ Player.prototype.videoTracks = function videoTracks() { // if we have not yet loadTech_, we create videoTracks_ // these will be passed to the tech during loading if (!this.tech_) { this.videoTracks_ = this.videoTracks_ || new _videoTrackList2['default'](); return this.videoTracks_; } return this.tech_.videoTracks(); }; /** * Get the {@link AudioTrackList} * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#audiotracklist * * @return {AudioTrackList} * the current audio track list */ Player.prototype.audioTracks = function audioTracks() { // if we have not yet loadTech_, we create videoTracks_ // these will be passed to the tech during loading if (!this.tech_) { this.audioTracks_ = this.audioTracks_ || new _audioTrackList2['default'](); return this.audioTracks_; } return this.tech_.audioTracks(); }; /** * Get the {@link TextTrackList} * * Text tracks are tracks of timed text events. * - Captions: text displayed over the video * for the hearing impaired * - Subtitles: text displayed over the video for * those who don't understand language in the video * - Chapters: text displayed in a menu allowing the user to jump * to particular points (chapters) in the video * - Descriptions: (not yet implemented) audio descriptions that are read back to * the user by a screen reading device * * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {TextTrackList|undefined} * The current TextTrackList or undefined if * or undefined if we don't have a tech */ Player.prototype.textTracks = function textTracks() { // cannot use techGet_ directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. if (this.tech_) { return this.tech_.textTracks(); } }; /** * Get the "remote" {@link TextTrackList}. Remote Text Tracks * are tracks that were added to the HTML video element and can * be removed, whereas normal texttracks cannot be removed. * * * @return {TextTrackList|undefined} * The current remote text track list or undefined * if we don't have a tech */ Player.prototype.remoteTextTracks = function remoteTextTracks() { if (this.tech_) { return this.tech_.remoteTextTracks(); } }; /** * Get the "remote" {@link HTMLTrackElementList}. * This gives the user all of the DOM elements that match up * with the remote {@link TextTrackList}. * * @return {HTMLTrackElementList} * The current remote text track list elements * or undefined if we don't have a tech */ Player.prototype.remoteTextTrackEls = function remoteTextTrackEls() { if (this.tech_) { return this.tech_.remoteTextTrackEls(); } }; /** * A helper method for adding a {@link TextTrack} to our * {@link TextTrackList}. * * In addition to the W3C settings we allow adding additional info through options. * * @see http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {string} [kind] * the kind of TextTrack you are adding * * @param {string} [label] * the label to give the TextTrack label * * @param {string} [language] * the language to set on the TextTrack * * @return {TextTrack|undefined} * the TextTrack that was added or undefined * if there is no tech */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (this.tech_) { return this.tech_.addTextTrack(kind, label, language); } }; /** * Create a remote {@link TextTrack} and an {@link HTMLTrackElement}. It will * automatically removed from the video element whenever the source changes, unless * manualCleanup is set to false. * * @param {Object} options * Options to pass to {@link HTMLTrackElement} during creation. See * {@link HTMLTrackElement} for object properties that you should use. * * @param {boolean} [manualCleanup=true] if set to false, the TextTrack will be * * @return {HTMLTrackElement} * the HTMLTrackElement that was created and added * to the HTMLTrackElementList and the remote * TextTrackList * * @deprecated The default value of the "manualCleanup" parameter will default * to "false" in upcoming versions of Video.js */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options, manualCleanup) { if (this.tech_) { return this.tech_.addRemoteTextTrack(options, manualCleanup); } }; /** * Remove a remote {@link TextTrack} from the respective * {@link TextTrackList} and {@link HTMLTrackElementList}. * * @param {Object} track * Remote {@link TextTrack} to remove * * @return {undefined} * does not return anything */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack() { var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref3$track = _ref3.track, track = _ref3$track === undefined ? arguments[0] : _ref3$track; // destructure the input into an object with a track argument, defaulting to arguments[0] // default the whole argument to an empty object if nothing was passed in if (this.tech_) { return this.tech_.removeRemoteTextTrack(track); } }; /** * Gets available media playback quality metrics as specified by the W3C's Media * Playback Quality API. * * @see [Spec]{@link https://wicg.github.io/media-playback-quality} * * @return {Object|undefined} * An object with supported media playback quality metrics or undefined if there * is no tech or the tech does not support it. */ Player.prototype.getVideoPlaybackQuality = function getVideoPlaybackQuality() { return this.techGet_('getVideoPlaybackQuality'); }; /** * Get video width * * @return {number} * current video width */ Player.prototype.videoWidth = function videoWidth() { return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0; }; /** * Get video height * * @return {number} * current video height */ Player.prototype.videoHeight = function videoHeight() { return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0; }; // Methods to add support for // initialTime: function() { return this.techCall_('initialTime'); }, // startOffsetTime: function() { return this.techCall_('startOffsetTime'); }, // played: function() { return this.techCall_('played'); }, // defaultPlaybackRate: function() { return this.techCall_('defaultPlaybackRate'); }, // defaultMuted: function() { return this.techCall_('defaultMuted'); } /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {string} [code] * the language code to set the player to * * @return {string|Player} * - The current language code when getting * - A reference to the player when setting */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = String(code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} * An array of of supported languages */ Player.prototype.languages = function languages() { return (0, _mergeOptions2['default'])(Player.prototype.options_.languages, this.languages_); }; /** * returns a JavaScript object reperesenting the current track * information. **DOES not return it as JSON** * * @return {Object} * Object representing the current of track info */ Player.prototype.toJSON = function toJSON() { var options = (0, _mergeOptions2['default'])(this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = (0, _mergeOptions2['default'])(track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Creates a simple modal dialog (an instance of the {@link ModalDialog} * component) that immediately overlays the player with arbitrary * content and removes itself when closed. * * @param {string|Function|Element|Array|null} content * Same as {@link ModalDialog#content}'s param of the same name. * The most straight-forward usage is to provide a string or DOM * element. * * @param {Object} [options] * Extra options which will be passed on to the {@link ModalDialog}. * * @return {ModalDialog} * the {@link ModalDialog} that was created */ Player.prototype.createModal = function createModal(content, options) { var _this5 = this; options = options || {}; options.content = content || ''; var modal = new _modalDialog2['default'](this, options); this.addChild(modal); modal.on('dispose', function () { _this5.removeChild(modal); }); return modal.open(); }; /** * Gets tag settings * * @param {Element} tag * The player tag * * @return {Object} * An object containing all of the settings * for a player tag */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { sources: [], tracks: [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; if (Dom.hasElClass(tag, 'vjs-fluid')) { tagOptions.fluid = true; } // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON // If empty string, make it a parsable json object. var _safeParseTuple = (0, _tuple2['default'])(dataSetup || '{}'), err = _safeParseTuple[0], data = _safeParseTuple[1]; if (err) { _log2['default'].error(err); } (0, _obj.assign)(tagOptions, data); } (0, _obj.assign)(baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; /** * Determine wether or not flexbox is supported * * @return {boolean} * - true if flexbox is supported * - false if flexbox is not supported */ Player.prototype.flexNotSupported_ = function flexNotSupported_() { var elem = _document2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || // IE10-specific (2012 flex spec) 'msFlexOrder' in elem.style); }; return Player; }(_component2['default']); /** * Global player list * * @type {Object} */ Player.players = {}; var navigator = _window2['default'].navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0.00, // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'controlBar', 'errorDisplay', 'textTrackSettings'], language: navigator && (navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language) || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this media.' }; [ /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method Player#ended */ 'ended', /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method Player#seeking */ 'seeking', /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method Player#seekable */ 'seekable', /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {number} the current network activity state * @method Player#networkState */ 'networkState', /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {number} the current playback rendering state * @method Player#readyState */ 'readyState'].forEach(function (fn) { Player.prototype[fn] = function () { return this.techGet_(fn); }; }); TECH_EVENTS_RETRIGGER.forEach(function (event) { Player.prototype['handleTech' + (0, _toTitleCase2['default'])(event) + '_'] = function () { return this.trigger(event); }; }); /** * Fired when the player has initial duration and dimension information * * @event Player#loadedmetadata * @type {EventTarget~Event} */ /** * Fired when the player has downloaded data at the current playback position * * @event Player#loadeddata * @type {EventTarget~Event} */ /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event Player#timeupdate * @type {EventTarget~Event} */ /** * Fired when the volume changes * * @event Player#volumechange * @type {EventTarget~Event} */ _component2['default'].registerComponent('Player', Player); exports['default'] = Player; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.createTimeRange = undefined; exports.createTimeRanges = createTimeRanges; var _log = __webpack_require__(13); var _log2 = _interopRequireDefault(_log); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Returns the time for the specified index at the start or end * of a TimeRange object. * * @function time-ranges:indexFunction * * @param {number} [index=0] * The range number to return the time for. * * @return {number} * The time that offset at the specified index. * * @depricated index must be set to a value, in the future this will throw an error. */ /** * An object that contains ranges of time for various reasons. * * @typedef {Object} TimeRange * * @property {number} length * The number of time ranges represented by this Object * * @property {time-ranges:indexFunction} start * Returns the time offset at which a specified time range begins. * * @property {time-ranges:indexFunction} end * Returns the time offset at which a specified time range begins. * * @see https://developer.mozilla.org/en-US/docs/Web/API/TimeRanges */ /** * Check if any of the time ranges are over the maximum index. * * @param {string} fnName * The function name to use for logging * * @param {number} index * The index to check * * @param {number} maxIndex * The maximum possible index * * @throws {Error} if the timeRanges provided are over the maxIndex */ function rangeCheck(fnName, index, maxIndex) { if (index < 0 || index > maxIndex) { throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is greater than or equal to the maximum bound (' + maxIndex + ').'); } } /** * Check if any of the time ranges are over the maximum index. * * @param {string} fnName * The function name to use for logging * * @param {string} valueIndex * The proprety that should be used to get the time. should be 'start' or 'end' * * @param {Array} ranges * An array of time ranges * * @param {Array} [rangeIndex=0] * The index to start the search at * * @return {number} * The time that offset at the specified index. * * * @depricated rangeIndex must be set to a value, in the future this will throw an error. * @throws {Error} if rangeIndex is more than the length of ranges */ /** * @file time-ranges.js * @module time-ranges */ function getRange(fnName, valueIndex, ranges, rangeIndex) { if (rangeIndex === undefined) { _log2['default'].warn('DEPRECATED: Function \'' + fnName + '\' on \'TimeRanges\' called without an index argument.'); rangeIndex = 0; } rangeCheck(fnName, rangeIndex, ranges.length - 1); return ranges[rangeIndex][valueIndex]; } /** * Create a time range object givent ranges of time. * * @param {Array} [ranges] * An array of time ranges. */ function createTimeRangesObj(ranges) { if (ranges === undefined || ranges.length === 0) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: ranges.length, start: getRange.bind(null, 'start', 0, ranges), end: getRange.bind(null, 'end', 1, ranges) }; } /** * Should create a fake `TimeRange` object which mimics an HTML5 time range instance. * * @param {number|Array} start * The start of a single range or an array of ranges * * @param {number} end * The end of a single range. * * @private */ function createTimeRanges(start, end) { if (Array.isArray(start)) { return createTimeRangesObj(start); } else if (start === undefined || end === undefined) { return createTimeRangesObj(); } return createTimeRangesObj([[start, end]]); } exports.createTimeRange = createTimeRanges; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.bufferedPercent = bufferedPercent; var _timeRanges = __webpack_require__(25); /** * Compute the percentage of the media that has been buffered. * * @param {TimeRange} buffered * The current `TimeRange` object representing buffered time ranges * * @param {number} duration * Total duration of the media * * @return {number} * Percent buffered of the total duration in decimal form. */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0; var start = void 0; var end = void 0; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = (0, _timeRanges.createTimeRange)(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } /** * @file buffer.js * @module buffer */ /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Store the browser-specific methods for the fullscreen API. * * @type {Object} * @see [Specification]{@link https://fullscreen.spec.whatwg.org} * @see [Map Approach From Screenfull.js]{@link https://github.com/sindresorhus/screenfull.js} */ var FullscreenApi = {}; // browser API methods /** * @file fullscreen-api.js * @module fullscreen-api * @private */ var apiMap = [['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = void 0; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _document2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var _i = 0; _i < browserApi.length; _i++) { FullscreenApi[specApi[_i]] = browserApi[_i]; } } exports['default'] = FullscreenApi; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _obj = __webpack_require__(14); /** * A Custom `MediaError` class which mimics the standard HTML5 `MediaError` class. * * @param {number|string|Object|MediaError} value * This can be of multiple types: * - number: should be a standard error code * - string: an error message (the code will be 0) * - Object: arbitrary properties * - `MediaError` (native): used to populate a video.js `MediaError` object * - `MediaError` (video.js): will return itself if it's already a * video.js `MediaError` object. * * @see [MediaError Spec]{@link https://dev.w3.org/html5/spec-author-view/video.html#mediaerror} * @see [Encrypted MediaError Spec]{@link https://www.w3.org/TR/2013/WD-encrypted-media-20130510/#error-codes} * * @class MediaError */ function MediaError(value) { // Allow redundant calls to this constructor to avoid having `instanceof` // checks peppered around the code. if (value instanceof MediaError) { return value; } if (typeof value === 'number') { this.code = value; } else if (typeof value === 'string') { // default code is zero, so this is a custom error this.message = value; } else if ((0, _obj.isObject)(value)) { // We assign the `code` property manually because native `MediaError` objects // do not expose it as an own/enumerable property of the object. if (typeof value.code === 'number') { this.code = value.code; } (0, _obj.assign)(this, value); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } } /** * The error code that refers two one of the defined `MediaError` types * * @type {Number} */ /** * @file media-error.js */ MediaError.prototype.code = 0; /** * An optional message that to show with the error. Message is not part of the HTML5 * video spec but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /** * An optional status code that can be set by plugins to allow even more detail about * the error. For example a plugin might provide a specific HTTP status code and an * error message for that code. Then when the plugin gets that error this class will * know how to display an error message for it. This allows a custom message to show * up on the `Player` error overlay. * * @type {Array} */ MediaError.prototype.status = null; /** * Errors indexed by the W3C standard. The order **CANNOT CHANGE**! See the * specification listed under {@link MediaError} for more information. * * @enum {array} * @readonly * @property {string} 0 - MEDIA_ERR_CUSTOM * @property {string} 1 - MEDIA_ERR_CUSTOM * @property {string} 2 - MEDIA_ERR_ABORTED * @property {string} 3 - MEDIA_ERR_NETWORK * @property {string} 4 - MEDIA_ERR_SRC_NOT_SUPPORTED * @property {string} 5 - MEDIA_ERR_ENCRYPTED */ MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', 'MEDIA_ERR_ABORTED', 'MEDIA_ERR_NETWORK', 'MEDIA_ERR_DECODE', 'MEDIA_ERR_SRC_NOT_SUPPORTED', 'MEDIA_ERR_ENCRYPTED']; /** * The default `MediaError` messages based on the {@link MediaError.errorTypes}. * * @type {Array} * @constant */ MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } // jsdocs for instance/static members added above // instance methods use `#` and static methods use `.` /** * W3C error code for any custom error. * * @member MediaError#MEDIA_ERR_CUSTOM * @constant {number} * @default 0 */ /** * W3C error code for any custom error. * * @member MediaError.MEDIA_ERR_CUSTOM * @constant {number} * @default 0 */ /** * W3C error code for media error aborted. * * @member MediaError#MEDIA_ERR_ABORTED * @constant {number} * @default 1 */ /** * W3C error code for media error aborted. * * @member MediaError.MEDIA_ERR_ABORTED * @constant {number} * @default 1 */ /** * W3C error code for any network error. * * @member MediaError#MEDIA_ERR_NETWORK * @constant {number} * @default 2 */ /** * W3C error code for any network error. * * @member MediaError.MEDIA_ERR_NETWORK * @constant {number} * @default 2 */ /** * W3C error code for any decoding error. * * @member MediaError#MEDIA_ERR_DECODE * @constant {number} * @default 3 */ /** * W3C error code for any decoding error. * * @member MediaError.MEDIA_ERR_DECODE * @constant {number} * @default 3 */ /** * W3C error code for any time that a source is not supported. * * @member MediaError#MEDIA_ERR_SRC_NOT_SUPPORTED * @constant {number} * @default 4 */ /** * W3C error code for any time that a source is not supported. * * @member MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED * @constant {number} * @default 4 */ /** * W3C error code for any time that a source is encrypted. * * @member MediaError#MEDIA_ERR_ENCRYPTED * @constant {number} * @default 5 */ /** * W3C error code for any time that a source is encrypted. * * @member MediaError.MEDIA_ERR_ENCRYPTED * @constant {number} * @default 5 */ exports['default'] = MediaError; /***/ }), /* 29 */ /***/ (function(module, exports) { module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } /***/ }), /* 30 */ /***/ (function(module, exports) { 'use strict'; exports.__esModule = true; /** * @file text-track-list-converter.js Utilities for capturing text track state and * re-creating tracks based on a capture. * * @module text-track-list-converter */ /** * Examine a single {@link TextTrack} and return a JSON-compatible javascript object that * represents the {@link TextTrack}'s state. * * @param {TextTrack} track * The text track to query. * * @return {Object} * A serializable javascript representation of the TextTrack. * @private */ var trackToJson_ = function trackToJson_(track) { var ret = ['kind', 'label', 'language', 'id', 'inBandMetadataTrackDispatchType', 'mode', 'src'].reduce(function (acc, prop, i) { if (track[prop]) { acc[prop] = track[prop]; } return acc; }, { cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }) }); return ret; }; /** * Examine a {@link Tech} and return a JSON-compatible javascript array that represents the * state of all {@link TextTrack}s currently configured. The return array is compatible with * {@link text-track-list-converter:jsonToTextTracks}. * * @param {Tech} tech * The tech object to query * * @return {Array} * A serializable javascript representation of the {@link Tech}s * {@link TextTrackList}. */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.$$('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); if (trackEl.src) { json.src = trackEl.src; } return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Create a set of remote {@link TextTrack}s on a {@link Tech} based on an array of javascript * object {@link TextTrack} representations. * * @param {Array} json * An array of `TextTrack` representation objects, like those that would be * produced by `textTracksToJson`. * * @param {Tech} tech * The `Tech` to create the `TextTrack`s on. */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _dom = __webpack_require__(11); var Dom = _interopRequireWildcard(_dom); var _fn = __webpack_require__(20); var Fn = _interopRequireWildcard(_fn); var _component = __webpack_require__(19); var _component2 = _interopRequireDefault(_component); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file modal-dialog.js */ var MODAL_CLASS_NAME = 'vjs-modal-dialog'; var ESC = 27; /** * The `ModalDialog` displays over the video and its controls, which blocks * interaction with the player until it is closed. * * Modal dialogs include a "Close" button and will close when that button * is activated - or when ESC is pressed anywhere. * * @extends Component */ var ModalDialog = function (_Component) { _inherits(ModalDialog, _Component); /** * Create an instance of this class. * * @param {Player} player * The `Player` that this class should be attached to. * * @param {Object} [options] * The key/value store of player options. * * @param {Mixed} [options.content=undefined] * Provide customized content for this modal. * * @param {string} [options.description] * A text description for the modal, primarily for accessibility. * * @param {boolean} [options.fillAlways=false] * Normally, modals are automatically filled only the first time * they open. This tells the modal to refresh its content * every time it opens. * * @param {string} [options.label] * A text label for the modal, primarily for accessibility. * * @param {boolean} [options.temporary=true] * If `true`, the modal can only be opened once; it will be * disposed as soon as it's closed. * * @param {boolean} [options.uncloseable=false] * If `true`, the user will not be able to close the modal * through the UI in the normal ways. Programmatic closing is * still possible. */ function ModalDialog(player, options) { _classCallCheck(this, ModalDialog); var _this = _possibleConstructorReturn(this, _Component.call(this, player, options)); _this.opened_ = _this.hasBeenOpened_ = _this.hasBeenFilled_ = false; _this.closeable(!_this.options_.uncloseable); _this.content(_this.options_.content); // Make sure the contentEl is defined AFTER any children are initialized // because we only want the contents of the modal in the contentEl // (not the UI elements like the close button). _this.contentEl_ = Dom.createEl('div', { className: MODAL_CLASS_NAME + '-content' }, { role: 'document' }); _this.descEl_ = Dom.createEl('p', { className: MODAL_CLASS_NAME + '-description vjs-offscreen', id: _this.el().getAttribute('aria-describedby') }); Dom.textContent(_this.descEl_, _this.description()); _this.el_.appendChild(_this.descEl_); _this.el_.appendChild(_this.contentEl_); return _this; } /** * Create the `ModalDialog`'s DOM element * * @return {Element} * The DOM element that gets created. */ ModalDialog.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass(), tabIndex: -1 }, { 'aria-describedby': this.id() + '_description', 'aria-hidden': 'true', 'aria-label': this.label(), 'role': 'dialog' }); }; /** * Builds the default DOM `className`. * * @return {string} * The DOM `className` for this object. */ ModalDialog.prototype.buildCSSClass = function buildCSSClass() { return MODAL_CLASS_NAME + ' vjs-hidden ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handles `keydown` events on the document, looking for ESC, which closes * the modal. * * @param {EventTarget~Event} e * The keypress that triggered this event. * * @listens keydown */ ModalDialog.prototype.handleKeyPress = function handleKeyPress(e) { if (e.which === ESC && this.closeable()) { this.close(); } }; /** * Returns the label string for this modal. Primarily used for accessibility. * * @return {string} * the localized or raw label of this modal. */ ModalDialog.prototype.label = function label() { return this.options_.label || this.localize('Modal Window'); }; /** * Returns the description string for this modal. Primarily used for * accessibility. * * @return {string} * The localized or raw description of this modal. */ ModalDialog.prototype.description = function description() { var desc = this.options_.description || this.localize('This is a modal window.'); // Append a universal closeability message if the modal is closeable. if (this.closeable()) { desc += ' ' + this.localize('This modal can be closed by pressing the Escape key or activating the close button.'); } return desc; }; /** * Opens the modal. * * @fires ModalDialog#beforemodalopen * @fires ModalDialog#modalopen * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.open = function open() { if (!this.opened_) { var player = this.player(); /** * Fired just before a `ModalDialog` is opened. * * @event ModalDialog#beforemodalopen * @type {EventTarget~Event} */ this.trigger('beforemodalopen'); this.opened_ = true; // Fill content if the modal has never opened before and // never been filled. if (this.options_.fillAlways || !this.hasBeenOpened_ && !this.hasBeenFilled_) { this.fill(); } // If the player was playing, pause it and take note of its previously // playing state. this.wasPlaying_ = !player.paused(); if (this.options_.pauseOnOpen && this.wasPlaying_) { player.pause(); } if (this.closeable()) { this.on(this.el_.ownerDocument, 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(false); this.show(); this.el().setAttribute('aria-hidden', 'false'); /** * Fired just after a `ModalDialog` is opened. * * @event ModalDialog#modalopen * @type {EventTarget~Event} */ this.trigger('modalopen'); this.hasBeenOpened_ = true; } return this; }; /** * If the `ModalDialog` is currently open or closed. * * @param {boolean} [value] * If given, it will open (`true`) or close (`false`) the modal. * * @return {boolean} * the current open state of the modaldialog */ ModalDialog.prototype.opened = function opened(value) { if (typeof value === 'boolean') { this[value ? 'open' : 'close'](); } return this.opened_; }; /** * Closes the modal, does nothing if the `ModalDialog` is * not open. * * @fires ModalDialog#beforemodalclose * @fires ModalDialog#modalclose * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.close = function close() { if (this.opened_) { var player = this.player(); /** * Fired just before a `ModalDialog` is closed. * * @event ModalDialog#beforemodalclose * @type {EventTarget~Event} */ this.trigger('beforemodalclose'); this.opened_ = false; if (this.wasPlaying_ && this.options_.pauseOnOpen) { player.play(); } if (this.closeable()) { this.off(this.el_.ownerDocument, 'keydown', Fn.bind(this, this.handleKeyPress)); } player.controls(true); this.hide(); this.el().setAttribute('aria-hidden', 'true'); /** * Fired just after a `ModalDialog` is closed. * * @event ModalDialog#modalclose * @type {EventTarget~Event} */ this.trigger('modalclose'); if (this.options_.temporary) { this.dispose(); } } return this; }; /** * Check to see if the `ModalDialog` is closeable via the UI. * * @param {boolean} [value] * If given as a boolean, it will set the `closeable` option. * * @return {boolean} * Returns the final value of the closable option. */ ModalDialog.prototype.closeable = function closeable(value) { if (typeof value === 'boolean') { var closeable = this.closeable_ = !!value; var close = this.getChild('closeButton'); // If this is being made closeable and has no close button, add one. if (closeable && !close) { // The close button should be a child of the modal - not its // content element, so temporarily change the content element. var temp = this.contentEl_; this.contentEl_ = this.el_; close = this.addChild('closeButton', { controlText: 'Close Modal Dialog' }); this.contentEl_ = temp; this.on(close, 'close', this.close); } // If this is being made uncloseable and has a close button, remove it. if (!closeable && close) { this.off(close, 'close', this.close); this.removeChild(close); close.dispose(); } } return this.closeable_; }; /** * Fill the modal's content element with the modal's "content" option. * The content element will be emptied before this change takes place. * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.fill = function fill() { return this.fillWith(this.content()); }; /** * Fill the modal's content element with arbitrary content. * The content element will be emptied before this change takes place. * * @fires ModalDialog#beforemodalfill * @fires ModalDialog#modalfill * * @param {Mixed} [content] * The same rules apply to this as apply to the `content` option. * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.fillWith = function fillWith(content) { var contentEl = this.contentEl(); var parentEl = contentEl.parentNode; var nextSiblingEl = contentEl.nextSibling; /** * Fired just before a `ModalDialog` is filled with content. * * @event ModalDialog#beforemodalfill * @type {EventTarget~Event} */ this.trigger('beforemodalfill'); this.hasBeenFilled_ = true; // Detach the content element from the DOM before performing // manipulation to avoid modifying the live DOM multiple times. parentEl.removeChild(contentEl); this.empty(); Dom.insertContent(contentEl, content); /** * Fired just after a `ModalDialog` is filled with content. * * @event ModalDialog#modalfill * @type {EventTarget~Event} */ this.trigger('modalfill'); // Re-inject the re-filled content element. if (nextSiblingEl) { parentEl.insertBefore(contentEl, nextSiblingEl); } else { parentEl.appendChild(contentEl); } return this; }; /** * Empties the content element. This happens anytime the modal is filled. * * @fires ModalDialog#beforemodalempty * @fires ModalDialog#modalempty * * @return {ModalDialog} * Returns itself; method can be chained. */ ModalDialog.prototype.empty = function empty() { /** * Fired just before a `ModalDialog` is emptied. * * @event ModalDialog#beforemodalempty * @type {EventTarget~Event} */ this.trigger('beforemodalempty'); Dom.emptyEl(this.contentEl()); /** * Fired just after a `ModalDialog` is emptied. * * @event ModalDialog#modalempty * @type {EventTarget~Event} */ this.trigger('modalempty'); return this; }; /** * Gets or sets the modal content, which gets normalized before being * rendered into the DOM. * * This does not update the DOM or fill the modal, but it is called during * that process. * * @param {Mixed} [value] * If defined, sets the internal content value to be used on the * next call(s) to `fill`. This value is normalized before being * inserted. To "clear" the internal content value, pass `null`. * * @return {Mixed} * The current content of the modal dialog */ ModalDialog.prototype.content = function content(value) { if (typeof value !== 'undefined') { this.content_ = value; } return this.content_; }; return ModalDialog; }(_component2['default']); /** * Default options for `ModalDialog` default options. * * @type {Object} * @private */ ModalDialog.prototype.options_ = { pauseOnOpen: true, temporary: true }; _component2['default'].registerComponent('ModalDialog', ModalDialog); exports['default'] = ModalDialog; /***/ }), /* 32 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _component = __webpack_require__(19); var _component2 = _interopRequireDefault(_component); var _htmlTrackElement = __webpack_require__(33); var _htmlTrackElement2 = _interopRequireDefault(_htmlTrackElement); var _htmlTrackElementList = __webpack_require__(45); var _htmlTrackElementList2 = _interopRequireDefault(_htmlTrackElementList); var _mergeOptions = __webpack_require__(22); var _mergeOptions2 = _interopRequireDefault(_mergeOptions); var _textTrack = __webpack_require__(34); var _textTrack2 = _interopRequireDefault(_textTrack); var _textTrackList = __webpack_require__(46); var _textTrackList2 = _interopRequireDefault(_textTrackList); var _videoTrackList = __webpack_require__(48); var _videoTrackList2 = _interopRequireDefault(_videoTrackList); var _audioTrackList = __webpack_require__(49); var _audioTrackList2 = _interopRequireDefault(_audioTrackList); var _fn = __webpack_require__(20); var Fn = _interopRequireWildcard(_fn); var _log = __webpack_require__(13); var _log2 = _interopRequireDefault(_log); var _timeRanges = __webpack_require__(25); var _buffer = __webpack_require__(26); var _mediaError = __webpack_require__(28); var _mediaError2 = _interopRequireDefault(_mediaError); var _window = __webpack_require__(7); var _window2 = _interopRequireDefault(_window); var _document = __webpack_require__(8); var _document2 = _interopRequireDefault(_document); var _obj = __webpack_require__(14); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /** * @file tech.js */ /** * An Object containing a structure like: `{src: 'url', type: 'mimetype'}` or string * that just contains the src url alone. * * `var SourceObject = {src: 'http://ex.com/video.mp4', type: 'video/mp4'};` * `var SourceString = 'http://example.com/some-video.mp4';` * * @typedef {Object|string} Tech~SourceObject * * @property {string} src * The url to the source * * @property {string} type * The mime type of the source */ /** * A function used by {@link Tech} to create a new {@link TextTrack}. * * @param {Tech} self * An instance of the Tech class. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @param {Object} [options={}] * An object with additional text track options * * @return {TextTrack} * The text track that was created. */ function createTrackHelper(self, kind, label, language) { var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _textTrack2['default'](options); tracks.addTrack_(track); return track; } /** * This is the base class for media playback technology controllers, such as * {@link Flash} and {@link HTML5} * * @extends Component */ var Tech = function (_Component) { _inherits(Tech, _Component); /** * Create an instance of this Tech. * * @param {Object} [options] * The key/value store of player options. * * @param {Component~ReadyCallback} ready * Callback function to call when the `HTML5` Tech is ready. */ function Tech() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var ready = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function () {}; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; // keep track of whether the current source has played at all to // implement a very limited played() var _this = _possibleConstructorReturn(this, _Component.call(this, null, options, ready)); _this.hasStarted_ = false; _this.on('playing', function () { this.hasStarted_ = true; }); _this.on('loadstart', function () { this.hasStarted_ = false; }); _this.textTracks_ = options.textTracks; _this.videoTracks_ = options.videoTracks; _this.audioTracks_ = options.audioTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!_this.featuresProgressEvents) { _this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!_this.featuresTimeupdateEvents) { _this.manualTimeUpdatesOn(); } ['Text', 'Audio', 'Video'].forEach(function (track) { if (options['native' + track + 'Tracks'] === false) { _this['featuresNative' + track + 'Tracks'] = false; } }); if (options.nativeCaptions === false) { _this.featuresNativeTextTracks = false; } if (!_this.featuresNativeTextTracks) { _this.emulateTextTracks(); } _this.autoRemoteTextTracks_ = new _textTrackList2['default'](); _this.initTextTrackListeners(); _this.initTrackListeners(); // Turn on component tap events only if not using native controls if (!options.nativeControlsForTouch) { _this.emitTapEvents(); } if (_this.constructor) { _this.name_ = _this.constructor.name || 'Unknown Tech'; } return _this; } /* Fallbacks for unsupported event types ================================================================================ */ /** * Polyfill the `progress` event for browsers that don't support it natively. * * @see {@link Tech#trackProgress} */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * This is used to trigger a `progress` event when the buffered percent changes. It * sets an interval function that will be called every 500 milliseconds to check if the * buffer end percent has changed. * * > This function is called by {@link Tech#manualProgressOn} * * @param {EventTarget~Event} event * The `ready` event that caused this to run. * * @listens Tech#ready * @fires Tech#progress */ Tech.prototype.trackProgress = function trackProgress(event) { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { /** * See {@link Player#progress} * * @event Tech#progress * @type {EventTarget~Event} */ this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update our internal duration on a `durationchange` event by calling * {@link Tech#duration}. * * @param {EventTarget~Event} event * The `durationchange` event that caused this to run. * * @listens Tech#durationchange */ Tech.prototype.onDurationChange = function onDurationChange(event) { this.duration_ = this.duration(); }; /** * Get and create a `TimeRange` object for buffering. * * @return {TimeRange} * The time range object that was created. */ Tech.prototype.buffered = function buffered() { return (0, _timeRanges.createTimeRange)(0, 0); }; /** * Get the percentage of the current video that is currently buffered. * * @return {number} * A number from 0 to 1 that represents the decimal percentage of the * video that is buffered. * */ Tech.prototype.bufferedPercent = function bufferedPercent() { return (0, _buffer.bufferedPercent)(this.buffered(), this.duration_); }; /** * Turn off the polyfill for `progress` events that was created in * {@link Tech#manualProgressOn} * Stop manually tracking progress events by clearing the interval that was set in * {@link Tech#trackProgress}. */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /** * Polyfill the `timeupdate` event for browsers that don't support it. * * @see {@link Tech#trackCurrentTime} */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Turn off the polyfill for `timeupdate` events that was created in * {@link Tech#manualTimeUpdatesOn} */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Sets up an interval function to track current time and trigger `timeupdate` every * 250 milliseconds. * * @listens Tech#play * @triggers Tech#timeupdate */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { /** * Triggered at an interval of 250ms to indicated that time is passing in the video. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }, 250); }; /** * Stop the interval function created in {@link Tech#trackCurrentTime} so that the * `timeupdate` event is no longer triggered. * * @listens {Tech#pause} */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off all event polyfills, clear the `Tech`s {@link AudioTrackList}, * {@link VideoTrackList}, and {@link TextTrackList}, and dispose of this Tech. * * @fires Component#dispose */ Tech.prototype.dispose = function dispose() { // clear out all tracks because we can't reuse them between techs this.clearTracks(['audio', 'video', 'text']); // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * Clear out a single `TrackList` or an array of `TrackLists` given their names. * * > Note: Techs without source handlers should call this between sources for `video` * & `audio` tracks. You don't want to use them between tracks! * * @param {string[]|string} types * TrackList names to clear, valid names are `video`, `audio`, and * `text`. */ Tech.prototype.clearTracks = function clearTracks(types) { var _this2 = this; types = [].concat(types); // clear out all tracks because we can't reuse them between techs types.forEach(function (type) { var list = _this2[type + 'Tracks']() || []; var i = list.length; while (i--) { var track = list[i]; if (type === 'text') { _this2.removeRemoteTextTrack(track); } list.removeTrack_(track); } }); }; /** * Remove any TextTracks added via addRemoteTextTrack that are * flagged for automatic garbage collection */ Tech.prototype.cleanupAutoTextTracks = function cleanupAutoTextTracks() { var list = this.autoRemoteTextTracks_ || []; var i = list.length; while (i--) { var track = list[i]; this.removeRemoteTextTrack(track); } }; /** * Reset the tech, which will removes all sources and reset the internal readyState. * * @abstract */ Tech.prototype.reset = function reset() {}; /** * Get or set an error on the Tech. * * @param {MediaError} [err] * Error to set on the Tech * * @return {MediaError|null} * The current error object on the tech, or null if there isn't one. */ Tech.prototype.error = function error(err) { if (err !== undefined) { this.error_ = new _mediaError2['default'](err); this.trigger('error'); } return this.error_; }; /** * Returns the `TimeRange`s that have been played through for the current source. * * > NOTE: This implementation is incomplete. It does not track the played `TimeRange`. * It only checks wether the source has played at all or not. * * @return {TimeRange} * - A single time range if this video has played * - An empty set of ranges if not. */ Tech.prototype.played = function played() { if (this.hasStarted_) { return (0, _timeRanges.createTimeRange)(0, 0); } return (0, _timeRanges.createTimeRange)(); }; /** * Causes a manual time update to occur if {@link Tech#manualTimeUpdatesOn} was * previously called. * * @fires Tech#timeupdate */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { /** * A manual `timeupdate` event. * * @event Tech#timeupdate * @type {EventTarget~Event} */ this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Turn on listeners for {@link TextTrackList} events. This adds * {@link EventTarget~EventListeners} for `texttrackchange`, `addtrack` and * `removetrack`. * * @fires Tech#texttrackchange */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { /** * Triggered when tracks are added or removed on the Tech {@link TextTrackList} * * @event Tech#texttrackchange * @type {EventTarget~Event} */ this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) { return; } tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Turn on listeners for {@link VideoTrackList} and {@link {AudioTrackList} events. * This adds {@link EventTarget~EventListeners} for `addtrack`, and `removetrack`. * * @fires Tech#audiotrackchange * @fires Tech#videotrackchange */ Tech.prototype.initTrackListeners = function initTrackListeners() { var _this3 = this; var trackTypes = ['video', 'audio']; trackTypes.forEach(function (type) { /** * Triggered when tracks are added or removed on the Tech {@link AudioTrackList} * * @event Tech#audiotrackchange * @type {EventTarget~Event} */ /** * Triggered when tracks are added or removed on the Tech {@link VideoTrackList} * * @event Tech#videotrackchange * @type {EventTarget~Event} */ var trackListChanges = function trackListChanges() { _this3.trigger(type + 'trackchange'); }; var tracks = _this3[type + 'Tracks'](); tracks.addEventListener('removetrack', trackListChanges); tracks.addEventListener('addtrack', trackListChanges); _this3.on('dispose', function () { tracks.removeEventListener('removetrack', trackListChanges); tracks.removeEventListener('addtrack', trackListChanges); }); }); }; /** * Emulate TextTracks using vtt.js if necessary * * @fires Tech#vttjsloaded * @fires Tech#vttjserror */ Tech.prototype.addWebVttScript_ = function addWebVttScript_() { var _this4 = this; if (_window2['default'].WebVTT) { return; } // Initially, Tech.el_ is a child of a dummy-div wait until the Component system // signals that the Tech is ready at which point Tech.el_ is part of the DOM // before inserting the WebVTT script if (_document2['default'].body.contains(this.el())) { var vtt = __webpack_require__(50); // load via require if available and vtt.js script location was not passed in // as an option. novtt builds will turn the above require call into an empty object // which will cause this if check to always fail. if (!this.options_['vtt.js'] && (0, _obj.isPlain)(vtt) && Object.keys(vtt).length > 0) { this.trigger('vttjsloaded'); return; } // load vtt.js via the script location option or the cdn of no location was // passed in var script = _document2['default'].createElement('script'); script.src = this.options_['vtt.js'] || 'https://vjs.zencdn.net/vttjs/0.12.4/vtt.min.js'; script.onload = function () { /** * Fired when vtt.js is loaded. * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this4.trigger('vttjsloaded'); }; script.onerror = function () { /** * Fired when vtt.js was not loaded due to an error * * @event Tech#vttjsloaded * @type {EventTarget~Event} */ _this4.trigger('vttjserror'); }; this.on('dispose', function () { script.onload = null; script.onerror = null; }); // but have not loaded yet and we set it to true before the inject so that // we don't overwrite the injected window.WebVTT if it loads right away _window2['default'].WebVTT = true; this.el().parentNode.appendChild(script); } else { this.ready(this.addWebVttScript_); } }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { var _this5 = this; var tracks = this.textTracks(); if (!tracks) { return; } var remoteTracks = this.remoteTextTracks(); var handleAddTrack = function handleAddTrack(e) { return tracks.addTrack_(e.track); }; var handleRemoveTrack = function handleRemoveTrack(e) { return tracks.removeTrack_(e.track); }; remoteTracks.on('addtrack', handleAddTrack); remoteTracks.on('removetrack', handleRemoveTrack); this.addWebVttScript_(); var updateDisplay = function updateDisplay() { return _this5.trigger('texttrackchange'); }; var textTracksChanges = function textTracksChanges() { updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }; textTracksChanges(); tracks.addEventListener('change', textTracksChanges); tracks.addEventListener('addtrack', textTracksChanges); tracks.addEventListener('removetrack', textTracksChanges); this.on('dispose', function () { remoteTracks.off('addtrack', handleAddTrack); remoteTracks.off('removetrack', handleRemoveTrack); tracks.removeEventListener('change', textTracksChanges); tracks.removeEventListener('addtrack', textTracksChanges); tracks.removeEventListener('removetrack', textTracksChanges); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); } }); }; /** * Get the `Tech`s {@link VideoTrackList}. * * @return {VideoTrackList} * The video track list that the Tech is currently using. */ Tech.prototype.videoTracks = function videoTracks() { this.videoTracks_ = this.videoTracks_ || new _videoTrackList2['default'](); return this.videoTracks_; }; /** * Get the `Tech`s {@link AudioTrackList}. * * @return {AudioTrackList} * The audio track list that the Tech is currently using. */ Tech.prototype.audioTracks = function audioTracks() { this.audioTracks_ = this.audioTracks_ || new _audioTrackList2['default'](); return this.audioTracks_; }; /** * Get the `Tech`s {@link TextTrackList}. * * @return {TextTrackList} * The text track list that the Tech is currently using. */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _textTrackList2['default'](); return this.textTracks_; }; /** * Get the `Tech`s remote {@link TextTrackList}, which is created from elements * that were added to the DOM. * * @return {TextTrackList} * The remote text track list that the Tech is currently using. */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _textTrackList2['default'](); return this.remoteTextTracks_; }; /** * Get The `Tech`s {HTMLTrackElementList}, which are the elements in the DOM that are * being used as TextTracks. * * @return {HTMLTrackElementList} * The current HTML track elements that exist for the tech. */ Tech.prototype.remoteTextTrackEls = function remoteTextTrackEls() { this.remoteTextTrackEls_ = this.remoteTextTrackEls_ || new _htmlTrackElementList2['default'](); return this.remoteTextTrackEls_; }; /** * Create and returns a remote {@link TextTrack} object. * * @param {string} kind * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata) * * @param {string} [label] * Label to identify the text track * * @param {string} [language] * Two letter language abbreviation * * @return {TextTrack} * The TextTrack that gets created. */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Create an emulated TextTrack for use by addRemoteTextTrack * * This is intended to be overridden by classes that inherit from * Tech in order to create native or custom TextTracks. * * @param {Object} options * The object should contain the options to initialize the TextTrack with. * * @param {string} [options.kind] * `TextTrack` kind (subtitles, captions, descriptions, chapters, or metadata). * * @param {string} [options.label]. * Label to identify the text track * * @param {string} [options.language] * Two letter language abbreviation. * * @return {HTMLTrackElement} * The track element that gets created. */ Tech.prototype.createRemoteTextTrack = function createRemoteTextTrack(options) { var track = (0, _mergeOptions2['default'])(options, { tech: this }); return new _htmlTrackElement2['default'](track); }; /** * Creates a remote text track object and returns an html track element. * * > Note: This can be an emulated {@link HTMLTrackElement} or a native one. * * @param {Object} options * See {@link Tech#createRemoteTextTrack} for more detailed properties. * * @param {boolean} [manualCleanup=true] * - When false: the TextTrack will be automatically removed from the video * element whenever the source changes * - When True: The TextTrack will have to be cleaned up manually * * @return {HTMLTrackElement} * An Html Track Element. * * @deprecated The default functionality for this function will be equivalent * to "manualCleanup=false" in the future. The manualCleanup parameter will * also be removed. */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var manualCleanup = arguments[1]; var htmlTrackElement = this.createRemoteTextTrack(options); if (manualCleanup !== true && manualCleanup !== false) { // deprecation warning _log2['default'].warn('Calling addRemoteTextTrack without explicitly setting the "manualCleanup" parameter to `true` is deprecated and default to `false` in future version of video.js'); manualCleanup = true; } // store HTMLTrackElement and TextTrack to remote list this.remoteTextTrackEls().addTrackElement_(htmlTrackElement); this.remoteTextTracks().addTrack_(htmlTrackElement.track); if (manualCleanup !== true) { // create the TextTrackList if it doesn't exist this.autoRemoteTextTracks_.addTrack_(htmlTrackElement.track); } return htmlTrackElement; }; /** * Remove a remote text track from the remote `TextTrackList`. * * @param {TextTrack} track * `TextTrack` to remove from the `TextTrackList` */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { var trackElement = this.remoteTextTrackEls().getTrackElementByTrack_(track); // remove HTMLTrackElement and TextTrack from remote list this.remoteTextTrackEls().removeTrackElement_(trackElement); this.remoteTextTracks().removeTrack_(track); this.autoRemoteTextTracks_.removeTrack_(track); }; /** * Gets available media playback quality metrics as specified by the W3C's Media * Playback Quality API. * * @see [Spec]{@link https://wicg.github.io/media-playback-quality} * * @return {Object} * An object with supported media playback quality metrics * * @abstract */ Tech.prototype.getVideoPlaybackQuality = function getVideoPlaybackQuality() { return {}; }; /** * A method to set a poster from a `Tech`. * * @abstract */ Tech.prototype.setPoster = function setPoster() {}; /** * A method to check for the presence of the 'playsinine'