UNPKG

videojs-playlist

Version:
2,122 lines (1,775 loc) 76.3 kB
(function (QUnit,sinon,videojs) { 'use strict'; QUnit = QUnit && QUnit.hasOwnProperty('default') ? QUnit['default'] : QUnit; sinon = sinon && sinon.hasOwnProperty('default') ? sinon['default'] : sinon; videojs = videojs && videojs.hasOwnProperty('default') ? videojs['default'] : videojs; var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; var win; if (typeof window !== "undefined") { win = window; } else if (typeof commonjsGlobal !== "undefined") { win = commonjsGlobal; } else if (typeof self !== "undefined"){ win = self; } else { win = {}; } var window_1 = win; /** * Validates a number of seconds to use as the auto-advance delay. * * @private * @param {number} s * The number to check * * @return {boolean} * Whether this is a valid second or not */ var validSeconds = function validSeconds(s) { return typeof s === 'number' && !isNaN(s) && s >= 0 && s < Infinity; }; /** * Resets the auto-advance behavior of a player. * * @param {Player} player * The player to reset the behavior on */ var reset = function reset(player) { var aa = player.playlist.autoadvance_; if (aa.timeout) { player.clearTimeout(aa.timeout); } if (aa.trigger) { player.off('ended', aa.trigger); } aa.timeout = null; aa.trigger = null; }; /** * Sets up auto-advance behavior on a player. * * @param {Player} player * the current player * * @param {number} delay * The number of seconds to wait before each auto-advance. * * @return {undefined} * Used to short circuit function logic */ var setup = function setup(player, delay) { reset(player); // Before queuing up new auto-advance behavior, check if `seconds` was // called with a valid value. if (!validSeconds(delay)) { player.playlist.autoadvance_.delay = null; return; } player.playlist.autoadvance_.delay = delay; player.playlist.autoadvance_.trigger = function () { // This calls setup again, which will reset the existing auto-advance and // set up another auto-advance for the next "ended" event. var cancelOnPlay = function cancelOnPlay() { return setup(player, delay); }; // If there is a "play" event while we're waiting for an auto-advance, // we need to cancel the auto-advance. This could mean the user seeked // back into the content or restarted the content. This is reproducible // with an auto-advance > 0. player.one('play', cancelOnPlay); player.playlist.autoadvance_.timeout = player.setTimeout(function () { reset(player); player.off('play', cancelOnPlay); player.playlist.next(); }, delay * 1000); }; player.one('ended', player.playlist.autoadvance_.trigger); }; /** * Used to change the reset function in this module at runtime * This should only be used in tests. * * @param {Function} fn * The function to se the reset to */ var setReset_ = function setReset_(fn) { reset = fn; }; /* globals window, HTMLElement */ 'use strict'; /**! * is * the definitive JavaScript type testing library * * @copyright 2013-2014 Enrico Marino / Jordan Harband * @license MIT */ var objProto = Object.prototype; var owns = objProto.hasOwnProperty; var toStr = objProto.toString; var symbolValueOf; if (typeof Symbol === 'function') { symbolValueOf = Symbol.prototype.valueOf; } var isActualNaN = function (value) { return value !== value; }; var NON_HOST_TYPES = { 'boolean': 1, number: 1, string: 1, undefined: 1 }; var base64Regex = /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{4}|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)$/; var hexRegex = /^[A-Fa-f0-9]+$/; /** * Expose `is` */ var is = {}; /** * Test general. */ /** * is.type * Test if `value` is a type of `type`. * * @param {Mixed} value value to test * @param {String} type type * @return {Boolean} true if `value` is a type of `type`, false otherwise * @api public */ is.a = is.type = function (value, type) { return typeof value === type; }; /** * is.defined * Test if `value` is defined. * * @param {Mixed} value value to test * @return {Boolean} true if 'value' is defined, false otherwise * @api public */ is.defined = function (value) { return typeof value !== 'undefined'; }; /** * is.empty * Test if `value` is empty. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is empty, false otherwise * @api public */ is.empty = function (value) { var type = toStr.call(value); var key; if (type === '[object Array]' || type === '[object Arguments]' || type === '[object String]') { return value.length === 0; } if (type === '[object Object]') { for (key in value) { if (owns.call(value, key)) { return false; } } return true; } return !value; }; /** * is.equal * Test if `value` is equal to `other`. * * @param {Mixed} value value to test * @param {Mixed} other value to compare with * @return {Boolean} true if `value` is equal to `other`, false otherwise */ is.equal = function equal(value, other) { if (value === other) { return true; } var type = toStr.call(value); var key; if (type !== toStr.call(other)) { return false; } if (type === '[object Object]') { for (key in value) { if (!is.equal(value[key], other[key]) || !(key in other)) { return false; } } for (key in other) { if (!is.equal(value[key], other[key]) || !(key in value)) { return false; } } return true; } if (type === '[object Array]') { key = value.length; if (key !== other.length) { return false; } while (key--) { if (!is.equal(value[key], other[key])) { return false; } } return true; } if (type === '[object Function]') { return value.prototype === other.prototype; } if (type === '[object Date]') { return value.getTime() === other.getTime(); } return false; }; /** * is.hosted * Test if `value` is hosted by `host`. * * @param {Mixed} value to test * @param {Mixed} host host to test with * @return {Boolean} true if `value` is hosted by `host`, false otherwise * @api public */ is.hosted = function (value, host) { var type = typeof host[value]; return type === 'object' ? !!host[value] : !NON_HOST_TYPES[type]; }; /** * is.instance * Test if `value` is an instance of `constructor`. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an instance of `constructor` * @api public */ is.instance = is['instanceof'] = function (value, constructor) { return value instanceof constructor; }; /** * is.nil / is.null * Test if `value` is null. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is null, false otherwise * @api public */ is.nil = is['null'] = function (value) { return value === null; }; /** * is.undef / is.undefined * Test if `value` is undefined. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is undefined, false otherwise * @api public */ is.undef = is.undefined = function (value) { return typeof value === 'undefined'; }; /** * Test arguments. */ /** * is.args * Test if `value` is an arguments object. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an arguments object, false otherwise * @api public */ is.args = is.arguments = function (value) { var isStandardArguments = toStr.call(value) === '[object Arguments]'; var isOldArguments = !is.array(value) && is.arraylike(value) && is.object(value) && is.fn(value.callee); return isStandardArguments || isOldArguments; }; /** * Test array. */ /** * is.array * Test if 'value' is an array. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an array, false otherwise * @api public */ is.array = Array.isArray || function (value) { return toStr.call(value) === '[object Array]'; }; /** * is.arguments.empty * Test if `value` is an empty arguments object. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an empty arguments object, false otherwise * @api public */ is.args.empty = function (value) { return is.args(value) && value.length === 0; }; /** * is.array.empty * Test if `value` is an empty array. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an empty array, false otherwise * @api public */ is.array.empty = function (value) { return is.array(value) && value.length === 0; }; /** * is.arraylike * Test if `value` is an arraylike object. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an arguments object, false otherwise * @api public */ is.arraylike = function (value) { return !!value && !is.bool(value) && owns.call(value, 'length') && isFinite(value.length) && is.number(value.length) && value.length >= 0; }; /** * Test boolean. */ /** * is.bool * Test if `value` is a boolean. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a boolean, false otherwise * @api public */ is.bool = is['boolean'] = function (value) { return toStr.call(value) === '[object Boolean]'; }; /** * is.false * Test if `value` is false. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is false, false otherwise * @api public */ is['false'] = function (value) { return is.bool(value) && Boolean(Number(value)) === false; }; /** * is.true * Test if `value` is true. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is true, false otherwise * @api public */ is['true'] = function (value) { return is.bool(value) && Boolean(Number(value)) === true; }; /** * Test date. */ /** * is.date * Test if `value` is a date. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a date, false otherwise * @api public */ is.date = function (value) { return toStr.call(value) === '[object Date]'; }; /** * is.date.valid * Test if `value` is a valid date. * * @param {Mixed} value value to test * @returns {Boolean} true if `value` is a valid date, false otherwise */ is.date.valid = function (value) { return is.date(value) && !isNaN(Number(value)); }; /** * Test element. */ /** * is.element * Test if `value` is an html element. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an HTML Element, false otherwise * @api public */ is.element = function (value) { return value !== undefined && typeof HTMLElement !== 'undefined' && value instanceof HTMLElement && value.nodeType === 1; }; /** * Test error. */ /** * is.error * Test if `value` is an error object. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an error object, false otherwise * @api public */ is.error = function (value) { return toStr.call(value) === '[object Error]'; }; /** * Test function. */ /** * is.fn / is.function (deprecated) * Test if `value` is a function. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a function, false otherwise * @api public */ is.fn = is['function'] = function (value) { var isAlert = typeof window !== 'undefined' && value === window.alert; if (isAlert) { return true; } var str = toStr.call(value); return str === '[object Function]' || str === '[object GeneratorFunction]' || str === '[object AsyncFunction]'; }; /** * Test number. */ /** * is.number * Test if `value` is a number. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a number, false otherwise * @api public */ is.number = function (value) { return toStr.call(value) === '[object Number]'; }; /** * is.infinite * Test if `value` is positive or negative infinity. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is positive or negative Infinity, false otherwise * @api public */ is.infinite = function (value) { return value === Infinity || value === -Infinity; }; /** * is.decimal * Test if `value` is a decimal number. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a decimal number, false otherwise * @api public */ is.decimal = function (value) { return is.number(value) && !isActualNaN(value) && !is.infinite(value) && value % 1 !== 0; }; /** * is.divisibleBy * Test if `value` is divisible by `n`. * * @param {Number} value value to test * @param {Number} n dividend * @return {Boolean} true if `value` is divisible by `n`, false otherwise * @api public */ is.divisibleBy = function (value, n) { var isDividendInfinite = is.infinite(value); var isDivisorInfinite = is.infinite(n); var isNonZeroNumber = is.number(value) && !isActualNaN(value) && is.number(n) && !isActualNaN(n) && n !== 0; return isDividendInfinite || isDivisorInfinite || (isNonZeroNumber && value % n === 0); }; /** * is.integer * Test if `value` is an integer. * * @param value to test * @return {Boolean} true if `value` is an integer, false otherwise * @api public */ is.integer = is['int'] = function (value) { return is.number(value) && !isActualNaN(value) && value % 1 === 0; }; /** * is.maximum * Test if `value` is greater than 'others' values. * * @param {Number} value value to test * @param {Array} others values to compare with * @return {Boolean} true if `value` is greater than `others` values * @api public */ is.maximum = function (value, others) { if (isActualNaN(value)) { throw new TypeError('NaN is not a valid value'); } else if (!is.arraylike(others)) { throw new TypeError('second argument must be array-like'); } var len = others.length; while (--len >= 0) { if (value < others[len]) { return false; } } return true; }; /** * is.minimum * Test if `value` is less than `others` values. * * @param {Number} value value to test * @param {Array} others values to compare with * @return {Boolean} true if `value` is less than `others` values * @api public */ is.minimum = function (value, others) { if (isActualNaN(value)) { throw new TypeError('NaN is not a valid value'); } else if (!is.arraylike(others)) { throw new TypeError('second argument must be array-like'); } var len = others.length; while (--len >= 0) { if (value > others[len]) { return false; } } return true; }; /** * is.nan * Test if `value` is not a number. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is not a number, false otherwise * @api public */ is.nan = function (value) { return !is.number(value) || value !== value; }; /** * is.even * Test if `value` is an even number. * * @param {Number} value value to test * @return {Boolean} true if `value` is an even number, false otherwise * @api public */ is.even = function (value) { return is.infinite(value) || (is.number(value) && value === value && value % 2 === 0); }; /** * is.odd * Test if `value` is an odd number. * * @param {Number} value value to test * @return {Boolean} true if `value` is an odd number, false otherwise * @api public */ is.odd = function (value) { return is.infinite(value) || (is.number(value) && value === value && value % 2 !== 0); }; /** * is.ge * Test if `value` is greater than or equal to `other`. * * @param {Number} value value to test * @param {Number} other value to compare with * @return {Boolean} * @api public */ is.ge = function (value, other) { if (isActualNaN(value) || isActualNaN(other)) { throw new TypeError('NaN is not a valid value'); } return !is.infinite(value) && !is.infinite(other) && value >= other; }; /** * is.gt * Test if `value` is greater than `other`. * * @param {Number} value value to test * @param {Number} other value to compare with * @return {Boolean} * @api public */ is.gt = function (value, other) { if (isActualNaN(value) || isActualNaN(other)) { throw new TypeError('NaN is not a valid value'); } return !is.infinite(value) && !is.infinite(other) && value > other; }; /** * is.le * Test if `value` is less than or equal to `other`. * * @param {Number} value value to test * @param {Number} other value to compare with * @return {Boolean} if 'value' is less than or equal to 'other' * @api public */ is.le = function (value, other) { if (isActualNaN(value) || isActualNaN(other)) { throw new TypeError('NaN is not a valid value'); } return !is.infinite(value) && !is.infinite(other) && value <= other; }; /** * is.lt * Test if `value` is less than `other`. * * @param {Number} value value to test * @param {Number} other value to compare with * @return {Boolean} if `value` is less than `other` * @api public */ is.lt = function (value, other) { if (isActualNaN(value) || isActualNaN(other)) { throw new TypeError('NaN is not a valid value'); } return !is.infinite(value) && !is.infinite(other) && value < other; }; /** * is.within * Test if `value` is within `start` and `finish`. * * @param {Number} value value to test * @param {Number} start lower bound * @param {Number} finish upper bound * @return {Boolean} true if 'value' is is within 'start' and 'finish' * @api public */ is.within = function (value, start, finish) { if (isActualNaN(value) || isActualNaN(start) || isActualNaN(finish)) { throw new TypeError('NaN is not a valid value'); } else if (!is.number(value) || !is.number(start) || !is.number(finish)) { throw new TypeError('all arguments must be numbers'); } var isAnyInfinite = is.infinite(value) || is.infinite(start) || is.infinite(finish); return isAnyInfinite || (value >= start && value <= finish); }; /** * Test object. */ /** * is.object * Test if `value` is an object. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is an object, false otherwise * @api public */ is.object = function (value) { return toStr.call(value) === '[object Object]'; }; /** * is.primitive * Test if `value` is a primitive. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a primitive, false otherwise * @api public */ is.primitive = function isPrimitive(value) { if (!value) { return true; } if (typeof value === 'object' || is.object(value) || is.fn(value) || is.array(value)) { return false; } return true; }; /** * is.hash * Test if `value` is a hash - a plain object literal. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a hash, false otherwise * @api public */ is.hash = function (value) { return is.object(value) && value.constructor === Object && !value.nodeType && !value.setInterval; }; /** * Test regexp. */ /** * is.regexp * Test if `value` is a regular expression. * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a regexp, false otherwise * @api public */ is.regexp = function (value) { return toStr.call(value) === '[object RegExp]'; }; /** * Test string. */ /** * is.string * Test if `value` is a string. * * @param {Mixed} value value to test * @return {Boolean} true if 'value' is a string, false otherwise * @api public */ is.string = function (value) { return toStr.call(value) === '[object String]'; }; /** * Test base64 string. */ /** * is.base64 * Test if `value` is a valid base64 encoded string. * * @param {Mixed} value value to test * @return {Boolean} true if 'value' is a base64 encoded string, false otherwise * @api public */ is.base64 = function (value) { return is.string(value) && (!value.length || base64Regex.test(value)); }; /** * Test base64 string. */ /** * is.hex * Test if `value` is a valid hex encoded string. * * @param {Mixed} value value to test * @return {Boolean} true if 'value' is a hex encoded string, false otherwise * @api public */ is.hex = function (value) { return is.string(value) && (!value.length || hexRegex.test(value)); }; /** * is.symbol * Test if `value` is an ES6 Symbol * * @param {Mixed} value value to test * @return {Boolean} true if `value` is a Symbol, false otherise * @api public */ is.symbol = function (value) { return typeof Symbol === 'function' && toStr.call(value) === '[object Symbol]' && typeof symbolValueOf.call(value) === 'symbol'; }; var is_1 = is; 'use strict'; /*! * node.extend * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * @fileoverview * Port of jQuery.extend that actually works on node.js */ var extend$1 = function extend() { var target = arguments[0] || {}; var i = 1; var length = arguments.length; var deep = false; var options, name, src, copy, copyIsArray, clone; // Handle a deep copy situation if (typeof target === 'boolean') { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if (typeof target !== 'object' && !is_1.fn(target)) { target = {}; } for (; i < length; i++) { // Only deal with non-null/undefined values options = arguments[i]; if (options != null) { if (typeof options === 'string') { options = options.split(''); } // Extend the base object for (name in options) { src = target[name]; copy = options[name]; // Prevent never-ending loop if (target === copy) { continue; } // Recurse if we're merging plain objects or arrays if (deep && copy && (is_1.hash(copy) || (copyIsArray = is_1.array(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && is_1.array(src) ? src : []; } else { clone = src && is_1.hash(src) ? src : {}; } // Never move original objects, clone them target[name] = extend(deep, clone, copy); // Don't bring in undefined values } else if (typeof copy !== 'undefined') { target[name] = copy; } } } } // Return the modified object return target; }; /** * @public */ extend$1.version = '1.1.3'; /** * Exports module. */ var extend_1 = extend$1; 'use strict'; var node_extend = extend_1; var proxy = function proxy(props) { var player = node_extend(true, {}, videojs.EventTarget.prototype, { play: function play() {}, paused: function paused() {}, ended: function ended() {}, poster: function poster() {}, src: function src() {}, currentSrc: function currentSrc() {}, addRemoteTextTrack: function addRemoteTextTrack() {}, removeRemoteTextTrack: function removeRemoteTextTrack() {}, remoteTextTracks: function remoteTextTracks() {}, playlist: { autoadvance_: {}, currentIndex_: -1, autoadvance: function autoadvance() {}, contains: function contains() {}, currentItem: function currentItem() {}, first: function first() {}, indexOf: function indexOf() {}, next: function next() {}, previous: function previous() {} }, ready: function ready(cb) { return cb(); }, setTimeout: function setTimeout(cb, wait) { return window_1.setTimeout(cb, wait); }, clearTimeout: function clearTimeout(id) { return window_1.clearTimeout(id); } }, props); player.constructor = videojs.getComponent('Player'); player.playlist.player_ = player; return player; }; QUnit.module('auto-advance'); QUnit.test('set up ended listener if one does not exist yet', function (assert) { var player = proxy(); var ones = []; player.one = function (type) { ones.push(type); }; setup(player, 0); assert.equal(ones.length, 1, 'there should have been only one one event added'); assert.equal(ones[0], 'ended', 'the event we want to one is "ended"'); }); QUnit.test('off previous listener if exists before adding a new one', function (assert) { var player = proxy(); var ones = []; var offs = []; player.one = function (type) { ones.push(type); }; player.off = function (type) { offs.push(type); }; setup(player, 0); assert.equal(ones.length, 1, 'there should have been only one one event added'); assert.equal(ones[0], 'ended', 'the event we want to one is "ended"'); assert.equal(offs.length, 0, 'we should not have off-ed anything yet'); setup(player, 10); assert.equal(ones.length, 2, 'there should have been only two one event added'); assert.equal(ones[0], 'ended', 'the event we want to one is "ended"'); assert.equal(ones[1], 'ended', 'the event we want to one is "ended"'); assert.equal(offs.length, 1, 'there should have been only one off event added'); assert.equal(offs[0], 'ended', 'the event we want to off is "ended"'); }); QUnit.test('do nothing if timeout is weird', function (assert) { var player = proxy(); var ones = []; var offs = []; player.one = function (type) { ones.push(type); }; player.off = function (type) { offs.push(type); }; setup(player, -1); setup(player, -100); setup(player, null); setup(player, {}); setup(player, []); assert.equal(offs.length, 0, 'we did nothing'); assert.equal(ones.length, 0, 'we did nothing'); }); QUnit.test('reset if timeout is weird after we advance', function (assert) { var player = proxy(); var ones = []; var offs = []; player.one = function (type) { ones.push(type); }; player.off = function (type) { offs.push(type); }; setup(player, 0); setup(player, -1); setup(player, 0); setup(player, -100); setup(player, 0); setup(player, null); setup(player, 0); setup(player, {}); setup(player, 0); setup(player, []); setup(player, 0); setup(player, NaN); setup(player, 0); setup(player, Infinity); setup(player, 0); setup(player, -Infinity); assert.equal(offs.length, 8, 'we reset the advance 8 times'); assert.equal(ones.length, 8, 'we autoadvanced 8 times'); }); QUnit.test('reset if we have already started advancing', function (assert) { var player = proxy(); var oldClearTimeout = window_1.clearTimeout; var clears = 0; window_1.clearTimeout = function () { clears++; }; // pretend we started autoadvancing player.playlist.autoadvance_.timeout = 1; setup(player, 0); assert.equal(clears, 1, 'we reset the auto advance'); window_1.clearTimeout = oldClearTimeout; }); QUnit.test('timeout is given in seconds', function (assert) { var player = proxy(); var oldSetTimeout = window_1.setTimeout; player.addEventListener = Function.prototype; window_1.setTimeout = function (fn, timeout) { assert.equal(timeout, 10 * 1000, 'timeout was given in seconds'); }; setup(player, 10); player.trigger('ended'); window_1.setTimeout = oldSetTimeout; }); QUnit.test('cancel a pending auto-advance if play is requested', function (assert) { var clock = sinon.useFakeTimers(); var player = proxy(); sinon.spy(player.playlist, 'next'); setup(player, 10); player.trigger('ended'); clock.tick(10000); assert.equal(player.playlist.next.callCount, 1, 'next was called'); setup(player, 10); player.trigger('ended'); clock.tick(5000); player.trigger('play'); clock.tick(5000); assert.equal(player.playlist.next.callCount, 1, 'next was not called because a "play" occurred'); player.trigger('ended'); clock.tick(10000); assert.equal(player.playlist.next.callCount, 2, 'next was called again because the content ended again and the appropriate wait time elapsed'); }); /** * Removes all remote text tracks from a player. * * @param {Player} player * The player to clear tracks on */ var clearTracks = function clearTracks(player) { var tracks = player.remoteTextTracks(); var i = tracks && tracks.length || 0; // This uses a `while` loop rather than `forEach` because the // `TextTrackList` object is a live DOM list (not an array). while (i--) { player.removeRemoteTextTrack(tracks[i]); } }; /** * Plays an item on a player's playlist. * * @param {Player} player * The player to play the item on * * @param {Object} item * A source from the playlist. * * @return {Player} * The player that is now playing the item */ var playItem = function playItem(player, item) { var replay = !player.paused() || player.ended(); player.trigger('beforeplaylistitem', item); player.poster(item.poster || ''); player.src(item.sources); clearTracks(player); player.ready(function () { (item.textTracks || []).forEach(player.addRemoteTextTrack.bind(player)); player.trigger('playlistitem', item); if (replay) { player.play(); } setup(player, player.playlist.autoadvance_.delay); }); return player; }; QUnit.module('play-item'); QUnit.test('clearTracks will try and remove all tracks', function (assert) { var player = proxy(); var remoteTracks = [1, 2, 3]; var removedTracks = []; player.remoteTextTracks = function () { return remoteTracks; }; player.removeRemoteTextTrack = function (tt) { removedTracks.push(tt); }; clearTracks(player); assert.deepEqual(removedTracks.sort(), remoteTracks.sort(), 'the removed tracks are equivalent to our remote tracks'); }); QUnit.test('will not try to play if paused', function (assert) { var player = proxy(); var tryPlay = false; player.paused = function () { return true; }; player.play = function () { tryPlay = true; }; playItem(player, { sources: [1, 2, 3], textTracks: [4, 5, 6], poster: 'http://example.com/poster.png' }); assert.ok(!tryPlay, 'we did not reply on paused'); }); QUnit.test('will try to play if not paused', function (assert) { var player = proxy(); var tryPlay = false; player.paused = function () { return false; }; player.play = function () { tryPlay = true; }; playItem(player, { sources: [1, 2, 3], textTracks: [4, 5, 6], poster: 'http://example.com/poster.png' }); assert.ok(tryPlay, 'we replayed on not-paused'); }); QUnit.test('will not try to play if paused and not ended', function (assert) { var player = proxy(); var tryPlay = false; player.paused = function () { return true; }; player.ended = function () { return false; }; player.play = function () { tryPlay = true; }; playItem(player, { sources: [1, 2, 3], textTracks: [4, 5, 6], poster: 'http://example.com/poster.png' }); assert.ok(!tryPlay, 'we did not replaye on paused and not ended'); }); QUnit.test('will try to play if paused and ended', function (assert) { var player = proxy(); var tryPlay = false; player.paused = function () { return true; }; player.ended = function () { return true; }; player.play = function () { tryPlay = true; }; playItem(player, { sources: [1, 2, 3], poster: 'http://example.com/poster.png' }); assert.ok(tryPlay, 'we replayed on not-paused'); }); QUnit.test('fires "beforeplaylistitem" and "playlistitem"', function (assert) { var player = proxy(); var beforeSpy = sinon.spy(); var spy = sinon.spy(); player.on('beforeplaylistitem', beforeSpy); player.on('playlistitem', spy); playItem(player, { sources: [1, 2, 3], poster: 'http://example.com/poster.png' }); assert.strictEqual(beforeSpy.callCount, 1); assert.strictEqual(spy.callCount, 1); }); 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; }; var asyncGenerator = function () { function AwaitValue(value) { this.value = value; } function AsyncGenerator(gen) { var front, back; function send(key, arg) { return new Promise(function (resolve, reject) { var request = { key: key, arg: arg, resolve: resolve, reject: reject, next: null }; if (back) { back = back.next = request; } else { front = back = request; resume(key, arg); } }); } function resume(key, arg) { try { var result = gen[key](arg); var value = result.value; if (value instanceof AwaitValue) { Promise.resolve(value.value).then(function (arg) { resume("next", arg); }, function (arg) { resume("throw", arg); }); } else { settle(result.done ? "return" : "normal", result.value); } } catch (err) { settle("throw", err); } } function settle(type, value) { switch (type) { case "return": front.resolve({ value: value, done: true }); break; case "throw": front.reject(value); break; default: front.resolve({ value: value, done: false }); break; } front = front.next; if (front) { resume(front.key, front.arg); } else { back = null; } } this._invoke = send; if (typeof gen.return !== "function") { this.return = undefined; } } if (typeof Symbol === "function" && Symbol.asyncIterator) { AsyncGenerator.prototype[Symbol.asyncIterator] = function () { return this; }; } AsyncGenerator.prototype.next = function (arg) { return this._invoke("next", arg); }; AsyncGenerator.prototype.throw = function (arg) { return this._invoke("throw", arg); }; AsyncGenerator.prototype.return = function (arg) { return this._invoke("return", arg); }; return { wrap: function (fn) { return function () { return new AsyncGenerator(fn.apply(this, arguments)); }; }, await: function (value) { return new AwaitValue(value); } }; }(); /** * Given two sources, check to see whether the two sources are equal. * If both source urls have a protocol, the protocols must match, otherwise, protocols * are ignored. * * @private * @param {string|Object} source1 * The first source * * @param {string|Object} source2 * The second source * * @return {boolean} * The result */ var sourceEquals = function sourceEquals(source1, source2) { var src1 = source1; var src2 = source2; if ((typeof source1 === 'undefined' ? 'undefined' : _typeof(source1)) === 'object') { src1 = source1.src; } if ((typeof source2 === 'undefined' ? 'undefined' : _typeof(source2)) === 'object') { src2 = source2.src; } if (/^\/\//.test(src1)) { src2 = src2.slice(src2.indexOf('//')); } if (/^\/\//.test(src2)) { src1 = src1.slice(src1.indexOf('//')); } return src1 === src2; }; /** * Look through an array of playlist items for a specific `source`; * checking both the value of elements and the value of their `src` * property. * * @private * @param {Array} arr * An array of playlist items to look through * * @param {string} src * The source to look for * * @return {number} * The index of that source or -1 */ var indexInSources = function indexInSources(arr, src) { for (var i = 0; i < arr.length; i++) { var sources = arr[i].sources; if (Array.isArray(sources)) { for (var j = 0; j < sources.length; j++) { var source = sources[j]; if (source && sourceEquals(source, src)) { return i; } } } } return -1; }; /** * Randomize the contents of an array. * * @private * @param {Array} arr * An array. * * @return {Array} * The same array that was passed in. */ var randomize = function randomize(arr) { var index = -1; var lastIndex = arr.length - 1; while (++index < arr.length) { var rand = index + Math.floor(Math.random() * (lastIndex - index + 1)); var value = arr[rand]; arr[rand] = arr[index]; arr[index] = value; } return arr; }; /** * Factory function for creating new playlist implementation on the given player. * * API summary: * * playlist(['a', 'b', 'c']) // setter * playlist() // getter * playlist.currentItem() // getter, 0 * playlist.currentItem(1) // setter, 1 * playlist.next() // 'c' * playlist.previous() // 'b' * playlist.first() // 'a' * playlist.last() // 'c' * playlist.autoadvance(5) // 5 second delay * playlist.autoadvance() // cancel autoadvance * * @param {Player} player * The current player * * @param {Array=} initialList * If given, an initial list of sources with which to populate * the playlist. * * @param {number=} initialIndex * If given, the index of the item in the list that should * be loaded first. If -1, no video is loaded. If omitted, The * the first video is loaded. * * @return {Function} * Returns the playlist function specific to the given player. */ function factory(player, initialList) { var initialIndex = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var list = null; var changing = false; /** * Get/set the playlist for a player. * * This function is added as an own property of the player and has its * own methods which can be called to manipulate the internal state. * * @param {Array} [newList] * If given, a new list of sources with which to populate the * playlist. Without this, the function acts as a getter. * * @param {number} [newIndex] * If given, the index of the item in the list that should * be loaded first. If -1, no video is loaded. If omitted, The * the first video is loaded. * * @return {Array} * The playlist */ var playlist = player.playlist = function (newList) { var newIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; if (changing) { throw new Error('do not call playlist() during a playlist change'); } if (Array.isArray(newList)) { // @todo - Simplify this to `list.slice()` for v5. var previousPlaylist = Array.isArray(list) ? list.slice() : null; list = newList.slice(); // Mark the playlist as changing during the duringplaylistchange lifecycle. changing = true; player.trigger({ type: 'duringplaylistchange', nextIndex: newIndex, nextPlaylist: list, previousIndex: playlist.currentIndex_, // @todo - Simplify this to simply pass along `previousPlaylist` for v5. previousPlaylist: previousPlaylist || [] }); changing = false; if (newIndex !== -1) { playlist.currentItem(newIndex); } // The only time the previous playlist is null is the first call to this // function. This allows us to fire the `duringplaylistchange` event // every time the playlist is populated and to maintain backward // compatibility by not firing the `playlistchange` event on the initial // population of the list. // // @todo - Remove this condition in preparation for v5. if (previousPlaylist) { player.setTimeout(function () { player.trigger('playlistchange'); }, 0); } } // Always return a shallow clone of the playlist list. return list.slice(); }; // On a new source, if there is no current item, disable auto-advance. player.on('loadstart', function () { if (playlist.currentItem() === -1) { reset(player); } }); playlist.currentIndex_ = -1; playlist.player_ = player; playlist.autoadvance_ = {}; playlist.repeat_ = false; /** * Get or set the current item in the playlist. * * During the duringplaylistchange event, acts only as a getter. * * @param {number} [index] * If given as a valid value, plays the playlist item at that index. * * @return {number} * The current item index. */ playlist.currentItem = function (index) { // If the playlist is changing, only act as a getter. if (changing) { return playlist.currentIndex_; } if (typeof index === 'number' && playlist.currentIndex_ !== index && index >= 0 && index < list.length) { playlist.currentIndex_ = index; playItem(playlist.player_, list[playlist.currentIndex_]); } else { playlist.currentIndex_ = playlist.indexOf(playlist.player_.currentSrc() || ''); } return playlist.currentIndex_; }; /** * Checks if the playlist contains a value. * * @param {string|Object|Array} value * The value to check * * @return {boolean} * The result */ playlist.contains = function (value) { return playlist.indexOf(value) !== -1; }; /** * Gets the index of a value in the playlist or -1 if not found. * * @param {string|Object|Array} value * The value to find the index of * * @return {number} * The index or -1 */ playlist.indexOf = function (value) { if (typeof value === 'string') { return indexInSources(list, value); } var sources = Array.isArray(value) ? value : value.sources; for (var i = 0; i < sources.length; i++) { var source = sources[i]; if (typeof source === 'string') { return indexInSources(list, source); } else if (source.src) { return indexInSources(list, source.src); } } return -1; }; /** * Get the index of the current item in the playlist. This is identical to * calling `currentItem()` with no arguments. * * @return {number} * The current item index. */ playlist.currentIndex = function () { return playlist.currentItem(); }; /** * Get the index of the last item in the playlist. * * @return {number} * The index of the last item in the playlist or -1 if there are no * items. */ playlist.lastIndex = function () { return list.length - 1; }; /** * Get the index of the next item in the playlist. * * @return {number} * The index of the next item in the playlist or -1 if there is no * current item. */ playlist.nextIndex = function () { var current = playlist.currentItem(); if (current === -1) { return -1; } var lastIndex = playlist.lastIndex(); // When repeating, loop back to the beginning on the last item. if (playlist.repeat_ && current === lastIndex) { return 0; } // Don't go past the end of the playlist. return Math.min(current + 1, lastIndex); }; /** * Get the index of the previous item in the playlist. * * @return {number} * The index of the previous item in the playlist or -1 if there is * no current item. */ playlist.previousIndex = function () { var current = playlist.currentItem(); if (current === -1) { return -1; } // When repeating, loop back to the end of the playlist. if (playlist.repeat_ && current === 0) { return playlist.lastIndex(); } // Don't go past the beginning of the playlist. return Math.max(current - 1, 0); }; /** * Plays the first item in the playlist. * * @return {Object|undefined} * Returns undefined and has no side effects if the list is empty. */ playlist.first = function () { if (changing) { return; } if (list.length) { return list[playlist.currentItem(0)]; } playlist.currentIndex_ = -1; }; /** * Plays the last item in the playlist. * * @return {Object|undefined} * Returns undefined and has no side effects if the list is empty. */ playlist.last = function () { if (changing) { return; } if (list.length) { return list[playlist.currentItem(playlist.lastIndex())]; } playlist.currentIndex_ = -1; }; /** * Plays the next item in the playlist. * * @return {Object|undefined} * Returns undefined and has no side effects if on last item. */ playlist.next = function () { if (changing) { return; } var index = playlist.nextIndex(); if (index !== playlist.currentIndex_) { return list[playlist.currentItem(index)]; } }; /** * Plays the previous item in the playlist. * * @return {Object|undefined} * Returns undefined and has no side effects if on first item. */ playlist.previous = function () { if (changing) { return; } var index = playlist.previousIndex(); if (index !== playlist.currentIndex_) { return list[playlist.currentItem(index)]; } }; /** * Set up auto-advance on the playlist. * * @param {number} [delay] * The number of seconds to wait before each auto-advance. */ playlist.autoadvance = function (delay) { setup(playlist.player_, delay); }; /** * Sets `repeat` option, which makes the "next" video of the last video in * the playlist be the first video in the playlist. * * @param {boolean} [val] * The value to set repeat to * * @return {boolean} * The current value of repeat */ playlist.repeat = function (val) { if (val === undefined) { return playlist.repeat_; } if (typeof val !== 'boolean') { videojs.log.error('videojs-playlist: Invalid value for repeat', val); return; } playlist.repeat_ = !!val; return playlist.repeat_; }; /** * Sorts the playlist array. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort} * @fires playlistsorted * * @param {Function} compare * A comparator function as per the native Array method. */ playlist.sort = function (compare) { // Bail if the array is empty. if (!list.length) { return; } list.sort(compare); // If the playlist is changing, don't trigger events. if (changing) { return; } /** * Triggered after the playlist is sorted internally. * * @event playlistsorted * @type {Object} */ player.trigger('playlistsorted'); }; /** * Reverses the playlist array. * * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse} * @fires playlistsorted */ playlist.reverse = function () { // Bail if the array is empty. if (!list.length) { return; } list.reverse(); // If the playlist is changing, don't trigger events. if (changing) { return; } /** * Triggered after the playlist is sorted internally. * * @event playlistsorted * @type {Object} */ player.trigger('playlistsorted'); }; /** * Shuffle the contents of the list randomly. * * @see {@link https://github.com/lodash/lodash/blob/40e096b6d5291a025e365a0f4c010d9a0efb9a69/shuffle.js} * @fires playlistsorted * @todo Make the `rest` option default to `true` in v5.0.0. * @param {Object} [options] * An object containing shuffle options. * * @param {boolean} [options.rest = false] * By default, the entire playlist is randomized. However, this may * not be desirable in all cases, such as when a user is already * watching a video. * * When `true` is passed for this option, it will only shuffle * playlist items after the current item. For example, when on the * first item, will shuffle the second item and beyond. */ playlist.shuffle = function () { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, rest = _ref.rest; var index = 0; var arr = list; // When options.rest is true, start randomization at the item after the // current item. if (rest) { index = playlist.currentIndex_ + 1; arr = list.slice(index); } // Bail if the array is empty or too short to shuffle. if (arr.length <= 1) { return; } randomize(arr); // When options.rest is true, splice the randomized sub-array back into // the original array. if (rest) { var _list; (_list = list).splice.apply(_list, [index, arr.length].concat(arr)); } // If the playlist is changing, don't trigger events. if (changing) { return; } /** * Triggered after the playlist is sorted internally. * * @event playlistsorted * @type {Object} */ player.trigger('playlistsorted'); }; // If an initial list was given, populate the playlist with it. if (Array.isArray(initialList)) { playlist(initialList.slice(), initialIndex); // If there is no initial list given, silently set an empty array. } else { list = []; } return playlist; } var videoList = [{ sources: [{ src: 'http://media.w3.org/2010/05/sintel/trailer.mp4', type: 'video/mp4' }], poster: 'http://media.w3.org/2010/05/sintel/poster.png' }, { sources: [{ src: 'http://media.w3.org/2010/05/bunny/trailer.mp4', type: 'video/mp4' }], poster: 'http://media.w3.org/2010/05/bunny/poster.png' }, { sources: [{ src: 'http://vjs.zencdn.net/v/oceans.mp4', type: 'video/mp4' }], poster: 'http://www.videojs.com/img/poster.jpg' }, { sources: [{ src: 'http://media.w