/** * @fileoverview main function src. */ // html5 shiv. must be in to support older browsers. document.createelement('video'); document.createelement('audio'); document.createelement('track'); /** * doubles as the main function for users to create a player instance and also * the main library object. * * **aliases** videojs, _v_ (deprecated) * * the `vjs` function can be used to initialize or retrieve a player. * * var myplayer = vjs('my_video_id'); * * @param {string|element} id video element or video element id * @param {object=} options optional options object for config/settings * @param {function=} ready optional ready callback * @return {vjs.player} a player instance * @namespace */ var vjs = function(id, options, ready){ var tag; // element of id // 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 (vjs.players[id]) { return vjs.players[id]; // otherwise get element for id } else { tag = vjs.el(id); } // id is a media element } else { tag = id; } // check for a useable element if (!tag || !tag.nodename) { // re: nodename, could be a box div also throw new typeerror('the element or id supplied is not valid. (videojs)'); // returns } // element may have a player attr referring to an already created player instance. // if not, set up a new player and return the instance. return tag['player'] || new vjs.player(tag, options, ready); }; // extended name, also available externally, window.videojs var videojs = window['videojs'] = vjs; // cdn version. used to target right flash swf. vjs.cdn_version = '4.11'; vjs.access_protocol = ('https:' == document.location.protocol ? 'https://' : 'http://'); /** * global player instance options, surfaced from vjs.player.prototype.options_ * vjs.options = vjs.player.prototype.options_ * all options should use string keys so they avoid * renaming by closure compiler * @type {object} */ vjs.options = { // default order of fallback technology 'techorder': ['html5','flash'], // techorder: ['flash','html5'], 'html5': {}, 'flash': {}, // default of web browser is 300x150. should rely on source width/height. 'width': 300, 'height': 150, // defaultvolume: 0.85, 'defaultvolume': 0.00, // the freakin seaguls are driving me crazy! // default playback rates 'playbackrates': [], // add playback rate selection by adding rates // 'playbackrates': [0.5, 1, 1.5, 2], // default inactivity timeout 'inactivitytimeout': 2000, // included control sets 'children': { 'medialoader': {}, 'posterimage': {}, 'texttrackdisplay': {}, 'loadingspinner': {}, 'bigplaybutton': {}, 'controlbar': {}, 'errordisplay': {} }, 'language': document.getelementsbytagname('html')[0].getattribute('lang') || 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 video.' }; // set cdn version of swf // the added (+) blocks the replace from changing this 4.11 string if (vjs.cdn_version !== 'generated'+'_cdn_vsn') { videojs.options['flash']['swf'] = vjs.access_protocol + 'vjs.zencdn.net/'+vjs.cdn_version+'/video-js.swf'; } /** * utility function for adding languages to the default options. useful for * amending multiple language support at runtime. * * example: vjs.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 global languages dictionary object */ vjs.addlanguage = function(code, data){ if(vjs.options['languages'][code] !== undefined) { vjs.options['languages'][code] = vjs.util.mergeoptions(vjs.options['languages'][code], data); } else { vjs.options['languages'][code] = data; } return vjs.options['languages']; }; /** * global player list * @type {object} */ vjs.players = {}; /*! * 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 (typeof define === 'function' && define['amd']) { define([], function(){ return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } /** * core object/class for objects that use inheritance + constructors * * to create a class that can be subclassed itself, extend the coreobject class. * * var animal = coreobject.extend(); * var horse = animal.extend(); * * the constructor can be defined through the init property of an object argument. * * var animal = coreobject.extend({ * init: function(name, sound){ * this.name = name; * } * }); * * other methods and properties can be added the same way, or directly to the * prototype. * * var animal = coreobject.extend({ * init: function(name){ * this.name = name; * }, * getname: function(){ * return this.name; * }, * sound: '...' * }); * * animal.prototype.makesound = function(){ * alert(this.sound); * }; * * to create an instance of a class, use the create method. * * var fluffy = animal.create('fluffy'); * fluffy.getname(); // -> fluffy * * methods and properties can be overridden in subclasses. * * var horse = animal.extend({ * sound: 'neighhhhh!' * }); * * var horsey = horse.create('horsey'); * horsey.getname(); // -> horsey * horsey.makesound(); // -> alert: neighhhhh! * * @class * @constructor */ vjs.coreobject = vjs['coreobject'] = function(){}; // manually exporting vjs['coreobject'] here for closure compiler // because of the use of the extend/create class methods // if we didn't do this, those functions would get flattened to something like // `a = ...` and `this.prototype` would refer to the global object instead of // coreobject /** * create a new object that inherits from this object * * var animal = coreobject.extend(); * var horse = animal.extend(); * * @param {object} props functions and properties to be applied to the * new object's prototype * @return {vjs.coreobject} an object that inherits from coreobject * @this {*} */ vjs.coreobject.extend = function(props){ var init, subobj; props = props || {}; // 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 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. subobj = function(){ init.apply(this, arguments); }; // inherit from this object's prototype subobj.prototype = vjs.obj.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 = vjs.coreobject.extend; // make a function for creating instances subobj.create = vjs.coreobject.create; // 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; }; /** * create a new instance of this object class * * var myanimal = animal.create(); * * @return {vjs.coreobject} an instance of a coreobject subclass * @this {*} */ vjs.coreobject.create = function(){ // create a new object that inherits from this object's prototype var inst = vjs.obj.create(this.prototype); // apply this constructor function to the new object this.apply(inst, arguments); // return the new object return inst; }; /** * @fileoverview 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. */ /** * 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|array} type type of event to bind to. * @param {function} fn event listener. * @private */ vjs.on = function(elem, type, fn){ if (vjs.obj.isarray(type)) { return _handlemultipleevents(vjs.on, elem, type, fn); } var data = vjs.getdata(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 = vjs.guid++; data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event){ if (data.disabled) return; event = vjs.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 { handlerscopy[m].call(elem, event); } } } }; } if (data.handlers[type].length == 1) { if (elem.addeventlistener) { elem.addeventlistener(type, data.dispatcher, false); } 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|array=} type type of listener to remove. don't include to remove all events from element. * @param {function} fn specific listener to remove. don't include to remove listeners for an event type. * @private */ vjs.off = function(elem, type, fn) { // don't want to add a cache object through getdata if not needed if (!vjs.hasdata(elem)) return; var data = vjs.getdata(elem); // if no events exist, nothing to unbind if (!data.handlers) { return; } if (vjs.obj.isarray(type)) { return _handlemultipleevents(vjs.off, elem, type, fn); } // utility function var removetype = function(t){ data.handlers[t] = []; vjs.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); } } } vjs.cleanupevents(elem, type); }; /** * clean up the listener cache and dispatchers * @param {element|object} elem element to clean up * @param {string} type type of event to clean up * @private */ vjs.cleanupevents = function(elem, type) { var data = vjs.getdata(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 (vjs.isempty(data.handlers)) { delete data.handlers; delete data.dispatcher; delete data.disabled; // data.handlers = null; // data.dispatcher = null; // data.disabled = null; } // finally remove the expando if there is no data left if (vjs.isempty(data)) { vjs.removedata(elem); } }; /** * fix a native event to have standard property values * @param {object} event event object to fix * @return {object} * @private */ vjs.fixevent = function(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 || window.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 if (key !== 'layerx' && key !== 'layery' && key !== 'keylocation') { // 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 || document; } // handle which other element the event is related to 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; event.isdefaultprevented = returntrue; event.defaultprevented = true; }; event.isdefaultprevented = returnfalse; event.defaultprevented = false; // stop the event from bubbling event.stoppropagation = function () { if (old.stoppropagation) { old.stoppropagation(); } event.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) { var doc = document.documentelement, body = document.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 = (event.button & 1 ? 0 : (event.button & 4 ? 1 : (event.button & 2 ? 2 : 0))); } } // returns fixed-up instance return event; }; /** * trigger an event for an element * @param {element|object} elem element to trigger an event on * @param {event|object|string} event a string (the type) or an event object with a type attribute * @private */ vjs.trigger = function(elem, event) { // 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 hasdata first. var elemdata = (vjs.hasdata(elem)) ? vjs.getdata(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 = vjs.fixevent(event); // if the passed element has a dispatcher, executes the established handlers. if (elemdata.dispatcher) { elemdata.dispatcher.call(elem, event); } // 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 !== false) { vjs.trigger(parent, event); // if at the top of the dom, triggers the default action unless disabled. } else if (!parent && !event.defaultprevented) { var targetdata = vjs.getdata(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; /* original version of js ninja events wasn't complete. * we've since updated to the latest version, but keeping this around * for now just in case. */ // // added in addition to book. book code was broke. // event = typeof event === 'object' ? // event[vjs.expando] ? // event : // new vjs.event(type, event) : // new vjs.event(type); // event.type = type; // if (handler) { // handler.call(elem, event); // } // // clean up the event in case it is being reused // event.result = undefined; // event.target = elem; }; /** * trigger a listener only once for an event * @param {element|object} elem element or object to * @param {string|array} type * @param {function} fn * @private */ vjs.one = function(elem, type, fn) { if (vjs.obj.isarray(type)) { return _handlemultipleevents(vjs.one, elem, type, fn); } var func = function(){ vjs.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 || vjs.guid++; vjs.on(elem, type, func); }; /** * 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 {function} callback event listener. * @private */ function _handlemultipleevents(fn, elem, type, callback) { vjs.arr.foreach(type, function(type) { fn(elem, type, callback); //call the event method for each one of the types }); } var hasownprop = object.prototype.hasownproperty; /** * creates an element and applies properties. * @param {string=} tagname name of tag to be created. * @param {object=} properties element properties to be applied. * @return {element} * @private */ vjs.createel = function(tagname, properties){ var el; tagname = tagname || 'div'; properties = properties || {}; el = document.createelement(tagname); vjs.obj.each(properties, function(propname, val){ // not remembering why we were checking for dash // but using setattribute means you have to use getattribute // the check for dash checks for the aria-* attributes, like aria-label, aria-valuemin. // the additional check for "role" is because the default method for adding attributes does not // add the attribute "role". my guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. the w3c allows for aria-* attributes to be used in pre-html5 docs. // http://www.w3.org/tr/wai-aria-primer/#ariahtml. using setattribute gets around this problem. if (propname.indexof('aria-') !== -1 || propname == 'role') { el.setattribute(propname, val); } else { el[propname] = val; } }); return el; }; /** * uppercase the first letter of a string * @param {string} string string to be uppercased * @return {string} * @private */ vjs.capitalize = function(string){ return string.charat(0).touppercase() + string.slice(1); }; /** * object functions container * @type {object} * @private */ vjs.obj = {}; /** * object.create shim for prototypal inheritance * * https://developer.mozilla.org/en-us/docs/javascript/reference/global_objects/object/create * * @function * @param {object} obj object to use as prototype * @private */ vjs.obj.create = object.create || function(obj){ //create a new function called 'f' which is just an empty object. function f() {} //the prototype of the 'f' function should point to the //parameter of the anonymous function. f.prototype = obj; //create a new constructor function based off of the 'f' function. return new f(); }; /** * loop through each property in an object and call a function * whose arguments are (key,value) * @param {object} obj object of properties * @param {function} fn function to be called on each property. * @this {*} * @private */ vjs.obj.each = function(obj, fn, context){ for (var key in obj) { if (hasownprop.call(obj, key)) { fn.call(context || this, key, obj[key]); } } }; /** * merge two objects together and return the original. * @param {object} obj1 * @param {object} obj2 * @return {object} * @private */ vjs.obj.merge = function(obj1, obj2){ if (!obj2) { return obj1; } for (var key in obj2){ if (hasownprop.call(obj2, key)) { obj1[key] = obj2[key]; } } return obj1; }; /** * merge two objects, and merge any properties that are objects * instead of just overwriting one. uses to merge options hashes * where deeper default settings are important. * @param {object} obj1 object to override * @param {object} obj2 overriding object * @return {object} new object. obj1 and obj2 will be untouched. * @private */ vjs.obj.deepmerge = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (hasownprop.call(obj2, key)) { val1 = obj1[key]; val2 = obj2[key]; // check if both properties are pure objects and do a deep merge if so if (vjs.obj.isplain(val1) && vjs.obj.isplain(val2)) { obj1[key] = vjs.obj.deepmerge(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; }; /** * make a copy of the supplied object * @param {object} obj object to copy * @return {object} copy of object * @private */ vjs.obj.copy = function(obj){ return vjs.obj.merge({}, obj); }; /** * check if an object is plain, and not a dom node or any object sub-instance * @param {object} obj object to check * @return {boolean} true if plain, false otherwise * @private */ vjs.obj.isplain = function(obj){ return !!obj && typeof obj === 'object' && obj.tostring() === '[object object]' && obj.constructor === object; }; /** * check if an object is array * since instanceof array will not work on arrays created in another frame we need to use array.isarray, but since ie8 does not support array.isarray we need this shim * @param {object} obj object to check * @return {boolean} true if plain, false otherwise * @private */ vjs.obj.isarray = array.isarray || function(arr) { return object.prototype.tostring.call(arr) === '[object array]'; }; /** * check to see whether the input is nan or not. * nan is the only javascript construct that isn't equal to itself * @param {number} num number to check * @return {boolean} true if nan, false otherwise * @private */ vjs.isnan = function(num) { return num !== num; }; /** * 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 {*} 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} * @private */ vjs.bind = function(context, fn, uid) { // make sure the function has a unique id if (!fn.guid) { fn.guid = vjs.guid++; } // create the new function that changes the context var ret = function() { 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 ret.guid = (uid) ? uid + '_' + fn.guid : fn.guid; return ret; }; /** * 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 */ vjs.cache = {}; /** * unique id for an element or function * @type {number} * @private */ vjs.guid = 1; /** * unique attribute name to store an element's guid in * @type {string} * @constant * @private */ vjs.expando = '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} * @private */ vjs.getdata = function(el){ var id = el[vjs.expando]; if (!id) { id = el[vjs.expando] = vjs.guid++; vjs.cache[id] = {}; } return vjs.cache[id]; }; /** * returns the cache object where data for an element is stored * @param {element} el element to store data for. * @return {object} * @private */ vjs.hasdata = function(el){ var id = el[vjs.expando]; return !(!id || vjs.isempty(vjs.cache[id])); }; /** * delete data for the element from the cache and the guid attr from getelementbyid * @param {element} el remove data for an element * @private */ vjs.removedata = function(el){ var id = el[vjs.expando]; if (!id) { return; } // remove all stored data // changed to = null // http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/ // vjs.cache[id] = null; delete vjs.cache[id]; // remove the expando property from the dom node try { delete el[vjs.expando]; } catch(e) { if (el.removeattribute) { el.removeattribute(vjs.expando); } else { // ie doesn't appear to support removeattribute on the document element el[vjs.expando] = null; } } }; /** * check if an object is empty * @param {object} obj the object to check for emptiness * @return {boolean} * @private */ vjs.isempty = function(obj) { for (var prop in obj) { // inlude null properties as empty. if (obj[prop] !== null) { return false; } } return true; }; /** * check if an element has a css class * @param {element} element element to check * @param {string} classtocheck classname to check * @private */ vjs.hasclass = function(element, classtocheck){ return ((' ' + element.classname + ' ').indexof(' ' + classtocheck + ' ') !== -1); }; /** * add a css class name to an element * @param {element} element element to add class name to * @param {string} classtoadd classname to add * @private */ vjs.addclass = function(element, classtoadd){ if (!vjs.hasclass(element, classtoadd)) { element.classname = element.classname === '' ? classtoadd : element.classname + ' ' + classtoadd; } }; /** * remove a css class name from an element * @param {element} element element to remove from class name * @param {string} classtoadd classname to remove * @private */ vjs.removeclass = function(element, classtoremove){ var classnames, i; if (!vjs.hasclass(element, classtoremove)) {return;} classnames = element.classname.split(' '); // no arr.indexof in ie8, and we don't want to add a big shim for (i = classnames.length - 1; i >= 0; i--) { if (classnames[i] === classtoremove) { classnames.splice(i,1); } } element.classname = classnames.join(' '); }; /** * element for testing browser html5 video capabilities * @type {element} * @constant * @private */ vjs.test_vid = vjs.createel('video'); /** * useragent for browser testing. * @type {string} * @constant * @private */ vjs.user_agent = navigator.useragent; /** * device is an iphone * @type {boolean} * @constant * @private */ vjs.is_iphone = (/iphone/i).test(vjs.user_agent); vjs.is_ipad = (/ipad/i).test(vjs.user_agent); vjs.is_ipod = (/ipod/i).test(vjs.user_agent); vjs.is_ios = vjs.is_iphone || vjs.is_ipad || vjs.is_ipod; vjs.ios_version = (function(){ var match = vjs.user_agent.match(/os (\d+)_/i); if (match && match[1]) { return match[1]; } })(); vjs.is_android = (/android/i).test(vjs.user_agent); vjs.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 = vjs.user_agent.match(/android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parsefloat(match[1]); minor = match[2] && parsefloat(match[2]); if (major && minor) { return parsefloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); // old android is defined as version older than 2.3, and requiring a webkit version of the android browser vjs.is_old_android = vjs.is_android && (/webkit/i).test(vjs.user_agent) && vjs.android_version < 2.3; vjs.is_firefox = (/firefox/i).test(vjs.user_agent); vjs.is_chrome = (/chrome/i).test(vjs.user_agent); vjs.touch_enabled = !!(('ontouchstart' in window) || window.documenttouch && document instanceof window.documenttouch); vjs.background_size_supported = 'backgroundsize' in vjs.test_vid.style; /** * apply attributes to an html element. * @param {element} el target element. * @param {object=} attributes element attributes to be applied. * @private */ vjs.setelementattributes = function(el, attributes){ vjs.obj.each(attributes, function(attrname, attrvalue) { 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} * @private */ vjs.getelementattributes = function(tag){ var obj, knownbooleans, attrs, attrname, attrval; 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 knownbooleans = ','+'autoplay,controls,loop,muted,default'+','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrname = attrs[i].name; 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 computed style value for an element * from http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element/ * @param {element} el element to get style value for * @param {string} strcssrule style name * @return {string} style value * @private */ vjs.getcomputeddimension = function(el, strcssrule){ var strvalue = ''; if(document.defaultview && document.defaultview.getcomputedstyle){ strvalue = document.defaultview.getcomputedstyle(el, '').getpropertyvalue(strcssrule); } else if(el.currentstyle){ // ie8 width/height support strvalue = el['client'+strcssrule.substr(0,1).touppercase() + strcssrule.substr(1)] + 'px'; } return strvalue; }; /** * insert an element as the first child node of another * @param {element} child element to insert * @param {[type]} parent element to insert child into * @private */ vjs.insertfirst = function(child, parent){ if (parent.firstchild) { parent.insertbefore(child, parent.firstchild); } else { parent.appendchild(child); } }; /** * object to hold browser support information * @type {object} * @private */ vjs.browser = {}; /** * shorthand for document.getelementbyid() * also allows for css (jquery) id syntax. but nothing other than ids. * @param {string} id element id * @return {element} element with supplied id * @private */ vjs.el = function(id){ if (id.indexof('#') === 0) { id = id.slice(1); } return document.getelementbyid(id); }; /** * 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 * @param {number} seconds number of seconds to be turned into a string * @param {number} guide number (in seconds) to model the string after * @return {string} time formatted as h:mm:ss or m:ss * @private */ vjs.formattime = function(seconds, guide) { // default to using seconds as guide guide = guide || seconds; var s = math.floor(seconds % 60), m = math.floor(seconds / 60 % 60), h = math.floor(seconds / 3600), gm = math.floor(guide / 60 % 60), gh = math.floor(guide / 3600); // handle invalid times if (isnan(seconds) || seconds === infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // check if we need to show hours h = (h > 0 || gh > 0) ? h + ':' : ''; // if hours are showing, we may need to add a leading zero. // always show at least one digit of minutes. m = (((h || gm >= 10) && m < 10) ? '0' + m : m) + ':'; // check if leading zero is need for seconds s = (s < 10) ? '0' + s : s; return h + m + s; }; // attempt to block the ability to select text while dragging controls vjs.blocktextselection = function(){ document.body.focus(); document.onselectstart = function () { return false; }; }; // turn off text selection blocking vjs.unblocktextselection = function(){ document.onselectstart = function () { return true; }; }; /** * trim whitespace from the ends of a string. * @param {string} string string to trim * @return {string} trimmed string * @private */ vjs.trim = function(str){ return (str+'').replace(/^\s+|\s+$/g, ''); }; /** * should round off a number to a decimal place * @param {number} num number to round * @param {number} dec number of decimal places to round to * @return {number} rounded number * @private */ vjs.round = function(num, dec) { if (!dec) { dec = 0; } return math.round(num*math.pow(10,dec))/math.pow(10,dec); }; /** * should create a fake timerange object * mimics an html5 time range instance, which has functions that * return the start and end times for a range * timeranges are returned by the buffered() method * @param {number} start start time in seconds * @param {number} end end time in seconds * @return {object} fake timerange object * @private */ vjs.createtimerange = function(start, end){ return { length: 1, start: function() { return start; }, end: function() { return end; } }; }; /** * add to local storage (may removable) * @private */ vjs.setlocalstorage = function(key, value){ try { // ie was throwing errors referencing the var anywhere without this var localstorage = window.localstorage || false; if (!localstorage) { return; } localstorage[key] = value; } catch(e) { if (e.code == 22 || e.code == 1014) { // webkit == 22 / firefox == 1014 vjs.log('localstorage full (videojs)', e); } else { if (e.code == 18) { vjs.log('localstorage not allowed (videojs)', e); } else { vjs.log('localstorage error (videojs)', e); } } } }; /** * get absolute version of relative url. used to tell flash correct url. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * @param {string} url url to make absolute * @return {string} absolute url * @private */ vjs.getabsoluteurl = function(url){ // check if absolute url if (!url.match(/^https?:\/\//)) { // convert to absolute url. flash hosted off-site needs an absolute url. url = vjs.createel('div', { innerhtml: 'x' }).firstchild.href; } return url; }; /** * resolve and parse the elements of a url * @param {string} url the url to parse * @return {object} an object of url details */ vjs.parseurl = function(url) { var div, a, addtobody, props, details; props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the url a = vjs.createel('a', { href: url }); // ie8 (and 9?) fix // ie8 doesn't parse the url correctly until the anchor is actually // added to the body, and an innerhtml is needed to trigger the parsing addtobody = (a.host === '' && a.protocol !== 'file:'); if (addtobody) { div = vjs.createel('div'); div.innerhtml = ''; a = div.firstchild; // prevent the div from affecting layout div.setattribute('style', 'display:none; position:absolute;'); document.body.appendchild(div); } // copy the specific url properties to a new object // this is also needed for ie8 because the anchor loses its // properties when it's removed from the dom details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } if (addtobody) { document.body.removechild(div); } return details; }; /** * log messages to the console and history based on the type of message * * @param {string} type the type of message, or `null` for `log` * @param {[type]} args the args to be passed to the log * @private */ function _logtype(type, args){ var argsarray, noop, console; // convert args to an array to get array functions argsarray = array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in vjs.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 noop = function(){}; console = window['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsarray.unshift(type.touppercase()+':'); } else { // default to log with no prefix type = 'log'; } // add to history vjs.log.history.push(argsarray); // add console prefix after adding to history argsarray.unshift('videojs:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsarray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsarray.join(' ')); } } /** * log plain debug messages */ vjs.log = function(){ _logtype(null, arguments); }; /** * keep a history of log messages * @type {array} */ vjs.log.history = []; /** * log error messages */ vjs.log.error = function(){ _logtype('error', arguments); }; /** * log warning messages */ vjs.log.warn = function(){ _logtype('warn', arguments); }; // offset left // getboundingclientrect technique from john resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ vjs.findposition = function(el) { var box, docel, body, clientleft, scrollleft, left, clienttop, scrolltop, top; if (el.getboundingclientrect && el.parentnode) { box = el.getboundingclientrect(); } if (!box) { return { left: 0, top: 0 }; } docel = document.documentelement; body = document.body; clientleft = docel.clientleft || body.clientleft || 0; scrollleft = window.pagexoffset || body.scrollleft; left = box.left + scrollleft - clientleft; clienttop = docel.clienttop || body.clienttop || 0; scrolltop = window.pageyoffset || body.scrolltop; top = box.top + scrolltop - clienttop; // android sometimes returns slightly off decimal values, so need to round return { left: vjs.round(left), top: vjs.round(top) }; }; /** * array functions container * @type {object} * @private */ vjs.arr = {}; /* * loops through an array and runs a function for each item inside it. * @param {array} array the array * @param {function} callback the function to be run for each item * @param {*} thisarg the `this` binding of callback * @returns {array} the array * @private */ vjs.arr.foreach = function(array, callback, thisarg) { if (vjs.obj.isarray(array) && callback instanceof function) { for (var i = 0, len = array.length; i < len; ++i) { callback.call(thisarg || vjs, array[i], i, array); } } return array; }; /** * simple http request for retrieving external files (e.g. text tracks) * * ##### example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responsebody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'get', * responsetype: 'text' * }, function(error, response, responsebody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * api is modeled after the raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/raynos/xhr/blob/master/index.js * * @param {object|string} options options block or url string * @param {function} callback the callback function * @returns {object} the request */ vjs.xhr = function(options, callback){ var xhr, request, urlinfo, winloc, fileurl, crossorigin, aborttimeout, successhandler, errorhandler; // if options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // merge with default options videojs.util.mergeoptions({ method: 'get', timeout: 45 * 1000 }, options); callback = callback || function(){}; successhandler = function(){ window.cleartimeout(aborttimeout); callback(null, request, request.response || request.responsetext); }; errorhandler = function(err){ window.cleartimeout(aborttimeout); if (!err || typeof err === 'string') { err = new error(err); } callback(err, request); }; xhr = window.xmlhttprequest; if (typeof xhr === 'undefined') { // shim xmlhttprequest for older ies xhr = function () { try { return new window.activexobject('msxml2.xmlhttp.6.0'); } catch (e) {} try { return new window.activexobject('msxml2.xmlhttp.3.0'); } catch (f) {} try { return new window.activexobject('msxml2.xmlhttp'); } catch (g) {} throw new error('this browser does not support xmlhttprequest.'); }; } request = new xhr(); // store a reference to the url on the request instance request.uri = options.uri; urlinfo = vjs.parseurl(options.uri); winloc = window.location; // check if url is for another domain/origin // ie8 doesn't know location.origin, so we won't rely on it here crossorigin = (urlinfo.protocol + urlinfo.host) !== (winloc.protocol + winloc.host); // xdomainrequest -- use for ie if xmlhttprequest2 isn't available // 'withcredentials' is only available in xmlhttprequest2 // also xdomainrequest has a lot of gotchas, so only use if cross domain if (crossorigin && window.xdomainrequest && !('withcredentials' in request)) { request = new window.xdomainrequest(); request.onload = successhandler; request.onerror = errorhandler; // these blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function(){}; request.ontimeout = function(){}; // xmlhttprequest } else { fileurl = (urlinfo.protocol == 'file:' || winloc.protocol == 'file:'); request.onreadystatechange = function() { if (request.readystate === 4) { if (request.timedout) { return errorhandler('timeout'); } if (request.status === 200 || fileurl && request.status === 0) { successhandler(); } else { errorhandler(); } } }; if (options.timeout) { aborttimeout = window.settimeout(function() { if (request.readystate !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } } // open the connection try { // third arg is async, or ignored by xdomainrequest request.open(options.method || 'get', options.uri, true); } catch(err) { return errorhandler(err); } // withcredentials only supported by xmlhttprequest2 if(options.withcredentials) { request.withcredentials = true; } if (options.responsetype) { request.responsetype = options.responsetype; } // send the request try { request.send(); } catch(err) { return errorhandler(err); } return request; }; /** * utility functions namespace * @namespace * @type {object} */ vjs.util = {}; /** * merge two options objects, recursively merging any plain object properties as * well. previously `deepmerge` * * @param {object} obj1 object to override values in * @param {object} obj2 overriding object * @return {object} new object -- obj1 and obj2 will be untouched */ vjs.util.mergeoptions = function(obj1, obj2){ var key, val1, val2; // make a copy of obj1 so we're not overwriting original values. // like prototype.options_ and all sub options objects obj1 = vjs.obj.copy(obj1); for (key in obj2){ if (obj2.hasownproperty(key)) { val1 = obj1[key]; val2 = obj2[key]; // check if both properties are pure objects and do a deep merge if so if (vjs.obj.isplain(val1) && vjs.obj.isplain(val2)) { obj1[key] = vjs.util.mergeoptions(val1, val2); } else { obj1[key] = obj2[key]; } } } return obj1; };/** * @fileoverview player component - base class for all ui objects * */ /** * base ui component class * * components are embeddable ui objects that are represented by both a * javascript object and an element in the dom. they can be children of other * components, and can have many children themselves. * * // adding a button to the player * var button = player.addchild('button'); * button.el(); // -> button element * *
*
button
*
* * components are also event emitters. * * button.on('click', function(){ * console.log('button clicked!'); * }); * * button.trigger('customevent'); * * @param {object} player main player * @param {object=} options * @class * @constructor * @extends vjs.coreobject */ vjs.component = vjs.coreobject.extend({ /** * the constructor function for the class * * @constructor */ init: function(player, options, ready){ this.player_ = player; // make a copy of prototype.options_ to protect against overriding global defaults this.options_ = vjs.obj.copy(this.options_); // updated options with supplied options options = 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 this.id_ = ((player.id && player.id()) || 'no_player') + '_component_' + vjs.guid++; } this.name_ = options['name'] || null; // create element if one wasn't provided in options this.el_ = options['el'] || this.createel(); this.children_ = []; this.childindex_ = {}; this.childnameindex_ = {}; // add any child components in options 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 */ vjs.component.prototype.dispose = function(){ 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_); } vjs.removedata(this.el_); this.el_ = null; }; /** * reference to main player instance * * @type {vjs.player} * @private */ vjs.component.prototype.player_ = true; /** * return the component's player * * @return {vjs.player} */ vjs.component.prototype.player = function(){ return this.player_; }; /** * the component's options object * * @type {object} * @private */ vjs.component.prototype.options_; /** * deep merge of options objects * * whenever a property is an object on both options objects * the two properties will be merged using vjs.obj.deepmerge. * * this is used for merging options for child components. we * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * * parent.prototype.options_ = { * children: { * 'childone': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childtwo': {}, * 'childthree': {} * } * } * newoptions = { * children: { * 'childone': { 'foo': 'baz', 'abc': '123' } * 'childtwo': null, * 'childfour': {} * } * } * * this.options(newoptions); * * result * * { * children: { * 'childone': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childtwo': null, // disabled. won't be initialized. * 'childthree': {}, * 'childfour': {} * } * } * * @param {object} obj object of new option values * @return {object} a new object of this.options_ and obj merged */ vjs.component.prototype.options = function(obj){ if (obj === undefined) return this.options_; return this.options_ = vjs.util.mergeoptions(this.options_, obj); }; /** * the dom element for the component * * @type {element} * @private */ vjs.component.prototype.el_; /** * create the component's dom element * * @param {string=} tagname element's node type. e.g. 'div' * @param {object=} attributes an object of element attributes that should be set on the element * @return {element} */ vjs.component.prototype.createel = function(tagname, attributes){ return vjs.createel(tagname, attributes); }; vjs.component.prototype.localize = function(string){ var lang = this.player_.language(), languages = this.player_.languages(); if (languages && languages[lang] && languages[lang][string]) { return languages[lang][string]; } return string; }; /** * get the component's dom element * * var domel = mycomponent.el(); * * @return {element} */ vjs.component.prototype.el = function(){ return this.el_; }; /** * an optional element where, if defined, children will be inserted instead of * directly in `el_` * * @type {element} * @private */ vjs.component.prototype.contentel_; /** * return the component's dom element for embedding content. * will either be el_ or a new element defined in createel. * * @return {element} */ vjs.component.prototype.contentel = function(){ return this.contentel_ || this.el_; }; /** * the id for the component * * @type {string} * @private */ vjs.component.prototype.id_; /** * get the component's id * * var id = mycomponent.id(); * * @return {string} */ vjs.component.prototype.id = function(){ return this.id_; }; /** * the name for the component. often used to reference the component. * * @type {string} * @private */ vjs.component.prototype.name_; /** * get the component's name. the name is often used to reference the component. * * var name = mycomponent.name(); * * @return {string} */ vjs.component.prototype.name = function(){ return this.name_; }; /** * array of child components * * @type {array} * @private */ vjs.component.prototype.children_; /** * get an array of all child components * * var kids = mycomponent.children(); * * @return {array} the children */ vjs.component.prototype.children = function(){ return this.children_; }; /** * object of child components by id * * @type {object} * @private */ vjs.component.prototype.childindex_; /** * returns a child component with the provided id * * @return {vjs.component} */ vjs.component.prototype.getchildbyid = function(id){ return this.childindex_[id]; }; /** * object of child components by name * * @type {object} * @private */ vjs.component.prototype.childnameindex_; /** * returns a child component with the provided name * * @return {vjs.component} */ vjs.component.prototype.getchild = function(name){ return this.childnameindex_[name]; }; /** * adds a child component inside this component * * mycomponent.el(); * // ->
* mycomonent.children(); * // [empty array] * * var mybutton = mycomponent.addchild('mybutton'); * // ->
mybutton
* // -> mybutton === mycomonent.children()[0]; * * pass in options for child constructors and options for children of the child * * var mybutton = mycomponent.addchild('mybutton', { * text: 'press me', * children: { * buttonchildexample: { * buttonchildoption: true * } * } * }); * * @param {string|vjs.component} child the class name or instance of a child to add * @param {object=} options options, including options to be passed to children of the child. * @return {vjs.component} the child component (created by this process if a string was used) * @suppress {accesscontrols|checkregexp|checktypes|checkvars|const|constantproperty|deprecated|duplicate|es5strict|fileoverviewtags|globalthis|invalidcasts|missingproperties|nonstandardjsdocs|strictmoduledepcheck|undefinednames|undefinedvars|unknowndefines|uselesscode|visibility} */ vjs.component.prototype.addchild = function(child, options){ var component, componentclass, componentname; // if child is a string, create new component with options if (typeof child === 'string') { componentname = child; // make sure options is at least an empty object to protect against errors options = options || {}; // if no componentclass in options, assume componentclass is the name lowercased // (e.g. playbutton) componentclass = options['componentclass'] || vjs.capitalize(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 // closure compiler throws an 'incomplete alias' warning if we use the vjs variable directly. // every class should be exported, so this should never be a problem here. component = new window['videojs'][componentclass](this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(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 && 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']()) { this.contentel().appendchild(component['el']()); } // return so it can stored on parent object if desired. return component; }; /** * remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {vjs.component} component component to remove */ vjs.component.prototype.removechild = function(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 components from options * * // when an instance of mycomponent is created, all children in options * // will be added to the instance by their name strings and options * mycomponent.prototype.options_.children = { * mychildcomponent: { * mychildoption: true * } * } * * // or when creating the component * var mycomp = new mycomponent(player, { * children: { * mychildcomponent: { * mychildoption: true * } * } * }); * * the children option can also be an array of child names or * child options objects (that also include a 'name' key). * * var mycomp = new mycomponent(player, { * children: [ * 'button', * { * name: 'button', * someotheroption: true * } * ] * }); * */ vjs.component.prototype.initchildren = function(){ var parent, parentoptions, children, child, name, opts, handleadd; parent = this; parentoptions = parent.options(); children = parentoptions['children']; if (children) { handleadd = function(name, 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. vjs.options['children']['posterimage'] = false if (opts === false) return; // 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 parent[name] = parent.addchild(name, opts); }; // allow for an array of children details to passed in the options if (vjs.obj.isarray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; if (typeof child == 'string') { // ['mycomponent'] name = child; opts = {}; } else { // [{ name: 'mycomponent', otheroption: true }] name = child.name; opts = child; } handleadd(name, opts); } } else { vjs.obj.each(children, handleadd); } } }; /** * allows sub components to stack css class names * * @return {string} the constructed class name */ vjs.component.prototype.buildcssclass = function(){ // child classes can include a function that does: // return 'class name' + this._super(); return ''; }; /* events ============================================================================= */ /** * add an event listener to this component's element * * var myfunc = function(){ * var mycomponent = this; * // do something when the event is fired * }; * * mycomponent.on('eventtype', myfunc); * * the context of myfunc will be mycomponent unless previously bound. * * alternatively, you can add a listener to another element or component. * * mycomponent.on(otherelement, 'eventname', myfunc); * mycomponent.on(othercomponent, 'eventname', myfunc); * * the benefit of using this over `vjs.on(otherelement, 'eventname', myfunc)` * and `othercomponent.on('eventname', myfunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * it will also bind mycomponent as the context of myfunc. * * **note**: when using this on elements in the page other than window * and document (both permanent), if you remove the element from the dom * you need to call `vjs.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {string|vjs.component} first the event type or other component * @param {function|string} second the event handler or event type * @param {function} third the event handler * @return {vjs.component} self */ vjs.component.prototype.on = function(first, second, third){ var target, type, fn, removeondispose, cleanremover, thiscomponent; if (typeof first === 'string' || vjs.obj.isarray(first)) { vjs.on(this.el_, first, vjs.bind(this, second)); // targeting another component or element } else { target = first; type = second; fn = vjs.bind(this, third); thiscomponent = this; // when this component is disposed, remove the listener from the other component removeondispose = function(){ thiscomponent.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. cleanremover = function(){ thiscomponent.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 vjs.on(target, type, fn); vjs.on(target, 'dispose', cleanremover); // should be a component // not using `instanceof vjs.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 * * mycomponent.off('eventtype', myfunc); * * if myfunc is excluded, all listeners for the event type will be removed. * if eventtype is excluded, all listeners will be removed from the component. * * alternatively you can use `off` to remove listeners that were added to other * elements or components using `mycomponent.on(othercomponent...`. * in this case both the event type and listener function are required. * * mycomponent.off(otherelement, 'eventtype', myfunc); * mycomponent.off(othercomponent, 'eventtype', myfunc); * * @param {string=|vjs.component} first the event type or other component * @param {function=|string} second the listener function or event type * @param {function=} third the listener for other component * @return {vjs.component} */ vjs.component.prototype.off = function(first, second, third){ var target, othercomponent, type, fn, otherel; if (!first || typeof first === 'string' || vjs.obj.isarray(first)) { vjs.off(this.el_, first, second); } else { target = first; type = second; // ensure there's at least a guid, even if the function hasn't been used fn = vjs.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 vjs.off(target, type, fn); // remove the listener for cleaning the dispose listener vjs.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * add an event listener to be triggered only once and then removed * * mycomponent.one('eventname', myfunc); * * alternatively you can add a listener to another element or component * that will be triggered only once. * * mycomponent.one(otherelement, 'eventname', myfunc); * mycomponent.one(othercomponent, 'eventname', myfunc); * * @param {string|vjs.component} first the event type or other component * @param {function|string} second the listener function or event type * @param {function=} third the listener function for other component * @return {vjs.component} */ vjs.component.prototype.one = function(first, second, third) { var target, type, fn, thiscomponent, newfunc; if (typeof first === 'string' || vjs.obj.isarray(first)) { vjs.one(this.el_, first, vjs.bind(this, second)); } else { target = first; type = second; fn = vjs.bind(this, third); thiscomponent = this; newfunc = function(){ thiscomponent.off(target, type, newfunc); fn.apply(this, 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 * * mycomponent.trigger('eventname'); * mycomponent.trigger({'type':'eventname'}); * * @param {event|object|string} event a string (the type) or an event object with a type attribute * @return {vjs.component} self */ vjs.component.prototype.trigger = function(event){ vjs.trigger(this.el_, event); return this; }; /* ready ================================================================================ */ /** * is the component loaded * this can mean different things depending on the component. * * @private * @type {boolean} */ vjs.component.prototype.isready_; /** * trigger ready as soon as initialization is finished * * allows for delaying ready. override on a sub class prototype. * if you set this.isreadyoninitfinish_ it will affect all components. * specially used when waiting for the flash player to asynchronously load. * * @type {boolean} * @private */ vjs.component.prototype.isreadyoninitfinish_ = true; /** * list of ready listeners * * @type {array} * @private */ vjs.component.prototype.readyqueue_; /** * bind a listener to the component's ready state * * different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {function} fn ready listener * @return {vjs.component} */ vjs.component.prototype.ready = function(fn){ if (fn) { if (this.isready_) { fn.call(this); } else { if (this.readyqueue_ === undefined) { this.readyqueue_ = []; } this.readyqueue_.push(fn); } } return this; }; /** * trigger the ready listeners * * @return {vjs.component} */ vjs.component.prototype.triggerready = function(){ this.isready_ = true; var readyqueue = this.readyqueue_; if (readyqueue && readyqueue.length > 0) { for (var i = 0, j = readyqueue.length; i < j; i++) { readyqueue[i].call(this); } // reset ready queue this.readyqueue_ = []; // allow for using event listeners also, in case you want to do something everytime a source is ready. this.trigger('ready'); } }; /* display ============================================================================= */ /** * check if a component's element has a css class name * * @param {string} classtocheck classname to check * @return {vjs.component} */ vjs.component.prototype.hasclass = function(classtocheck){ return vjs.hasclass(this.el_, classtocheck); }; /** * add a css class name to the component's element * * @param {string} classtoadd classname to add * @return {vjs.component} */ vjs.component.prototype.addclass = function(classtoadd){ vjs.addclass(this.el_, classtoadd); return this; }; /** * remove a css class name from the component's element * * @param {string} classtoremove classname to remove * @return {vjs.component} */ vjs.component.prototype.removeclass = function(classtoremove){ vjs.removeclass(this.el_, classtoremove); return this; }; /** * show the component element if hidden * * @return {vjs.component} */ vjs.component.prototype.show = function(){ this.el_.style.display = 'block'; return this; }; /** * hide the component element if currently showing * * @return {vjs.component} */ vjs.component.prototype.hide = function(){ this.el_.style.display = 'none'; return this; }; /** * lock an item in its visible state * to be used with fadein/fadeout. * * @return {vjs.component} * @private */ vjs.component.prototype.lockshowing = function(){ this.addclass('vjs-lock-showing'); return this; }; /** * unlock an item to be hidden * to be used with fadein/fadeout. * * @return {vjs.component} * @private */ vjs.component.prototype.unlockshowing = function(){ this.removeclass('vjs-lock-showing'); return this; }; /** * disable component by making it unshowable * * currently private because we're moving towards more css-based states. * @private */ vjs.component.prototype.disable = function(){ this.hide(); this.show = function(){}; }; /** * set or get the width of the component (css values) * * setting the video tag dimension values only works with values in pixels. * percent values will not work. * some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {number|string=} num optional width number * @param {boolean} skiplisteners skip the 'resize' event trigger * @return {vjs.component} this component, when setting the width * @return {number|string} the width, when getting */ vjs.component.prototype.width = function(num, skiplisteners){ return this.dimension('width', num, skiplisteners); }; /** * get or set the height of the component (css values) * * setting the video tag dimension values only works with values in pixels. * percent values will not work. * some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {number|string=} num new component height * @param {boolean=} skiplisteners skip the resize event trigger * @return {vjs.component} this component, when setting the height * @return {number|string} the height, when getting */ vjs.component.prototype.height = function(num, skiplisteners){ return this.dimension('height', num, skiplisteners); }; /** * set both width and height at the same time * * @param {number|string} width * @param {number|string} height * @return {vjs.component} the component */ vjs.component.prototype.dimensions = function(width, height){ // skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * get or set width or height * * this is the shared code for the width() and height() methods. * all for an integer, integer + 'px' or integer + '%'; * * known issue: hidden elements officially have a width of 0. we're defaulting * to the style.width value and falling back to computedstyle which has the * hidden element issue. info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {string} widthorheight 'width' or 'height' * @param {number|string=} num new dimension * @param {boolean=} skiplisteners skip resize event trigger * @return {vjs.component} the component if a dimension was set * @return {number|string} the dimension if nothing was set * @private */ vjs.component.prototype.dimension = function(widthorheight, num, skiplisteners){ if (num !== undefined) { if (num === null || vjs.isnan(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) { 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 } else { return parseint(this.el_['offset'+vjs.capitalize(widthorheight)], 10); // computedstyle version. // only difference is if the element is hidden it will return // the percent value (e.g. '100%'') // instead of zero like offsetwidth returns. // var val = vjs.getcomputedstylevalue(this.el_, widthorheight); // var pxindex = val.indexof('px'); // if (pxindex !== -1) { // return val.slice(0, pxindex); // } else { // return val; // } } }; /** * fired when the width and/or height of the component changes * @event resize */ vjs.component.prototype.onresize; /** * emit 'tap' events when touch events are supported * * this is used to support toggling the controls through a tap on the video. * * we're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * @private */ vjs.component.prototype.emittapevents = function(){ var touchstart, firsttouch, touchtime, couldbetap, notap, xdiff, ydiff, touchdistance, tapmovementthreshold; // track the start time so we can determine how long the touch lasted touchstart = 0; firsttouch = null; // maximum movement allowed during a touch event to still be considered a tap tapmovementthreshold = 22; this.on('touchstart', function(event) { // if more than one finger, don't consider treating this as a click if (event.touches.length === 1) { firsttouch = event.touches[0]; // 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 xdiff = event.touches[0].pagex - firsttouch.pagex; ydiff = event.touches[0].pagey - firsttouch.pagey; touchdistance = math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchdistance > tapmovementthreshold) { couldbetap = false; } } }); notap = function(){ 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 touchtime = new date().gettime() - touchstart; // the touch needs to be quick in order to consider it a tap if (touchtime < 250) { event.preventdefault(); // don't let browser turn this into a click 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 // vjs.fixevent runs (e.g. event.target) } } }); }; /** * report user touch activity when touch events occur * * user activity is used to determine when controls should show/hide. it's * relatively 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. we can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). user activity is * 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) * * also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * * here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. */ vjs.component.prototype.enabletouchactivity = function() { var report, touchholding, touchend; // don't continue if the root player doesn't support reporting user activity if (!this.player().reportuseractivity) { return; } // listener for reporting that the user is active report = vjs.bind(this.player(), this.player().reportuseractivity); 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); }); touchend = function(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); }; /** * creates timeout and sets up disposal automatically. * @param {function} fn the function to run after the timeout. * @param {number} timeout number of ms to delay before executing specified function. * @return {number} returns the timeout id */ vjs.component.prototype.settimeout = function(fn, timeout) { fn = vjs.bind(this, fn); // window.settimeout would be preferable here, but due to some bizarre issue with sinon and/or phantomjs, we can't. var timeoutid = settimeout(fn, timeout); var disposefn = function() { this.cleartimeout(timeoutid); }; disposefn.guid = 'vjs-timeout-'+ timeoutid; this.on('dispose', disposefn); return timeoutid; }; /** * clears a timeout and removes the associated dispose listener * @param {number} timeoutid the id of the timeout to clear * @return {number} returns the timeout id */ vjs.component.prototype.cleartimeout = function(timeoutid) { cleartimeout(timeoutid); var disposefn = function(){}; disposefn.guid = 'vjs-timeout-'+ timeoutid; this.off('dispose', disposefn); return timeoutid; }; /** * creates an interval and sets up disposal automatically. * @param {function} fn the function to run every n seconds. * @param {number} interval number of ms to delay before executing specified function. * @return {number} returns the interval id */ vjs.component.prototype.setinterval = function(fn, interval) { fn = vjs.bind(this, fn); var intervalid = setinterval(fn, interval); var disposefn = function() { this.clearinterval(intervalid); }; disposefn.guid = 'vjs-interval-'+ intervalid; this.on('dispose', disposefn); return intervalid; }; /** * clears an interval and removes the associated dispose listener * @param {number} intervalid the id of the interval to clear * @return {number} returns the interval id */ vjs.component.prototype.clearinterval = function(intervalid) { clearinterval(intervalid); var disposefn = function(){}; disposefn.guid = 'vjs-interval-'+ intervalid; this.off('dispose', disposefn); return intervalid; }; /* button - base class for all buttons ================================================================================ */ /** * base class for all buttons * @param {vjs.player|object} player * @param {object=} options * @class * @constructor */ vjs.button = vjs.component.extend({ /** * @constructor * @inheritdoc */ init: function(player, options){ vjs.component.call(this, player, options); this.emittapevents(); this.on('tap', this.onclick); this.on('click', this.onclick); this.on('focus', this.onfocus); this.on('blur', this.onblur); } }); vjs.button.prototype.createel = function(type, props){ var el; // add standard aria and tabindex info props = vjs.obj.merge({ classname: this.buildcssclass(), 'role': 'button', 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabindex: 0 }, props); el = vjs.component.prototype.createel.call(this, type, props); // if innerhtml hasn't been overridden (bigplaybutton), add content elements if (!props.innerhtml) { this.contentel_ = vjs.createel('div', { classname: 'vjs-control-content' }); this.controltext_ = vjs.createel('span', { classname: 'vjs-control-text', innerhtml: this.localize(this.buttontext) || 'need text' }); this.contentel_.appendchild(this.controltext_); el.appendchild(this.contentel_); } return el; }; vjs.button.prototype.buildcssclass = function(){ // todo: change vjs-control to vjs-button? return 'vjs-control ' + vjs.component.prototype.buildcssclass.call(this); }; // click - override with specific functionality for button vjs.button.prototype.onclick = function(){}; // focus - add keyboard functionality to element vjs.button.prototype.onfocus = function(){ vjs.on(document, 'keydown', vjs.bind(this, this.onkeypress)); }; // keypress (document level) - trigger click when keys are pressed vjs.button.prototype.onkeypress = function(event){ // check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { event.preventdefault(); this.onclick(); } }; // blur - remove keyboard triggers vjs.button.prototype.onblur = function(){ vjs.off(document, 'keydown', vjs.bind(this, this.onkeypress)); }; /* slider ================================================================================ */ /** * the base functionality for sliders like the volume bar and seek bar * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.slider = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); // set property names to bar and handle to match with the child slider class is looking for this.bar = this.getchild(this.options_['barname']); this.handle = this.getchild(this.options_['handlename']); this.on('mousedown', this.onmousedown); this.on('touchstart', this.onmousedown); this.on('focus', this.onfocus); this.on('blur', this.onblur); this.on('click', this.onclick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerevent, this.update); } }); vjs.slider.prototype.createel = function(type, props) { props = props || {}; // add the slider element class to all sub classes props.classname = props.classname + ' vjs-slider'; props = vjs.obj.merge({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabindex: 0 }, props); return vjs.component.prototype.createel.call(this, type, props); }; vjs.slider.prototype.onmousedown = function(event){ event.preventdefault(); vjs.blocktextselection(); this.addclass('vjs-sliding'); this.on(document, 'mousemove', this.onmousemove); this.on(document, 'mouseup', this.onmouseup); this.on(document, 'touchmove', this.onmousemove); this.on(document, 'touchend', this.onmouseup); this.onmousemove(event); }; // to be overridden by a subclass vjs.slider.prototype.onmousemove = function(){}; vjs.slider.prototype.onmouseup = function() { vjs.unblocktextselection(); this.removeclass('vjs-sliding'); this.off(document, 'mousemove', this.onmousemove); this.off(document, 'mouseup', this.onmouseup); this.off(document, 'touchmove', this.onmousemove); this.off(document, 'touchend', this.onmouseup); this.update(); }; vjs.slider.prototype.update = function(){ // in volumebar init we have a settimeout for update that pops and update to the end of the // execution stack. the player is destroyed before then update will cause an error if (!this.el_) return; // if scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // on html5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing) ? this.player_.getcache().currenttime / this.player_.duration() : this.player_.currenttime() / this.player_.duration(); var barprogress, progress = this.getpercent(), handle = this.handle, bar = this.bar; // protect against no duration and other division issues if (isnan(progress)) { progress = 0; } barprogress = progress; // if there is a handle, we need to account for the handle in our calculation for progress bar // so that it doesn't fall short of or extend past the handle. if (handle) { var box = this.el_, boxwidth = box.offsetwidth, handlewidth = handle.el().offsetwidth, // the width of the handle in percent of the containing box // in ie, widths may not be ready yet causing nan handlepercent = (handlewidth) ? handlewidth / boxwidth : 0, // get the adjusted size of the box, considering that the handle's center never touches the left or right side. // there is a margin of half the handle's width on both sides. boxadjustedpercent = 1 - handlepercent, // adjust the progress that we'll use to set widths to the new adjusted box width adjustedprogress = progress * boxadjustedpercent; // the bar does reach the left side, so we need to account for this in the bar's width barprogress = adjustedprogress + (handlepercent / 2); // move the handle from the left based on the adjected progress handle.el().style.left = vjs.round(adjustedprogress * 100, 2) + '%'; } // set the new bar width if (bar) { bar.el().style.width = vjs.round(barprogress * 100, 2) + '%'; } }; vjs.slider.prototype.calculatedistance = function(event){ var el, box, boxx, boxy, boxw, boxh, handle, pagex, pagey; el = this.el_; box = vjs.findposition(el); boxw = boxh = el.offsetwidth; handle = this.handle; if (this.options()['vertical']) { boxy = box.top; if (event.changedtouches) { pagey = event.changedtouches[0].pagey; } else { pagey = event.pagey; } if (handle) { var handleh = handle.el().offsetheight; // adjusted x and width, so handle doesn't go outside the bar boxy = boxy + (handleh / 2); boxh = boxh - handleh; } // percent that the click is through the adjusted area return math.max(0, math.min(1, ((boxy - pagey) + boxh) / boxh)); } else { boxx = box.left; if (event.changedtouches) { pagex = event.changedtouches[0].pagex; } else { pagex = event.pagex; } if (handle) { var handlew = handle.el().offsetwidth; // adjusted x and width, so handle doesn't go outside the bar boxx = boxx + (handlew / 2); boxw = boxw - handlew; } // percent that the click is through the adjusted area return math.max(0, math.min(1, (pagex - boxx) / boxw)); } }; vjs.slider.prototype.onfocus = function(){ this.on(document, 'keydown', this.onkeypress); }; vjs.slider.prototype.onkeypress = function(event){ if (event.which == 37 || event.which == 40) { // left and down arrows event.preventdefault(); this.stepback(); } else if (event.which == 38 || event.which == 39) { // up and right arrows event.preventdefault(); this.stepforward(); } }; vjs.slider.prototype.onblur = function(){ this.off(document, 'keydown', this.onkeypress); }; /** * listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * @param {object} event event object */ vjs.slider.prototype.onclick = function(event){ event.stopimmediatepropagation(); event.preventdefault(); }; /** * seekbar behavior includes play progress bar, and seek handle * needed so it can determine seek position based on handle position/size * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.sliderhandle = vjs.component.extend(); /** * default value of the slider * * @type {number} * @private */ vjs.sliderhandle.prototype.defaultvalue = 0; /** @inheritdoc */ vjs.sliderhandle.prototype.createel = function(type, props) { props = props || {}; // add the slider element class to all sub classes props.classname = props.classname + ' vjs-slider-handle'; props = vjs.obj.merge({ innerhtml: ''+this.defaultvalue+'' }, props); return vjs.component.prototype.createel.call(this, 'div', props); }; /* menu ================================================================================ */ /** * the menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @param {vjs.player|object} player * @param {object=} options * @class * @constructor */ vjs.menu = vjs.component.extend(); /** * add a menu item to the menu * @param {object|string} component component or component type to add */ vjs.menu.prototype.additem = function(component){ this.addchild(component); component.on('click', vjs.bind(this, function(){ this.unlockshowing(); })); }; /** @inheritdoc */ vjs.menu.prototype.createel = function(){ var contenteltype = this.options().contenteltype || 'ul'; this.contentel_ = vjs.createel(contenteltype, { classname: 'vjs-menu-content' }); var el = vjs.component.prototype.createel.call(this, 'div', { append: this.contentel_, classname: 'vjs-menu' }); el.appendchild(this.contentel_); // prevent clicks from bubbling up. needed for menu buttons, // where a click on the parent is significant vjs.on(el, 'click', function(event){ event.preventdefault(); event.stopimmediatepropagation(); }); return el; }; /** * the component for a menu item. `
  • ` * * @param {vjs.player|object} player * @param {object=} options * @class * @constructor */ vjs.menuitem = vjs.button.extend({ /** @constructor */ init: function(player, options){ vjs.button.call(this, player, options); this.selected(options['selected']); } }); /** @inheritdoc */ vjs.menuitem.prototype.createel = function(type, props){ return vjs.button.prototype.createel.call(this, 'li', vjs.obj.merge({ classname: 'vjs-menu-item', innerhtml: this.localize(this.options_['label']) }, props)); }; /** * handle a click on the menu item, and set it to selected */ vjs.menuitem.prototype.onclick = function(){ this.selected(true); }; /** * set this menu item as selected or not * @param {boolean} selected */ vjs.menuitem.prototype.selected = function(selected){ if (selected) { this.addclass('vjs-selected'); this.el_.setattribute('aria-selected',true); } else { this.removeclass('vjs-selected'); this.el_.setattribute('aria-selected',false); } }; /** * a button class with a popup menu * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.menubutton = vjs.button.extend({ /** @constructor */ init: function(player, options){ vjs.button.call(this, player, options); this.menu = this.createmenu(); // add list to element this.addchild(this.menu); // automatically hide empty menu buttons if (this.items && this.items.length === 0) { this.hide(); } this.on('keydown', this.onkeypress); this.el_.setattribute('aria-haspopup', true); this.el_.setattribute('role', 'button'); } }); /** * track the state of the menu button * @type {boolean} * @private */ vjs.menubutton.prototype.buttonpressed_ = false; vjs.menubutton.prototype.createmenu = function(){ var menu = new vjs.menu(this.player_); // add a title list item to the top if (this.options().title) { menu.contentel().appendchild(vjs.createel('li', { classname: 'vjs-menu-title', innerhtml: vjs.capitalize(this.options().title), tabindex: -1 })); } this.items = this['createitems'](); if (this.items) { // add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.additem(this.items[i]); } } return menu; }; /** * create the list of menu items. specific to each subclass. */ vjs.menubutton.prototype.createitems = function(){}; /** @inheritdoc */ vjs.menubutton.prototype.buildcssclass = function(){ return this.classname + ' vjs-menu-button ' + vjs.button.prototype.buildcssclass.call(this); }; // focus - add keyboard functionality to element // this function is not needed anymore. instead, the keyboard functionality is handled by // treating the button as triggering a submenu. when the button is pressed, the submenu // appears. pressing the button again makes the submenu disappear. vjs.menubutton.prototype.onfocus = function(){}; // can't turn off list display that we turned on with focus, because list would go away. vjs.menubutton.prototype.onblur = function(){}; vjs.menubutton.prototype.onclick = function(){ // when you click the button it adds focus, which will show the menu indefinitely. // so we'll remove focus when the mouse leaves the button. // focus is needed for tab navigation. this.one('mouseout', vjs.bind(this, function(){ this.menu.unlockshowing(); this.el_.blur(); })); if (this.buttonpressed_){ this.unpressbutton(); } else { this.pressbutton(); } }; vjs.menubutton.prototype.onkeypress = function(event){ event.preventdefault(); // check for space bar (32) or enter (13) keys if (event.which == 32 || event.which == 13) { if (this.buttonpressed_){ this.unpressbutton(); } else { this.pressbutton(); } // check for escape (27) key } else if (event.which == 27){ if (this.buttonpressed_){ this.unpressbutton(); } } }; vjs.menubutton.prototype.pressbutton = function(){ this.buttonpressed_ = true; this.menu.lockshowing(); this.el_.setattribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; vjs.menubutton.prototype.unpressbutton = function(){ this.buttonpressed_ = false; this.menu.unlockshowing(); this.el_.setattribute('aria-pressed', false); }; /** * custom mediaerror to mimic the html5 mediaerror * @param {number} code the media error code */ vjs.mediaerror = function(code){ if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object vjs.obj.merge(this, code); } if (!this.message) { this.message = vjs.mediaerror.defaultmessages[this.code] || ''; } }; /** * the error code that refers two one of the defined * mediaerror types * @type {number} */ vjs.mediaerror.prototype.code = 0; /** * an optional message to be shown with the error. * message is not part of the html5 video spec * but allows for more informative custom errors. * @type {string} */ vjs.mediaerror.prototype.message = ''; /** * an optional status code that can be set by plugins * to allow even more detail about the error. * for example the hls plugin might provide the specific * http status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * @type {[type]} */ vjs.mediaerror.prototype.status = null; vjs.mediaerror.errortypes = [ 'media_err_custom', // = 0 'media_err_aborted', // = 1 'media_err_network', // = 2 'media_err_decode', // = 3 'media_err_src_not_supported', // = 4 'media_err_encrypted' // = 5 ]; vjs.mediaerror.defaultmessages = { 1: 'you aborted the video playback', 2: 'a network error caused the video download to fail part-way.', 3: 'the video playback was aborted due to a corruption problem or because the video used features your browser did not support.', 4: 'the video could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'the video 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 < vjs.mediaerror.errortypes.length; errnum++) { vjs.mediaerror[vjs.mediaerror.errortypes[errnum]] = errnum; // values should be accessible on both the class and instance vjs.mediaerror.prototype[vjs.mediaerror.errortypes[errnum]] = errnum; } (function(){ var apimap, specapi, browserapi, i; /** * store the browser-specific methods for the fullscreen api * @type {object|undefined} * @private */ vjs.browser.fullscreenapi; // browser api methods // map approach from screenful.js - https://github.com/sindresorhus/screenfull.js apimap = [ // spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/overview.html [ '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' ] ]; specapi = apimap[0]; // determine the supported set of functions for (i=0; i * * * ``` * * after an instance has been created it can be accessed globally using `video('example_video_1')`. * * @class * @extends vjs.component */ vjs.player = vjs.component.extend({ /** * player's constructor function * * @constructs * @method init * @param {element} tag the original video tag used for configuring options * @param {object=} options player options * @param {function=} ready ready callback function */ init: function(tag, options, ready){ this.tag = tag; // store the original tag used to set options // make sure tag id exists tag.id = tag.id || 'vjs_video_' + vjs.guid++; // store the tag attributes used to restore html5 element this.tagattributes = tag && vjs.getelementattributes(tag); // 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 = vjs.obj.merge(this.gettagsettings(tag), options); // update current language this.language_ = options['language'] || vjs.options['language']; // update supported languages this.languages_ = options['languages'] || vjs.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; // we don't want the player to report touch activity on itself // see enabletouchactivity in component options.reporttouchactivity = false; // set isaudio based on whether or not an audio tag was used this.isaudio(this.tag.nodename.tolowercase() === 'audio'); // run base component initializing with new options. // builds the element through createel() // inits and embeds any child components in opts vjs.component.call(this, this, options, ready); // 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'); } if (this.isaudio()) { this.addclass('vjs-audio'); } // todo: make this smarter. toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (vjs.touch_enabled) { // this.addclass('vjs-touch-enabled'); // } // make player easily findable by id vjs.players[this.id_] = this; if (options['plugins']) { vjs.obj.each(options['plugins'], function(key, val){ this[key](val); }, this); } this.listenforuseractivity(); } }); /** * the player's stored language code * * @type {string} * @private */ vjs.player.prototype.language_; /** * the player's language code * @param {string} languagecode the locale string * @return {string} the locale string when getting * @return {vjs.player} self, when setting */ vjs.player.prototype.language = function (languagecode) { if (languagecode === undefined) { return this.language_; } this.language_ = languagecode; return this; }; /** * the player's stored language dictionary * * @type {object} * @private */ vjs.player.prototype.languages_; vjs.player.prototype.languages = function(){ return this.languages_; }; /** * player instance options, surfaced using vjs.options * vjs.options = vjs.player.prototype.options_ * make changes in vjs.options, not here. * all options should use string keys so they avoid * renaming by closure compiler * @type {object} * @private */ vjs.player.prototype.options_ = vjs.options; /** * destroys the video player and does any necessary cleanup * * myplayer.dispose(); * * this is especially helpful if you are dynamically adding and removing videos * to/from the dom. */ vjs.player.prototype.dispose = function(){ this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); // kill reference to this player vjs.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 dispose vjs.component.prototype.dispose.call(this); }; vjs.player.prototype.gettagsettings = function(tag){ var tagoptions, datasetup, options = { 'sources': [], 'tracks': [] }; tagoptions = vjs.getelementattributes(tag); datasetup = tagoptions['data-setup']; // check if data-setup attr exists. if (datasetup !== null){ // parse options json // if empty string, make it a parsable json object. vjs.obj.merge(tagoptions, vjs.json.parse(datasetup || '{}')); } vjs.obj.merge(options, tagoptions); // get tag children settings if (tag.haschildnodes()) { var children, child, childname, i, j; children = tag.childnodes; for (i=0,j=children.length; i 0) { techoptions['starttime'] = this.cache_.currenttime; } this.cache_.src = source.src; } // initialize tech instance this.tech = new window['videojs'][techname](this, techoptions); this.tech.ready(techready); }; vjs.player.prototype.unloadtech = function(){ this.isready_ = false; this.tech.dispose(); this.tech = false; }; // there's many issues around changing the size of a flash (or other plugin) object. // first is a plugin reload issue in firefox that has been around for 11 years: https://bugzilla.mozilla.org/show_bug.cgi?id=90268 // then with the new fullscreen api, mozilla and webkit browsers will reload the flash object after going to fullscreen. // to get around this, we're unloading the tech, caching source and currenttime values, and reloading the tech once the plugin is resized. // reloadtech: function(betweenfn){ // vjs.log('unloadingtech') // this.unloadtech(); // vjs.log('unloadedtech') // if (betweenfn) { betweenfn.call(); } // vjs.log('loadingtech') // this.loadtech(this.techname, { src: this.cache_.src }) // vjs.log('loadedtech') // }, // /* player event handlers (how the player reacts to certain events) // ================================================================================ */ /** * fired when the user agent begins looking for media data * @event loadstart */ vjs.player.prototype.onloadstart = function() { // todo: update to use `emptied` event instead. see #1277. // 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()) { this.trigger('firstplay'); } else { // reset the hasstarted state this.hasstarted(false); this.one('play', function(){ this.hasstarted(true); }); } }; vjs.player.prototype.hasstarted_ = false; vjs.player.prototype.hasstarted = function(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 when the player has initial duration and dimension information * @event loadedmetadata */ vjs.player.prototype.onloadedmetadata; /** * fired when the player has downloaded data at the current playback position * @event loadeddata */ vjs.player.prototype.onloadeddata; /** * fired when the player has finished downloading the source data * @event loadedalldata */ vjs.player.prototype.onloadedalldata; /** * fired whenever the media begins or resumes playback * @event play */ vjs.player.prototype.onplay = function(){ this.removeclass('vjs-paused'); this.addclass('vjs-playing'); }; /** * fired whenever the media begins waiting * @event waiting */ vjs.player.prototype.onwaiting = function(){ this.addclass('vjs-waiting'); }; /** * a handler for events that signal that waiting has ended * which is not consistent between browsers. see #1351 * @private */ vjs.player.prototype.onwaitend = function(){ this.removeclass('vjs-waiting'); }; /** * fired whenever the player is jumping to a new time * @event seeking */ vjs.player.prototype.onseeking = function(){ this.addclass('vjs-seeking'); }; /** * fired when the player has finished jumping to a new time * @event seeked */ vjs.player.prototype.onseeked = function(){ this.removeclass('vjs-seeking'); }; /** * fired the first time a video is played * * not part of the hls spec, and we're not sure if this is the best * implementation yet, so use sparingly. if you don't have a reason to * prevent playback, use `myplayer.one('play');` instead. * * @event firstplay */ vjs.player.prototype.onfirstplay = function(){ //if the first starttime attribute is specified //then we will start at the given offset in seconds if(this.options_['starttime']){ this.currenttime(this.options_['starttime']); } this.addclass('vjs-has-started'); }; /** * fired whenever the media has been paused * @event pause */ vjs.player.prototype.onpause = function(){ this.removeclass('vjs-playing'); this.addclass('vjs-paused'); }; /** * 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 timeupdate */ vjs.player.prototype.ontimeupdate; /** * fired while the user agent is downloading media data * @event progress */ vjs.player.prototype.onprogress = function(){ // add custom event for when source is finished downloading. if (this.bufferedpercent() == 1) { this.trigger('loadedalldata'); } }; /** * fired when the end of the media resource is reached (currenttime == duration) * @event ended */ vjs.player.prototype.onended = function(){ if (this.options_['loop']) { this.currenttime(0); this.play(); } else if (!this.paused()) { this.pause(); } }; /** * fired when the duration of the media resource is first known or changed * @event durationchange */ vjs.player.prototype.ondurationchange = function(){ // allows for caching value instead of asking player each time. // we need to get the techget response and check for a value so we don't // accidentally cause the stack to blow up. var duration = this.techget('duration'); if (duration) { if (duration < 0) { duration = infinity; } this.duration(duration); // determine if the stream is live and propagate styles down to ui. if (duration === infinity) { this.addclass('vjs-live'); } else { this.removeclass('vjs-live'); } } }; /** * fired when the volume changes * @event volumechange */ vjs.player.prototype.onvolumechange; /** * fired when the player switches in or out of fullscreen mode * @event fullscreenchange */ vjs.player.prototype.onfullscreenchange = function() { if (this.isfullscreen()) { this.addclass('vjs-fullscreen'); } else { this.removeclass('vjs-fullscreen'); } }; // /* player api // ================================================================================ */ /** * object for cached values. * @private */ vjs.player.prototype.cache_; vjs.player.prototype.getcache = function(){ return this.cache_; }; // pass values to the playback tech vjs.player.prototype.techcall = function(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); }); // otherwise call method now } else { try { this.tech[method](arg); } catch(e) { vjs.log(e); throw e; } } }; // get calls can't wait for the tech, and sometimes don't need to. vjs.player.prototype.techget = function(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) { vjs.log('video.js: ' + method + ' method not defined for '+this.techname+' playback technology.', e); } else { // when a method isn't available on the object it throws a typeerror if (e.name == 'typeerror') { vjs.log('video.js: ' + method + ' unavailable on '+this.techname+' playback technology element.', e); this.tech.isready_ = false; } else { vjs.log(e); } } throw e; } } return; }; /** * start media playback * * myplayer.play(); * * @return {vjs.player} self */ vjs.player.prototype.play = function(){ this.techcall('play'); return this; }; /** * pause the video playback * * myplayer.pause(); * * @return {vjs.player} self */ vjs.player.prototype.pause = function(){ this.techcall('pause'); return this; }; /** * check if the player is paused * * var ispaused = myplayer.paused(); * var isplaying = !myplayer.paused(); * * @return {boolean} false if the media is currently playing, or true otherwise */ vjs.player.prototype.paused = function(){ // the initial state of paused should be true (in safari it's actually false) return (this.techget('paused') === false) ? false : true; }; /** * get or set the current time (in seconds) * * // get * var whereyouat = myplayer.currenttime(); * * // set * myplayer.currenttime(120); // 2 minutes into the video * * @param {number|string=} seconds the time to seek to * @return {number} the time in seconds, when not setting * @return {vjs.player} self, when the current time is set */ vjs.player.prototype.currenttime = function(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. return this.cache_.currenttime = (this.techget('currenttime') || 0); }; /** * get the length in time of the video in seconds * * var lengthofvideo = myplayer.duration(); * * **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. * * @return {number} the duration of the video in seconds */ vjs.player.prototype.duration = function(seconds){ if (seconds !== undefined) { // cache the last set value for optimized scrubbing (esp. flash) this.cache_.duration = parsefloat(seconds); return this; } if (this.cache_.duration === undefined) { this.ondurationchange(); } return this.cache_.duration || 0; }; /** * calculates how much time is left. * * var timeleft = myplayer.remainingtime(); * * not a native video element function, but useful * @return {number} the time remaining in seconds */ vjs.player.prototype.remainingtime = function(){ return this.duration() - this.currenttime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // buffered returns a timerange object. // kind of like an array of portions of the video that have been downloaded. /** * get a timerange object with the times of the video that have been downloaded * * if you just want the percent of the video that's been downloaded, * use bufferedpercent. * * // number of different ranges of time have been buffered. usually 1. * numberofranges = bufferedtimerange.length, * * // time in seconds when the first range starts. usually 0. * firstrangestart = bufferedtimerange.start(0), * * // time in seconds when the first range ends * firstrangeend = bufferedtimerange.end(0), * * // length in seconds of the first time range * firstrangelength = firstrangeend - firstrangestart; * * @return {object} a mock timerange object (following html spec) */ vjs.player.prototype.buffered = function(){ var buffered = this.techget('buffered'); if (!buffered || !buffered.length) { buffered = vjs.createtimerange(0,0); } return buffered; }; /** * get the percent (as a decimal) of the video that's been downloaded * * var howmuchisdownloaded = myplayer.bufferedpercent(); * * 0 means none, 1 means all. * (this method isn't in the html5 spec, but it's very convenient) * * @return {number} a decimal between 0 and 1 representing the percent */ vjs.player.prototype.bufferedpercent = function(){ var duration = this.duration(), buffered = this.buffered(), bufferedduration = 0, start, end; if (!duration) { return 0; } for (var i=0; i duration) { end = duration; } bufferedduration += end - start; } return bufferedduration / 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 */ vjs.player.prototype.bufferedend = function(){ var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length-1); if (end > duration) { end = duration; } return end; }; /** * get or set the current volume of the media * * // get * var howloudisit = myplayer.volume(); * * // set * myplayer.volume(0.5); // set volume to half * * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {number} percentasdecimal the new volume as a decimal percent * @return {number} the current volume, when getting * @return {vjs.player} self, when setting */ vjs.player.prototype.volume = function(percentasdecimal){ var vol; if (percentasdecimal !== undefined) { vol = math.max(0, math.min(1, parsefloat(percentasdecimal))); // force value to between 0 and 1 this.cache_.volume = vol; this.techcall('setvolume', vol); vjs.setlocalstorage('volume', 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 * * // get * var isvolumemuted = myplayer.muted(); * * // set * myplayer.muted(true); // mute the volume * * @param {boolean=} muted true to mute, false to unmute * @return {boolean} true if mute is on, false if not, when getting * @return {vjs.player} self, when setting mute */ vjs.player.prototype.muted = function(muted){ if (muted !== undefined) { this.techcall('setmuted', muted); return this; } return this.techget('muted') || false; // default to false }; // check if current tech can support native fullscreen // (e.g. with built in controls like ios, so not our flash swf) vjs.player.prototype.supportsfullscreen = function(){ return this.techget('supportsfullscreen') || false; }; /** * is the player in fullscreen * @type {boolean} * @private */ vjs.player.prototype.isfullscreen_ = false; /** * check if the player is in fullscreen mode * * // get * var fullscreenornot = myplayer.isfullscreen(); * * // set * myplayer.isfullscreen(true); // tell the player it's in fullscreen * * 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 update the player's fullscreen state * @return {boolean} true if fullscreen, false if not * @return {vjs.player} self, when setting */ vjs.player.prototype.isfullscreen = function(isfs){ if (isfs !== undefined) { this.isfullscreen_ = !!isfs; return this; } return this.isfullscreen_; }; /** * old naming for isfullscreen() * @deprecated for lowercase 's' version */ vjs.player.prototype.isfullscreen = function(isfs){ vjs.log.warn('player.isfullscreen() has been deprecated, use player.isfullscreen() with a lowercase "s")'); return this.isfullscreen(isfs); }; /** * increase the size of the video to full screen * * myplayer.requestfullscreen(); * * 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. * * @return {vjs.player} self */ vjs.player.prototype.requestfullscreen = function(){ var fsapi = vjs.browser.fullscreenapi; this.isfullscreen(true); if (fsapi) { // 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 vjs.on(document, fsapi['fullscreenchange'], vjs.bind(this, function(e){ this.isfullscreen(document[fsapi.fullscreenelement]); // if cancelling fullscreen, remove event listener. if (this.isfullscreen() === false) { vjs.off(document, fsapi['fullscreenchange'], arguments.callee); } 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(); this.trigger('fullscreenchange'); } return this; }; /** * old naming for requestfullscreen * @deprecated for lower case 's' version */ vjs.player.prototype.requestfullscreen = function(){ vjs.log.warn('player.requestfullscreen() has been deprecated, use player.requestfullscreen() with a lowercase "s")'); return this.requestfullscreen(); }; /** * return the video to its normal size after having been in full screen mode * * myplayer.exitfullscreen(); * * @return {vjs.player} self */ vjs.player.prototype.exitfullscreen = function(){ var fsapi = vjs.browser.fullscreenapi; this.isfullscreen(false); // check for browser element fullscreen support if (fsapi) { document[fsapi.exitfullscreen](); } else if (this.tech.supportsfullscreen()) { this.techcall('exitfullscreen'); } else { this.exitfullwindow(); this.trigger('fullscreenchange'); } return this; }; /** * old naming for exitfullscreen * @deprecated for exitfullscreen */ vjs.player.prototype.cancelfullscreen = function(){ vjs.log.warn('player.cancelfullscreen() has been deprecated, use player.exitfullscreen()'); return this.exitfullscreen(); }; // when fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. vjs.player.prototype.enterfullwindow = function(){ this.isfullwindow = true; // storing original doc overflow value to return to when fullscreen is off this.docorigoverflow = document.documentelement.style.overflow; // add listener for esc key to exit fullscreen vjs.on(document, 'keydown', vjs.bind(this, this.fullwindowonesckey)); // hide any scroll bars document.documentelement.style.overflow = 'hidden'; // apply fullscreen styles vjs.addclass(document.body, 'vjs-full-window'); this.trigger('enterfullwindow'); }; vjs.player.prototype.fullwindowonesckey = function(event){ if (event.keycode === 27) { if (this.isfullscreen() === true) { this.exitfullscreen(); } else { this.exitfullwindow(); } } }; vjs.player.prototype.exitfullwindow = function(){ this.isfullwindow = false; vjs.off(document, 'keydown', this.fullwindowonesckey); // unhide scroll bars. document.documentelement.style.overflow = this.docorigoverflow; // remove fullscreen styles vjs.removeclass(document.body, 'vjs-full-window'); // resize the box, controller, and poster to original sizes // this.positionall(); this.trigger('exitfullwindow'); }; vjs.player.prototype.selectsource = function(sources){ // loop through each playback technology in the options order for (var i=0,j=this.options_['techorder'];i 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 activitycheck loop // causing a flicker if (!this.useractivity_) { this.useractive(false); } }, timeout); } } }, 250); }; /** * gets or sets the current playback rate. * @param {boolean} rate new playback rate to set. * @return {number} returns the new playback rate when setting * @return {number} returns the current playback rate when getting */ vjs.player.prototype.playbackrate = function(rate) { if (rate !== undefined) { this.techcall('setplaybackrate', rate); return this; } if (this.tech && this.tech['featuresplaybackrate']) { return this.techget('playbackrate'); } else { return 1.0; } }; /** * store the current audio state * @type {boolean} * @private */ vjs.player.prototype.isaudio_ = false; /** * gets or sets the audio flag * * @param {boolean} bool true signals that this is an audio player. * @return {boolean} returns true if player is audio, false if not when getting * @return {vjs.player} returns the player if setting * @private */ vjs.player.prototype.isaudio = function(bool) { if (bool !== undefined) { this.isaudio_ = !!bool; return this; } return this.isaudio_; }; // methods to add support for // networkstate: function(){ return this.techcall('networkstate'); }, // readystate: function(){ return this.techcall('readystate'); }, // initialtime: function(){ return this.techcall('initialtime'); }, // startoffsettime: function(){ return this.techcall('startoffsettime'); }, // played: function(){ return this.techcall('played'); }, // seekable: function(){ return this.techcall('seekable'); }, // videotracks: function(){ return this.techcall('videotracks'); }, // audiotracks: function(){ return this.techcall('audiotracks'); }, // videowidth: function(){ return this.techcall('videowidth'); }, // videoheight: function(){ return this.techcall('videoheight'); }, // defaultplaybackrate: function(){ return this.techcall('defaultplaybackrate'); }, // mediagroup: function(){ return this.techcall('mediagroup'); }, // controller: function(){ return this.techcall('controller'); }, // defaultmuted: function(){ return this.techcall('defaultmuted'); } // todo // currentsrclist: the array of sources including other formats and bitrates // playlist: array of source lists in order of playback /** * container of main controls * @param {vjs.player|object} player * @param {object=} options * @class * @constructor * @extends vjs.component */ vjs.controlbar = vjs.component.extend(); vjs.controlbar.prototype.options_ = { loadevent: 'play', children: { 'playtoggle': {}, 'currenttimedisplay': {}, 'timedivider': {}, 'durationdisplay': {}, 'remainingtimedisplay': {}, 'livedisplay': {}, 'progresscontrol': {}, 'fullscreentoggle': {}, 'volumecontrol': {}, 'mutetoggle': {}, // 'volumemenubutton': {}, 'playbackratemenubutton': {} } }; vjs.controlbar.prototype.createel = function(){ return vjs.createel('div', { classname: 'vjs-control-bar' }); }; /** * displays the live indicator * todo - future make it click to snap to live * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.livedisplay = vjs.component.extend({ init: function(player, options){ vjs.component.call(this, player, options); } }); vjs.livedisplay.prototype.createel = function(){ var el = vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-live-controls vjs-control' }); this.contentel_ = vjs.createel('div', { classname: 'vjs-live-display', innerhtml: '' + this.localize('stream type') + '' + this.localize('live'), 'aria-live': 'off' }); el.appendchild(this.contentel_); return el; }; /** * button to toggle between play and pause * @param {vjs.player|object} player * @param {object=} options * @class * @constructor */ vjs.playtoggle = vjs.button.extend({ /** @constructor */ init: function(player, options){ vjs.button.call(this, player, options); this.on(player, 'play', this.onplay); this.on(player, 'pause', this.onpause); } }); vjs.playtoggle.prototype.buttontext = 'play'; vjs.playtoggle.prototype.buildcssclass = function(){ return 'vjs-play-control ' + vjs.button.prototype.buildcssclass.call(this); }; // onclick - toggle between play and pause vjs.playtoggle.prototype.onclick = function(){ if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; // onplay - add the vjs-playing class to the element so it can change appearance vjs.playtoggle.prototype.onplay = function(){ this.removeclass('vjs-paused'); this.addclass('vjs-playing'); this.el_.children[0].children[0].innerhtml = this.localize('pause'); // change the button text to "pause" }; // onpause - add the vjs-paused class to the element so it can change appearance vjs.playtoggle.prototype.onpause = function(){ this.removeclass('vjs-playing'); this.addclass('vjs-paused'); this.el_.children[0].children[0].innerhtml = this.localize('play'); // change the button text to "play" }; /** * displays the current time * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.currenttimedisplay = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); this.on(player, 'timeupdate', this.updatecontent); } }); vjs.currenttimedisplay.prototype.createel = function(){ var el = vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-current-time vjs-time-controls vjs-control' }); this.contentel_ = vjs.createel('div', { classname: 'vjs-current-time-display', innerhtml: 'current time ' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendchild(this.contentel_); return el; }; vjs.currenttimedisplay.prototype.updatecontent = function(){ // allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getcache().currenttime : this.player_.currenttime(); this.contentel_.innerhtml = '' + this.localize('current time') + ' ' + vjs.formattime(time, this.player_.duration()); }; /** * displays the duration * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.durationdisplay = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updatecontent); } }); vjs.durationdisplay.prototype.createel = function(){ var el = vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-duration vjs-time-controls vjs-control' }); this.contentel_ = vjs.createel('div', { classname: 'vjs-duration-display', innerhtml: '' + this.localize('duration time') + ' ' + '0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendchild(this.contentel_); return el; }; vjs.durationdisplay.prototype.updatecontent = function(){ var duration = this.player_.duration(); if (duration) { this.contentel_.innerhtml = '' + this.localize('duration time') + ' ' + vjs.formattime(duration); // label the duration time for screen reader users } }; /** * the separator between the current time and duration * * can be hidden if it's not needed in the design. * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.timedivider = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); } }); vjs.timedivider.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-time-divider', innerhtml: '
    /
    ' }); }; /** * displays the time left in the video * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.remainingtimedisplay = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); this.on(player, 'timeupdate', this.updatecontent); } }); vjs.remainingtimedisplay.prototype.createel = function(){ var el = vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-remaining-time vjs-time-controls vjs-control' }); this.contentel_ = vjs.createel('div', { classname: 'vjs-remaining-time-display', innerhtml: '' + this.localize('remaining time') + ' ' + '-0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendchild(this.contentel_); return el; }; vjs.remainingtimedisplay.prototype.updatecontent = function(){ if (this.player_.duration()) { this.contentel_.innerhtml = '' + this.localize('remaining time') + ' ' + '-'+ vjs.formattime(this.player_.remainingtime()); } // allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing) ? this.player_.getcache().currenttime : this.player_.currenttime(); // this.contentel_.innerhtml = vjs.formattime(time, this.player_.duration()); }; /** * toggle fullscreen video * @param {vjs.player|object} player * @param {object=} options * @class * @extends vjs.button */ vjs.fullscreentoggle = vjs.button.extend({ /** * @constructor * @memberof vjs.fullscreentoggle * @instance */ init: function(player, options){ vjs.button.call(this, player, options); } }); vjs.fullscreentoggle.prototype.buttontext = 'fullscreen'; vjs.fullscreentoggle.prototype.buildcssclass = function(){ return 'vjs-fullscreen-control ' + vjs.button.prototype.buildcssclass.call(this); }; vjs.fullscreentoggle.prototype.onclick = function(){ if (!this.player_.isfullscreen()) { this.player_.requestfullscreen(); this.controltext_.innerhtml = this.localize('non-fullscreen'); } else { this.player_.exitfullscreen(); this.controltext_.innerhtml = this.localize('fullscreen'); } }; /** * the progress control component contains the seek bar, load progress, * and play progress * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.progresscontrol = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); } }); vjs.progresscontrol.prototype.options_ = { children: { 'seekbar': {} } }; vjs.progresscontrol.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-progress-control vjs-control' }); }; /** * seek bar and holder for the progress bars * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.seekbar = vjs.slider.extend({ /** @constructor */ init: function(player, options){ vjs.slider.call(this, player, options); this.on(player, 'timeupdate', this.updateariaattributes); player.ready(vjs.bind(this, this.updateariaattributes)); } }); vjs.seekbar.prototype.options_ = { children: { 'loadprogressbar': {}, 'playprogressbar': {}, 'seekhandle': {} }, 'barname': 'playprogressbar', 'handlename': 'seekhandle' }; vjs.seekbar.prototype.playerevent = 'timeupdate'; vjs.seekbar.prototype.createel = function(){ return vjs.slider.prototype.createel.call(this, 'div', { classname: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; vjs.seekbar.prototype.updateariaattributes = function(){ // allows for smooth scrubbing, when player can't keep up. var time = (this.player_.scrubbing) ? this.player_.getcache().currenttime : this.player_.currenttime(); this.el_.setattribute('aria-valuenow',vjs.round(this.getpercent()*100, 2)); // machine readable value of progress bar (percentage complete) this.el_.setattribute('aria-valuetext',vjs.formattime(time, this.player_.duration())); // human readable value of progress bar (time complete) }; vjs.seekbar.prototype.getpercent = function(){ return this.player_.currenttime() / this.player_.duration(); }; vjs.seekbar.prototype.onmousedown = function(event){ vjs.slider.prototype.onmousedown.call(this, event); this.player_.scrubbing = true; this.videowasplaying = !this.player_.paused(); this.player_.pause(); }; vjs.seekbar.prototype.onmousemove = function(event){ var newtime = this.calculatedistance(event) * this.player_.duration(); // don't let video end while scrubbing. if (newtime == this.player_.duration()) { newtime = newtime - 0.1; } // set new time (tell player to seek to new time) this.player_.currenttime(newtime); }; vjs.seekbar.prototype.onmouseup = function(event){ vjs.slider.prototype.onmouseup.call(this, event); this.player_.scrubbing = false; if (this.videowasplaying) { this.player_.play(); } }; vjs.seekbar.prototype.stepforward = function(){ this.player_.currenttime(this.player_.currenttime() + 5); // more quickly fast forward for keyboard-only users }; vjs.seekbar.prototype.stepback = function(){ this.player_.currenttime(this.player_.currenttime() - 5); // more quickly rewind for keyboard-only users }; /** * shows load progress * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.loadprogressbar = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); this.on(player, 'progress', this.update); } }); vjs.loadprogressbar.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-load-progress', innerhtml: '' + this.localize('loaded') + ': 0%' }); }; vjs.loadprogressbar.prototype.update = function(){ var i, start, end, part, buffered = this.player_.buffered(), duration = this.player_.duration(), bufferedend = this.player_.bufferedend(), children = this.el_.children, // get the percent width of a time compared to the total end percentify = function (time, end){ var percent = (time / end) || 0; // no nan return (percent * 100) + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedend, duration); // add child elements to represent the individual buffered time ranges for (i = 0; i < buffered.length; i++) { start = buffered.start(i), end = buffered.end(i), part = children[i]; if (!part) { part = this.el_.appendchild(vjs.createel()); } // set the percent based on the width of the progress bar (bufferedend) part.style.left = percentify(start, bufferedend); part.style.width = percentify(end - start, bufferedend); } // remove unused buffered range elements for (i = children.length; i > buffered.length; i--) { this.el_.removechild(children[i-1]); } }; /** * shows play progress * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.playprogressbar = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); } }); vjs.playprogressbar.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-play-progress', innerhtml: '' + this.localize('progress') + ': 0%' }); }; /** * the seek handle shows the current position of the playhead during playback, * and can be dragged to adjust the playhead. * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.seekhandle = vjs.sliderhandle.extend({ init: function(player, options) { vjs.sliderhandle.call(this, player, options); this.on(player, 'timeupdate', this.updatecontent); } }); /** * the default value for the handle content, which may be read by screen readers * * @type {string} * @private */ vjs.seekhandle.prototype.defaultvalue = '00:00'; /** @inheritdoc */ vjs.seekhandle.prototype.createel = function() { return vjs.sliderhandle.prototype.createel.call(this, 'div', { classname: 'vjs-seek-handle', 'aria-live': 'off' }); }; vjs.seekhandle.prototype.updatecontent = function() { var time = (this.player_.scrubbing) ? this.player_.getcache().currenttime : this.player_.currenttime(); this.el_.innerhtml = '' + vjs.formattime(time, this.player_.duration()) + ''; }; /** * the component for controlling the volume level * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.volumecontrol = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech['featuresvolumecontrol'] === false) { this.addclass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresvolumecontrol'] === false) { this.addclass('vjs-hidden'); } else { this.removeclass('vjs-hidden'); } }); } }); vjs.volumecontrol.prototype.options_ = { children: { 'volumebar': {} } }; vjs.volumecontrol.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-volume-control vjs-control' }); }; /** * the bar that contains the volume level and can be clicked on to adjust the level * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.volumebar = vjs.slider.extend({ /** @constructor */ init: function(player, options){ vjs.slider.call(this, player, options); this.on(player, 'volumechange', this.updateariaattributes); player.ready(vjs.bind(this, this.updateariaattributes)); } }); vjs.volumebar.prototype.updateariaattributes = function(){ // current value of volume bar as a percentage this.el_.setattribute('aria-valuenow',vjs.round(this.player_.volume()*100, 2)); this.el_.setattribute('aria-valuetext',vjs.round(this.player_.volume()*100, 2)+'%'); }; vjs.volumebar.prototype.options_ = { children: { 'volumelevel': {}, 'volumehandle': {} }, 'barname': 'volumelevel', 'handlename': 'volumehandle' }; vjs.volumebar.prototype.playerevent = 'volumechange'; vjs.volumebar.prototype.createel = function(){ return vjs.slider.prototype.createel.call(this, 'div', { classname: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; vjs.volumebar.prototype.onmousemove = function(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculatedistance(event)); }; vjs.volumebar.prototype.getpercent = function(){ if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; vjs.volumebar.prototype.stepforward = function(){ this.player_.volume(this.player_.volume() + 0.1); }; vjs.volumebar.prototype.stepback = function(){ this.player_.volume(this.player_.volume() - 0.1); }; /** * shows volume level * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.volumelevel = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); } }); vjs.volumelevel.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-volume-level', innerhtml: '' }); }; /** * the volume handle can be dragged to adjust the volume level * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.volumehandle = vjs.sliderhandle.extend(); vjs.volumehandle.prototype.defaultvalue = '00:00'; /** @inheritdoc */ vjs.volumehandle.prototype.createel = function(){ return vjs.sliderhandle.prototype.createel.call(this, 'div', { classname: 'vjs-volume-handle' }); }; /** * a button component for muting the audio * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.mutetoggle = vjs.button.extend({ /** @constructor */ init: function(player, options){ vjs.button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresvolumecontrol'] === false) { this.addclass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresvolumecontrol'] === false) { this.addclass('vjs-hidden'); } else { this.removeclass('vjs-hidden'); } }); } }); vjs.mutetoggle.prototype.createel = function(){ return vjs.button.prototype.createel.call(this, 'div', { classname: 'vjs-mute-control vjs-control', innerhtml: '
    ' + this.localize('mute') + '
    ' }); }; vjs.mutetoggle.prototype.onclick = function(){ this.player_.muted( this.player_.muted() ? false : true ); }; vjs.mutetoggle.prototype.update = function(){ var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // don't rewrite the button text if the actual text doesn't change. // this causes unnecessary and confusing information for screen reader users. // this check is needed because this function gets called every time the volume level is changed. if(this.player_.muted()){ if(this.el_.children[0].children[0].innerhtml!=this.localize('unmute')){ this.el_.children[0].children[0].innerhtml = this.localize('unmute'); // change the button text to "unmute" } } else { if(this.el_.children[0].children[0].innerhtml!=this.localize('mute')){ this.el_.children[0].children[0].innerhtml = this.localize('mute'); // change the button text to "mute" } } /* todo improve muted icon classes */ for (var i = 0; i < 4; i++) { vjs.removeclass(this.el_, 'vjs-vol-'+i); } vjs.addclass(this.el_, 'vjs-vol-'+level); }; /** * menu button with a popup for showing the volume slider. * @constructor */ vjs.volumemenubutton = vjs.menubutton.extend({ /** @constructor */ init: function(player, options){ vjs.menubutton.call(this, player, options); // same listeners as mutetoggle this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresvolumecontrol'] === false) { this.addclass('vjs-hidden'); } this.on(player, 'loadstart', function(){ if (player.tech['featuresvolumecontrol'] === false) { this.addclass('vjs-hidden'); } else { this.removeclass('vjs-hidden'); } }); this.addclass('vjs-menu-button'); } }); vjs.volumemenubutton.prototype.createmenu = function(){ var menu = new vjs.menu(this.player_, { contenteltype: 'div' }); var vc = new vjs.volumebar(this.player_, this.options_['volumebar']); vc.on('focus', function() { menu.lockshowing(); }); vc.on('blur', function() { menu.unlockshowing(); }); menu.addchild(vc); return menu; }; vjs.volumemenubutton.prototype.onclick = function(){ vjs.mutetoggle.prototype.onclick.call(this); vjs.menubutton.prototype.onclick.call(this); }; vjs.volumemenubutton.prototype.createel = function(){ return vjs.button.prototype.createel.call(this, 'div', { classname: 'vjs-volume-menu-button vjs-menu-button vjs-control', innerhtml: '
    ' + this.localize('mute') + '
    ' }); }; vjs.volumemenubutton.prototype.update = vjs.mutetoggle.prototype.update; /** * the component for controlling the playback rate * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.playbackratemenubutton = vjs.menubutton.extend({ /** @constructor */ init: function(player, options){ vjs.menubutton.call(this, player, options); this.updatevisibility(); this.updatelabel(); this.on(player, 'loadstart', this.updatevisibility); this.on(player, 'ratechange', this.updatelabel); } }); vjs.playbackratemenubutton.prototype.buttontext = 'playback rate'; vjs.playbackratemenubutton.prototype.classname = 'vjs-playback-rate'; vjs.playbackratemenubutton.prototype.createel = function(){ var el = vjs.menubutton.prototype.createel.call(this); this.labelel_ = vjs.createel('div', { classname: 'vjs-playback-rate-value', innerhtml: 1.0 }); el.appendchild(this.labelel_); return el; }; // menu creation vjs.playbackratemenubutton.prototype.createmenu = function(){ var menu = new vjs.menu(this.player()); var rates = this.player().options()['playbackrates']; if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addchild( new vjs.playbackratemenuitem(this.player(), { 'rate': rates[i] + 'x'}) ); } } return menu; }; vjs.playbackratemenubutton.prototype.updateariaattributes = function(){ // current playback rate this.el().setattribute('aria-valuenow', this.player().playbackrate()); }; vjs.playbackratemenubutton.prototype.onclick = function(){ // select next rate option var currentrate = this.player().playbackrate(); var rates = this.player().options()['playbackrates']; // this will select first one if the last one currently selected var newrate = rates[0]; for (var i = 0; i currentrate) { newrate = rates[i]; break; } } this.player().playbackrate(newrate); }; vjs.playbackratemenubutton.prototype.playbackratesupported = function(){ return this.player().tech && this.player().tech['featuresplaybackrate'] && this.player().options()['playbackrates'] && this.player().options()['playbackrates'].length > 0 ; }; /** * hide playback rate controls when they're no playback rate options to select */ vjs.playbackratemenubutton.prototype.updatevisibility = function(){ if (this.playbackratesupported()) { this.removeclass('vjs-hidden'); } else { this.addclass('vjs-hidden'); } }; /** * update button label when rate changed */ vjs.playbackratemenubutton.prototype.updatelabel = function(){ if (this.playbackratesupported()) { this.labelel_.innerhtml = this.player().playbackrate() + 'x'; } }; /** * the specific menu item type for selecting a playback rate * * @constructor */ vjs.playbackratemenuitem = vjs.menuitem.extend({ contenteltype: 'button', /** @constructor */ init: function(player, options){ var label = this.label = options['rate']; var rate = this.rate = parsefloat(label, 10); // modify options for parent menuitem class's init. options['label'] = label; options['selected'] = rate === 1; vjs.menuitem.call(this, player, options); this.on(player, 'ratechange', this.update); } }); vjs.playbackratemenuitem.prototype.onclick = function(){ vjs.menuitem.prototype.onclick.call(this); this.player().playbackrate(this.rate); }; vjs.playbackratemenuitem.prototype.update = function(){ this.selected(this.player().playbackrate() == this.rate); }; /* poster image ================================================================================ */ /** * the component that handles showing the poster image. * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.posterimage = vjs.button.extend({ /** @constructor */ init: function(player, options){ vjs.button.call(this, player, options); this.update(); player.on('posterchange', vjs.bind(this, this.update)); } }); /** * clean up the poster image */ vjs.posterimage.prototype.dispose = function(){ this.player().off('posterchange', this.update); vjs.button.prototype.dispose.call(this); }; /** * create the poster image element * @return {element} */ vjs.posterimage.prototype.createel = function(){ var el = vjs.createel('div', { classname: 'vjs-poster', // don't want poster to be tabbable. tabindex: -1 }); // to ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. for browsers that // do not support `background-size` (e.g. ie8), fall back on using a regular // img element. if (!vjs.background_size_supported) { this.fallbackimg_ = vjs.createel('img'); el.appendchild(this.fallbackimg_); } return el; }; /** * event handler for updates to the player's poster source */ vjs.posterimage.prototype.update = function(){ var url = this.player().poster(); this.setsrc(url); // if there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { // remove the display style property that hide() adds // as opposed to show() which sets display to block // in the future it might be worth creating an `unhide` component method this.el_.style.display = ''; } else { this.hide(); } }; /** * set the poster source depending on the display method */ vjs.posterimage.prototype.setsrc = function(url){ var backgroundimage; if (this.fallbackimg_) { this.fallbackimg_.src = url; } else { backgroundimage = ''; // any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundimage = 'url("' + url + '")'; } this.el_.style.backgroundimage = backgroundimage; } }; /** * event handler for clicks on the poster image */ vjs.posterimage.prototype.onclick = function(){ // we don't want a click to trigger playback when controls are disabled // but css should be hiding the poster to prevent that from happening this.player_.play(); }; /* loading spinner ================================================================================ */ /** * loading spinner for waiting events * @param {vjs.player|object} player * @param {object=} options * @class * @constructor */ vjs.loadingspinner = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); // moving display handling to css // player.on('canplay', vjs.bind(this, this.hide)); // player.on('canplaythrough', vjs.bind(this, this.hide)); // player.on('playing', vjs.bind(this, this.hide)); // player.on('seeking', vjs.bind(this, this.show)); // in some browsers seeking does not trigger the 'playing' event, // so we also need to trap 'seeked' if we are going to set a // 'seeking' event // player.on('seeked', vjs.bind(this, this.hide)); // player.on('ended', vjs.bind(this, this.hide)); // not showing spinner on stalled any more. browsers may stall and then not trigger any events that would remove the spinner. // checked in chrome 16 and safari 5.1.2. http://help.videojs.com/discussions/problems/883-why-is-the-download-progress-showing // player.on('stalled', vjs.bind(this, this.show)); // player.on('waiting', vjs.bind(this, this.show)); } }); vjs.loadingspinner.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-loading-spinner' }); }; /* big play button ================================================================================ */ /** * initial play button. shows before the video has played. the hiding of the * big play button is done via css and player states. * @param {vjs.player|object} player * @param {object=} options * @class * @constructor */ vjs.bigplaybutton = vjs.button.extend(); vjs.bigplaybutton.prototype.createel = function(){ return vjs.button.prototype.createel.call(this, 'div', { classname: 'vjs-big-play-button', innerhtml: '', 'aria-label': 'play video' }); }; vjs.bigplaybutton.prototype.onclick = function(){ this.player_.play(); }; /** * display that an error has occurred making the video unplayable * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.errordisplay = vjs.component.extend({ init: function(player, options){ vjs.component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } }); vjs.errordisplay.prototype.createel = function(){ var el = vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-error-display' }); this.contentel_ = vjs.createel('div'); el.appendchild(this.contentel_); return el; }; vjs.errordisplay.prototype.update = function(){ if (this.player().error()) { this.contentel_.innerhtml = this.localize(this.player().error().message); } }; /** * @fileoverview media technology controller - base class for media playback * technology controllers like flash and html5 */ /** * base class for media (html5 video, flash) controllers * @param {vjs.player|object} player central player instance * @param {object=} options options object * @constructor */ vjs.mediatechcontroller = vjs.component.extend({ /** @constructor */ init: function(player, options, ready){ options = options || {}; // we don't want the tech to report user activity automatically. // this is done manually in addcontrolslisteners options.reporttouchactivity = false; vjs.component.call(this, player, options, ready); // 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(); } this.initcontrolslisteners(); } }); /** * set up click and touch listeners for the playback element * on desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls 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 */ vjs.mediatechcontroller.prototype.initcontrolslisteners = function(){ var player, activatecontrols; player = this.player(); activatecontrols = function(){ if (player.controls() && !player.usingnativecontrols()) { this.addcontrolslisteners(); } }; // set up event listeners once the tech is ready and has an element to apply // listeners to this.ready(activatecontrols); this.on(player, 'controlsenabled', activatecontrols); this.on(player, 'controlsdisabled', this.removecontrolslisteners); // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function(){ if (this.networkstate && this.networkstate() > 0) { this.player().trigger('loadstart'); } }); }; vjs.mediatechcontroller.prototype.addcontrolslisteners = function(){ var userwasactive; // 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('mousedown', this.onclick); // 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('touchstart', function(event) { userwasactive = this.player_.useractive(); }); this.on('touchmove', function(event) { if (userwasactive){ this.player().reportuseractivity(); } }); this.on('touchend', function(event) { // stop the mouse events from also happening event.preventdefault(); }); // turn on component tap events this.emittapevents(); // the tap listener needs to come after the touchend listener because the tap // listener cancels out any reporteduseractivity when setting useractive(false) this.on('tap', this.ontap); }; /** * remove the listeners used for click and tap controls. this is needed for * toggling to controls disabled, where a tap/touch should do nothing. */ vjs.mediatechcontroller.prototype.removecontrolslisteners = function(){ // we don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off('tap'); this.off('touchstart'); this.off('touchmove'); this.off('touchleave'); this.off('touchcancel'); this.off('touchend'); this.off('click'); this.off('mousedown'); }; /** * handle a click on the media element. by default will play/pause the media. */ vjs.mediatechcontroller.prototype.onclick = function(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.player().controls()) { if (this.player().paused()) { this.player().play(); } else { this.player().pause(); } } }; /** * handle a tap on the media element. by default it will toggle the user * activity state, which hides and shows the controls. */ vjs.mediatechcontroller.prototype.ontap = function(){ this.player().useractive(!this.player().useractive()); }; /* fallbacks for unsupported event types ================================================================================ */ // manually trigger progress events based on changes to the buffered amount // many flash players and older html5 browsers don't send progress or progress-like events vjs.mediatechcontroller.prototype.manualprogresson = function(){ this.manualprogress = true; // trigger progress watching when a source begins loading this.trackprogress(); }; vjs.mediatechcontroller.prototype.manualprogressoff = function(){ this.manualprogress = false; this.stoptrackingprogress(); }; vjs.mediatechcontroller.prototype.trackprogress = function(){ this.progressinterval = this.setinterval(function(){ // don't trigger unless buffered amount is greater than last time var bufferedpercent = this.player().bufferedpercent(); if (this.bufferedpercent_ != bufferedpercent) { this.player().trigger('progress'); } this.bufferedpercent_ = bufferedpercent; if (bufferedpercent === 1) { this.stoptrackingprogress(); } }, 500); }; vjs.mediatechcontroller.prototype.stoptrackingprogress = function(){ this.clearinterval(this.progressinterval); }; /*! time tracking -------------------------------------------------------------- */ vjs.mediatechcontroller.prototype.manualtimeupdateson = function(){ var player = this.player_; this.manualtimeupdates = true; this.on(player, 'play', this.trackcurrenttime); this.on(player, 'pause', this.stoptrackingcurrenttime); // timeupdate is also called by .currenttime whenever current time is set // watch for native timeupdate event this.one('timeupdate', function(){ // update known progress support for this playback technology this['featurestimeupdateevents'] = true; // turn off manual progress tracking this.manualtimeupdatesoff(); }); }; vjs.mediatechcontroller.prototype.manualtimeupdatesoff = function(){ this.manualtimeupdates = false; this.stoptrackingcurrenttime(); this.off('play', this.trackcurrenttime); this.off('pause', this.stoptrackingcurrenttime); }; vjs.mediatechcontroller.prototype.trackcurrenttime = function(){ if (this.currenttimeinterval) { this.stoptrackingcurrenttime(); } this.currenttimeinterval = this.setinterval(function(){ this.player().trigger('timeupdate'); }, 250); // 42 = 24 fps // 250 is what webkit uses // ff uses 15 }; // turn off play progress tracking (when paused or dragging) vjs.mediatechcontroller.prototype.stoptrackingcurrenttime = function(){ 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.player().trigger('timeupdate'); }; vjs.mediatechcontroller.prototype.dispose = function() { // turn off any manual progress or timeupdate tracking if (this.manualprogress) { this.manualprogressoff(); } if (this.manualtimeupdates) { this.manualtimeupdatesoff(); } vjs.component.prototype.dispose.call(this); }; vjs.mediatechcontroller.prototype.setcurrenttime = function() { // improve the accuracy of manual timeupdates if (this.manualtimeupdates) { this.player().trigger('timeupdate'); } }; /** * provide a default setposter method for techs * * poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. */ vjs.mediatechcontroller.prototype.setposter = function(){}; vjs.mediatechcontroller.prototype['featuresvolumecontrol'] = true; // resizing plugins using request fullscreen reloads the plugin vjs.mediatechcontroller.prototype['featuresfullscreenresize'] = false; vjs.mediatechcontroller.prototype['featuresplaybackrate'] = false; // optional events that we can manually mimic with timers // currently not triggered by video-js-swf vjs.mediatechcontroller.prototype['featuresprogressevents'] = false; vjs.mediatechcontroller.prototype['featurestimeupdateevents'] = false; /** * a functional mixin for techs that want to use the source handler pattern. * * ##### example: * * videojs.mediatechcontroller.withsourcehandlers.call(mytech); * */ vjs.mediatechcontroller.withsourcehandlers = function(tech){ /** * register a source handler * source handlers are scripts for handling specific formats. * the source handler pattern is used for adaptive formats (hls, dash) that * manually load video data and feed it into a source buffer (media source extensions) * @param {function} handler the source handler * @param {boolean} first register it before any existing handlers */ tech.registersourcehandler = function(handler, index){ var handlers = tech.sourcehandlers; if (!handlers) { handlers = tech.sourcehandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /** * return the first source handler that supports the source * todo: answer question: should 'probably' be prioritized over 'maybe' * @param {object} source the source object * @returns {object} the first source handler that supports the source * @returns {null} null if no source handler is found */ tech.selectsourcehandler = function(source){ var handlers = tech.sourcehandlers || [], can; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canhandlesource(source); if (can) { return handlers[i]; } } return null; }; /** * check if the tech can support the given source * @param {object} srcobj the source object * @return {string} 'probably', 'maybe', or '' (empty string) */ tech.canplaysource = function(srcobj){ var sh = tech.selectsourcehandler(srcobj); if (sh) { return sh.canhandlesource(srcobj); } return ''; }; /** * create a function for setting the source using a source object * and source handlers. * should never be called unless a source handler was found. * @param {object} source a source object with src and type keys * @return {vjs.mediatechcontroller} self */ tech.prototype.setsource = function(source){ var sh = tech.selectsourcehandler(source); // dispose any existing source handler this.disposesourcehandler(); this.off('dispose', this.disposesourcehandler); this.currentsource_ = source; this.sourcehandler_ = sh.handlesource(source, this); this.on('dispose', this.disposesourcehandler); return this; }; /** * clean up any existing source handler */ tech.prototype.disposesourcehandler = function(){ if (this.sourcehandler_ && this.sourcehandler_.dispose) { this.sourcehandler_.dispose(); } }; }; /** * @fileoverview html5 media controller - wrapper for html5 media api */ /** * html5 media controller - wrapper for html5 media api * @param {vjs.player|object} player * @param {object=} options * @param {function=} ready * @constructor */ vjs.html5 = vjs.mediatechcontroller.extend({ /** @constructor */ init: function(player, options, ready){ vjs.mediatechcontroller.call(this, player, options, ready); this.setuptriggers(); var source = options['source']; // set the source if one is provided // 1) check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentsrc !== source.src || (player.tag && player.tag.initnetworkstate_ === 3))) { this.setsource(source); } // determine if native controls should be used // our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. right now this will block custom // controls on touch enabled laptops like the chrome pixel if (vjs.touch_enabled && player.options()['nativecontrolsfortouch'] === true) { this.usenativecontrols(); } // 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 player.ready(function(){ if (this.tag && this.options_['autoplay'] && this.paused()) { delete this.tag['poster']; // chrome fix. fixed in chrome v16. this.play(); } }); this.triggerready(); } }); vjs.html5.prototype.dispose = function(){ vjs.html5.disposemediaelement(this.el_); vjs.mediatechcontroller.prototype.dispose.call(this); }; vjs.html5.prototype.createel = function(){ var player = this.player_, // if possible, reuse original tag for html5 playback technology element el = player.tag, newel, clone; // check if this browser supports moving the element into the box. // on the iphone video will break if you move the element, // so we have to create a brand new element. if (!el || this['movingmediaelementindom'] === false) { // if the original tag is still there, clone and remove it. if (el) { clone = el.clonenode(false); vjs.html5.disposemediaelement(el); el = clone; player.tag = null; } else { el = vjs.createel('video'); vjs.setelementattributes(el, vjs.obj.merge(player.tagattributes || {}, { id:player.id() + '_html5_api', 'class':'vjs-tech' }) ); } // associate the player with the new tag el['player'] = player; vjs.insertfirst(el, player.el()); } // update specific tag settings, in case they were overridden var settingsattrs = ['autoplay','preload','loop','muted']; for (var i = settingsattrs.length - 1; i >= 0; i--) { var attr = settingsattrs[i]; var overwriteattrs = {}; if (typeof player.options_[attr] !== 'undefined') { overwriteattrs[attr] = player.options_[attr]; } vjs.setelementattributes(el, overwriteattrs); } return el; // jenniisawesome = true; }; // make video events trigger player events // may seem verbose here, but makes other apis possible. // triggers removed using this.off when disposed vjs.html5.prototype.setuptriggers = function(){ for (var i = vjs.html5.events.length - 1; i >= 0; i--) { this.on(vjs.html5.events[i], this.eventhandler); } }; vjs.html5.prototype.eventhandler = function(evt){ // in the case of an error on the video element, set the error prop // on the player and let the player handle triggering the event. on // some platforms, error events fire that do not cause the error // property on the video element to be set. see #1465 for an example. if (evt.type == 'error' && this.error()) { this.player().error(this.error().code); // in some cases we pass the event directly to the player } else { // no need for media events to bubble up. evt.bubbles = false; this.player().trigger(evt); } }; vjs.html5.prototype.usenativecontrols = function(){ var tech, player, controlson, controlsoff, cleanup; tech = this; player = this.player(); // if the player controls are enabled turn on the native controls tech.setcontrols(player.controls()); // update the native controls when player controls state is updated controlson = function(){ tech.setcontrols(true); }; controlsoff = function(){ tech.setcontrols(false); }; player.on('controlsenabled', controlson); player.on('controlsdisabled', controlsoff); // clean up when not using native controls anymore cleanup = function(){ player.off('controlsenabled', controlson); player.off('controlsdisabled', controlsoff); }; tech.on('dispose', cleanup); player.on('usingcustomcontrols', cleanup); // update the state of the player to using native controls player.usingnativecontrols(true); }; vjs.html5.prototype.play = function(){ this.el_.play(); }; vjs.html5.prototype.pause = function(){ this.el_.pause(); }; vjs.html5.prototype.paused = function(){ return this.el_.paused; }; vjs.html5.prototype.currenttime = function(){ return this.el_.currenttime; }; vjs.html5.prototype.setcurrenttime = function(seconds){ try { this.el_.currenttime = seconds; } catch(e) { vjs.log(e, 'video is not ready. (video.js)'); // this.warning(videojs.warnings.videonotready); } }; vjs.html5.prototype.duration = function(){ return this.el_.duration || 0; }; vjs.html5.prototype.buffered = function(){ return this.el_.buffered; }; vjs.html5.prototype.volume = function(){ return this.el_.volume; }; vjs.html5.prototype.setvolume = function(percentasdecimal){ this.el_.volume = percentasdecimal; }; vjs.html5.prototype.muted = function(){ return this.el_.muted; }; vjs.html5.prototype.setmuted = function(muted){ this.el_.muted = muted; }; vjs.html5.prototype.width = function(){ return this.el_.offsetwidth; }; vjs.html5.prototype.height = function(){ return this.el_.offsetheight; }; vjs.html5.prototype.supportsfullscreen = function(){ if (typeof this.el_.webkitenterfullscreen == 'function') { // seems to be broken in chromium/chrome && safari in leopard if (/android/.test(vjs.user_agent) || !/chrome|mac os x 10.5/.test(vjs.user_agent)) { return true; } } return false; }; vjs.html5.prototype.enterfullscreen = function(){ var video = this.el_; if ('webkitdisplayingfullscreen' in video) { this.one('webkitbeginfullscreen', function() { this.player_.isfullscreen(true); this.one('webkitendfullscreen', function() { this.player_.isfullscreen(false); this.player_.trigger('fullscreenchange'); }); this.player_.trigger('fullscreenchange'); }); } if (video.paused && video.networkstate <= video.have_metadata) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get ios ~6.1 devices into a play/pause loop this.settimeout(function(){ video.pause(); video.webkitenterfullscreen(); }, 0); } else { video.webkitenterfullscreen(); } }; vjs.html5.prototype.exitfullscreen = function(){ this.el_.webkitexitfullscreen(); }; vjs.html5.prototype.src = function(src) { if (src === undefined) { return this.el_.src; } else { // setting src through `src` instead of `setsrc` will be deprecated this.setsrc(src); } }; vjs.html5.prototype.setsrc = function(src) { this.el_.src = src; }; vjs.html5.prototype.load = function(){ this.el_.load(); }; vjs.html5.prototype.currentsrc = function(){ return this.el_.currentsrc; }; vjs.html5.prototype.poster = function(){ return this.el_.poster; }; vjs.html5.prototype.setposter = function(val){ this.el_.poster = val; }; vjs.html5.prototype.preload = function(){ return this.el_.preload; }; vjs.html5.prototype.setpreload = function(val){ this.el_.preload = val; }; vjs.html5.prototype.autoplay = function(){ return this.el_.autoplay; }; vjs.html5.prototype.setautoplay = function(val){ this.el_.autoplay = val; }; vjs.html5.prototype.controls = function(){ return this.el_.controls; }; vjs.html5.prototype.setcontrols = function(val){ this.el_.controls = !!val; }; vjs.html5.prototype.loop = function(){ return this.el_.loop; }; vjs.html5.prototype.setloop = function(val){ this.el_.loop = val; }; vjs.html5.prototype.error = function(){ return this.el_.error; }; vjs.html5.prototype.seeking = function(){ return this.el_.seeking; }; vjs.html5.prototype.ended = function(){ return this.el_.ended; }; vjs.html5.prototype.defaultmuted = function(){ return this.el_.defaultmuted; }; vjs.html5.prototype.playbackrate = function(){ return this.el_.playbackrate; }; vjs.html5.prototype.setplaybackrate = function(val){ this.el_.playbackrate = val; }; vjs.html5.prototype.networkstate = function(){ return this.el_.networkstate; }; /** * check if html5 video is supported by this browser/device * @return {boolean} */ vjs.html5.issupported = function(){ // ie9 with no media player is a liar! (#984) try { vjs.test_vid['volume'] = 0.5; } catch (e) { return false; } return !!vjs.test_vid.canplaytype; }; // add source handler pattern functions to this tech vjs.mediatechcontroller.withsourcehandlers(vjs.html5); /** * the default native source handler. * this simply passes the source to the video element. nothing fancy. * @param {object} source the source object * @param {vjs.html5} tech the instance of the html5 tech */ vjs.html5.nativesourcehandler = {}; /** * check if the video element can handle the source natively * @param {object} source the source object * @return {string} 'probably', 'maybe', or '' (empty string) */ vjs.html5.nativesourcehandler.canhandlesource = function(source){ var ext; function canplaytype(type){ // ie9 on windows 7 without mediaplayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return !!vjs.test_vid.canplaytype(type); } catch(e) { return ''; } } // if a type was provided we should rely on that if (source.type) { return canplaytype(source.type); } else { // if no type, fall back to checking 'video/[extension]' ext = source.src.match(/\.([^\/\?]+)(\?[^\/]+)?$/i)[1]; return canplaytype('video/'+ext); } }; /** * pass the source to the video element * adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {object} source the source object * @param {vjs.html5} tech the instance of the html5 tech */ vjs.html5.nativesourcehandler.handlesource = function(source, tech){ tech.setsrc(source.src); }; /** * clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.html5.nativesourcehandler.dispose = function(){}; // register the native source handler vjs.html5.registersourcehandler(vjs.html5.nativesourcehandler); /** * check if the volume can be changed in this browser/device. * volume cannot be changed in a lot of mobile devices. * specifically, it can't be changed from 1 on ios. * @return {boolean} */ vjs.html5.cancontrolvolume = function(){ var volume = vjs.test_vid.volume; vjs.test_vid.volume = (volume / 2) + 0.1; return volume !== vjs.test_vid.volume; }; /** * check if playbackrate is supported in this browser/device. * @return {[type]} [description] */ vjs.html5.cancontrolplaybackrate = function(){ var playbackrate = vjs.test_vid.playbackrate; vjs.test_vid.playbackrate = (playbackrate / 2) + 0.1; return playbackrate !== vjs.test_vid.playbackrate; }; /** * set the tech's volume control support status * @type {boolean} */ vjs.html5.prototype['featuresvolumecontrol'] = vjs.html5.cancontrolvolume(); /** * set the tech's playbackrate support status * @type {boolean} */ vjs.html5.prototype['featuresplaybackrate'] = vjs.html5.cancontrolplaybackrate(); /** * set the tech's status on moving the video element. * in ios, if you move a video element in the dom, it breaks video playback. * @type {boolean} */ vjs.html5.prototype['movingmediaelementindom'] = !vjs.is_ios; /** * set the the tech's fullscreen resize support status. * html video is able to automatically resize when going to fullscreen. * (no longer appears to be used. can probably be removed.) */ vjs.html5.prototype['featuresfullscreenresize'] = true; /** * set the tech's progress event support status * (this disables the manual progress events of the mediatechcontroller) */ vjs.html5.prototype['featuresprogressevents'] = true; // html5 feature detection and device fixes --------------------------------- // (function() { var canplaytype, mpegurlre = /^application\/(?:x-|vnd\.apple\.)mpegurl/i, mp4re = /^video\/mp4/i; vjs.html5.patchcanplaytype = function() { // android 4.0 and above can play hls to some extent but it reports being unable to do so if (vjs.android_version >= 4.0) { if (!canplaytype) { canplaytype = vjs.test_vid.constructor.prototype.canplaytype; } vjs.test_vid.constructor.prototype.canplaytype = function(type) { if (type && mpegurlre.test(type)) { return 'maybe'; } return canplaytype.call(this, type); }; } // override android 2.2 and less canplaytype method which is broken if (vjs.is_old_android) { if (!canplaytype) { canplaytype = vjs.test_vid.constructor.prototype.canplaytype; } vjs.test_vid.constructor.prototype.canplaytype = function(type){ if (type && mp4re.test(type)) { return 'maybe'; } return canplaytype.call(this, type); }; } }; vjs.html5.unpatchcanplaytype = function() { var r = vjs.test_vid.constructor.prototype.canplaytype; vjs.test_vid.constructor.prototype.canplaytype = canplaytype; canplaytype = null; return r; }; // by default, patch the video element vjs.html5.patchcanplaytype(); })(); // list of all html5 events (various uses). vjs.html5.events = 'loadstart,suspend,abort,error,emptied,stalled,loadedmetadata,loadeddata,canplay,canplaythrough,playing,waiting,seeking,seeked,ended,durationchange,timeupdate,progress,play,pause,ratechange,volumechange'.split(','); vjs.html5.disposemediaelement = function(el){ if (!el) { return; } el['player'] = null; if (el.parentnode) { el.parentnode.removechild(el); } // remove any child track or source nodes to prevent their loading while(el.haschildnodes()) { el.removechild(el.firstchild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeattribute('src'); // force the media element to update its loading state by calling load() // however ie on windows 7n has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function() { try { el.load(); } catch (e) { // not supported } })(); } }; /** * @fileoverview videojs-swf - custom flash player with html5-ish api * https://github.com/zencoder/video-js-swf * not using setuptriggers. using global onevent func to distribute events */ /** * flash media controller - wrapper for fallback swf api * * @param {vjs.player} player * @param {object=} options * @param {function=} ready * @constructor */ vjs.flash = vjs.mediatechcontroller.extend({ /** @constructor */ init: function(player, options, ready){ vjs.mediatechcontroller.call(this, player, options, ready); var source = options['source'], // which element to embed in parentel = options['parentel'], // create a temporary element to be replaced by swf object placeholder = this.el_ = vjs.createel('div', { id: player.id() + '_temp_flash' }), // generate id for swf object objid = player.id()+'_flash_api', // store player options in local var for optimization // todo: switch to using player methods instead of options // e.g. player.autoplay(); playeroptions = player.options_, // merge default flashvars with ones passed in to init flashvars = vjs.obj.merge({ // swf callback functions 'readyfunction': 'videojs.flash.onready', 'eventproxyfunction': 'videojs.flash.onevent', 'erroreventproxyfunction': 'videojs.flash.onerror', // player settings 'autoplay': playeroptions.autoplay, 'preload': playeroptions.preload, 'loop': playeroptions.loop, 'muted': playeroptions.muted }, options['flashvars']), // merge default parames with ones passed in params = vjs.obj.merge({ 'wmode': 'opaque', // opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // using bgcolor prevents a white flash when the object is loading }, options['params']), // merge default attributes with ones passed in attributes = vjs.obj.merge({ 'id': objid, 'name': objid, // both id and name needed or swf to identify itself 'class': 'vjs-tech' }, options['attributes']) ; // if source was supplied pass as a flash var. if (source) { this.ready(function(){ this.setsource(source); }); } // add placeholder to player div vjs.insertfirst(placeholder, parentel); // having issues with flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // this allows resetting the playhead when we catch the reload if (options['starttime']) { this.ready(function(){ this.load(); this.play(); this['currenttime'](options['starttime']); }); } // firefox doesn't bubble mousemove events to parent. videojs/video-js-swf#37 // bugzilla bug: https://bugzilla.mozilla.org/show_bug.cgi?id=836786 if (vjs.is_firefox) { this.ready(function(){ this.on('mousemove', function(){ // since it's a custom event, don't bubble higher than the player this.player().trigger({ 'type':'mousemove', 'bubbles': false }); }); }); } // native click events on the swf aren't triggered on ie11, win8.1rt // use stageclick events triggered from inside the swf instead player.on('stageclick', player.reportuseractivity); this.el_ = vjs.flash.embed(options['swf'], placeholder, flashvars, params, attributes); } }); vjs.flash.prototype.dispose = function(){ vjs.mediatechcontroller.prototype.dispose.call(this); }; vjs.flash.prototype.play = function(){ this.el_.vjs_play(); }; vjs.flash.prototype.pause = function(){ this.el_.vjs_pause(); }; vjs.flash.prototype.src = function(src){ if (src === undefined) { return this['currentsrc'](); } // setting src through `src` not `setsrc` will be deprecated return this.setsrc(src); }; vjs.flash.prototype.setsrc = function(src){ // make sure source url is absolute. src = vjs.getabsoluteurl(src); this.el_.vjs_src(src); // currently the swf doesn't autoplay if you load a source later. // e.g. load player w/ no source, wait 2s, set src. if (this.player_.autoplay()) { var tech = this; this.settimeout(function(){ tech.play(); }, 0); } }; vjs.flash.prototype['setcurrenttime'] = function(time){ this.lastseektarget_ = time; this.el_.vjs_setproperty('currenttime', time); vjs.mediatechcontroller.prototype.setcurrenttime.call(this); }; vjs.flash.prototype['currenttime'] = function(time){ // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastseektarget_ || 0; } return this.el_.vjs_getproperty('currenttime'); }; vjs.flash.prototype['currentsrc'] = function(){ if (this.currentsource_) { return this.currentsource_.src; } else { return this.el_.vjs_getproperty('currentsrc'); } }; vjs.flash.prototype.load = function(){ this.el_.vjs_load(); }; vjs.flash.prototype.poster = function(){ this.el_.vjs_getproperty('poster'); }; vjs.flash.prototype['setposter'] = function(){ // poster images are not handled by the flash tech so make this a no-op }; vjs.flash.prototype.buffered = function(){ return vjs.createtimerange(0, this.el_.vjs_getproperty('buffered')); }; vjs.flash.prototype.supportsfullscreen = function(){ return false; // flash does not allow fullscreen through javascript }; vjs.flash.prototype.enterfullscreen = function(){ return false; }; (function(){ // create setters and getters for attributes var api = vjs.flash.prototype, readwrite = 'rtmpconnection,rtmpstream,preload,defaultplaybackrate,playbackrate,autoplay,loop,mediagroup,controller,controls,volume,muted,defaultmuted'.split(','), readonly = 'error,networkstate,readystate,seeking,initialtime,duration,startoffsettime,paused,played,seekable,ended,videotracks,audiotracks,videowidth,videoheight,texttracks'.split(','), // overridden: buffered, currenttime, currentsrc i; function createsetter(attr){ var attrupper = attr.charat(0).touppercase() + attr.slice(1); api['set'+attrupper] = function(val){ return this.el_.vjs_setproperty(attr, val); }; } function creategetter(attr) { api[attr] = function(){ return this.el_.vjs_getproperty(attr); }; } // create getter and setters for all read/write attributes for (i = 0; i < readwrite.length; i++) { creategetter(readwrite[i]); createsetter(readwrite[i]); } // create getters for read-only attributes for (i = 0; i < readonly.length; i++) { creategetter(readonly[i]); } })(); /* flash support testing -------------------------------------------------------- */ vjs.flash.issupported = function(){ return vjs.flash.version()[0] >= 10; // return swfobject.hasflashplayerversion('10'); }; // add source handler pattern functions to this tech vjs.mediatechcontroller.withsourcehandlers(vjs.flash); /** * the default native source handler. * this simply passes the source to the video element. nothing fancy. * @param {object} source the source object * @param {vjs.flash} tech the instance of the flash tech */ vjs.flash.nativesourcehandler = {}; /** * check flash can handle the source natively * @param {object} source the source object * @return {string} 'probably', 'maybe', or '' (empty string) */ vjs.flash.nativesourcehandler.canhandlesource = function(source){ var type; if (!source.type) { return ''; } // strip code information from the type because we don't get that specific type = source.type.replace(/;.*/,'').tolowercase(); if (type in vjs.flash.formats) { return 'maybe'; } return ''; }; /** * pass the source to the flash object * adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {object} source the source object * @param {vjs.flash} tech the instance of the flash tech */ vjs.flash.nativesourcehandler.handlesource = function(source, tech){ tech.setsrc(source.src); }; /** * clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ vjs.flash.nativesourcehandler.dispose = function(){}; // register the native source handler vjs.flash.registersourcehandler(vjs.flash.nativesourcehandler); vjs.flash.formats = { 'video/flv': 'flv', 'video/x-flv': 'flv', 'video/mp4': 'mp4', 'video/m4v': 'mp4' }; vjs.flash['onready'] = function(currswf){ var el, player; el = vjs.el(currswf); // get player from the player div property player = el && el.parentnode && el.parentnode['player']; // if there is no el or player then the tech has been disposed // and the tech element was removed from the player div if (player) { // reference player on tech element el['player'] = player; // check that the flash object is really ready vjs.flash['checkready'](player.tech); } }; // the swf isn't always ready when it says it is. sometimes the api functions still need to be added to the object. // if it's not ready, we set a timeout to check again shortly. vjs.flash['checkready'] = function(tech){ // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if api property exists if (tech.el().vjs_getproperty) { // tell tech it's ready tech.triggerready(); } else { // wait longer this.settimeout(function(){ vjs.flash['checkready'](tech); }, 50); } }; // trigger events from the swf on the player vjs.flash['onevent'] = function(swfid, eventname){ var player = vjs.el(swfid)['player']; player.trigger(eventname); }; // log errors from the swf vjs.flash['onerror'] = function(swfid, err){ var player = vjs.el(swfid)['player']; var msg = 'flash: '+err; if (err == 'srcnotfound') { player.error({ code: 4, message: msg }); // errors we haven't categorized into the media errors } else { player.error(msg); } }; // flash version check vjs.flash.version = function(){ var version = '0,0,0'; // ie try { version = new window.activexobject('shockwaveflash.shockwaveflash').getvariable('$version').replace(/\d+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch(e) { try { if (navigator.mimetypes['application/x-shockwave-flash'].enabledplugin){ version = (navigator.plugins['shockwave flash 2.0'] || navigator.plugins['shockwave flash']).description.replace(/\d+/g, ',').match(/^,?(.+),?$/)[1]; } } catch(err) {} } return version.split(','); }; // flash embedding method. only used in non-iframe mode vjs.flash.embed = function(swf, placeholder, flashvars, params, attributes){ var code = vjs.flash.getembedcode(swf, flashvars, params, attributes), // get element by embedding code and retrieving created element obj = vjs.createel('div', { innerhtml: code }).childnodes[0], par = placeholder.parentnode ; placeholder.parentnode.replacechild(obj, placeholder); // ie6 seems to have an issue where it won't initialize the swf object after injecting it. // this is a dumb fix var newobj = par.childnodes[0]; settimeout(function(){ newobj.style.display = 'block'; }, 1000); return obj; }; vjs.flash.getembedcode = function(swf, flashvars, params, attributes){ var objtag = ''; }); attributes = vjs.obj.merge({ // add swf to attributes (need both for ie and others to work) 'data': swf, // default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // create attributes string vjs.obj.each(attributes, function(key, val){ attrsstring += (key + '="' + val + '" '); }); return objtag + attrsstring + '>' + paramsstring + ''; }; vjs.flash.streamingformats = { 'rtmp/mp4': 'mp4', 'rtmp/flv': 'flv' }; vjs.flash.streamfromparts = function(connection, stream) { return connection + '&' + stream; }; vjs.flash.streamtoparts = function(src) { var parts = { connection: '', stream: '' }; if (! src) { return parts; } // look for the normal url separator we expect, '&'. // if found, we split the url into two pieces around the // first '&'. var connend = src.indexof('&'); var streambegin; if (connend !== -1) { streambegin = connend + 1; } else { // if there's not a '&', we use the last '/' as the delimiter. connend = streambegin = src.lastindexof('/') + 1; if (connend === 0) { // really, there's not a '/'? connend = streambegin = src.length; } } parts.connection = src.substring(0, connend); parts.stream = src.substring(streambegin, src.length); return parts; }; vjs.flash.isstreamingtype = function(srctype) { return srctype in vjs.flash.streamingformats; }; // rtmp has four variations, any string starting // with one of these protocols should be valid vjs.flash.rtmp_re = /^rtmp[set]?:\/\//i; vjs.flash.isstreamingsrc = function(src) { return vjs.flash.rtmp_re.test(src); }; /** * a source handler for rtmp urls * @type {object} */ vjs.flash.rtmpsourcehandler = {}; /** * check flash can handle the source natively * @param {object} source the source object * @return {string} 'probably', 'maybe', or '' (empty string) */ vjs.flash.rtmpsourcehandler.canhandlesource = function(source){ if (vjs.flash.isstreamingtype(source.type) || vjs.flash.isstreamingsrc(source.src)) { return 'maybe'; } return ''; }; /** * pass the source to the flash object * adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {object} source the source object * @param {vjs.flash} tech the instance of the flash tech */ vjs.flash.rtmpsourcehandler.handlesource = function(source, tech){ var srcparts = vjs.flash.streamtoparts(source.src); tech.setrtmpconnection(srcparts.connection); tech.setrtmpstream(srcparts.stream); }; // register the native source handler vjs.flash.registersourcehandler(vjs.flash.rtmpsourcehandler); /** * the media loader is the component that decides which playback technology to load * when the player is initialized. * * @constructor */ vjs.medialoader = vjs.component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.component.call(this, player, options, ready); // if there are no sources when the player is initialized, // load the first supported playback technology. if (!player.options_['sources'] || player.options_['sources'].length === 0) { for (var i=0,j=player.options_['techorder']; i 0) { track.disable(); } } // get track kind from shown track or disablesamekind kind = (showtrack) ? showtrack.kind() : ((disablesamekind) ? disablesamekind : false); // trigger trackchange event, captionstrackchange, subtitlestrackchange, etc. if (kind) { this.trigger(kind+'trackchange'); } return this; }; /** * the base class for all text tracks * * handles the parsing, hiding, and showing of text track cues * * @param {vjs.player|object} player * @param {object=} options * @constructor */ vjs.texttrack = vjs.component.extend({ /** @constructor */ init: function(player, options){ vjs.component.call(this, player, options); // apply track info to track object // options will often be a track element // build id if one doesn't exist this.id_ = options['id'] || ('vjs_' + options['kind'] + '_' + options['language'] + '_' + vjs.guid++); this.src_ = options['src']; // 'default' is a reserved keyword in js so we use an abbreviated version this.dflt_ = options['default'] || options['dflt']; this.title_ = options['title']; this.language_ = options['srclang']; this.label_ = options['label']; this.cues_ = []; this.activecues_ = []; this.readystate_ = 0; this.mode_ = 0; player.on('dispose', vjs.bind(this, this.deactivate, this.id_)); } }); /** * track kind value. captions, subtitles, etc. * @private */ vjs.texttrack.prototype.kind_; /** * get the track kind value * @return {string} */ vjs.texttrack.prototype.kind = function(){ return this.kind_; }; /** * track src value * @private */ vjs.texttrack.prototype.src_; /** * get the track src value * @return {string} */ vjs.texttrack.prototype.src = function(){ return this.src_; }; /** * track default value * if default is used, subtitles/captions to start showing * @private */ vjs.texttrack.prototype.dflt_; /** * get the track default value. ('default' is a reserved keyword) * @return {boolean} */ vjs.texttrack.prototype.dflt = function(){ return this.dflt_; }; /** * track title value * @private */ vjs.texttrack.prototype.title_; /** * get the track title value * @return {string} */ vjs.texttrack.prototype.title = function(){ return this.title_; }; /** * language - two letter string to represent track language, e.g. 'en' for english * spec def: readonly attribute domstring language; * @private */ vjs.texttrack.prototype.language_; /** * get the track language value * @return {string} */ vjs.texttrack.prototype.language = function(){ return this.language_; }; /** * track label e.g. 'english' * spec def: readonly attribute domstring label; * @private */ vjs.texttrack.prototype.label_; /** * get the track label value * @return {string} */ vjs.texttrack.prototype.label = function(){ return this.label_; }; /** * all cues of the track. cues have a starttime, endtime, text, and other properties. * spec def: readonly attribute texttrackcuelist cues; * @private */ vjs.texttrack.prototype.cues_; /** * get the track cues * @return {array} */ vjs.texttrack.prototype.cues = function(){ return this.cues_; }; /** * activecues is all cues that are currently showing * spec def: readonly attribute texttrackcuelist activecues; * @private */ vjs.texttrack.prototype.activecues_; /** * get the track active cues * @return {array} */ vjs.texttrack.prototype.activecues = function(){ return this.activecues_; }; /** * readystate describes if the text file has been loaded * const unsigned short none = 0; * const unsigned short loading = 1; * const unsigned short loaded = 2; * const unsigned short error = 3; * readonly attribute unsigned short readystate; * @private */ vjs.texttrack.prototype.readystate_; /** * get the track readystate * @return {number} */ vjs.texttrack.prototype.readystate = function(){ return this.readystate_; }; /** * mode describes if the track is showing, hidden, or disabled * const unsigned short off = 0; * const unsigned short hidden = 1; (still triggering cuechange events, but not visible) * const unsigned short showing = 2; * attribute unsigned short mode; * @private */ vjs.texttrack.prototype.mode_; /** * get the track mode * @return {number} */ vjs.texttrack.prototype.mode = function(){ return this.mode_; }; /** * create basic div to hold cue text * @return {element} */ vjs.texttrack.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-' + this.kind_ + ' vjs-text-track' }); }; /** * show: mode showing (2) * indicates that the text track is active. if no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * the user agent is maintaining a list of which cues are active, and events are being fired accordingly. * in addition, for text tracks whose kind is subtitles or captions, the cues are being displayed over the video as appropriate; * for text tracks whose kind is descriptions, the user agent is making the cues available to the user in a non-visual fashion; * and for text tracks whose kind is chapters, the user agent is making available to the user a mechanism by which the user can navigate to any point in the media resource by selecting a cue. * the showing by default state is used in conjunction with the default attribute on track elements to indicate that the text track was enabled due to that attribute. * this allows the user agent to override the state if a later track is discovered that is more appropriate per the user's preferences. */ vjs.texttrack.prototype.show = function(){ this.activate(); this.mode_ = 2; // show element. vjs.component.prototype.show.call(this); }; /** * hide: mode hidden (1) * indicates that the text track is active, but that the user agent is not actively displaying the cues. * if no attempt has yet been made to obtain the track's cues, the user agent will perform such an attempt momentarily. * the user agent is maintaining a list of which cues are active, and events are being fired accordingly. */ vjs.texttrack.prototype.hide = function(){ // when hidden, cues are still triggered. disable to stop triggering. this.activate(); this.mode_ = 1; // hide element. vjs.component.prototype.hide.call(this); }; /** * disable: mode off/disable (0) * indicates that the text track is not active. other than for the purposes of exposing the track in the dom, the user agent is ignoring the text track. * no cues are active, no events are fired, and the user agent will not attempt to obtain the track's cues. */ vjs.texttrack.prototype.disable = function(){ // if showing, hide. if (this.mode_ == 2) { this.hide(); } // stop triggering cues this.deactivate(); // switch mode to off this.mode_ = 0; }; /** * turn on cue tracking. tracks that are showing or hidden are active. */ vjs.texttrack.prototype.activate = function(){ // load text file if it hasn't been yet. if (this.readystate_ === 0) { this.load(); } // only activate if not already active. if (this.mode_ === 0) { // update current cue on timeupdate // using unique id for bind function so other tracks don't remove listener this.player_.on('timeupdate', vjs.bind(this, this.update, this.id_)); // reset cue time on media end this.player_.on('ended', vjs.bind(this, this.reset, this.id_)); // add to display if (this.kind_ === 'captions' || this.kind_ === 'subtitles') { this.player_.getchild('texttrackdisplay').addchild(this); } } }; /** * turn off cue tracking. */ vjs.texttrack.prototype.deactivate = function(){ // using unique id for bind function so other tracks don't remove listener this.player_.off('timeupdate', vjs.bind(this, this.update, this.id_)); this.player_.off('ended', vjs.bind(this, this.reset, this.id_)); this.reset(); // reset // remove from display this.player_.getchild('texttrackdisplay').removechild(this); }; // a readiness state // one of the following: // // not loaded // indicates that the text track is known to exist (e.g. it has been declared with a track element), but its cues have not been obtained. // // loading // indicates that the text track is loading and there have been no fatal errors encountered so far. further cues might still be added to the track. // // loaded // indicates that the text track has been loaded with no fatal errors. no new cues will be added to the track except if the text track corresponds to a mutabletexttrack object. // // failed to load // indicates that the text track was enabled, but when the user agent attempted to obtain it, this failed in some way (e.g. url could not be resolved, network error, unknown text track format). some or all of the cues are likely missing and will not be obtained. vjs.texttrack.prototype.load = function(){ // only load if not loaded yet. if (this.readystate_ === 0) { this.readystate_ = 1; vjs.xhr(this.src_, vjs.bind(this, function(err, response, responsebody){ if (err) { return this.onerror(err); } this.parsecues(responsebody); })); } }; vjs.texttrack.prototype.onerror = function(err){ this.error = err; this.readystate_ = 3; this.trigger('error'); }; // parse the webvtt text format for cue times. // todo: separate parser into own class so alternative timed text formats can be used. (ttml, dfxp) vjs.texttrack.prototype.parsecues = function(srccontent) { var cue, time, text, lines = srccontent.split('\n'), line = '', id; for (var i=1, j=lines.length; i') == -1) { id = line; // advance to next line for timing. line = vjs.trim(lines[++i]); } else { id = this.cues_.length; } // first line - number cue = { id: id, // cue number index: this.cues_.length // position in array }; // timing line time = line.split(/[\t ]+/); cue.starttime = this.parsecuetime(time[0]); cue.endtime = this.parsecuetime(time[2]); // additional lines - cue text text = []; // loop until a blank line or end of lines // assuming trim('') returns false for blank lines while (lines[++i] && (line = vjs.trim(lines[i]))) { text.push(line); } cue.text = text.join('
    '); // add this cue this.cues_.push(cue); } } this.readystate_ = 2; this.trigger('loaded'); }; vjs.texttrack.prototype.parsecuetime = function(timetext) { var parts = timetext.split(':'), time = 0, hours, minutes, other, seconds, ms; // check if optional hours place is included // 00:00:00.000 vs. 00:00.000 if (parts.length == 3) { hours = parts[0]; minutes = parts[1]; other = parts[2]; } else { hours = 0; minutes = parts[0]; other = parts[1]; } // break other (seconds, milliseconds, and flags) by spaces // todo: make additional cue layout settings work with flags other = other.split(/\s+/); // remove seconds. seconds is the first part before any spaces. seconds = other.splice(0,1)[0]; // could use either . or , for decimal seconds = seconds.split(/\.|,/); // get milliseconds ms = parsefloat(seconds[1]); seconds = seconds[0]; // hours => seconds time += parsefloat(hours) * 3600; // minutes => seconds time += parsefloat(minutes) * 60; // add seconds time += parsefloat(seconds); // add milliseconds if (ms) { time += ms/1000; } return time; }; // update active cues whenever timeupdate events are triggered on the player. vjs.texttrack.prototype.update = function(){ if (this.cues_.length > 0) { // get current player time, adjust for track offset var offset = this.player_.options()['tracktimeoffset'] || 0; var time = this.player_.currenttime() + offset; // check if the new time is outside the time box created by the the last update. if (this.prevchange === undefined || time < this.prevchange || this.nextchange <= time) { var cues = this.cues_, // create a new time box for this state. newnextchange = this.player_.duration(), // start at beginning of the timeline newprevchange = 0, // start at end reverse = false, // set the direction of the loop through the cues. optimized the cue check. newcues = [], // store new active cues. // store where in the loop the current active cues are, to provide a smart starting point for the next loop. firstactiveindex, lastactiveindex, cue, i; // loop vars // check if time is going forwards or backwards (scrubbing/rewinding) // if we know the direction we can optimize the starting position and direction of the loop through the cues array. if (time >= this.nextchange || this.nextchange === undefined) { // nextchange should happen // forwards, so start at the index of the first active cue and loop forward i = (this.firstactiveindex !== undefined) ? this.firstactiveindex : 0; } else { // backwards, so start at the index of the last active cue and loop backward reverse = true; i = (this.lastactiveindex !== undefined) ? this.lastactiveindex : cues.length - 1; } while (true) { // loop until broken cue = cues[i]; // cue ended at this point if (cue.endtime <= time) { newprevchange = math.max(newprevchange, cue.endtime); if (cue.active) { cue.active = false; } // no earlier cues should have an active start time. // nevermind. assume first cue could have a duration the same as the video. // in that case we need to loop all the way back to the beginning. // if (reverse && cue.starttime) { break; } // cue hasn't started } else if (time < cue.starttime) { newnextchange = math.min(newnextchange, cue.starttime); if (cue.active) { cue.active = false; } // no later cues should have an active start time. if (!reverse) { break; } // cue is current } else { if (reverse) { // add cue to front of array to keep in time order newcues.splice(0,0,cue); // if in reverse, the first current cue is our lastactivecue if (lastactiveindex === undefined) { lastactiveindex = i; } firstactiveindex = i; } else { // add cue to end of array newcues.push(cue); // if forward, the first current cue is our firstactiveindex if (firstactiveindex === undefined) { firstactiveindex = i; } lastactiveindex = i; } newnextchange = math.min(newnextchange, cue.endtime); newprevchange = math.max(newprevchange, cue.starttime); cue.active = true; } if (reverse) { // reverse down the array of cues, break if at first if (i === 0) { break; } else { i--; } } else { // walk up the array fo cues, break if at last if (i === cues.length - 1) { break; } else { i++; } } } this.activecues_ = newcues; this.nextchange = newnextchange; this.prevchange = newprevchange; this.firstactiveindex = firstactiveindex; this.lastactiveindex = lastactiveindex; this.updatedisplay(); this.trigger('cuechange'); } } }; // add cue html to display vjs.texttrack.prototype.updatedisplay = function(){ var cues = this.activecues_, html = '', i=0,j=cues.length; for (;i'; } this.el_.innerhtml = html; }; // set all loop helper values back vjs.texttrack.prototype.reset = function(){ this.nextchange = 0; this.prevchange = this.player_.duration(); this.firstactiveindex = 0; this.lastactiveindex = 0; }; // create specific track types /** * the track component for managing the hiding and showing of captions * * @constructor */ vjs.captionstrack = vjs.texttrack.extend(); vjs.captionstrack.prototype.kind_ = 'captions'; // exporting here because track creation requires the track kind // to be available on global object. e.g. new window['videojs'][kind + 'track'] /** * the track component for managing the hiding and showing of subtitles * * @constructor */ vjs.subtitlestrack = vjs.texttrack.extend(); vjs.subtitlestrack.prototype.kind_ = 'subtitles'; /** * the track component for managing the hiding and showing of chapters * * @constructor */ vjs.chapterstrack = vjs.texttrack.extend(); vjs.chapterstrack.prototype.kind_ = 'chapters'; /* text track display ============================================================================= */ // global container for both subtitle and captions text. simple div container. /** * the component for displaying text track cues * * @constructor */ vjs.texttrackdisplay = vjs.component.extend({ /** @constructor */ init: function(player, options, ready){ vjs.component.call(this, player, options, ready); // this used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // should probably be moved to an external track loader when we support // tracks that don't need a display. if (player.options_['tracks'] && player.options_['tracks'].length > 0) { this.player_.addtexttracks(player.options_['tracks']); } } }); vjs.texttrackdisplay.prototype.createel = function(){ return vjs.component.prototype.createel.call(this, 'div', { classname: 'vjs-text-track-display' }); }; /** * the specific menu item type for selecting a language within a text track kind * * @constructor */ vjs.texttrackmenuitem = vjs.menuitem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track']; // modify options for parent menuitem class's init. options['label'] = track.label(); options['selected'] = track.dflt(); vjs.menuitem.call(this, player, options); this.on(player, track.kind() + 'trackchange', this.update); } }); vjs.texttrackmenuitem.prototype.onclick = function(){ vjs.menuitem.prototype.onclick.call(this); this.player_.showtexttrack(this.track.id_, this.track.kind()); }; vjs.texttrackmenuitem.prototype.update = function(){ this.selected(this.track.mode() == 2); }; /** * a special menu item for turning of a specific type of text track * * @constructor */ vjs.offtexttrackmenuitem = vjs.texttrackmenuitem.extend({ /** @constructor */ init: function(player, options){ // create pseudo track info // requires options['kind'] options['track'] = { kind: function() { return options['kind']; }, player: player, label: function(){ return options['kind'] + ' off'; }, dflt: function(){ return false; }, mode: function(){ return false; } }; vjs.texttrackmenuitem.call(this, player, options); this.selected(true); } }); vjs.offtexttrackmenuitem.prototype.onclick = function(){ vjs.texttrackmenuitem.prototype.onclick.call(this); this.player_.showtexttrack(this.track.id_, this.track.kind()); }; vjs.offtexttrackmenuitem.prototype.update = function(){ var tracks = this.player_.texttracks(), i=0, j=tracks.length, track, off = true; for (;i 0) { this.show(); } return menu; }; /** * @constructor */ vjs.chapterstrackmenuitem = vjs.menuitem.extend({ /** @constructor */ init: function(player, options){ var track = this.track = options['track'], cue = this.cue = options['cue'], currenttime = player.currenttime(); // modify options for parent menuitem class's init. options['label'] = cue.text; options['selected'] = (cue.starttime <= currenttime && currenttime < cue.endtime); vjs.menuitem.call(this, player, options); track.on('cuechange', vjs.bind(this, this.update)); } }); vjs.chapterstrackmenuitem.prototype.onclick = function(){ vjs.menuitem.prototype.onclick.call(this); this.player_.currenttime(this.cue.starttime); this.update(this.cue.starttime); }; vjs.chapterstrackmenuitem.prototype.update = function(){ var cue = this.cue, currenttime = this.player_.currenttime(); // vjs.log(currenttime, cue.starttime); this.selected(cue.starttime <= currenttime && currenttime < cue.endtime); }; // add buttons to controlbar vjs.obj.merge(vjs.controlbar.prototype.options_['children'], { 'subtitlesbutton': {}, 'captionsbutton': {}, 'chaptersbutton': {} }); // vjs.cue = vjs.component.extend({ // /** @constructor */ // init: function(player, options){ // vjs.component.call(this, player, options); // } // }); /** * @fileoverview add json support * @suppress {undefinedvars} * (compiler doesn't like json not being declared) */ /** * javascript json implementation * (parse method only) * https://github.com/douglascrockford/json-js/blob/master/json2.js * only using for parse method when parsing data-setup attribute json. * @suppress {undefinedvars} * @namespace * @private */ vjs.json; if (typeof window.json !== 'undefined' && typeof window.json.parse === 'function') { vjs.json = window.json; } else { vjs.json = {}; var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; /** * parse the json * * @memberof vjs.json * @param {string} text the json string to parse * @param {function=} [reviver] optional function that can transform the results * @return {object|array} the parsed json */ vjs.json.parse = function (text, reviver) { var j; function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (object.prototype.hasownproperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } text = string(text); cx.lastindex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charcodeat(0).tostring(16)).slice(-4); }); } if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fa-f]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[ee][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof reviver === 'function' ? walk({'': j}, '') : j; } throw new syntaxerror('json.parse(): invalid or malformed json data'); }; } /** * @fileoverview functions for automatically setting up a player * based on the data-setup attribute of the video tag */ // automatically set up any tags that have a data-setup attribute vjs.autosetup = function(){ var options, mediael, player, i, e; // 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 = document.getelementsbytagname('video'); var audios = document.getelementsbytagname('audio'); var mediaels = []; if (vids && vids.length > 0) { for(i=0, e=vids.length; i 0) { for(i=0, e=audios.length; i 0) { for (i=0,e=mediaels.length; i