+ * // -> 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, componentId;
+
+ // If 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 || {};
+
+ // Assume name of set is a lowercased name of the UI Class (PlayButton, etc.)
+ 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, children, child, name, opts;
+
+ parent = this;
+ children = this.options()['children'];
+
+ if (children) {
+ // Allow for an array of children details to passed in the options
+ if (children instanceof Array) {
+ for (var i = 0; i < children.length; i++) {
+ child = children[i];
+
+ if (typeof child == 'string') {
+ name = child;
+ opts = {};
+ } else {
+ name = child.name;
+ opts = child;
+ }
+
+ parent[name] = parent.addChild(name, opts);
+ }
+ } else {
+ vjs.obj.each(children, function (name, opts) {
+ // Allow for disabling default components
+ // e.g. vjs.options['children']['posterImage'] = false
+ if (opts === false) return;
+
+ // Set property name on player. Could cause conflicts with other prop names, but it's worth making refs easy.
+ parent[name] = parent.addChild(name, opts);
+ });
+ }
+ }
+};
+
+/**
+ * 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 myPlayer = this;
+ * // Do something when the event is fired
+ * };
+ *
+ * myPlayer.on("eventName", myFunc);
+ *
+ * The context will be the component.
+ *
+ * @param {String} type The event type e.g. 'click'
+ * @param {Function} fn The event listener
+ * @return {vjs.Component} self
+ */
+vjs.Component.prototype.on = function (type, fn) {
+ vjs.on(this.el_, type, vjs.bind(this, fn));
+ return this;
+};
+
+/**
+ * Remove an event listener from the component's element
+ *
+ * myComponent.off("eventName", myFunc);
+ *
+ * @param {String=} type Event type. Without type it will remove all listeners.
+ * @param {Function=} fn Event listener. Without fn it will remove all listeners for a type.
+ * @return {vjs.Component}
+ */
+vjs.Component.prototype.off = function (type, fn) {
+ vjs.off(this.el_, type, fn);
+ return this;
+};
+
+/**
+ * Add an event listener to be triggered only once and then removed
+ *
+ * @param {String} type Event type
+ * @param {Function} fn Event listener
+ * @return {vjs.Component}
+ */
+vjs.Component.prototype.one = function (type, fn) {
+ vjs.one(this.el_, type, vjs.bind(this, fn));
+ return this;
+};
+
+/**
+ * Trigger an event on an element
+ *
+ * myComponent.trigger('eventName');
+ *
+ * @param {String} type The event type to trigger, e.g. 'click'
+ * @param {Event|Object} event The event object to be passed to the listener
+ * @return {vjs.Component} self
+ */
+vjs.Component.prototype.trigger = function (type, event) {
+ vjs.trigger(this.el_, type, 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 asynchrnously 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 happend
+ * 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
+ ============================================================================= */
+
+/**
+ * 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 movign 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) {
+
+ // 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 requireing 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;
+
+ // 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
+ clearInterval(touchHolding);
+ // report at the same interval as activityCheck
+ touchHolding = setInterval(report, 250);
+ });
+
+ touchEnd = function (event) {
+ report();
+ // stop the interval that maintains activity if the touch is holding
+ clearInterval(touchHolding);
+ };
+
+ this.on('touchmove', report);
+ this.on('touchend', touchEnd);
+ this.on('touchcancel', touchEnd);
+};
+
+/* 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.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, 'keyup', 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, 'keyup', 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.player_.on('controlsvisible', vjs.bind(this, this.update));
+
+ player.on(this.playerEvent, vjs.bind(this, this.update));
+
+ this.boundEvents = {};
+ }
+});
+
+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.boundEvents.move = vjs.bind(this, this.onMouseMove);
+ this.boundEvents.end = vjs.bind(this, this.onMouseUp);
+
+ vjs.on(document, 'mousemove', this.boundEvents.move);
+ vjs.on(document, 'mouseup', this.boundEvents.end);
+ vjs.on(document, 'touchmove', this.boundEvents.move);
+ vjs.on(document, 'touchend', this.boundEvents.end);
+
+ this.onMouseMove(event);
+};
+
+vjs.Slider.prototype.onMouseUp = function () {
+ vjs.unblockTextSelection();
+ vjs.off(document, 'mousemove', this.boundEvents.move, false);
+ vjs.off(document, 'mouseup', this.boundEvents.end, false);
+ vjs.off(document, 'touchmove', this.boundEvents.move, false);
+ vjs.off(document, 'touchend', this.boundEvents.end, false);
+
+ 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
+ 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 () {
+ vjs.on(document, 'keyup', vjs.bind(this, this.onKeyPress));
+};
+
+vjs.Slider.prototype.onKeyPress = function (event) {
+ if (event.which == 37) { // Left Arrow
+ event.preventDefault();
+ this.stepBack();
+ } else if (event.which == 39) { // Right Arrow
+ event.preventDefault();
+ this.stepForward();
+ }
+};
+
+vjs.Slider.prototype.onBlur = function () {
+ vjs.off(document, 'keyup', vjs.bind(this, 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: '
'
+ }, 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.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('keyup', 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-specifc 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 < apiMap.length; i++) {
+ // check for exitFullscreen function
+ if (apiMap[i][1] in document) {
+ browserApi = apiMap[i];
+ break;
+ }
+ }
+
+ // map the browser API names to the spec API names
+ // or leave vjs.browser.fullscreenAPI undefined
+ if (browserApi) {
+ vjs.browser.fullscreenAPI = {};
+
+ for (i = 0; i < browserApi.length; i++) {
+ vjs.browser.fullscreenAPI[specApi[i]] = browserApi[i];
+ }
+ }
+
+})();
+/**
+ * An instance of the `vjs.Player` class is created when any of the Video.js setup methods are used to initialize a video.
+ *
+ * ```js
+ * var myPlayer = videojs('example_video_1');
+ * ```
+ *
+ * In the follwing example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready.
+ *
+ * ```html
+ *
+ * ```
+ *
+ * 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++;
+
+ // 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);
+
+ // 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;
+
+ // 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');
+ }
+
+ // 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();
+ }
+});
+
+/**
+ * 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;
+ }
+
+ // Ensure that tracking progress and time progress will stop and plater deleted
+ this.stopTrackingProgress();
+ this.stopTrackingCurrentTime();
+
+ if (this.tech) {
+ this.tech.dispose();
+ }
+
+ // Component dispose
+ vjs.Component.prototype.dispose.call(this);
+};
+
+vjs.Player.prototype.getTagSettings = function (tag) {
+ var options = {
+ 'sources': [],
+ 'tracks': []
+ };
+
+ vjs.obj.merge(options, vjs.getAttributeValues(tag));
+
+ // Get tag children settings
+ if (tag.hasChildNodes()) {
+ var children, child, childName, i, j;
+
+ children = tag.childNodes;
+
+ for (i = 0, j = children.length; i < j; i++) {
+ child = children[i];
+ // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/
+ childName = child.nodeName.toLowerCase();
+ if (childName === 'source') {
+ options['sources'].push(vjs.getAttributeValues(child));
+ } else if (childName === 'track') {
+ options['tracks'].push(vjs.getAttributeValues(child));
+ }
+ }
+ }
+
+ return options;
+};
+
+vjs.Player.prototype.createEl = function () {
+ var el = this.el_ = vjs.Component.prototype.createEl.call(this, 'div');
+ var tag = this.tag;
+
+ // Remove width/height attrs from tag so CSS can make it 100% width/height
+ tag.removeAttribute('width');
+ tag.removeAttribute('height');
+ // Empty video tag tracks so the built-in player doesn't use them also.
+ // This may not be fast enough to stop HTML5 browsers from reading the tags
+ // so we'll need to turn off any default tracks if we're manually doing
+ // captions and subtitles. videoElement.textTracks
+ if (tag.hasChildNodes()) {
+ var nodes, nodesLength, i, node, nodeName, removeNodes;
+
+ nodes = tag.childNodes;
+ nodesLength = nodes.length;
+ removeNodes = [];
+
+ while (nodesLength--) {
+ node = nodes[nodesLength];
+ nodeName = node.nodeName.toLowerCase();
+ if (nodeName === 'track') {
+ removeNodes.push(node);
+ }
+ }
+
+ for (i = 0; i < removeNodes.length; i++) {
+ tag.removeChild(removeNodes[i]);
+ }
+ }
+
+ // Give video tag ID and class to player div
+ // ID will now reference player box, not the video tag
+ el.id = tag.id;
+ el.className = tag.className;
+
+ // Update tag id/class for use as HTML5 playback tech
+ // Might think we should do this after embedding in container so .vjs-tech class
+ // doesn't flash 100% width/height, but class only applies with .video-js parent
+ tag.id += '_html5_api';
+ tag.className = 'vjs-tech';
+
+ // Make player findable on elements
+ tag['player'] = el['player'] = this;
+ // Default state of video is paused
+ this.addClass('vjs-paused');
+
+ // Make box use width/height of tag, or rely on default implementation
+ // Enforce with CSS since width/height attrs don't work on divs
+ this.width(this.options_['width'], true); // (true) Skip resize listener on load
+ this.height(this.options_['height'], true);
+
+ // Wrap video tag in div (el/box) container
+ if (tag.parentNode) {
+ tag.parentNode.insertBefore(el, tag);
+ }
+ vjs.insertFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup.
+
+ // The event listeners need to be added before the children are added
+ // in the component init because the tech (loaded with mediaLoader) may
+ // fire events, like loadstart, that these events need to capture.
+ // Long term it might be better to expose a way to do this in component.init
+ // like component.initEventListeners() that runs between el creation and
+ // adding children
+ this.el_ = el;
+ this.on('loadstart', this.onLoadStart);
+ this.on('ended', this.onEnded);
+ this.on('play', this.onPlay);
+ this.on('firstplay', this.onFirstPlay);
+ this.on('pause', this.onPause);
+ this.on('progress', this.onProgress);
+ this.on('durationchange', this.onDurationChange);
+ this.on('fullscreenchange', this.onFullscreenChange);
+
+ return el;
+};
+
+// /* Media Technology (tech)
+// ================================================================================ */
+// Load/Create an instance of playback technlogy including element and API methods
+// And append playback element in player div.
+vjs.Player.prototype.loadTech = function (techName, source) {
+
+ // Pause and remove current playback technology
+ if (this.tech) {
+ this.unloadTech();
+ }
+
+ // get rid of the HTML5 video tag as soon as we are using another tech
+ if (techName !== 'Html5' && this.tag) {
+ vjs.Html5.disposeMediaElement(this.tag);
+ this.tag = null;
+ }
+
+ this.techName = techName;
+
+ // Turn off API access because we're loading a new tech that might load asynchronously
+ this.isReady_ = false;
+
+ var techReady = function () {
+ this.player_.triggerReady();
+
+ // Manually track progress in cases where the browser/flash player doesn't report it.
+ if (!this.features['progressEvents']) {
+ this.player_.manualProgressOn();
+ }
+
+ // Manually track timeudpates in cases where the browser/flash player doesn't report it.
+ if (!this.features['timeupdateEvents']) {
+ this.player_.manualTimeUpdatesOn();
+ }
+ };
+
+ // Grab tech-specific options from player options and add source and parent element to use.
+ var techOptions = vjs.obj.merge({ 'source': source, 'parentEl': this.el_ }, this.options_[techName.toLowerCase()]);
+
+ if (source) {
+ if (source.src == this.cache_.src && this.cache_.currentTime > 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();
+
+ // Turn off any manual progress or timeupdate tracking
+ if (this.manualProgress) {
+ this.manualProgressOff();
+ }
+
+ if (this.manualTimeUpdates) {
+ this.manualTimeUpdatesOff();
+ }
+
+ 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')
+// },
+
+/* 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.Player.prototype.manualProgressOn = function () {
+ this.manualProgress = true;
+
+ // Trigger progress watching when a source begins loading
+ this.trackProgress();
+
+ // Watch for a native progress event call on the tech element
+ // In HTML5, some older versions don't support the progress event
+ // So we're assuming they don't, and turning off manual progress if they do.
+ // As opposed to doing user agent detection
+ if (this.tech) {
+ this.tech.one('progress', function () {
+
+ // Update known progress support for this playback technology
+ this.features['progressEvents'] = true;
+
+ // Turn off manual progress tracking
+ this.player_.manualProgressOff();
+ });
+ }
+};
+
+vjs.Player.prototype.manualProgressOff = function () {
+ this.manualProgress = false;
+ this.stopTrackingProgress();
+};
+
+vjs.Player.prototype.trackProgress = function () {
+
+ this.progressInterval = setInterval(vjs.bind(this, function () {
+ // Don't trigger unless buffered amount is greater than last time
+ // log(this.cache_.bufferEnd, this.buffered().end(0), this.duration())
+ /* TODO: update for multiple buffered regions */
+ if (this.cache_.bufferEnd < this.buffered().end(0)) {
+ this.trigger('progress');
+ } else if (this.bufferedPercent() == 1) {
+ this.stopTrackingProgress();
+ this.trigger('progress'); // Last update
+ }
+ }), 500);
+};
+vjs.Player.prototype.stopTrackingProgress = function () {
+ clearInterval(this.progressInterval);
+};
+
+/*! Time Tracking -------------------------------------------------------------- */
+vjs.Player.prototype.manualTimeUpdatesOn = function () {
+ this.manualTimeUpdates = true;
+
+ this.on('play', this.trackCurrentTime);
+ this.on('pause', this.stopTrackingCurrentTime);
+ // timeupdate is also called by .currentTime whenever current time is set
+
+ // Watch for native timeupdate event
+ if (this.tech) {
+ this.tech.one('timeupdate', function () {
+ // Update known progress support for this playback technology
+ this.features['timeupdateEvents'] = true;
+ // Turn off manual progress tracking
+ this.player_.manualTimeUpdatesOff();
+ });
+ }
+};
+
+vjs.Player.prototype.manualTimeUpdatesOff = function () {
+ this.manualTimeUpdates = false;
+ this.stopTrackingCurrentTime();
+ this.off('play', this.trackCurrentTime);
+ this.off('pause', this.stopTrackingCurrentTime);
+};
+
+vjs.Player.prototype.trackCurrentTime = function () {
+ if (this.currentTimeInterval) {
+ this.stopTrackingCurrentTime();
+ }
+ this.currentTimeInterval = setInterval(vjs.bind(this, function () {
+ this.trigger('timeupdate');
+ }), 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
+};
+
+// Turn off play progress tracking (when paused or dragging)
+vjs.Player.prototype.stopTrackingCurrentTime = function () {
+ clearInterval(this.currentTimeInterval);
+
+ // #1002 - if the video ends right before the next timeupdate would happen,
+ // the progress bar won't make it all the way to the end
+ this.trigger('timeupdate');
+};
+// /* 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 () {
+ vjs.removeClass(this.el_, 'vjs-paused');
+ vjs.addClass(this.el_, 'vjs-playing');
+};
+
+/**
+ * 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 () {
+ vjs.removeClass(this.el_, 'vjs-playing');
+ vjs.addClass(this.el_, 'vjs-paused');
+};
+
+/**
+ * Fired when the current playback position has changed
+ *
+ * During playback this is fired every 15-250 milliseconds, depnding 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();
+ }
+};
+
+/**
+ * Fired when the duration of the media resource is first known or changed
+ * @event durationchange
+ */
+vjs.Player.prototype.onDurationChange = function () {
+ // Allows for cacheing 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);
+
+ // improve the accuracy of manual timeupdates
+ if (this.manualTimeUpdates) {
+ this.trigger('timeupdate');
+ }
+
+ 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 performace 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 optimiized 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. Not in spec, but useful.
+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.
+// So far no browsers return more than one range (portion)
+
+/**
+ * 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'),
+ start = 0,
+ buflast = buffered.length - 1,
+ // Default end to 0 and store in values
+ end = this.cache_.bufferEnd = this.cache_.bufferEnd || 0;
+
+ if (buffered && buflast >= 0 && buffered.end(buflast) !== end) {
+ end = buffered.end(buflast);
+ // Storing values allows them be overridden by setBufferedFromProgress
+ this.cache_.bufferEnd = end;
+ }
+
+ return vjs.createTimeRange(start, end);
+};
+
+/**
+ * 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 () {
+ return (this.duration()) ? this.buffered().end(0) / this.duration() : 0;
+};
+
+/**
+ * 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 lik 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 cancelling 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 < j.length; i++) {
+ var techName = vjs.capitalize(j[i]),
+ tech = window['videojs'][techName];
+
+ // Check if the current tech is defined before continuing
+ if (!tech) {
+ vjs.log.error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.');
+ continue;
+ }
+
+ // Check if the browser supports this technology
+ if (tech.isSupported()) {
+ // Loop through each source object
+ for (var a = 0, b = sources; a < b.length; a++) {
+ var source = b[a];
+
+ // Check if source can be played with this technology
+ if (tech['canPlaySource'](source)) {
+ return { source: source, tech: techName };
+ }
+ }
+ }
+ }
+
+ return false;
+};
+
+/**
+ * The source function updates the video source
+ *
+ * There are three types of variables you can pass as the argument.
+ *
+ * **URL String**: A URL to the the video file. Use this method if you are sure
+ * the current playback technology (HTML5/Flash) can support the source you
+ * provide. Currently only MP4 files can be used in both HTML5 and Flash.
+ *
+ * myPlayer.src("http://www.example.com/path/to/video.mp4");
+ *
+ * **Source Object (or element):** A javascript object containing information
+ * about the source file. Use this method if you want the player to determine if
+ * it can support the file using the type information.
+ *
+ * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" });
+ *
+ * **Array of Source Objects:** To provide multiple versions of the source so
+ * that it can be played using HTML5 across browsers you can use an array of
+ * source objects. Video.js will detect which version is supported and load that
+ * file.
+ *
+ * myPlayer.src([
+ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" },
+ * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" },
+ * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" }
+ * ]);
+ *
+ * @param {String|Object|Array=} source The source URL, object, or array of sources
+ * @return {String} The current video source when getting
+ * @return {String} The player when setting
+ */
+vjs.Player.prototype.src = function (source) {
+ if (source === undefined) {
+ return this.techGet('src');
+ }
+
+ // Case: Array of source objects to choose from and pick the best to play
+ if (source instanceof Array) {
+
+ var sourceTech = this.selectSource(source),
+ techName;
+
+ if (sourceTech) {
+ source = sourceTech.source;
+ techName = sourceTech.tech;
+
+ // If this technology is already loaded, set source
+ if (techName == this.techName) {
+ this.src(source); // Passing the source object
+ // Otherwise load this technology with chosen source
+ } else {
+ this.loadTech(techName, source);
+ }
+ } else {
+ // this.el_.appendChild(vjs.createEl('p', {
+ // innerHTML: this.options()['notSupportedMessage']
+ // }));
+ this.error({ code: 4, message: this.options()['notSupportedMessage'] });
+ this.triggerReady(); // we could not find an appropriate tech, but let's still notify the delegate that this is it
+ }
+
+ // Case: Source object { src: '', type: '' ... }
+ } else if (source instanceof Object) {
+
+ if (window['videojs'][this.techName]['canPlaySource'](source)) {
+ this.src(source.src);
+ } else {
+ // Send through tech loop to check for a compatible technology.
+ this.src([source]);
+ }
+
+ // Case: URL String (http://myvideo...)
+ } else {
+ // Cache for getting last set source
+ this.cache_.src = source;
+
+ if (!this.isReady_) {
+ this.ready(function () {
+ this.src(source);
+ });
+ } else {
+ this.techCall('src', source);
+ if (this.options_['preload'] == 'auto') {
+ this.load();
+ }
+ if (this.options_['autoplay']) {
+ this.play();
+ }
+ }
+ }
+
+ return this;
+};
+
+// Begin loading the src data
+// http://dev.w3.org/html5/spec/video.html#dom-media-load
+vjs.Player.prototype.load = function () {
+ this.techCall('load');
+ return this;
+};
+
+// http://dev.w3.org/html5/spec/video.html#dom-media-currentsrc
+vjs.Player.prototype.currentSrc = function () {
+ return this.techGet('currentSrc') || this.cache_.src || '';
+};
+
+// Attributes/Options
+vjs.Player.prototype.preload = function (value) {
+ if (value !== undefined) {
+ this.techCall('setPreload', value);
+ this.options_['preload'] = value;
+ return this;
+ }
+ return this.techGet('preload');
+};
+vjs.Player.prototype.autoplay = function (value) {
+ if (value !== undefined) {
+ this.techCall('setAutoplay', value);
+ this.options_['autoplay'] = value;
+ return this;
+ }
+ return this.techGet('autoplay', value);
+};
+vjs.Player.prototype.loop = function (value) {
+ if (value !== undefined) {
+ this.techCall('setLoop', value);
+ this.options_['loop'] = value;
+ return this;
+ }
+ return this.techGet('loop');
+};
+
+/**
+ * the url of the poster image source
+ * @type {String}
+ * @private
+ */
+vjs.Player.prototype.poster_;
+
+/**
+ * get or set the poster image source url
+ *
+ * ##### EXAMPLE:
+ *
+ * // getting
+ * var currentPoster = myPlayer.poster();
+ *
+ * // setting
+ * myPlayer.poster('http://example.com/myImage.jpg');
+ *
+ * @param {String=} [src] Poster image source URL
+ * @return {String} poster URL when getting
+ * @return {vjs.Player} self when setting
+ */
+vjs.Player.prototype.poster = function (src) {
+ if (src === undefined) {
+ return this.poster_;
+ }
+
+ // update the internal poster variable
+ this.poster_ = src;
+
+ // update the tech's poster
+ this.techCall('setPoster', src);
+
+ // alert components that the poster has been set
+ this.trigger('posterchange');
+};
+
+/**
+ * Whether or not the controls are showing
+ * @type {Boolean}
+ * @private
+ */
+vjs.Player.prototype.controls_;
+
+/**
+ * Get or set whether or not the controls are showing.
+ * @param {Boolean} controls Set controls to showing or not
+ * @return {Boolean} Controls are showing
+ */
+vjs.Player.prototype.controls = function (bool) {
+ if (bool !== undefined) {
+ bool = !!bool; // force boolean
+ // Don't trigger a change event unless it actually changed
+ if (this.controls_ !== bool) {
+ this.controls_ = bool;
+ if (bool) {
+ this.removeClass('vjs-controls-disabled');
+ this.addClass('vjs-controls-enabled');
+ this.trigger('controlsenabled');
+ } else {
+ this.removeClass('vjs-controls-enabled');
+ this.addClass('vjs-controls-disabled');
+ this.trigger('controlsdisabled');
+ }
+ }
+ return this;
+ }
+ return this.controls_;
+};
+
+vjs.Player.prototype.usingNativeControls_;
+
+/**
+ * Toggle native controls on/off. Native controls are the controls built into
+ * devices (e.g. default iPhone controls), Flash, or other techs
+ * (e.g. Vimeo Controls)
+ *
+ * **This should only be set by the current tech, because only the tech knows
+ * if it can support native controls**
+ *
+ * @param {Boolean} bool True signals that native controls are on
+ * @return {vjs.Player} Returns the player
+ * @private
+ */
+vjs.Player.prototype.usingNativeControls = function (bool) {
+ if (bool !== undefined) {
+ bool = !!bool; // force boolean
+ // Don't trigger a change event unless it actually changed
+ if (this.usingNativeControls_ !== bool) {
+ this.usingNativeControls_ = bool;
+ if (bool) {
+ this.addClass('vjs-using-native-controls');
+
+ /**
+ * player is using the native device controls
+ *
+ * @event usingnativecontrols
+ * @memberof vjs.Player
+ * @instance
+ * @private
+ */
+ this.trigger('usingnativecontrols');
+ } else {
+ this.removeClass('vjs-using-native-controls');
+
+ /**
+ * player is using the custom HTML controls
+ *
+ * @event usingcustomcontrols
+ * @memberof vjs.Player
+ * @instance
+ * @private
+ */
+ this.trigger('usingcustomcontrols');
+ }
+ }
+ return this;
+ }
+ return this.usingNativeControls_;
+};
+
+/**
+ * Store the current media error
+ * @type {Object}
+ * @private
+ */
+vjs.Player.prototype.error_ = null;
+
+/**
+ * Set or get the current MediaError
+ * @param {*} err A MediaError or a String/Number to be turned into a MediaError
+ * @return {vjs.MediaError|null} when getting
+ * @return {vjs.Player} when setting
+ */
+vjs.Player.prototype.error = function (err) {
+ if (err === undefined) {
+ return this.error_;
+ }
+
+ // restoring to default
+ if (err === null) {
+ this.error_ = err;
+ this.removeClass('vjs-error');
+ return this;
+ }
+
+ // error instance
+ if (err instanceof vjs.MediaError) {
+ this.error_ = err;
+ } else {
+ this.error_ = new vjs.MediaError(err);
+ }
+
+ // fire an error event on the player
+ this.trigger('error');
+
+ // add the vjs-error classname to the player
+ this.addClass('vjs-error');
+
+ // log the name of the error type and any message
+ // ie8 just logs "[object object]" if you just log the error object
+ vjs.log.error('(CODE:' + this.error_.code + ' ' + vjs.MediaError.errorTypes[this.error_.code] + ')', this.error_.message, this.error_);
+
+ return this;
+};
+
+vjs.Player.prototype.ended = function () {
+ return this.techGet('ended');
+};
+vjs.Player.prototype.seeking = function () {
+ return this.techGet('seeking');
+};
+
+// When the player is first initialized, trigger activity so components
+// like the control bar show themselves if needed
+vjs.Player.prototype.userActivity_ = true;
+vjs.Player.prototype.reportUserActivity = function (event) {
+ this.userActivity_ = true;
+};
+
+vjs.Player.prototype.userActive_ = true;
+vjs.Player.prototype.userActive = function (bool) {
+ if (bool !== undefined) {
+ bool = !!bool;
+ if (bool !== this.userActive_) {
+ this.userActive_ = bool;
+ if (bool) {
+ // If the user was inactive and is now active we want to reset the
+ // inactivity timer
+ this.userActivity_ = true;
+ this.removeClass('vjs-user-inactive');
+ this.addClass('vjs-user-active');
+ this.trigger('useractive');
+ } else {
+ // We're switching the state to inactive manually, so erase any other
+ // activity
+ this.userActivity_ = false;
+
+ // Chrome/Safari/IE have bugs where when you change the cursor it can
+ // trigger a mousemove event. This causes an issue when you're hiding
+ // the cursor when the user is inactive, and a mousemove signals user
+ // activity. Making it impossible to go into inactive mode. Specifically
+ // this happens in fullscreen when we really need to hide the cursor.
+ //
+ // When this gets resolved in ALL browsers it can be removed
+ // https://code.google.com/p/chromium/issues/detail?id=103041
+ if (this.tech) {
+ this.tech.one('mousemove', function (e) {
+ e.stopPropagation();
+ e.preventDefault();
+ });
+ }
+
+ this.removeClass('vjs-user-active');
+ this.addClass('vjs-user-inactive');
+ this.trigger('userinactive');
+ }
+ }
+ return this;
+ }
+ return this.userActive_;
+};
+
+vjs.Player.prototype.listenForUserActivity = function () {
+ var onActivity, onMouseMove, onMouseDown, mouseInProgress, onMouseUp,
+ activityCheck, inactivityTimeout, lastMoveX, lastMoveY;
+
+ onActivity = vjs.bind(this, this.reportUserActivity);
+
+ onMouseMove = function (e) {
+ // #1068 - Prevent mousemove spamming
+ // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970
+ if (e.screenX != lastMoveX || e.screenY != lastMoveY) {
+ lastMoveX = e.screenX;
+ lastMoveY = e.screenY;
+ onActivity();
+ }
+ };
+
+ onMouseDown = function () {
+ onActivity();
+ // 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
+ clearInterval(mouseInProgress);
+ // Setting userActivity=true now and setting the interval to the same time
+ // as the activityCheck interval (250) should ensure we never miss the
+ // next activityCheck
+ mouseInProgress = setInterval(onActivity, 250);
+ };
+
+ onMouseUp = function (event) {
+ onActivity();
+ // Stop the interval that maintains activity if the mouse/touch is down
+ clearInterval(mouseInProgress);
+ };
+
+ // Any mouse movement will be considered user activity
+ this.on('mousedown', onMouseDown);
+ this.on('mousemove', onMouseMove);
+ this.on('mouseup', onMouseUp);
+
+ // Listen for keyboard navigation
+ // Shouldn't need to use inProgress interval because of key repeat
+ this.on('keydown', onActivity);
+ this.on('keyup', onActivity);
+
+ // Run an interval every 250 milliseconds instead of stuffing everything into
+ // the mousemove/touchmove function itself, to prevent performance degradation.
+ // `this.reportUserActivity` simply sets this.userActivity_ to true, which
+ // then gets picked up by this loop
+ // http://ejohn.org/blog/learning-from-twitter/
+ activityCheck = setInterval(vjs.bind(this, function () {
+ // Check to see if mouse/touch activity has happened
+ if (this.userActivity_) {
+ // Reset the activity tracker
+ this.userActivity_ = false;
+
+ // If the user state was inactive, set the state to active
+ this.userActive(true);
+
+ // Clear any existing inactivity timeout to start the timer over
+ clearTimeout(inactivityTimeout);
+
+ // In X seconds, if no more activity has occurred the user will be
+ // considered inactive
+ inactivityTimeout = setTimeout(vjs.bind(this, 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);
+ }
+ }), 2000);
+ }
+ }), 250);
+
+ // Clean up the intervals when we kill the player
+ this.on('dispose', function () {
+ clearInterval(activityCheck);
+ clearTimeout(inactivityTimeout);
+ });
+};
+
+vjs.Player.prototype.playbackRate = function (rate) {
+ if (rate !== undefined) {
+ this.techCall('setPlaybackRate', rate);
+ return this;
+ }
+
+ if (this.tech && this.tech.features && this.tech.features['playbackRate']) {
+ return this.techGet('playbackRate');
+ } else {
+ return 1.0;
+ }
+
+};
+
+// 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: 'Stream Type 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);
+
+ player.on('play', vjs.bind(this, this.onPlay));
+ player.on('pause', vjs.bind(this, 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 () {
+ vjs.removeClass(this.el_, 'vjs-paused');
+ vjs.addClass(this.el_, 'vjs-playing');
+ this.el_.children[0].children[0].innerHTML = '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 () {
+ vjs.removeClass(this.el_, 'vjs-playing');
+ vjs.addClass(this.el_, 'vjs-paused');
+ this.el_.children[0].children[0].innerHTML = '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);
+
+ player.on('timeupdate', vjs.bind(this, 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 = '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.
+ player.on('timeupdate', vjs.bind(this, 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: '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 = '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);
+
+ player.on('timeupdate', vjs.bind(this, 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: '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 = '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 = 'Non-Fullscreen';
+ } else {
+ this.player_.exitFullscreen();
+ this.controlText_.innerHTML = '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);
+ player.on('timeupdate', vjs.bind(this, 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);
+ player.on('progress', vjs.bind(this, this.update));
+ }
+});
+
+vjs.LoadProgressBar.prototype.createEl = function () {
+ return vjs.Component.prototype.createEl.call(this, 'div', {
+ className: 'vjs-load-progress',
+ innerHTML: 'Loaded: 0%'
+ });
+};
+
+vjs.LoadProgressBar.prototype.update = function () {
+ if (this.el_.style) {
+ this.el_.style.width = vjs.round(this.player_.bufferedPercent() * 100, 2) + '%';
+ }
+};
+
+
+/**
+ * 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: '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);
+ player.on('timeupdate', vjs.bind(this, 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.features && player.tech.features['volumeControl'] === false) {
+ this.addClass('vjs-hidden');
+ }
+ player.on('loadstart', vjs.bind(this, function () {
+ if (player.tech.features && player.tech.features['volumeControl'] === 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);
+ player.on('volumechange', vjs.bind(this, 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);
+
+ player.on('volumechange', vjs.bind(this, this.update));
+
+ // hide mute toggle if the current tech doesn't support volume control
+ if (player.tech && player.tech.features && player.tech.features['volumeControl'] === false) {
+ this.addClass('vjs-hidden');
+ }
+ player.on('loadstart', vjs.bind(this, function () {
+ if (player.tech.features && player.tech.features['volumeControl'] === 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: '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 != 'Unmute') {
+ this.el_.children[0].children[0].innerHTML = 'Unmute'; // change the button text to "Unmute"
+ }
+ } else {
+ if (this.el_.children[0].children[0].innerHTML != 'Mute') {
+ this.el_.children[0].children[0].innerHTML = '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
+ player.on('volumechange', vjs.bind(this, this.update));
+
+ // hide mute toggle if the current tech doesn't support volume control
+ if (player.tech && player.tech.features && player.tech.features.volumeControl === false) {
+ this.addClass('vjs-hidden');
+ }
+ player.on('loadstart', vjs.bind(this, function () {
+ if (player.tech.features && player.tech.features.volumeControl === 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_, vjs.obj.merge({vertical: true}, this.options_.volumeBar));
+ 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: '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();
+
+ player.on('loadstart', vjs.bind(this, this.updateVisibility));
+ player.on('ratechange', vjs.bind(this, this.updateLabel));
+ }
+});
+
+vjs.PlaybackRateMenuButton.prototype.createEl = function () {
+ var el = vjs.Component.prototype.createEl.call(this, 'div', {
+ className: 'vjs-playback-rate vjs-menu-button vjs-control',
+ innerHTML: 'Playback Rate
'
+ });
+
+ 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 < rates.length; i++) {
+ if (rates[i] > currentRate) {
+ newRate = rates[i];
+ break;
+ }
+ }
+ ;
+ this.player().playbackRate(newRate);
+};
+
+vjs.PlaybackRateMenuButton.prototype.playbackRateSupported = function () {
+ return this.player().tech
+ && this.player().tech.features['playbackRate']
+ && 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.player().on('ratechange', vjs.bind(this, 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);
+
+ if (player.poster()) {
+ this.src(player.poster());
+ }
+
+ if (!player.poster() || !player.controls()) {
+ this.hide();
+ }
+
+ player.on('posterchange', vjs.bind(this, function () {
+ this.src(player.poster());
+ }));
+
+ player.on('play', vjs.bind(this, this.hide));
+ }
+});
+
+// use the test el to check for backgroundSize style support
+var _backgroundSizeSupported = 'backgroundSize' in vjs.TEST_VID.style;
+
+vjs.PosterImage.prototype.createEl = function () {
+ var el = vjs.createEl('div', {
+ className: 'vjs-poster',
+
+ // Don't want poster to be tabbable.
+ tabIndex: -1
+ });
+
+ if (!_backgroundSizeSupported) {
+ // setup an img element as a fallback for IE8
+ el.appendChild(vjs.createEl('img'));
+ }
+
+ return el;
+};
+
+vjs.PosterImage.prototype.src = function (url) {
+ var el = this.el();
+
+ // getter
+ // can't think of a need for a getter here
+ // see #838 if on is needed in the future
+ // still don't want a getter to set src as undefined
+ if (url === undefined) {
+ return;
+ }
+
+ // setter
+ // 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 (_backgroundSizeSupported) {
+ el.style.backgroundImage = 'url("' + url + '")';
+ } else {
+ el.firstChild.src = url;
+ }
+};
+
+vjs.PosterImage.prototype.onClick = function () {
+ // Only accept clicks when controls are enabled
+ if (this.player().controls()) {
+ 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);
+
+ 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();
+ player.on('error', vjs.bind(this, 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.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);
+
+ 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, tech, activateControls, deactivateControls;
+
+ tech = this;
+ player = this.player();
+
+ var activateControls = function () {
+ if (player.controls() && !player.usingNativeControls()) {
+ tech.addControlsListeners();
+ }
+ };
+
+ deactivateControls = vjs.bind(tech, tech.removeControlsListeners);
+
+ // Set up event listeners once the tech is ready and has an element to apply
+ // listeners to
+ this.ready(activateControls);
+ player.on('controlsenabled', activateControls);
+ player.on('controlsdisabled', deactivateControls);
+};
+
+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) {
+ // Stop the mouse events from also happening
+ event.preventDefault();
+ userWasActive = this.player_.userActive();
+ });
+
+ this.on('touchmove', function (event) {
+ if (userWasActive) {
+ this.player().reportUserActivity();
+ }
+ });
+
+ // 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());
+};
+
+/**
+ * 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.features = {
+ 'volumeControl': true,
+
+ // Resizing plugins using request fullscreen reloads the plugin
+ 'fullscreenResize': false,
+ 'playbackRate': false,
+
+ // Optional events that we can manually mimic with timers
+ // currently not triggered by video-js-swf
+ 'progressEvents': false,
+ 'timeupdateEvents': false
+};
+
+vjs.media = {};
+
+/**
+ * List of default API methods for any MediaTechController
+ * @type {String}
+ */
+vjs.media.ApiMethods = 'play,pause,paused,currentTime,setCurrentTime,duration,buffered,volume,setVolume,muted,setMuted,width,height,supportsFullScreen,enterFullScreen,src,load,currentSrc,preload,setPreload,autoplay,setAutoplay,loop,setLoop,error,networkState,readyState,seeking,initialTime,startOffsetTime,played,seekable,ended,videoTracks,audioTracks,videoWidth,videoHeight,textTracks,defaultPlaybackRate,playbackRate,mediaGroup,controller,controls,defaultMuted'.split(',');
+// Create placeholder methods for each that warn when a method isn't supported by the current playback technology
+
+function createMethod(methodName) {
+ return function () {
+ throw new Error('The "' + methodName + '" method is not available on the playback technology\'s API');
+ };
+}
+
+for (var i = vjs.media.ApiMethods.length - 1; i >= 0; i--) {
+ var methodName = vjs.media.ApiMethods[i];
+ vjs.MediaTechController.prototype[vjs.media.ApiMethods[i]] = createMethod(methodName);
+}
+/**
+ * @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) {
+ // volume cannot be changed from 1 on iOS
+ this.features['volumeControl'] = vjs.Html5.canControlVolume();
+
+ // just in case; or is it excessively...
+ this.features['playbackRate'] = vjs.Html5.canControlPlaybackRate();
+
+ // In iOS, if you move a video element in the DOM, it breaks video playback.
+ this.features['movingMediaElementInDOM'] = !vjs.IS_IOS;
+
+ // HTML video is able to automatically resize when going to fullscreen
+ this.features['fullscreenResize'] = true;
+
+ vjs.MediaTechController.call(this, player, options, ready);
+ this.setupTriggers();
+
+ var source = options['source'];
+
+ // If the element source is already set, we may have missed the loadstart event, and want to trigger it.
+ // We don't want to set the source again and interrupt playback.
+ if (source && this.el_.currentSrc === source.src && this.el_.networkState > 0) {
+ player.trigger('loadstart');
+ // Otherwise set the source if one was provided.
+ } else if (source) {
+ this.el_.src = source.src;
+ }
+
+ // 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'] !== false) {
+ 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.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.features['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', {
+ id: player.id() + '_html5_api',
+ className: '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 attrs = ['autoplay', 'preload', 'loop', 'muted'];
+ for (var i = attrs.length - 1; i >= 0; i--) {
+ var attr = attrs[i];
+ if (player.options_[attr] !== null) {
+ el[attr] = player.options_[attr];
+ }
+ }
+
+ 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--) {
+ vjs.on(this.el_, vjs.Html5.Events[i], vjs.bind(this, this.eventHandler));
+ }
+};
+
+vjs.Html5.prototype.eventHandler = function (evt) {
+ // In the case of an error, set the error prop on the player
+ // and let the player handle triggering the event.
+ if (evt.type == '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 (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
+ setTimeout(function () {
+ video.pause();
+ video.webkitEnterFullScreen();
+ }, 0);
+ } else {
+ video.webkitEnterFullScreen();
+ }
+};
+vjs.Html5.prototype.exitFullScreen = function () {
+ this.el_.webkitExitFullScreen();
+};
+vjs.Html5.prototype.src = 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;
+};
+
+/* HTML5 Support Testing ---------------------------------------------------- */
+
+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;
+};
+
+vjs.Html5.canPlaySource = function (srcObj) {
+ // IE9 on Windows 7 without MediaPlayer throws an error here
+ // https://github.com/videojs/video.js/issues/519
+ try {
+ return !!vjs.TEST_VID.canPlayType(srcObj.type);
+ } catch (e) {
+ return '';
+ }
+ // TODO: Check Type
+ // If no Type, check ext
+ // Check Media Type
+};
+
+vjs.Html5.canControlVolume = function () {
+ var volume = vjs.TEST_VID.volume;
+ vjs.TEST_VID.volume = (volume / 2) + 0.1;
+ return volume !== vjs.TEST_VID.volume;
+};
+
+vjs.Html5.canControlPlaybackRate = function () {
+ var playbackRate = vjs.TEST_VID.playbackRate;
+ vjs.TEST_VID.playbackRate = (playbackRate / 2) + 0.1;
+ return playbackRate !== vjs.TEST_VID.playbackRate;
+};
+
+// 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 identifty itself
+ 'class': 'vjs-tech'
+ }, options['attributes']),
+
+ lastSeekTarget
+ ;
+
+ // If source was supplied pass as a flash var.
+ if (source) {
+ if (source.type && vjs.Flash.isStreamingType(source.type)) {
+ var parts = vjs.Flash.streamToParts(source.src);
+ flashVars['rtmpConnection'] = encodeURIComponent(parts.connection);
+ flashVars['rtmpStream'] = encodeURIComponent(parts.stream);
+ }
+ else {
+ flashVars['src'] = encodeURIComponent(vjs.getAbsoluteURL(source.src));
+ }
+ }
+
+ this['setCurrentTime'] = function (time) {
+ lastSeekTarget = time;
+ this.el_.vjs_setProperty('currentTime', time);
+ };
+ this['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 lastSeekTarget;
+ }
+ return this.el_.vjs_getProperty('currentTime');
+ };
+
+ // 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 () {
+ vjs.on(this.el(), 'mousemove', vjs.bind(this, function () {
+ // since it's a custom event, don't bubble higher than the player
+ this.player().trigger({ 'type': 'mousemove', 'bubbles': false });
+ }));
+ });
+ }
+
+ // Flash iFrame Mode
+ // In web browsers there are multiple instances where changing the parent element or visibility of a plugin causes the plugin to reload.
+ // - Firefox just about always. https://bugzilla.mozilla.org/show_bug.cgi?id=90268 (might be fixed by version 13)
+ // - Webkit when hiding the plugin
+ // - Webkit and Firefox when using requestFullScreen on a parent element
+ // Loading the flash plugin into a dynamically generated iFrame gets around most of these issues.
+ // Issues that remain include hiding the element and requestFullScreen in Firefox specifically
+
+ // There's on particularly annoying issue with this method which is that Firefox throws a security error on an offsite Flash object loaded into a dynamically created iFrame.
+ // Even though the iframe was inserted into a page on the web, Firefox + Flash considers it a local app trying to access an internet file.
+ // I tried mulitple ways of setting the iframe src attribute but couldn't find a src that worked well. Tried a real/fake source, in/out of domain.
+ // Also tried a method from stackoverflow that caused a security error in all browsers. http://stackoverflow.com/questions/2486901/how-to-set-document-domain-for-a-dynamically-generated-iframe
+ // In the end the solution I found to work was setting the iframe window.location.href right before doing a document.write of the Flash object.
+ // The only downside of this it seems to trigger another http request to the original page (no matter what's put in the href). Not sure why that is.
+
+ // NOTE (2012-01-29): Cannot get Firefox to load the remote hosted SWF into a dynamically created iFrame
+ // Firefox 9 throws a security error, unleess you call location.href right before doc.write.
+ // Not sure why that even works, but it causes the browser to look like it's continuously trying to load the page.
+ // Firefox 3.6 keeps calling the iframe onload function anytime I write to it, causing an endless loop.
+
+ if (options['iFrameMode'] === true && !vjs.IS_FIREFOX) {
+
+ // Create iFrame with vjs-tech class so it's 100% width/height
+ var iFrm = vjs.createEl('iframe', {
+ 'id': objId + '_iframe',
+ 'name': objId + '_iframe',
+ 'className': 'vjs-tech',
+ 'scrolling': 'no',
+ 'marginWidth': 0,
+ 'marginHeight': 0,
+ 'frameBorder': 0
+ });
+
+ // Update ready function names in flash vars for iframe window
+ flashVars['readyFunction'] = 'ready';
+ flashVars['eventProxyFunction'] = 'events';
+ flashVars['errorEventProxyFunction'] = 'errors';
+
+ // Tried multiple methods to get this to work in all browsers
+
+ // Tried embedding the flash object in the page first, and then adding a place holder to the iframe, then replacing the placeholder with the page object.
+ // The goal here was to try to load the swf URL in the parent page first and hope that got around the firefox security error
+ // var newObj = vjs.Flash.embed(options['swf'], placeHolder, flashVars, params, attributes);
+ // (in onload)
+ // var temp = vjs.createEl('a', { id:'asdf', innerHTML: 'asdf' } );
+ // iDoc.body.appendChild(temp);
+
+ // Tried embedding the flash object through javascript in the iframe source.
+ // This works in webkit but still triggers the firefox security error
+ // iFrm.src = 'javascript: document.write('"+vjs.Flash.getEmbedCode(options['swf'], flashVars, params, attributes)+"');";
+
+ // Tried an actual local iframe just to make sure that works, but it kills the easiness of the CDN version if you require the user to host an iframe
+ // We should add an option to host the iframe locally though, because it could help a lot of issues.
+ // iFrm.src = "iframe.html";
+
+ // Wait until iFrame has loaded to write into it.
+ vjs.on(iFrm, 'load', vjs.bind(this, function () {
+
+ var iDoc,
+ iWin = iFrm.contentWindow;
+
+ // The one working method I found was to use the iframe's document.write() to create the swf object
+ // This got around the security issue in all browsers except firefox.
+ // I did find a hack where if I call the iframe's window.location.href='', it would get around the security error
+ // However, the main page would look like it was loading indefinitely (URL bar loading spinner would never stop)
+ // Plus Firefox 3.6 didn't work no matter what I tried.
+ // if (vjs.USER_AGENT.match('Firefox')) {
+ // iWin.location.href = '';
+ // }
+
+ // Get the iFrame's document depending on what the browser supports
+ iDoc = iFrm.contentDocument ? iFrm.contentDocument : iFrm.contentWindow.document;
+
+ // Tried ensuring both document domains were the same, but they already were, so that wasn't the issue.
+ // Even tried adding /. that was mentioned in a browser security writeup
+ // document.domain = document.domain+'/.';
+ // iDoc.domain = document.domain+'/.';
+
+ // Tried adding the object to the iframe doc's innerHTML. Security error in all browsers.
+ // iDoc.body.innerHTML = swfObjectHTML;
+
+ // Tried appending the object to the iframe doc's body. Security error in all browsers.
+ // iDoc.body.appendChild(swfObject);
+
+ // Using document.write actually got around the security error that browsers were throwing.
+ // Again, it's a dynamically generated (same domain) iframe, loading an external Flash swf.
+ // Not sure why that's a security issue, but apparently it is.
+ iDoc.write(vjs.Flash.getEmbedCode(options['swf'], flashVars, params, attributes));
+
+ // Setting variables on the window needs to come after the doc write because otherwise they can get reset in some browsers
+ // So far no issues with swf ready event being called before it's set on the window.
+ iWin['player'] = this.player_;
+
+ // Create swf ready function for iFrame window
+ iWin['ready'] = vjs.bind(this.player_, function (currSwf) {
+ var el = iDoc.getElementById(currSwf),
+ player = this,
+ tech = player.tech;
+
+ // Update reference to playback technology element
+ tech.el_ = el;
+
+ // Make sure swf is actually ready. Sometimes the API isn't actually yet.
+ vjs.Flash.checkReady(tech);
+ });
+
+ // Create event listener for all swf events
+ iWin['events'] = vjs.bind(this.player_, function (swfID, eventName) {
+ var player = this;
+ if (player && player.techName === 'flash') {
+ player.trigger(eventName);
+ }
+ });
+
+ // Create error listener for all swf errors
+ iWin['errors'] = vjs.bind(this.player_, function (swfID, eventName) {
+ vjs.log('Flash Error', eventName);
+ });
+
+ }));
+
+ // Replace placeholder with iFrame (it will load now)
+ placeHolder.parentNode.replaceChild(iFrm, placeHolder);
+
+ // If not using iFrame mode, embed as normal object
+ } else {
+ 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();
+ }
+
+ if (vjs.Flash.isStreamingSrc(src)) {
+ src = vjs.Flash.streamToParts(src);
+ this.setRtmpConnection(src.connection);
+ this.setRtmpStream(src.stream);
+ } else {
+ // Make sure source URL is abosolute.
+ 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;
+ setTimeout(function () {
+ tech.play();
+ }, 0);
+ }
+};
+
+vjs.Flash.prototype.currentSrc = function () {
+ var src = this.el_.vjs_getProperty('currentSrc');
+ // no src, check and see if RTMP
+ if (src == null) {
+ var connection = this['rtmpConnection'](),
+ stream = this['rtmpStream']();
+
+ if (connection && stream) {
+ src = vjs.Flash.streamFromParts(connection, stream);
+ }
+ }
+ return src;
+};
+
+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;
+};
+
+// 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
+
+/**
+ * @this {*}
+ * @private
+ */
+var createSetter = function (attr) {
+ var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1);
+ api['set' + attrUpper] = function (val) {
+ return this.el_.vjs_setProperty(attr, val);
+ };
+};
+
+/**
+ * @this {*}
+ * @private
+ */
+var createGetter = function (attr) {
+ api[attr] = function () {
+ return this.el_.vjs_getProperty(attr);
+ };
+};
+
+(function () {
+ var i;
+ // 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');
+};
+
+vjs.Flash.canPlaySource = function (srcObj) {
+ var type;
+
+ if (!srcObj.type) {
+ return '';
+ }
+
+ type = srcObj.type.replace(/;.*/, '').toLowerCase();
+ if (type in vjs.Flash.formats || type in vjs.Flash.streamingFormats) {
+ return 'maybe';
+ }
+};
+
+vjs.Flash.formats = {
+ 'video/flv': 'FLV',
+ 'video/x-flv': 'FLV',
+ 'video/mp4': 'MP4',
+ 'video/m4v': 'MP4'
+};
+
+vjs.Flash.streamingFormats = {
+ 'rtmp/mp4': 'MP4',
+ 'rtmp/flv': 'FLV'
+};
+
+vjs.Flash['onReady'] = function (currSwf) {
+ var el = vjs.el(currSwf);
+
+ // Get player from box
+ // On firefox reloads, el might already have a player
+ var player = el['player'] || el.parentNode['player'],
+ tech = player.tech;
+
+ // Reference player on tech element
+ el['player'] = player;
+
+ // Update reference to playback technology element
+ tech.el_ = el;
+
+ vjs.Flash.checkReady(tech);
+};
+
+// The SWF isn't alwasy 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) {
+
+ // Check if API property exists
+ if (tech.el().vjs_getProperty) {
+
+ // If so, tell tech it's ready
+ tech.triggerReady();
+
+ // Otherwise wait longer.
+ } else {
+
+ 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.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);
+};
+/**
+ * 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 < j.length; i++) {
+ var techName = vjs.capitalize(j[i]),
+ tech = window['videojs'][techName];
+
+ // Check if the browser supports this technology
+ if (tech && tech.isSupported()) {
+ player.loadTech(techName);
+ break;
+ }
+ }
+ } else {
+ // // Loop through playback technologies (HTML5, Flash) and check for support.
+ // // Then load the best source.
+ // // A few assumptions here:
+ // // All playback technologies respect preload false.
+ player.src(player.options_['sources']);
+ }
+ }
+});
+/**
+ * @fileoverview Text Tracks
+ * Text tracks are tracks of timed text events.
+ * Captions - text displayed over the video for the hearing impared
+ * Subtitles - text displayed over the video for those who don't understand langauge in the video
+ * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video
+ * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device
+ */
+
+// Player Additions - Functions add to the player object for easier access to tracks
+
+/**
+ * List of associated text tracks
+ * @type {Array}
+ * @private
+ */
+vjs.Player.prototype.textTracks_;
+
+/**
+ * Get an array of associated text tracks. captions, subtitles, chapters, descriptions
+ * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks
+ * @return {Array} Array of track objects
+ * @private
+ */
+vjs.Player.prototype.textTracks = function () {
+ this.textTracks_ = this.textTracks_ || [];
+ return this.textTracks_;
+};
+
+/**
+ * Add a text track
+ * In addition to the W3C settings we allow adding additional info through options.
+ * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack
+ * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata
+ * @param {String=} label Optional label
+ * @param {String=} language Optional language
+ * @param {Object=} options Additional track options, like src
+ * @private
+ */
+vjs.Player.prototype.addTextTrack = function (kind, label, language, options) {
+ var tracks = this.textTracks_ = this.textTracks_ || [];
+ options = options || {};
+
+ options['kind'] = kind;
+ options['label'] = label;
+ options['language'] = language;
+
+ // HTML5 Spec says default to subtitles.
+ // Uppercase first letter to match class names
+ var Kind = vjs.capitalize(kind || 'subtitles');
+
+ // Create correct texttrack class. CaptionsTrack, etc.
+ var track = new window['videojs'][Kind + 'Track'](this, options);
+
+ tracks.push(track);
+
+ // If track.dflt() is set, start showing immediately
+ // TODO: Add a process to deterime the best track to show for the specific kind
+ // Incase there are mulitple defaulted tracks of the same kind
+ // Or the user has a set preference of a specific language that should override the default
+ // Note: The setTimeout is a workaround because with the html5 tech, the player is 'ready'
+ // before it's child components (including the textTrackDisplay) have finished loading.
+ if (track.dflt()) {
+ this.ready(function () {
+ setTimeout(function () {
+ track.show();
+ }, 0);
+ });
+ }
+
+ return track;
+};
+
+/**
+ * Add an array of text tracks. captions, subtitles, chapters, descriptions
+ * Track objects will be stored in the player.textTracks() array
+ * @param {Array} trackList Array of track elements or objects (fake track elements)
+ * @private
+ */
+vjs.Player.prototype.addTextTracks = function (trackList) {
+ var trackObj;
+
+ for (var i = 0; i < trackList.length; i++) {
+ trackObj = trackList[i];
+ this.addTextTrack(trackObj['kind'], trackObj['label'], trackObj['language'], trackObj);
+ }
+
+ return this;
+};
+
+// Show a text track
+// disableSameKind: disable all other tracks of the same kind. Value should be a track kind (captions, etc.)
+vjs.Player.prototype.showTextTrack = function (id, disableSameKind) {
+ var tracks = this.textTracks_,
+ i = 0,
+ j = tracks.length,
+ track, showTrack, kind;
+
+ // Find Track with same ID
+ for (; i < j; i++) {
+ track = tracks[i];
+ if (track.id() === id) {
+ track.show();
+ showTrack = track;
+
+ // Disable tracks of the same kind
+ } else if (disableSameKind && track.kind() == disableSameKind && track.mode() > 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;
+
+ this.player_.on('fullscreenchange', vjs.bind(this, this.adjustFontSize));
+ }
+});
+
+/**
+ * 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_;
+};
+
+/**
+ * Change the font size of the text track to make it larger when playing in fullscreen mode
+ * and restore it to its normal size when not in fullscreen mode.
+ */
+vjs.TextTrack.prototype.adjustFontSize = function () {
+ if (this.player_.isFullScreen()) {
+ // Scale the font by the same factor as increasing the video width to the full screen window width.
+ // Additionally, multiply that factor by 1.4, which is the default font size for
+ // the caption track (from the CSS)
+ this.el_.style.fontSize = screen.width / this.player_.width() * 1.4 * 100 + '%';
+ } else {
+ // Change the font size of the text track back to its original non-fullscreen size
+ this.el_.style.fontSize = '';
+ }
+};
+
+/**
+ * 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.get(this.src_, vjs.bind(this, this.parseCues), vjs.bind(this, this.onError));
+ }
+
+};
+
+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 < j; i++) {
+ // Line 0 should be 'WEBVTT', so skipping i=0
+
+ line = vjs.trim(lines[i]); // Trim whitespace and linebreaks
+
+ if (line) { // Loop until a line with content
+
+ // First line could be an optional cue ID
+ // Check if line has the time separator
+ if (line.indexOf('-->') == -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(' --> ');
+ cue.startTime = this.parseCueTime(time[0]);
+ cue.endTime = this.parseCueTime(time[1]);
+
+ // Additional lines - Cue Text
+ text = [];
+
+ // Loop until a blank line or end of lines
+ // Assumeing 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 < j; i++) {
+ html += '' + cues[i].text + '';
+ }
+
+ 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.player_.on(track.kind() + 'trackchange', vjs.bind(this, 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 < j; i++) {
+ track = tracks[i];
+ if (track.kind() == this.track.kind() && track.mode() == 2) {
+ off = false;
+ }
+ }
+
+ this.selected(off);
+};
+
+/**
+ * The base class for buttons that toggle specific text track types (e.g. subtitles)
+ *
+ * @constructor
+ */
+vjs.TextTrackButton = vjs.MenuButton.extend({
+ /** @constructor */
+ init: function (player, options) {
+ vjs.MenuButton.call(this, player, options);
+
+ if (this.items.length <= 1) {
+ this.hide();
+ }
+ }
+});
+
+// vjs.TextTrackButton.prototype.buttonPressed = false;
+
+// vjs.TextTrackButton.prototype.createMenu = function(){
+// var menu = new vjs.Menu(this.player_);
+
+// // Add a title list item to the top
+// // menu.el().appendChild(vjs.createEl('li', {
+// // className: 'vjs-menu-title',
+// // innerHTML: vjs.capitalize(this.kind_),
+// // tabindex: -1
+// // }));
+
+// this.items = this.createItems();
+
+// // Add menu items to the menu
+// for (var i = 0; i < this.items.length; i++) {
+// menu.addItem(this.items[i]);
+// }
+
+// // Add list to element
+// this.addChild(menu);
+
+// return menu;
+// };
+
+// Create a menu item for each text track
+vjs.TextTrackButton.prototype.createItems = function () {
+ var items = [], track;
+
+ // Add an OFF menu item to turn all tracks off
+ items.push(new vjs.OffTextTrackMenuItem(this.player_, { 'kind': this.kind_ }));
+
+ for (var i = 0; i < this.player_.textTracks().length; i++) {
+ track = this.player_.textTracks()[i];
+ if (track.kind() === this.kind_) {
+ items.push(new vjs.TextTrackMenuItem(this.player_, {
+ 'track': track
+ }));
+ }
+ }
+
+ return items;
+};
+
+/**
+ * The button component for toggling and selecting captions
+ *
+ * @constructor
+ */
+vjs.CaptionsButton = vjs.TextTrackButton.extend({
+ /** @constructor */
+ init: function (player, options, ready) {
+ vjs.TextTrackButton.call(this, player, options, ready);
+ this.el_.setAttribute('aria-label', 'Captions Menu');
+ }
+});
+vjs.CaptionsButton.prototype.kind_ = 'captions';
+vjs.CaptionsButton.prototype.buttonText = 'Captions';
+vjs.CaptionsButton.prototype.className = 'vjs-captions-button';
+
+/**
+ * The button component for toggling and selecting subtitles
+ *
+ * @constructor
+ */
+vjs.SubtitlesButton = vjs.TextTrackButton.extend({
+ /** @constructor */
+ init: function (player, options, ready) {
+ vjs.TextTrackButton.call(this, player, options, ready);
+ this.el_.setAttribute('aria-label', 'Subtitles Menu');
+ }
+});
+vjs.SubtitlesButton.prototype.kind_ = 'subtitles';
+vjs.SubtitlesButton.prototype.buttonText = 'Subtitles';
+vjs.SubtitlesButton.prototype.className = 'vjs-subtitles-button';
+
+// Chapters act much differently than other text tracks
+// Cues are navigation vs. other tracks of alternative languages
+/**
+ * The button component for toggling and selecting chapters
+ *
+ * @constructor
+ */
+vjs.ChaptersButton = vjs.TextTrackButton.extend({
+ /** @constructor */
+ init: function (player, options, ready) {
+ vjs.TextTrackButton.call(this, player, options, ready);
+ this.el_.setAttribute('aria-label', 'Chapters Menu');
+ }
+});
+vjs.ChaptersButton.prototype.kind_ = 'chapters';
+vjs.ChaptersButton.prototype.buttonText = 'Chapters';
+vjs.ChaptersButton.prototype.className = 'vjs-chapters-button';
+
+// Create a menu item for each text track
+vjs.ChaptersButton.prototype.createItems = function () {
+ var items = [], track;
+
+ for (var i = 0; i < this.player_.textTracks().length; i++) {
+ track = this.player_.textTracks()[i];
+ if (track.kind() === this.kind_) {
+ items.push(new vjs.TextTrackMenuItem(this.player_, {
+ 'track': track
+ }));
+ }
+ }
+
+ return items;
+};
+
+vjs.ChaptersButton.prototype.createMenu = function () {
+ var tracks = this.player_.textTracks(),
+ i = 0,
+ j = tracks.length,
+ track, chaptersTrack,
+ items = this.items = [];
+
+ for (; i < j; i++) {
+ track = tracks[i];
+ if (track.kind() == this.kind_ && track.dflt()) {
+ if (track.readyState() < 2) {
+ this.chaptersTrack = track;
+ track.on('loaded', vjs.bind(this, this.createMenu));
+ return;
+ } else {
+ chaptersTrack = track;
+ break;
+ }
+ }
+ }
+
+ var menu = this.menu = new vjs.Menu(this.player_);
+
+ menu.contentEl().appendChild(vjs.createEl('li', {
+ className: 'vjs-menu-title',
+ innerHTML: vjs.capitalize(this.kind_),
+ tabindex: -1
+ }));
+
+ if (chaptersTrack) {
+ var cues = chaptersTrack.cues_, cue, mi;
+ i = 0;
+ j = cues.length;
+
+ for (; i < j; i++) {
+ cue = cues[i];
+
+ mi = new vjs.ChaptersTrackMenuItem(this.player_, {
+ 'track': chaptersTrack,
+ 'cue': cue
+ });
+
+ items.push(mi);
+
+ menu.addChild(mi);
+ }
+ }
+
+ if (this.items.length > 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' && 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, vid, player,
+ vids = document.getElementsByTagName('video');
+
+ // Check if any media elements exist
+ if (vids && vids.length > 0) {
+
+ for (var i = 0, j = vids.length; i < j; i++) {
+ vid = vids[i];
+
+ // Check if element exists, has getAttribute func.
+ // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately.
+ if (vid && vid.getAttribute) {
+
+ // Make sure this player hasn't already been set up.
+ if (vid['player'] === undefined) {
+ options = vid.getAttribute('data-setup');
+
+ // Check if data-setup attr exists.
+ // We only auto-setup if they've added the data-setup attr.
+ if (options !== null) {
+
+ // Parse options JSON
+ // If empty string, make it a parsable json object.
+ options = vjs.JSON.parse(options || '{}');
+
+ // Create new video.js instance.
+ player = videojs(vid, options);
+ }
+ }
+
+ // If getAttribute isn't defined, we need to wait for the DOM.
+ } else {
+ vjs.autoSetupTimeout(1);
+ break;
+ }
+ }
+
+ // No videos were found, so keep looping unless page is finisehd loading.
+ } else if (!vjs.windowLoaded) {
+ vjs.autoSetupTimeout(1);
+ }
+};
+
+// Pause to let the DOM keep processing
+vjs.autoSetupTimeout = function (wait) {
+ setTimeout(vjs.autoSetup, wait);
+};
+
+if (document.readyState === 'complete') {
+ vjs.windowLoaded = true;
+} else {
+ vjs.one(window, 'load', function () {
+ vjs.windowLoaded = true;
+ });
+}
+
+// Run Auto-load players
+// You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version)
+vjs.autoSetupTimeout(1);
+/**
+ * the method for registering a video.js plugin
+ *
+ * @param {String} name The name of the plugin
+ * @param {Function} init The function that is run when the player inits
+ */
+vjs.plugin = function (name, init) {
+ vjs.Player.prototype[name] = init;
+};
diff --git a/gui/slick/js/video-js/video.js b/gui/slick/js/video-js/video.js
new file mode 100644
index 00000000..8adbd9b1
--- /dev/null
+++ b/gui/slick/js/video-js/video.js
@@ -0,0 +1,149 @@
+/*! Video.js v4.6.3 Copyright 2014 Brightcove, Inc. https://github.com/videojs/video.js/blob/master/LICENSE */
+(function() {var b=void 0,f=!0,j=null,l=!1;function m(){return function(){}}function q(a){return function(){return this[a]}}function r(a){return function(){return a}}var t;document.createElement("video");document.createElement("audio");document.createElement("track");function u(a,c,d){if("string"===typeof a){0===a.indexOf("#")&&(a=a.slice(1));if(u.Aa[a])return u.Aa[a];a=u.w(a)}if(!a||!a.nodeName)throw new TypeError("The element or ID supplied is not valid. (videojs)");return a.player||new u.Player(a,c,d)}
+var videojs=u;window.ke=window.le=u;u.Vb="4.6";u.Qc="https:"==document.location.protocol?"https://":"http://";u.options={techOrder:["html5","flash"],html5:{},flash:{},width:300,height:150,defaultVolume:0,playbackRates:[],children:{mediaLoader:{},posterImage:{},textTrackDisplay:{},loadingSpinner:{},bigPlayButton:{},controlBar:{},errorDisplay:{}},notSupportedMessage:"No compatible source was found for this video."};"GENERATED_CDN_VSN"!==u.Vb&&(videojs.options.flash.swf=u.Qc+"vjs.zencdn.net/"+u.Vb+"/video-js.swf");
+u.Aa={};"function"===typeof define&&define.amd?define([],function(){return videojs}):"object"===typeof exports&&"object"===typeof module&&(module.exports=videojs);u.pa=u.CoreObject=m();u.pa.extend=function(a){var c,d;a=a||{};c=a.init||a.h||this.prototype.init||this.prototype.h||m();d=function(){c.apply(this,arguments)};d.prototype=u.l.create(this.prototype);d.prototype.constructor=d;d.extend=u.pa.extend;d.create=u.pa.create;for(var e in a)a.hasOwnProperty(e)&&(d.prototype[e]=a[e]);return d};
+u.pa.create=function(){var a=u.l.create(this.prototype);this.apply(a,arguments);return a};u.d=function(a,c,d){var e=u.getData(a);e.D||(e.D={});e.D[c]||(e.D[c]=[]);d.v||(d.v=u.v++);e.D[c].push(d);e.X||(e.disabled=l,e.X=function(c){if(!e.disabled){c=u.pc(c);var d=e.D[c.type];if(d)for(var d=d.slice(0),k=0,p=d.length;ku.Ub;u.Yb=/Firefox/i.test(u.M);u.ae=/Chrome/i.test(u.M);u.fc=!!("ontouchstart"in window||window.Rc&&document instanceof window.Rc);
+u.Cb=function(a){var c,d,e,g;c={};if(a&&a.attributes&&0e?"0"+e:e)+":")+(10>d?"0"+d:d)};u.cd=function(){document.body.focus();document.onselectstart=r(l)};u.Ud=function(){document.onselectstart=r(f)};u.trim=function(a){return(a+"").replace(/^\s+|\s+$/g,"")};u.round=function(a,c){c||(c=0);return Math.round(a*Math.pow(10,c))/Math.pow(10,c)};
+u.zb=function(a,c){return{length:1,start:function(){return a},end:function(){return c}}};
+u.get=function(a,c,d,e){var g,h,k,p;d=d||m();"undefined"===typeof XMLHttpRequest&&(window.XMLHttpRequest=function(){try{return new window.ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(a){}try{return new window.ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(c){}try{return new window.ActiveXObject("Msxml2.XMLHTTP")}catch(d){}throw Error("This browser does not support XMLHttpRequest.");});h=new XMLHttpRequest;k=u.Gd(a);p=window.location;k.protocol+k.host!==p.protocol+p.host&&window.XDomainRequest&&!("withCredentials"in
+h)?(h=new window.XDomainRequest,h.onload=function(){c(h.responseText)},h.onerror=d,h.onprogress=m(),h.ontimeout=d):(g="file:"==k.protocol||"file:"==p.protocol,h.onreadystatechange=function(){4===h.readyState&&(200===h.status||g&&0===h.status?c(h.responseText):d(h.responseText))});try{h.open("GET",a,f),e&&(h.withCredentials=f)}catch(n){d(n);return}try{h.send()}catch(s){d(s)}};
+u.Ld=function(a){try{var c=window.localStorage||l;c&&(c.volume=a)}catch(d){22==d.code||1014==d.code?u.log("LocalStorage Full (VideoJS)",d):18==d.code?u.log("LocalStorage not allowed (VideoJS)",d):u.log("LocalStorage Error (VideoJS)",d)}};u.rc=function(a){a.match(/^https?:\/\//)||(a=u.e("div",{innerHTML:'x'}).firstChild.href);return a};
+u.Gd=function(a){var c,d,e,g;g="protocol hostname port pathname search hash host".split(" ");d=u.e("a",{href:a});if(e=""===d.host&&"file:"!==d.protocol)c=u.e("div"),c.innerHTML='',d=c.firstChild,c.setAttribute("style","display:none; position:absolute;"),document.body.appendChild(c);a={};for(var h=0;he&&(a.preventDefault(),this.k("tap")))})}
+u.s=u.a.extend({h:function(a,c){u.a.call(this,a,c);I(this);this.d("tap",this.q);this.d("click",this.q);this.d("focus",this.Va);this.d("blur",this.Ua)}});t=u.s.prototype;
+t.e=function(a,c){var d;c=u.l.B({className:this.S(),role:"button","aria-live":"polite",tabIndex:0},c);d=u.a.prototype.e.call(this,a,c);c.innerHTML||(this.u=u.e("div",{className:"vjs-control-content"}),this.xb=u.e("span",{className:"vjs-control-text",innerHTML:this.sa||"Need Text"}),this.u.appendChild(this.xb),d.appendChild(this.u));return d};t.S=function(){return"vjs-control "+u.a.prototype.S.call(this)};t.q=m();t.Va=function(){u.d(document,"keyup",u.bind(this,this.da))};
+t.da=function(a){if(32==a.which||13==a.which)a.preventDefault(),this.q()};t.Ua=function(){u.p(document,"keyup",u.bind(this,this.da))};u.Q=u.a.extend({h:function(a,c){u.a.call(this,a,c);this.bd=this.ja(this.j.barName);this.handle=this.ja(this.j.handleName);this.d("mousedown",this.Wa);this.d("touchstart",this.Wa);this.d("focus",this.Va);this.d("blur",this.Ua);this.d("click",this.q);this.c.d("controlsvisible",u.bind(this,this.update));a.d(this.Bc,u.bind(this,this.update));this.R={}}});t=u.Q.prototype;
+t.e=function(a,c){c=c||{};c.className+=" vjs-slider";c=u.l.B({role:"slider","aria-valuenow":0,"aria-valuemin":0,"aria-valuemax":100,tabIndex:0},c);return u.a.prototype.e.call(this,a,c)};t.Wa=function(a){a.preventDefault();u.cd();this.R.move=u.bind(this,this.Lb);this.R.end=u.bind(this,this.Mb);u.d(document,"mousemove",this.R.move);u.d(document,"mouseup",this.R.end);u.d(document,"touchmove",this.R.move);u.d(document,"touchend",this.R.end);this.Lb(a)};
+t.Mb=function(){u.Ud();u.p(document,"mousemove",this.R.move,l);u.p(document,"mouseup",this.R.end,l);u.p(document,"touchmove",this.R.move,l);u.p(document,"touchend",this.R.end,l);this.update()};t.update=function(){if(this.b){var a,c=this.Db(),d=this.handle,e=this.bd;isNaN(c)&&(c=0);a=c;if(d){a=this.b.offsetWidth;var g=d.w().offsetWidth;a=g?g/a:0;c*=1-a;a=c+a/2;d.w().style.left=u.round(100*c,2)+"%"}e.w().style.width=u.round(100*a,2)+"%"}};
+function J(a,c){var d,e,g,h;d=a.b;e=u.pd(d);h=g=d.offsetWidth;d=a.handle;if(a.j.Wd)return h=e.top,e=c.changedTouches?c.changedTouches[0].pageY:c.pageY,d&&(d=d.w().offsetHeight,h+=d/2,g-=d),Math.max(0,Math.min(1,(h-e+g)/g));g=e.left;e=c.changedTouches?c.changedTouches[0].pageX:c.pageX;d&&(d=d.w().offsetWidth,g+=d/2,h-=d);return Math.max(0,Math.min(1,(e-g)/h))}t.Va=function(){u.d(document,"keyup",u.bind(this,this.da))};
+t.da=function(a){37==a.which?(a.preventDefault(),this.Hc()):39==a.which&&(a.preventDefault(),this.Ic())};t.Ua=function(){u.p(document,"keyup",u.bind(this,this.da))};t.q=function(a){a.stopImmediatePropagation();a.preventDefault()};u.Y=u.a.extend();u.Y.prototype.defaultValue=0;u.Y.prototype.e=function(a,c){c=c||{};c.className+=" vjs-slider-handle";c=u.l.B({innerHTML:''+this.defaultValue+""},c);return u.a.prototype.e.call(this,"div",c)};u.ga=u.a.extend();
+function ca(a,c){a.V(c);c.d("click",u.bind(a,function(){G(this)}))}u.ga.prototype.e=function(){var a=this.options().lc||"ul";this.u=u.e(a,{className:"vjs-menu-content"});a=u.a.prototype.e.call(this,"div",{append:this.u,className:"vjs-menu"});a.appendChild(this.u);u.d(a,"click",function(a){a.preventDefault();a.stopImmediatePropagation()});return a};u.I=u.s.extend({h:function(a,c){u.s.call(this,a,c);this.selected(c.selected)}});
+u.I.prototype.e=function(a,c){return u.s.prototype.e.call(this,"li",u.l.B({className:"vjs-menu-item",innerHTML:this.j.label},c))};u.I.prototype.q=function(){this.selected(f)};u.I.prototype.selected=function(a){a?(this.o("vjs-selected"),this.b.setAttribute("aria-selected",f)):(this.r("vjs-selected"),this.b.setAttribute("aria-selected",l))};
+u.L=u.s.extend({h:function(a,c){u.s.call(this,a,c);this.za=this.va();this.V(this.za);this.O&&0===this.O.length&&this.G();this.d("keyup",this.da);this.b.setAttribute("aria-haspopup",f);this.b.setAttribute("role","button")}});t=u.L.prototype;t.ra=l;t.va=function(){var a=new u.ga(this.c);this.options().title&&a.ia().appendChild(u.e("li",{className:"vjs-menu-title",innerHTML:u.$(this.options().title),Sd:-1}));if(this.O=this.createItems())for(var c=0;ca&&(a=Infinity),this.duration(a),Infinity===a?this.o("vjs-live"):this.r("vjs-live"))};t.Bd=function(){this.isFullscreen()?this.o("vjs-fullscreen"):this.r("vjs-fullscreen")};
+function V(a,c,d){if(a.g&&!a.g.ca)a.g.K(function(){this[c](d)});else try{a.g[c](d)}catch(e){throw u.log(e),e;}}function U(a,c){if(a.g&&a.g.ca)try{return a.g[c]()}catch(d){throw a.g[c]===b?u.log("Video.js: "+c+" method not defined for "+a.Ca+" playback technology.",d):"TypeError"==d.name?(u.log("Video.js: "+c+" unavailable on "+a.Ca+" playback technology element.",d),a.g.ca=l):u.log(d),d;}}t.play=function(){V(this,"play");return this};t.pause=function(){V(this,"pause");return this};
+t.paused=function(){return U(this,"paused")===l?l:f};t.currentTime=function(a){return a!==b?(V(this,"setCurrentTime",a),this.Jb&&this.k("timeupdate"),this):this.z.currentTime=U(this,"currentTime")||0};t.duration=function(a){if(a!==b)return this.z.duration=parseFloat(a),this;this.z.duration===b&&this.zc();return this.z.duration||0};t.buffered=function(){var a=U(this,"buffered"),c=a.length-1,d=this.z.tb=this.z.tb||0;a&&(0<=c&&a.end(c)!==d)&&(d=a.end(c),this.z.tb=d);return u.zb(0,d)};
+t.bufferedPercent=function(){return this.duration()?this.buffered().end(0)/this.duration():0};t.volume=function(a){if(a!==b)return a=Math.max(0,Math.min(1,parseFloat(a))),this.z.volume=a,V(this,"setVolume",a),u.Ld(a),this;a=parseFloat(U(this,"volume"));return isNaN(a)?1:a};t.muted=function(a){return a!==b?(V(this,"setMuted",a),this):U(this,"muted")||l};t.ab=function(){return U(this,"supportsFullScreen")||l};t.wc=l;t.isFullscreen=function(a){return a!==b?(this.wc=!!a,this):this.wc};
+t.isFullScreen=function(a){u.log.warn('player.isFullScreen() has been deprecated, use player.isFullscreen() with a lowercase "s")');return this.isFullscreen(a)};
+t.requestFullscreen=function(){var a=u.Na.Bb;this.isFullscreen(f);a?(u.d(document,a.fullscreenchange,u.bind(this,function(c){this.isFullscreen(document[a.fullscreenElement]);this.isFullscreen()===l&&u.p(document,a.fullscreenchange,arguments.callee);this.k("fullscreenchange")})),this.b[a.requestFullscreen]()):this.g.ab()?V(this,"enterFullScreen"):(this.td=f,this.ld=document.documentElement.style.overflow,u.d(document,"keydown",u.bind(this,this.qc)),document.documentElement.style.overflow="hidden",
+u.o(document.body,"vjs-full-window"),this.k("enterFullWindow"),this.k("fullscreenchange"));return this};t.exitFullscreen=function(){var a=u.Na.Bb;this.isFullscreen(l);if(a)document[a.exitFullscreen]();else this.g.ab()?V(this,"exitFullScreen"):(ea(this),this.k("fullscreenchange"));return this};t.qc=function(a){27===a.keyCode&&(this.isFullscreen()===f?this.exitFullscreen():ea(this))};
+function ea(a){a.td=l;u.p(document,"keydown",a.qc);document.documentElement.style.overflow=a.ld;u.r(document.body,"vjs-full-window");a.k("exitFullWindow")}
+t.src=function(a){if(a===b)return U(this,"src");if(a instanceof Array){var c;a:{c=a;for(var d=0,e=this.j.techOrder;dStream Type LIVE',"aria-live":"off"});a.appendChild(this.u);return a};u.bc=u.s.extend({h:function(a,c){u.s.call(this,a,c);a.d("play",u.bind(this,this.Ob));a.d("pause",u.bind(this,this.Nb))}});t=u.bc.prototype;t.sa="Play";
+t.S=function(){return"vjs-play-control "+u.s.prototype.S.call(this)};t.q=function(){this.c.paused()?this.c.play():this.c.pause()};t.Ob=function(){u.r(this.b,"vjs-paused");u.o(this.b,"vjs-playing");this.b.children[0].children[0].innerHTML="Pause"};t.Nb=function(){u.r(this.b,"vjs-playing");u.o(this.b,"vjs-paused");this.b.children[0].children[0].innerHTML="Play"};u.fb=u.a.extend({h:function(a,c){u.a.call(this,a,c);a.d("timeupdate",u.bind(this,this.fa))}});
+u.fb.prototype.e=function(){var a=u.a.prototype.e.call(this,"div",{className:"vjs-current-time vjs-time-controls vjs-control"});this.u=u.e("div",{className:"vjs-current-time-display",innerHTML:'Current Time 0:00',"aria-live":"off"});a.appendChild(this.u);return a};u.fb.prototype.fa=function(){var a=this.c.$a?this.c.z.currentTime:this.c.currentTime();this.u.innerHTML='Current Time '+u.ya(a,this.c.duration())};
+u.gb=u.a.extend({h:function(a,c){u.a.call(this,a,c);a.d("timeupdate",u.bind(this,this.fa))}});u.gb.prototype.e=function(){var a=u.a.prototype.e.call(this,"div",{className:"vjs-duration vjs-time-controls vjs-control"});this.u=u.e("div",{className:"vjs-duration-display",innerHTML:'Duration Time 0:00',"aria-live":"off"});a.appendChild(this.u);return a};
+u.gb.prototype.fa=function(){var a=this.c.duration();a&&(this.u.innerHTML='Duration Time '+u.ya(a))};u.hc=u.a.extend({h:function(a,c){u.a.call(this,a,c)}});u.hc.prototype.e=function(){return u.a.prototype.e.call(this,"div",{className:"vjs-time-divider",innerHTML:"/
"})};u.nb=u.a.extend({h:function(a,c){u.a.call(this,a,c);a.d("timeupdate",u.bind(this,this.fa))}});
+u.nb.prototype.e=function(){var a=u.a.prototype.e.call(this,"div",{className:"vjs-remaining-time vjs-time-controls vjs-control"});this.u=u.e("div",{className:"vjs-remaining-time-display",innerHTML:'Remaining Time -0:00',"aria-live":"off"});a.appendChild(this.u);return a};u.nb.prototype.fa=function(){this.c.duration()&&(this.u.innerHTML='Remaining Time -'+u.ya(this.c.duration()-this.c.currentTime()))};
+u.Ia=u.s.extend({h:function(a,c){u.s.call(this,a,c)}});u.Ia.prototype.sa="Fullscreen";u.Ia.prototype.S=function(){return"vjs-fullscreen-control "+u.s.prototype.S.call(this)};u.Ia.prototype.q=function(){this.c.isFullscreen()?(this.c.exitFullscreen(),this.xb.innerHTML="Fullscreen"):(this.c.requestFullscreen(),this.xb.innerHTML="Non-Fullscreen")};u.mb=u.a.extend({h:function(a,c){u.a.call(this,a,c)}});u.mb.prototype.j={children:{seekBar:{}}};
+u.mb.prototype.e=function(){return u.a.prototype.e.call(this,"div",{className:"vjs-progress-control vjs-control"})};u.dc=u.Q.extend({h:function(a,c){u.Q.call(this,a,c);a.d("timeupdate",u.bind(this,this.ma));a.K(u.bind(this,this.ma))}});t=u.dc.prototype;t.j={children:{loadProgressBar:{},playProgressBar:{},seekHandle:{}},barName:"playProgressBar",handleName:"seekHandle"};t.Bc="timeupdate";t.e=function(){return u.Q.prototype.e.call(this,"div",{className:"vjs-progress-holder","aria-label":"video progress bar"})};
+t.ma=function(){var a=this.c.$a?this.c.z.currentTime:this.c.currentTime();this.b.setAttribute("aria-valuenow",u.round(100*this.Db(),2));this.b.setAttribute("aria-valuetext",u.ya(a,this.c.duration()))};t.Db=function(){return this.c.currentTime()/this.c.duration()};t.Wa=function(a){u.Q.prototype.Wa.call(this,a);this.c.$a=f;this.Xd=!this.c.paused();this.c.pause()};t.Lb=function(a){a=J(this,a)*this.c.duration();a==this.c.duration()&&(a-=0.1);this.c.currentTime(a)};
+t.Mb=function(a){u.Q.prototype.Mb.call(this,a);this.c.$a=l;this.Xd&&this.c.play()};t.Ic=function(){this.c.currentTime(this.c.currentTime()+5)};t.Hc=function(){this.c.currentTime(this.c.currentTime()-5)};u.jb=u.a.extend({h:function(a,c){u.a.call(this,a,c);a.d("progress",u.bind(this,this.update))}});u.jb.prototype.e=function(){return u.a.prototype.e.call(this,"div",{className:"vjs-load-progress",innerHTML:'Loaded: 0%'})};
+u.jb.prototype.update=function(){this.b.style&&(this.b.style.width=u.round(100*this.c.bufferedPercent(),2)+"%")};u.ac=u.a.extend({h:function(a,c){u.a.call(this,a,c)}});u.ac.prototype.e=function(){return u.a.prototype.e.call(this,"div",{className:"vjs-play-progress",innerHTML:'Progress: 0%'})};u.Ka=u.Y.extend({h:function(a,c){u.Y.call(this,a,c);a.d("timeupdate",u.bind(this,this.fa))}});u.Ka.prototype.defaultValue="00:00";
+u.Ka.prototype.e=function(){return u.Y.prototype.e.call(this,"div",{className:"vjs-seek-handle","aria-live":"off"})};u.Ka.prototype.fa=function(){var a=this.c.$a?this.c.z.currentTime:this.c.currentTime();this.b.innerHTML=''+u.ya(a,this.c.duration())+""};u.pb=u.a.extend({h:function(a,c){u.a.call(this,a,c);a.g&&(a.g.n&&a.g.n.volumeControl===l)&&this.o("vjs-hidden");a.d("loadstart",u.bind(this,function(){a.g.n&&a.g.n.volumeControl===l?this.o("vjs-hidden"):this.r("vjs-hidden")}))}});
+u.pb.prototype.j={children:{volumeBar:{}}};u.pb.prototype.e=function(){return u.a.prototype.e.call(this,"div",{className:"vjs-volume-control vjs-control"})};u.ob=u.Q.extend({h:function(a,c){u.Q.call(this,a,c);a.d("volumechange",u.bind(this,this.ma));a.K(u.bind(this,this.ma))}});t=u.ob.prototype;t.ma=function(){this.b.setAttribute("aria-valuenow",u.round(100*this.c.volume(),2));this.b.setAttribute("aria-valuetext",u.round(100*this.c.volume(),2)+"%")};
+t.j={children:{volumeLevel:{},volumeHandle:{}},barName:"volumeLevel",handleName:"volumeHandle"};t.Bc="volumechange";t.e=function(){return u.Q.prototype.e.call(this,"div",{className:"vjs-volume-bar","aria-label":"volume level"})};t.Lb=function(a){this.c.muted()&&this.c.muted(l);this.c.volume(J(this,a))};t.Db=function(){return this.c.muted()?0:this.c.volume()};t.Ic=function(){this.c.volume(this.c.volume()+0.1)};t.Hc=function(){this.c.volume(this.c.volume()-0.1)};
+u.ic=u.a.extend({h:function(a,c){u.a.call(this,a,c)}});u.ic.prototype.e=function(){return u.a.prototype.e.call(this,"div",{className:"vjs-volume-level",innerHTML:''})};u.qb=u.Y.extend();u.qb.prototype.defaultValue="00:00";u.qb.prototype.e=function(){return u.Y.prototype.e.call(this,"div",{className:"vjs-volume-handle"})};
+u.ha=u.s.extend({h:function(a,c){u.s.call(this,a,c);a.d("volumechange",u.bind(this,this.update));a.g&&(a.g.n&&a.g.n.volumeControl===l)&&this.o("vjs-hidden");a.d("loadstart",u.bind(this,function(){a.g.n&&a.g.n.volumeControl===l?this.o("vjs-hidden"):this.r("vjs-hidden")}))}});u.ha.prototype.e=function(){return u.s.prototype.e.call(this,"div",{className:"vjs-mute-control vjs-control",innerHTML:'Mute
'})};
+u.ha.prototype.q=function(){this.c.muted(this.c.muted()?l:f)};u.ha.prototype.update=function(){var a=this.c.volume(),c=3;0===a||this.c.muted()?c=0:0.33>a?c=1:0.67>a&&(c=2);this.c.muted()?"Unmute"!=this.b.children[0].children[0].innerHTML&&(this.b.children[0].children[0].innerHTML="Unmute"):"Mute"!=this.b.children[0].children[0].innerHTML&&(this.b.children[0].children[0].innerHTML="Mute");for(a=0;4>a;a++)u.r(this.b,"vjs-vol-"+a);u.o(this.b,"vjs-vol-"+c)};
+u.qa=u.L.extend({h:function(a,c){u.L.call(this,a,c);a.d("volumechange",u.bind(this,this.update));a.g&&(a.g.n&&a.g.n.Oc===l)&&this.o("vjs-hidden");a.d("loadstart",u.bind(this,function(){a.g.n&&a.g.n.Oc===l?this.o("vjs-hidden"):this.r("vjs-hidden")}));this.o("vjs-menu-button")}});u.qa.prototype.va=function(){var a=new u.ga(this.c,{lc:"div"}),c=new u.ob(this.c,u.l.B({Wd:f},this.j.me));a.V(c);return a};u.qa.prototype.q=function(){u.ha.prototype.q.call(this);u.L.prototype.q.call(this)};
+u.qa.prototype.e=function(){return u.s.prototype.e.call(this,"div",{className:"vjs-volume-menu-button vjs-menu-button vjs-control",innerHTML:'Mute
'})};u.qa.prototype.update=u.ha.prototype.update;u.cc=u.L.extend({h:function(a,c){u.L.call(this,a,c);this.Nc();this.Mc();a.d("loadstart",u.bind(this,this.Nc));a.d("ratechange",u.bind(this,this.Mc))}});t=u.cc.prototype;
+t.e=function(){var a=u.a.prototype.e.call(this,"div",{className:"vjs-playback-rate vjs-menu-button vjs-control",innerHTML:'Playback Rate
'});this.yc=u.e("div",{className:"vjs-playback-rate-value",innerHTML:1});a.appendChild(this.yc);return a};t.va=function(){var a=new u.ga(this.m()),c=this.m().options().playbackRates;if(c)for(var d=c.length-1;0<=d;d--)a.V(new u.lb(this.m(),{rate:c[d]+"x"}));return a};
+t.ma=function(){this.w().setAttribute("aria-valuenow",this.m().playbackRate())};t.q=function(){for(var a=this.m().playbackRate(),c=this.m().options().playbackRates,d=c[0],e=0;ea){d=c[e];break}this.m().playbackRate(d)};function fa(a){return a.m().g&&a.m().g.n.playbackRate&&a.m().options().playbackRates&&0',"aria-label":"play video"})};u.cb.prototype.q=function(){this.c.play()};u.hb=u.a.extend({h:function(a,c){u.a.call(this,a,c);this.update();a.d("error",u.bind(this,this.update))}});u.hb.prototype.e=function(){var a=u.a.prototype.e.call(this,"div",{className:"vjs-error-display"});this.u=u.e("div");a.appendChild(this.u);return a};
+u.hb.prototype.update=function(){this.m().error()&&(this.u.innerHTML=this.m().error().message)};
+u.t=u.a.extend({h:function(a,c,d){c=c||{};c.Fc=l;u.a.call(this,a,c,d);var e,g;g=this;e=this.m();a=function(){if(e.controls()&&!e.usingNativeControls()){var a;g.d("mousedown",g.q);g.d("touchstart",function(c){c.preventDefault();a=this.c.userActive()});g.d("touchmove",function(){a&&this.m().reportUserActivity()});I(g);g.d("tap",g.Ed)}};c=u.bind(g,g.Id);this.K(a);e.d("controlsenabled",a);e.d("controlsdisabled",c)}});t=u.t.prototype;
+t.Id=function(){this.p("tap");this.p("touchstart");this.p("touchmove");this.p("touchleave");this.p("touchcancel");this.p("touchend");this.p("click");this.p("mousedown")};t.q=function(a){0===a.button&&this.m().controls()&&(this.m().paused()?this.m().play():this.m().pause())};t.Ed=function(){this.m().userActive(!this.m().userActive())};t.Qb=m();t.n={volumeControl:f,fullscreenResize:l,playbackRate:l,progressEvents:l,timeupdateEvents:l};u.media={};u.media.bb="play pause paused currentTime setCurrentTime duration buffered volume setVolume muted setMuted width height supportsFullScreen enterFullScreen src load currentSrc preload setPreload autoplay setAutoplay loop setLoop error networkState readyState seeking initialTime startOffsetTime played seekable ended videoTracks audioTracks videoWidth videoHeight textTracks defaultPlaybackRate playbackRate mediaGroup controller controls defaultMuted".split(" ");
+function ha(){var a=u.media.bb[i];return function(){throw Error('The "'+a+"\" method is not available on the playback technology's API");}}for(var i=u.media.bb.length-1;0<=i;i--)u.t.prototype[u.media.bb[i]]=ha();
+u.f=u.t.extend({h:function(a,c,d){this.n.volumeControl=u.f.ed();this.n.playbackRate=u.f.dd();this.n.movingMediaElementInDOM=!u.Tc;this.n.fullscreenResize=f;u.t.call(this,a,c,d);for(d=u.f.ib.length-1;0<=d;d--)u.d(this.b,u.f.ib[d],u.bind(this,this.nd));(c=c.source)&&this.b.currentSrc===c.src&&0'});e=u.l.B({data:a,width:"100%",height:"100%"},e);u.l.wa(e,function(a,c){k+=a+'="'+c+'" '});return'"};u.i.Rd=function(a,c){return a+"&"+c};
+u.i.Jc=function(a){var c={wb:"",Rb:""};if(!a)return c;var d=a.indexOf("&"),e;-1!==d?e=d+1:(d=e=a.lastIndexOf("/")+1,0===d&&(d=e=a.length));c.wb=a.substring(0,d);c.Rb=a.substring(e,a.length);return c};u.i.vd=function(a){return a in u.i.Kc};u.i.Zc=/^rtmp[set]?:\/\//i;u.i.ud=function(a){return u.i.Zc.test(a)};
+u.Yc=u.a.extend({h:function(a,c,d){u.a.call(this,a,c,d);if(!a.j.sources||0===a.j.sources.length){c=0;for(d=a.j.techOrder;c");this.aa.push(c)}this.la=2;this.k("loaded")};
+function ra(a){var c=a.split(":");a=0;var d,e,g;3==c.length?(d=c[0],e=c[1],c=c[2]):(d=0,e=c[0],c=c[1]);c=c.split(/\s+/);c=c.splice(0,1)[0];c=c.split(/\.|,/);g=parseFloat(c[1]);c=c[0];a+=3600*parseFloat(d);a+=60*parseFloat(e);a+=parseFloat(c);g&&(a+=g/1E3);return a}
+t.update=function(){if(0=this.Ta||this.Ta===b?s=this.Ab!==b?this.Ab:0:(g=f,s=this.Hb!==b?this.Hb:c.length-1);for(;;){n=c[s];if(n.xa<=a)e=Math.max(e,n.xa),n.Ma&&(n.Ma=l);else if(a'+k[a].text+"";this.b.innerHTML=p;this.k("cuechange")}}};t.reset=function(){this.Ta=0;this.Pb=this.c.duration();this.Hb=this.Ab=0};u.Wb=u.C.extend();u.Wb.prototype.H="captions";u.ec=u.C.extend();u.ec.prototype.H="subtitles";u.Xb=u.C.extend();u.Xb.prototype.H="chapters";
+u.gc=u.a.extend({h:function(a,c,d){u.a.call(this,a,c,d);if(a.j.tracks&&0=this.O.length&&this.G()}});u.U.prototype.ua=function(){var a=[],c;a.push(new u.kb(this.c,{kind:this.H}));for(var d=0;de.readyState()){this.be=e;e.d("loaded",u.bind(this,this.va));return}g=e;break}a=this.za=new u.ga(this.c);a.ia().appendChild(u.e("li",{className:"vjs-menu-title",innerHTML:u.$(this.H),Sd:-1}));if(g){e=g.aa;for(var k,c=0,d=e.length;c 0
+ def hasColumn(self, tableName, column):
+ return column in self.tableInfo(tableName)
+
+ def addColumn(self, table, column, type="NUMERIC", default=0):
+ self.action("ALTER TABLE %s ADD %s %s" % (table, column, type))
+ self.action("UPDATE %s SET %s = ?" % (table, column), (default,))
+
def close(self):
"""Close database connection"""
if getattr(self, "connection", None) is not None:
diff --git a/sickbeard/failedProcessor.py b/sickbeard/failedProcessor.py
index b1862239..a5fad9eb 100644
--- a/sickbeard/failedProcessor.py
+++ b/sickbeard/failedProcessor.py
@@ -26,7 +26,7 @@ from sickbeard import search_queue
from sickbeard import failed_history
from sickbeard import scene_exceptions
-from sickbeard.name_parser.parser import NameParser, InvalidNameException
+from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException
class FailedProcessor(object):
@@ -62,6 +62,9 @@ class FailedProcessor(object):
except InvalidNameException:
self._log(u"Error: release name is invalid: " + releaseName, logger.WARNING)
raise exceptions.FailedProcessingFailed()
+ except InvalidShowException:
+ self._log(u"Error: unable to parse release name " + releaseName + " into a valid show", logger.WARNING)
+ raise exceptions.FailedProcessingFailed
logger.log(u"name_parser info: ", logger.DEBUG)
logger.log(u" - " + str(parsed.series_name), logger.DEBUG)
diff --git a/sickbeard/helpers.py b/sickbeard/helpers.py
index e1b943a0..7550a1ec 100644
--- a/sickbeard/helpers.py
+++ b/sickbeard/helpers.py
@@ -262,6 +262,9 @@ def download_file(url, filename):
def findCertainShow(showList, indexerid=None):
+ if not showList:
+ return None
+
if indexerid:
results = filter(lambda x: int(x.indexerid) == int(indexerid), showList)
else:
diff --git a/sickbeard/name_parser/parser.py b/sickbeard/name_parser/parser.py
index 7bcaafc4..bb0250ab 100644
--- a/sickbeard/name_parser/parser.py
+++ b/sickbeard/name_parser/parser.py
@@ -23,25 +23,24 @@ import threading
import regexes
import sickbeard
-from sickbeard import logger, helpers, scene_numbering, common, exceptions
+from sickbeard import logger, helpers, scene_numbering, common, exceptions, scene_exceptions
from dateutil import parser
nameparser_lock = threading.Lock()
+
class NameParser(object):
ALL_REGEX = 0
NORMAL_REGEX = 1
SPORTS_REGEX = 2
ANIME_REGEX = 3
- def __init__(self, file_name=True, showObj=None, epObj=None, useIndexers=False, convert=False,
+ def __init__(self, file_name=True, showObj=None, useIndexers=False, convert=False,
naming_pattern=False):
self.file_name = file_name
- self.showList = sickbeard.showList or []
- self.useIndexers = useIndexers
self.showObj = showObj
- self.epObj = epObj
+ self.useIndexers = useIndexers
self.convert = convert
self.naming_pattern = naming_pattern
@@ -121,7 +120,8 @@ class NameParser(object):
if not name:
return
- if not self.showObj and not self.naming_pattern:
+ self.showObj = None
+ if not self.naming_pattern:
# Regex pattern to return the Show / Series Name regardless of the file pattern tossed at it, matched 53 show name examples from regexes.py
show_pattern = '''(?:(?:\[.*?\])|(?:\d{3}[\.-]))*[ _\.]?(?P.*?(?:[ ._-]((?!\d{4}\W\d\d\W\d\d\W)\d{4}))?)(?:(?:(?:[ ._-]+\d+)|(?:[ ._-]+s\d{2}))|(?:\W+(?:(?:S\d[\dE._ -])|(?:\d\d?x)|(?:\d{4}\W\d\d\W\d\d)|(?:(?:part|pt)[\._ -]?(?:\d|[ivx]))|Season\W+\d+\W+|E\d+\W+|(?:\d{1,3}.+\d{1,}[a-zA-Z]{2}\W+[a-zA-Z]{3,}\W+\d{4}.+))))'''
show_pattern_alt = '''^(?P.*?(?:[ ._-]((?!\d{4}\W\d\d\W\d\d\W)\d{4}))?)(?:(?:(?:[ ._-]+\d+)|(?:[ ._-]+s\d{2}))|(?:\W+(?:(?:S\d[\dE._ -])|(?:\d\d?x)|(?:\d{4}\W\d\d\W\d\d)|(?:(?:part|pt)[\._ -]?(?:\d|[ivx]))|Season\W+\d+\W+|E\d+\W+|(?:\d{1,3}.+\d{1,}[a-zA-Z]{2}\W+[a-zA-Z]{3,}\W+\d{4}.+))))'''
@@ -131,7 +131,7 @@ class NameParser(object):
self.showObj = self._matchShowName(name, show_pattern_alt)
if not self.showObj:
- return
+ raise InvalidShowException("Unable to parse " + name.encode(sickbeard.SYS_ENCODING, 'xmlcharrefreplace'))
regexMode = self.ALL_REGEX
if self.showObj and self.showObj.is_anime:
@@ -521,8 +521,10 @@ class ParseResult(object):
new_absolute_numbers = []
if self.show.is_anime and len(self.ab_episode_numbers):
+ scene_season = scene_exceptions.get_scene_exception_by_name(self.series_name)[1]
for epAbsNo in self.ab_episode_numbers:
- ab = scene_numbering.get_indexer_absolute_numbering(self.show.indexerid, self.show.indexer, epAbsNo)
+ ab = scene_numbering.get_indexer_absolute_numbering(self.show.indexerid, self.show.indexer, epAbsNo,
+ True, scene_season)
if ab:
try:
(s, e) = helpers.get_all_episodes_from_absolute_number(self.show, None, [ab])
@@ -619,7 +621,13 @@ class NameParserCache(object):
logger.log("Using cached parse result for: " + name, logger.DEBUG)
return self._previous_parsed[name]
+
name_parser_cache = NameParserCache()
+
class InvalidNameException(Exception):
+ "The given name is not valid"
+
+
+class InvalidShowException(Exception):
"The given name is not valid"
\ No newline at end of file
diff --git a/sickbeard/nzbSplitter.py b/sickbeard/nzbSplitter.py
index 4b1618f8..dc3a868b 100644
--- a/sickbeard/nzbSplitter.py
+++ b/sickbeard/nzbSplitter.py
@@ -23,7 +23,7 @@ import xml.etree.cElementTree as etree
import xml.etree
import re
-from name_parser.parser import NameParser, InvalidNameException
+from name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from sickbeard import logger, classes, helpers
from sickbeard.common import Quality
@@ -118,6 +118,9 @@ def splitResult(result):
except InvalidNameException:
logger.log(u"Unable to parse the filename " + result.name + " into a valid episode", logger.WARNING)
return False
+ except InvalidShowException:
+ logger.log(u"Unable to parse the filename " + result.name + " into a valid show", logger.WARNING)
+ return False
# bust it up
season = parse_result.season_number if parse_result.season_number != None else 1
@@ -137,6 +140,9 @@ def splitResult(result):
except InvalidNameException:
logger.log(u"Unable to parse the filename " + newNZB + " into a valid episode", logger.WARNING)
return False
+ except InvalidShowException:
+ logger.log(u"Unable to parse the filename " + newNZB + " into a valid show", logger.WARNING)
+ return False
# make sure the result is sane
if (parse_result.season_number != None and parse_result.season_number != season) or (
diff --git a/sickbeard/postProcessor.py b/sickbeard/postProcessor.py
index 777a5a19..c90518b3 100644
--- a/sickbeard/postProcessor.py
+++ b/sickbeard/postProcessor.py
@@ -40,7 +40,7 @@ from sickbeard import name_cache
from sickbeard import encodingKludge as ek
from sickbeard.exceptions import ex
-from sickbeard.name_parser.parser import NameParser, InvalidNameException
+from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from lib import adba
@@ -480,11 +480,11 @@ class PostProcessor(object):
return to_return
# parse the name to break it into show name, season, and episode
- np = NameParser(file, useIndexers=True, convert=True)
- parse_result = np.parse(name)
-
- # couldn't find this in our show list
- if not parse_result.show:
+ try:
+ np = NameParser(file, useIndexers=True, convert=True)
+ parse_result = np.parse(name)
+ except InvalidShowException:
+ logger.log(u"Unable to parse the filename " + name + " into a valid show", logger.WARNING)
return to_return
if parse_result.air_by_date:
diff --git a/sickbeard/processTV.py b/sickbeard/processTV.py
index 615a6cd1..4beefa71 100644
--- a/sickbeard/processTV.py
+++ b/sickbeard/processTV.py
@@ -28,7 +28,7 @@ from sickbeard import db, helpers, exceptions
from sickbeard import encodingKludge as ek
from sickbeard.exceptions import ex
from sickbeard import logger
-from sickbeard.name_parser.parser import NameParser, InvalidNameException
+from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from sickbeard import common
from sickbeard import failedProcessor
@@ -269,14 +269,14 @@ def validateDir(path, dirName, nzbNameOriginal, failed):
try:
NameParser().parse(video, cache_result=False)
return True
- except InvalidNameException:
+ except (InvalidNameException, InvalidShowException):
pass
for dir in allDirs:
try:
NameParser().parse(dir, cache_result=False)
return True
- except InvalidNameException:
+ except (InvalidNameException, InvalidShowException):
pass
if sickbeard.UNPACK:
@@ -287,7 +287,7 @@ def validateDir(path, dirName, nzbNameOriginal, failed):
try:
NameParser().parse(packed, cache_result=False)
return True
- except InvalidNameException:
+ except (InvalidNameException, InvalidShowException):
pass
return False
diff --git a/sickbeard/properFinder.py b/sickbeard/properFinder.py
index e0301923..c316c6c8 100644
--- a/sickbeard/properFinder.py
+++ b/sickbeard/properFinder.py
@@ -33,7 +33,7 @@ from sickbeard import history
from sickbeard.common import DOWNLOADED, SNATCHED, SNATCHED_PROPER, Quality
-from name_parser.parser import NameParser, InvalidNameException
+from name_parser.parser import NameParser, InvalidNameException, InvalidShowException
class ProperFinder():
@@ -110,11 +110,11 @@ class ProperFinder():
except InvalidNameException:
logger.log(u"Unable to parse the filename " + curProper.name + " into a valid episode", logger.DEBUG)
continue
-
- if not parse_result.series_name:
+ except InvalidShowException:
+ logger.log(u"Unable to parse the filename " + curProper.name + " into a valid show", logger.WARNING)
continue
- if not parse_result.show:
+ if not parse_result.series_name:
continue
if not parse_result.episode_numbers:
diff --git a/sickbeard/providers/generic.py b/sickbeard/providers/generic.py
index a103364e..564dae1f 100644
--- a/sickbeard/providers/generic.py
+++ b/sickbeard/providers/generic.py
@@ -36,7 +36,7 @@ from sickbeard import tvcache
from sickbeard import encodingKludge as ek
from sickbeard.exceptions import ex
from lib.hachoir_parser import createParser
-from sickbeard.name_parser.parser import NameParser, InvalidNameException
+from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from sickbeard.common import Quality
@@ -278,13 +278,18 @@ class GenericProvider:
# parse the file name
try:
- myParser = NameParser(False, showObj=show, epObj=ep_obj, convert=True)
+ myParser = NameParser(False, convert=True)
parse_result = myParser.parse(title)
except InvalidNameException:
logger.log(u"Unable to parse the filename " + title + " into a valid episode", logger.WARNING)
continue
+ except InvalidShowException:
+ logger.log(u"Unable to parse the filename " + title + " into a valid show", logger.WARNING)
+ continue
+ showObj = parse_result.show
quality = parse_result.quality
+ release_group = parse_result.release_group
if not (self.show.air_by_date or self.show.sports):
if search_mode == 'sponly' and len(parse_result.episode_numbers):
@@ -359,10 +364,11 @@ class GenericProvider:
epObj.append(show.getEpisode(actual_season, curEp))
result = self.getResult(epObj)
+ result.show = showObj
result.url = url
result.name = title
result.quality = quality
- result.provider = self
+ result.release_group = release_group
result.content = None
if len(epObj) == 1:
diff --git a/sickbeard/providers/kat.py b/sickbeard/providers/kat.py
index 55278376..12000c4c 100644
--- a/sickbeard/providers/kat.py
+++ b/sickbeard/providers/kat.py
@@ -31,7 +31,7 @@ import urlparse
import sickbeard
import generic
from sickbeard.common import Quality, cpu_presets
-from sickbeard.name_parser.parser import NameParser, InvalidNameException
+from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from sickbeard import logger
from sickbeard import tvcache
from sickbeard import helpers
@@ -156,7 +156,7 @@ class KATProvider(generic.TorrentProvider):
try:
myParser = NameParser()
parse_result = myParser.parse(fileName)
- except InvalidNameException:
+ except (InvalidNameException, InvalidShowException):
return None
logger.log(u"Season quality for " + title + " is " + Quality.qualityStrings[quality], logger.DEBUG)
diff --git a/sickbeard/providers/publichd.py b/sickbeard/providers/publichd.py
index 38aa9b24..ff7a451d 100644
--- a/sickbeard/providers/publichd.py
+++ b/sickbeard/providers/publichd.py
@@ -29,8 +29,7 @@ import datetime
import sickbeard
import generic
-from sickbeard.common import Quality, cpu_presets
-from sickbeard.name_parser.parser import NameParser, InvalidNameException
+from sickbeard.common import Quality
from sickbeard import logger
from sickbeard import tvcache
from sickbeard import helpers
diff --git a/sickbeard/providers/thepiratebay.py b/sickbeard/providers/thepiratebay.py
index 7478e6da..95a8617e 100644
--- a/sickbeard/providers/thepiratebay.py
+++ b/sickbeard/providers/thepiratebay.py
@@ -28,7 +28,7 @@ import datetime
import sickbeard
import generic
from sickbeard.common import Quality, cpu_presets
-from sickbeard.name_parser.parser import NameParser, InvalidNameException
+from sickbeard.name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from sickbeard import db
from sickbeard import classes
from sickbeard import logger
@@ -153,7 +153,7 @@ class ThePirateBayProvider(generic.TorrentProvider):
try:
myParser = NameParser()
parse_result = myParser.parse(fileName)
- except InvalidNameException:
+ except (InvalidNameException, InvalidShowException):
return None
logger.log(u"Season quality for " + title + " is " + Quality.qualityStrings[quality], logger.DEBUG)
diff --git a/sickbeard/scene_numbering.py b/sickbeard/scene_numbering.py
index e42ddc7c..f89e8899 100644
--- a/sickbeard/scene_numbering.py
+++ b/sickbeard/scene_numbering.py
@@ -167,7 +167,7 @@ def get_indexer_numbering(indexer_id, indexer, sceneSeason, sceneEpisode, fallba
return (sceneSeason, sceneEpisode)
-def get_indexer_absolute_numbering(indexer_id, indexer, sceneAbsoluteNumber, fallback_to_xem=True):
+def get_indexer_absolute_numbering(indexer_id, indexer, sceneAbsoluteNumber, fallback_to_xem=True, scene_season=None):
"""
Returns a tuple, (season, episode, absolute_number) with the TVDB and TVRAGE numbering for (sceneAbsoluteNumber)
(this works like the reverse of get_absolute_numbering)
@@ -179,15 +179,20 @@ def get_indexer_absolute_numbering(indexer_id, indexer, sceneAbsoluteNumber, fal
indexer = int(indexer)
myDB = db.DBConnection()
- rows = myDB.select(
- "SELECT absolute_number FROM scene_numbering WHERE indexer = ? and indexer_id = ? and scene_absolute_number = ?",
- [indexer, indexer_id, sceneAbsoluteNumber])
+ if scene_season is None:
+ rows = myDB.select(
+ "SELECT absolute_number FROM scene_numbering WHERE indexer = ? and indexer_id = ? and scene_absolute_number = ?",
+ [indexer, indexer_id, sceneAbsoluteNumber])
+ else:
+ rows = myDB.select(
+ "SELECT absolute_number FROM scene_numbering WHERE indexer = ? and indexer_id = ? and scene_absolute_number = ? and scene_season = ?",
+ [indexer, indexer_id, sceneAbsoluteNumber, scene_season])
if rows:
return int(rows[0]["absolute_number"])
else:
if fallback_to_xem:
- return get_indexer_absolute_numbering_for_xem(indexer_id, indexer, sceneAbsoluteNumber)
+ return get_indexer_absolute_numbering_for_xem(indexer_id, indexer, sceneAbsoluteNumber, scene_season)
return sceneAbsoluteNumber
@@ -303,7 +308,7 @@ def get_indexer_numbering_for_xem(indexer_id, indexer, sceneSeason, sceneEpisode
return (sceneSeason, sceneEpisode)
-def get_indexer_absolute_numbering_for_xem(indexer_id, indexer, sceneAbsoluteNumber):
+def get_indexer_absolute_numbering_for_xem(indexer_id, indexer, sceneAbsoluteNumber, scene_season=None):
"""
Reverse of find_xem_numbering: lookup a tvdb season and episode using scene numbering
@@ -320,9 +325,14 @@ def get_indexer_absolute_numbering_for_xem(indexer_id, indexer, sceneAbsoluteNum
xem_refresh(indexer_id, indexer)
myDB = db.DBConnection()
- rows = myDB.select(
- "SELECT absolute_number FROM tv_episodes WHERE indexer = ? and showid = ? and scene_absolute_number = ?",
- [indexer, indexer_id, sceneAbsoluteNumber])
+ if scene_season is None:
+ rows = myDB.select(
+ "SELECT absolute_number FROM tv_episodes WHERE indexer = ? and showid = ? and scene_absolute_number = ?",
+ [indexer, indexer_id, sceneAbsoluteNumber])
+ else:
+ rows = myDB.select(
+ "SELECT absolute_number FROM tv_episodes WHERE indexer = ? and showid = ? and scene_absolute_number = ? and scene_season = ?",
+ [indexer, indexer_id, sceneAbsoluteNumber, scene_season])
if rows:
return int(rows[0]["absolute_number"])
diff --git a/sickbeard/search.py b/sickbeard/search.py
index a8450cfd..e3490f9d 100644
--- a/sickbeard/search.py
+++ b/sickbeard/search.py
@@ -328,9 +328,7 @@ def filterSearchResults(show, season, results):
for curEp in results:
# skip non-tv crap
results[curEp] = filter(
- lambda x: show_name_helpers.filterBadReleases(x.name) and show_name_helpers.isGoodResult(x.name, show,
- season=season),
- results[curEp])
+ lambda x: show_name_helpers.filterBadReleases(x.name) and x.show == show,results[curEp])
if curEp in foundResults:
foundResults[curEp] += results[curEp]
@@ -455,10 +453,7 @@ def searchProviders(show, season, episodes, manualSearch=False):
for curEp in searchResults:
# skip non-tv crap
searchResults[curEp] = filter(
- lambda x: show_name_helpers.filterBadReleases(x.name) and show_name_helpers.isGoodResult(x.name,
- show,
- season=season),
- searchResults[curEp])
+ lambda x: show_name_helpers.filterBadReleases(x.name) and x.show == show, searchResults[curEp])
if curEp in foundResults:
foundResults[provider.name][curEp] += searchResults[curEp]
@@ -547,10 +542,7 @@ def searchProviders(show, season, episodes, manualSearch=False):
individualResults = nzbSplitter.splitResult(bestSeasonNZB)
individualResults = filter(
- lambda x: show_name_helpers.filterBadReleases(x.name) and show_name_helpers.isGoodResult(x.name,
- show,
- season=season),
- individualResults)
+ lambda x: show_name_helpers.filterBadReleases(x.name) and x.show == show, individualResults)
for curResult in individualResults:
if len(curResult.episodes) == 1:
diff --git a/sickbeard/show_name_helpers.py b/sickbeard/show_name_helpers.py
index c1d6d118..d622d82c 100644
--- a/sickbeard/show_name_helpers.py
+++ b/sickbeard/show_name_helpers.py
@@ -28,7 +28,7 @@ from sickbeard.scene_exceptions import get_scene_exceptions
from sickbeard import logger
from sickbeard import db
from sickbeard import encodingKludge as ek
-from name_parser.parser import NameParser, InvalidNameException
+from name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from lib.unidecode import unidecode
from sickbeard.blackandwhitelist import BlackAndWhiteList
@@ -52,6 +52,9 @@ def filterBadReleases(name):
except InvalidNameException:
logger.log(u"Unable to parse the filename " + name + " into a valid episode", logger.WARNING)
return False
+ except InvalidShowException:
+ logger.log(u"Unable to parse the filename " + name + " into a valid show", logger.WARNING)
+ return False
# if any of the bad strings are in the name then say no
if sickbeard.IGNORE_WORDS:
diff --git a/sickbeard/tv.py b/sickbeard/tv.py
index 11dfa536..3b6ee39c 100644
--- a/sickbeard/tv.py
+++ b/sickbeard/tv.py
@@ -29,7 +29,7 @@ import sickbeard
import xml.etree.cElementTree as etree
-from name_parser.parser import NameParser, InvalidNameException
+from name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from lib import subliminal
@@ -436,7 +436,7 @@ class TVShow(object):
parse_result = None
np = NameParser(False)
parse_result = np.parse(ep_file_name)
- except InvalidNameException:
+ except (InvalidNameException, InvalidShowException):
pass
if not ' ' in ep_file_name and parse_result and parse_result.release_group:
@@ -2072,7 +2072,7 @@ class TVEpisode(object):
try:
np = NameParser(name, naming_pattern=True)
parse_result = np.parse(name)
- except InvalidNameException, e:
+ except (InvalidNameException, InvalidShowException), e:
logger.log(u"Unable to get parse release_group: " + ex(e), logger.DEBUG)
return ''
diff --git a/sickbeard/tvcache.py b/sickbeard/tvcache.py
index d3905fbc..5bf13395 100644
--- a/sickbeard/tvcache.py
+++ b/sickbeard/tvcache.py
@@ -32,7 +32,7 @@ from sickbeard.common import Quality
from sickbeard import helpers, show_name_helpers
from sickbeard.exceptions import MultipleShowObjectsException
from sickbeard.exceptions import AuthException
-from name_parser.parser import NameParser, InvalidNameException
+from name_parser.parser import NameParser, InvalidNameException, InvalidShowException
from sickbeard.rssfeeds import RSSFeeds
cache_lock = threading.Lock()
@@ -46,7 +46,7 @@ class CacheDBConnection(db.DBConnection):
try:
if not self.hasTable(providerName):
self.action(
- "CREATE TABLE [" + providerName + "] (name TEXT, season NUMERIC, episodes TEXT, indexerid NUMERIC, url TEXT, time NUMERIC, quality TEXT)")
+ "CREATE TABLE [" + providerName + "] (name TEXT, season NUMERIC, episodes TEXT, indexerid NUMERIC, url TEXT, time NUMERIC, quality TEXT, release_group TEXT)")
else:
sqlResults = self.select(
"SELECT url, COUNT(url) as count FROM [" + providerName + "] GROUP BY url HAVING count > 1")
@@ -56,6 +56,10 @@ class CacheDBConnection(db.DBConnection):
# add unique index to prevent further dupes from happening if one does not exist
self.action("CREATE UNIQUE INDEX IF NOT EXISTS idx_url ON " + providerName + " (url)")
+
+ # add release_group column to table if missing
+ if not self.hasColumn(providerName, 'release_group'):
+ self.addColumn(providerName, 'release_group', "TEXT", "")
except Exception, e:
if str(e) != "table [" + providerName + "] already exists":
raise
@@ -242,12 +246,11 @@ class TVCache():
except InvalidNameException:
logger.log(u"Unable to parse the filename " + name + " into a valid episode", logger.DEBUG)
return None
-
- if not parse_result or not parse_result.series_name:
+ except InvalidShowException:
+ logger.log(u"Unable to parse the filename " + name + " into a valid show", logger.WARNING)
return None
- if not parse_result.show:
- logger.log(u"No match for show: [" + parse_result.series_name + "], not caching ...", logger.DEBUG)
+ if not parse_result or not parse_result.series_name:
return None
season = episodes = None
@@ -279,11 +282,14 @@ class TVCache():
if not isinstance(name, unicode):
name = unicode(name, 'utf-8')
+ # get release group
+ release_group = parse_result.release_group
+
logger.log(u"Added RSS item: [" + name + "] to cache: [" + self.providerID + "]", logger.DEBUG)
return [
- "INSERT OR IGNORE INTO [" + self.providerID + "] (name, season, episodes, indexerid, url, time, quality) VALUES (?,?,?,?,?,?,?)",
- [name, season, episodeText, parse_result.show.indexerid, url, curTimestamp, quality]]
+ "INSERT OR IGNORE INTO [" + self.providerID + "] (name, season, episodes, indexerid, url, time, quality, release_group) VALUES (?,?,?,?,?,?,?,?)",
+ [name, season, episodeText, parse_result.show.indexerid, url, curTimestamp, quality, release_group]]
def searchCache(self, episodes, manualSearch=False):
@@ -334,6 +340,7 @@ class TVCache():
continue
curEp = int(curEp)
curQuality = int(curResult["quality"])
+ curReleaseGroup = curResult["release_group"]
# if the show says we want that episode then add it to the list
if not showObj.wantEpisode(curSeason, curEp, curQuality, manualSearch):
@@ -351,9 +358,11 @@ class TVCache():
logger.log(u"Found result " + title + " at " + url)
result = self.provider.getResult([epObj])
+ result.show = showObj
result.url = url
result.name = title
result.quality = curQuality
+ result.release_group = curReleaseGroup
result.content = self.provider.getURL(url) \
if self.provider.providerType == sickbeard.providers.generic.GenericProvider.TORRENT \
and not url.startswith('magnet') else None
diff --git a/sickbeard/webserve.py b/sickbeard/webserve.py
index a97b8304..2ef84235 100644
--- a/sickbeard/webserve.py
+++ b/sickbeard/webserve.py
@@ -22,7 +22,7 @@ import inspect
import traceback
import urlparse
-import os.path
+import os
import time
import urllib
@@ -80,6 +80,7 @@ except ImportError:
from lib import adba
from Cheetah.Template import Template
+
from tornado.web import RequestHandler, HTTPError
@@ -165,10 +166,27 @@ class MainHandler(RequestHandler):
if status_code == 401:
self.finish(self.http_error_401_handler())
elif status_code == 404:
- self.redirect('/home/')
- else:
- logger.log(traceback.format_exc(), logger.DEBUG)
- super(MainHandler, self).write_error(status_code, **kwargs)
+ self.redirect(urlparse.urljoin(sickbeard.WEB_ROOT, '/home/'))
+ elif self.settings.get("debug") and "exc_info" in kwargs:
+ exc_info = kwargs["exc_info"]
+ trace_info = ''.join(["%s
" % line for line in traceback.format_exception(*exc_info)])
+ request_info = ''.join(["%s: %s
" % (k, self.request.__dict__[k] ) for k in
+ self.request.__dict__.keys()])
+ error = exc_info[1]
+
+ self.set_header('Content-Type', 'text/html')
+ self.finish("""
+ %s
+
+ Error
+ %s
+ Traceback
+ %s
+ Request Info
+ %s
+
+ """ % (error, error,
+ trace_info, request_info))
def _dispatch(self):
@@ -212,7 +230,7 @@ class MainHandler(RequestHandler):
elif not func:
func = getattr(klass, 'index', None)
- if func:
+ if callable(func):
return func(**args)
raise HTTPError(404)
@@ -220,14 +238,14 @@ class MainHandler(RequestHandler):
def get(self, *args, **kwargs):
try:
self.finish(self._dispatch())
- except HTTPRedirect, inst:
- self.redirect(inst.url, inst.permanent, inst.status)
+ except HTTPRedirect, e:
+ self.redirect(e.url, e.permanent, e.status)
def post(self, *args, **kwargs):
try:
self.finish(self._dispatch())
- except HTTPRedirect, inst:
- self.redirect(inst.url, inst.permanent, inst.status)
+ except HTTPRedirect, e:
+ self.redirect(e.url, e.permanent, e.status)
def robots_txt(self, *args, **kwargs):
""" Keep web crawlers out """
@@ -469,8 +487,7 @@ class MainHandler(RequestHandler):
class PageTemplate(Template):
def __init__(self, headers, *args, **KWs):
- KWs['file'] = os.path.join(sickbeard.PROG_DIR, "gui/" + sickbeard.GUI_NAME + "/interfaces/default/",
- KWs['file'])
+ KWs['file'] = os.path.join(sickbeard.PROG_DIR, "gui/" + sickbeard.GUI_NAME + "/interfaces/default/",KWs['file'])
super(PageTemplate, self).__init__(*args, **KWs)
self.sbRoot = sickbeard.WEB_ROOT
@@ -506,6 +523,13 @@ class PageTemplate(Template):
{'title': logPageTitle, 'key': 'errorlogs'},
]
+ def compile(self, *args, **kwargs):
+ if not os.path.exists(os.path.join(sickbeard.CACHE_DIR, 'cheetah')):
+ os.mkdir(os.path.join(sickbeard.CACHE_DIR, 'cheetah'))
+
+ kwargs['cacheModuleFilesForTracebacks'] = True
+ kwargs['cacheDirForModuleFiles'] = os.path.join(sickbeard.CACHE_DIR, 'cheetah')
+ return super(PageTemplate, self).compile(*args, **kwargs)
class IndexerWebUI(MainHandler):
def __init__(self, config, log=None):
@@ -1055,7 +1079,8 @@ class Manage(MainHandler):
curErrors += Home(self.application, self.request).editShow(curShow, new_show_dir, anyQualities,
bestQualities, exceptions_list,
- new_flatten_folders, new_paused,
+ flatten_folders=new_flatten_folders,
+ paused=new_paused,
subtitles=new_subtitles, anime=new_anime,
scene=new_scene, directCall=True)
@@ -1401,7 +1426,8 @@ class ConfigGeneral(MainHandler):
update_shows_on_start=None, update_frequency=None, launch_browser=None, web_username=None,
use_api=None, api_key=None, indexer_default=None, timezone_display=None, cpu_preset=None,
web_password=None, version_notify=None, enable_https=None, https_cert=None, https_key=None,
- handle_reverse_proxy=None, sort_article=None, auto_update=None, notify_on_update=None, proxy_setting=None,
+ handle_reverse_proxy=None, sort_article=None, auto_update=None, notify_on_update=None,
+ proxy_setting=None,
anon_redirect=None, git_path=None, calendar_unprotected=None,
fuzzy_dating=None, trim_zero=None, date_preset=None, date_preset_na=None, time_preset=None,
indexer_timeout=None):
@@ -2650,7 +2676,7 @@ class NewHomeAddShows(MainHandler):
'display_dir': '' + ek.ek(os.path.dirname, cur_path) + os.sep + '' + ek.ek(
os.path.basename,
cur_path),
- }
+ }
# see if the folder is in XBMC already
dirResults = myDB.select("SELECT * FROM tv_shows WHERE location = ?", [cur_path])
@@ -3122,6 +3148,7 @@ class Home(MainHandler):
t.showlists = [["Shows", sickbeard.showList]]
t.submenu = HomeMenu()
+
return _munge(t)
addShows = NewHomeAddShows
diff --git a/sickbeard/webserveInit.py b/sickbeard/webserveInit.py
index 8e38aa11..2dd33df1 100644
--- a/sickbeard/webserveInit.py
+++ b/sickbeard/webserveInit.py
@@ -35,7 +35,7 @@ class MultiStaticFileHandler(StaticFileHandler):
raise HTTPError(404)
class SRWebServer(threading.Thread):
- def __init__(self, options=[], io_loop=None):
+ def __init__(self, options={}, io_loop=None):
threading.Thread.__init__(self)
self.daemon = True
self.alive = True
@@ -63,16 +63,17 @@ class SRWebServer(threading.Thread):
if not create_https_certificates(self.https_cert, self.https_key):
logger.log(u"Unable to create CERT/KEY files, disabling HTTPS")
sickbeard.ENABLE_HTTPS = False
- enable_https = False
+ self.enable_https = False
if not (os.path.exists(self.https_cert) and os.path.exists(self.https_key)):
logger.log(u"Disabled HTTPS because of missing CERT and KEY files", logger.WARNING)
sickbeard.ENABLE_HTTPS = False
- enable_https = False
+ self.enable_https = False
# Load the app
self.app = Application([],
- debug=False,
+ debug=True,
+ autoreload=False,
gzip=True,
xheaders=sickbeard.HANDLE_REVERSE_PROXY,
cookie_secret='61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo='
@@ -80,14 +81,14 @@ class SRWebServer(threading.Thread):
# Main Handler
self.app.add_handlers(".*$", [
- (r"%s" % self.options['web_root'], RedirectHandler, {'url': '%s/home/' % self.options['web_root']}),
(r'%s/api/(.*)(/?)' % self.options['web_root'], webapi.Api),
- (r'%s/(.*)(/?)' % self.options['web_root'], webserve.MainHandler)
+ (r'%s/(.*)(/?)' % self.options['web_root'], webserve.MainHandler),
+ (r'(.*)', webserve.MainHandler)
])
# Static Path Handler
self.app.add_handlers(".*$", [
- (r'%s/(favicon\.ico)' % self.options['web_root'], MultiStaticFileHandler,
+ (r'/(favicon\.ico)', MultiStaticFileHandler,
{'paths': [os.path.join(self.options['data_root'], 'images/ico/favicon.ico')]}),
(r'%s/%s/(.*)(/?)' % (self.options['web_root'], 'images'), MultiStaticFileHandler,
{'paths': [os.path.join(self.options['data_root'], 'images'),