myButton
+ * // -> myButton === myComonent.children()[0];
+ *
+ * Pass in options for child constructors and options for children of the child
+ *
+ * var myButton = myComponent.addChild('MyButton', {
+ * text: 'Press Me',
+ * children: {
+ * buttonChildExample: {
+ * buttonChildOption: true
+ * }
+ * }
+ * });
+ *
+ * @param {String|vjs.Component} child The class name or instance of a child to add
+ * @param {Object=} options Options, including options to be passed to children of the child.
+ * @return {vjs.Component} The child component (created by this process if a string was used)
+ * @suppress {accessControls|checkRegExp|checkTypes|checkVars|const|constantProperty|deprecated|duplicate|es5Strict|fileoverviewTags|globalThis|invalidCasts|missingProperties|nonStandardJsDocs|strictModuleDepCheck|undefinedNames|undefinedVars|unknownDefines|uselessCode|visibility}
+ */
+vjs.Component.prototype.addChild = function(child, options){
+ var component, componentClass, componentName, 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: '
'+this.defaultValue+' '
+ }, props);
+
+ return vjs.Component.prototype.createEl.call(this, 'div', props);
+};
+/* Menu
+================================================================================ */
+/**
+ * The Menu component is used to build pop up menus, including subtitle and
+ * captions selection menus.
+ *
+ * @param {vjs.Player|Object} player
+ * @param {Object=} options
+ * @class
+ * @constructor
+ */
+vjs.Menu = vjs.Component.extend();
+
+/**
+ * Add a menu item to the menu
+ * @param {Object|String} component Component or component type to add
+ */
+vjs.Menu.prototype.addItem = function(component){
+ this.addChild(component);
+ component.on('click', vjs.bind(this, function(){
+ this.unlockShowing();
+ }));
+};
+
+/** @inheritDoc */
+vjs.Menu.prototype.createEl = function(){
+ var contentElType = this.options().contentElType || 'ul';
+ this.contentEl_ = vjs.createEl(contentElType, {
+ className: 'vjs-menu-content'
+ });
+ var el = vjs.Component.prototype.createEl.call(this, 'div', {
+ append: this.contentEl_,
+ className: 'vjs-menu'
+ });
+ el.appendChild(this.contentEl_);
+
+ // Prevent clicks from bubbling up. Needed for Menu Buttons,
+ // where a click on the parent is significant
+ vjs.on(el, 'click', function(event){
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ });
+
+ return el;
+};
+
+/**
+ * The component for a menu item. `
`
+ *
+ * @param {vjs.Player|Object} player
+ * @param {Object=} options
+ * @class
+ * @constructor
+ */
+vjs.MenuItem = vjs.Button.extend({
+ /** @constructor */
+ init: function(player, options){
+ vjs.Button.call(this, player, options);
+ this.selected(options['selected']);
+ }
+});
+
+/** @inheritDoc */
+vjs.MenuItem.prototype.createEl = function(type, props){
+ return vjs.Button.prototype.createEl.call(this, 'li', vjs.obj.merge({
+ className: 'vjs-menu-item',
+ innerHTML: this.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
+ *
+ *
+ * ```
+ *
+ * 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 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'];iStream 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 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 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') == -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'+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 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; iu.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'"+h+" "};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'
+ + b64str
+ + ' ');
+
+
+ this.trigger({type:'updateend'});
+ };
+
+ // URL
+ videojs.URL = {
+ createObjectURL: function(object){
+ var url = objectUrlPrefix + urlCount;
+
+ urlCount++;
+
+ // setup the mapping back to object
+ videojs.mediaSources[url] = object;
+
+ return url;
+ }
+ };
+
+ // plugin
+ videojs.plugin('mediaSource', function(options){
+ var player = this;
+
+ player.on('loadstart', function(){
+ var url = player.currentSrc(),
+ trigger = function(event){
+ mediaSource.trigger(event);
+ },
+ mediaSource;
+
+ if (player.techName === 'Html5' && url.indexOf(objectUrlPrefix) === 0) {
+ // use the native media source implementation
+ mediaSource = videojs.mediaSources[url];
+
+ if (!mediaSource.nativeUrl) {
+ // initialize the native source
+ mediaSource.nativeSource = new NativeMediaSource();
+ mediaSource.nativeSource.addEventListener('sourceopen', trigger, false);
+ mediaSource.nativeSource.addEventListener('webkitsourceopen', trigger, false);
+ mediaSource.nativeUrl = nativeUrl.createObjectURL(mediaSource.nativeSource);
+ }
+ player.src(mediaSource.nativeUrl);
+ }
+ });
+ });
+
+})(this);
diff --git a/assets/videojs-media-sources.min.js b/assets/videojs-media-sources.min.js
new file mode 100644
index 0000000..6d6895e
--- /dev/null
+++ b/assets/videojs-media-sources.min.js
@@ -0,0 +1 @@
+(function(e){var t=0,n=e.MediaSource||e.WebKitMediaSource||{},r=e.URL||{},i,s=/video\/flv; codecs=["']vp6,aac["']/,o="blob:vjs-media-source/";i=function(){};i.prototype.init=function(){this.listeners=[]};i.prototype.addEventListener=function(e,t){if(!this.listeners[e]){this.listeners[e]=[]}this.listeners[e].unshift(t)};i.prototype.trigger=function(e){var t=this.listeners[e.type]||[],n=t.length;while(n--){t[n](e)}};videojs.MediaSource=function(){var e=this;videojs.MediaSource.prototype.init.call(this);this.sourceBuffers=[];this.readyState="closed";this.listeners={sourceopen:[function(t){e.swfObj=document.getElementById(t.swfId);e.readyState="open";if(e.swfObj){e.swfObj.vjs_load()}}],webkitsourceopen:[function(t){e.trigger({type:"sourceopen"})}]}};videojs.MediaSource.prototype=new i;videojs.MediaSource.prototype.addSourceBuffer=function(e){var t;if(s.test(e)){t=new videojs.SourceBuffer(this)}else{t=this.nativeSource.addSourceBuffer.apply(this.nativeSource,arguments)}this.sourceBuffers.push(t);return t};videojs.MediaSource.prototype.endOfStream=function(){this.swfObj.vjs_endOfStream();this.readyState="ended"};videojs.mediaSources={};videojs.MediaSource.open=function(e,t){var n=videojs.mediaSources[e];if(n){n.trigger({type:"sourceopen",swfId:t})}else{throw new Error("Media Source not found (Video.js)")}};videojs.SourceBuffer=function(e){videojs.SourceBuffer.prototype.init.call(this);this.source=e;this.buffer=[]};videojs.SourceBuffer.prototype=new i;videojs.SourceBuffer.prototype.appendBuffer=function(t){var n="",r=0,i=t.byteLength,s;this.buffer.push(t);for(r=0;r'+s+" ");this.trigger({type:"updateend"})};videojs.URL={createObjectURL:function(e){var n=o+t;t++;videojs.mediaSources[n]=e;return n}};videojs.plugin("mediaSource",function(e){var t=this;t.on("loadstart",function(){var e=t.currentSrc(),i=function(e){s.trigger(e)},s;if(t.techName==="Html5"&&e.indexOf(o)===0){s=videojs.mediaSources[e];if(!s.nativeUrl){s.nativeSource=new n;s.nativeSource.addEventListener("sourceopen",i,false);s.nativeSource.addEventListener("webkitsourceopen",i,false);s.nativeUrl=r.createObjectURL(s.nativeSource)}t.src(s.nativeUrl)}})})})(this)
diff --git a/assets/videojs.hls.js b/assets/videojs.hls.js
new file mode 100644
index 0000000..0d80d0f
--- /dev/null
+++ b/assets/videojs.hls.js
@@ -0,0 +1,3083 @@
+/*! videojs-contrib-hls - v0.7.2 - 2014-06-13
+* Copyright (c) 2014 Brightcove; Licensed */
+(function(window, videojs, document, undefined) {
+
+var
+
+ // the desired length of video to maintain in the buffer, in seconds
+ goalBufferLength = 5,
+
+ // a fudge factor to apply to advertised playlist bitrates to account for
+ // temporary flucations in client bandwidth
+ bandwidthVariance = 1.1,
+
+ /**
+ * A comparator function to sort two playlist object by bandwidth.
+ * @param left {object} a media playlist object
+ * @param right {object} a media playlist object
+ * @return {number} Greater than zero if the bandwidth attribute of
+ * left is greater than the corresponding attribute of right. Less
+ * than zero if the bandwidth of right is greater than left and
+ * exactly zero if the two are equal.
+ */
+ playlistBandwidth = function(left, right) {
+ var leftBandwidth, rightBandwidth;
+ if (left.attributes && left.attributes.BANDWIDTH) {
+ leftBandwidth = left.attributes.BANDWIDTH;
+ }
+ leftBandwidth = leftBandwidth || window.Number.MAX_VALUE;
+ if (right.attributes && right.attributes.BANDWIDTH) {
+ rightBandwidth = right.attributes.BANDWIDTH;
+ }
+ rightBandwidth = rightBandwidth || window.Number.MAX_VALUE;
+
+ return leftBandwidth - rightBandwidth;
+ },
+
+ /**
+ * A comparator function to sort two playlist object by resolution (width).
+ * @param left {object} a media playlist object
+ * @param right {object} a media playlist object
+ * @return {number} Greater than zero if the resolution.width attribute of
+ * left is greater than the corresponding attribute of right. Less
+ * than zero if the resolution.width of right is greater than left and
+ * exactly zero if the two are equal.
+ */
+ playlistResolution = function(left, right) {
+ var leftWidth, rightWidth;
+
+ if (left.attributes && left.attributes.RESOLUTION && left.attributes.RESOLUTION.width) {
+ leftWidth = left.attributes.RESOLUTION.width;
+ }
+
+ leftWidth = leftWidth || window.Number.MAX_VALUE;
+
+ if (right.attributes && right.attributes.RESOLUTION && right.attributes.RESOLUTION.width) {
+ rightWidth = right.attributes.RESOLUTION.width;
+ }
+
+ rightWidth = rightWidth || window.Number.MAX_VALUE;
+
+ // NOTE - Fallback to bandwidth sort as appropriate in cases where multiple renditions
+ // have the same media dimensions/ resolution
+ if (leftWidth === rightWidth && left.attributes.BANDWIDTH && right.attributes.BANDWIDTH) {
+ return left.attributes.BANDWIDTH - right.attributes.BANDWIDTH;
+ } else {
+ return leftWidth - rightWidth;
+ }
+ },
+
+ xhr,
+
+ /**
+ * TODO - Document this great feature.
+ *
+ * @param playlist
+ * @param time
+ * @returns int
+ */
+ getMediaIndexByTime = function(playlist, time) {
+ var index, counter, timeRanges, currentSegmentRange;
+
+ timeRanges = [];
+ for (index = 0; index < playlist.segments.length; index++) {
+ currentSegmentRange = {};
+ currentSegmentRange.start = (index === 0) ? 0 : timeRanges[index - 1].end;
+ currentSegmentRange.end = currentSegmentRange.start + playlist.segments[index].duration;
+ timeRanges.push(currentSegmentRange);
+ }
+
+ for (counter = 0; counter < timeRanges.length; counter++) {
+ if (time >= timeRanges[counter].start && time < timeRanges[counter].end) {
+ return counter;
+ }
+ }
+
+ return -1;
+
+ },
+
+ /**
+ * Determine the media index in one playlist that corresponds to a
+ * specified media index in another. This function can be used to
+ * calculate a new segment position when a playlist is reloaded or a
+ * variant playlist is becoming active.
+ * @param mediaIndex {number} the index into the original playlist
+ * to translate
+ * @param original {object} the playlist to translate the media
+ * index from
+ * @param update {object} the playlist to translate the media index
+ * to
+ * @param {number} the corresponding media index in the updated
+ * playlist
+ */
+ translateMediaIndex = function(mediaIndex, original, update) {
+ var
+ i,
+ originalSegment;
+
+ // no segments have been loaded from the original playlist
+ if (mediaIndex === 0) {
+ return 0;
+ }
+ if (!(update && update.segments)) {
+ // let the media index be zero when there are no segments defined
+ return 0;
+ }
+
+ // try to sync based on URI
+ i = update.segments.length;
+ originalSegment = original.segments[mediaIndex - 1];
+ while (i--) {
+ if (originalSegment.uri === update.segments[i].uri) {
+ return i + 1;
+ }
+ }
+
+ // sync on media sequence
+ return (original.mediaSequence + mediaIndex) - update.mediaSequence;
+ },
+
+ /**
+ * Calculate the total duration for a playlist based on segment metadata.
+ * @param playlist {object} a media playlist object
+ * @return {number} the currently known duration, in seconds
+ */
+ totalDuration = function(playlist) {
+ var
+ duration = 0,
+ segment,
+ i;
+
+ if (!playlist) {
+ return 0;
+ }
+
+ i = (playlist.segments || []).length;
+
+ // if present, use the duration specified in the playlist
+ if (playlist.totalDuration) {
+ return playlist.totalDuration;
+ }
+
+ // duration should be Infinity for live playlists
+ if (!playlist.endList) {
+ return window.Infinity;
+ }
+
+ while (i--) {
+ segment = playlist.segments[i];
+ duration += segment.duration || playlist.targetDuration || 0;
+ }
+ return duration;
+ },
+
+ resolveUrl,
+
+ initSource = function(player, mediaSource, srcUrl) {
+ var
+ segmentParser = new videojs.Hls.SegmentParser(),
+ settings = videojs.util.mergeOptions({}, player.options().hls),
+
+ lastSeekedTime,
+ segmentXhr,
+ fillBuffer,
+ updateDuration;
+
+
+ player.hls.currentTime = function() {
+ if (lastSeekedTime) {
+ return lastSeekedTime;
+ }
+ return this.el().vjs_getProperty('currentTime');
+ };
+ player.hls.setCurrentTime = function(currentTime) {
+ if (!(this.playlists && this.playlists.media())) {
+ // return immediately if the metadata is not ready yet
+ return 0;
+ }
+
+ // save the seek target so currentTime can report it correctly
+ // while the seek is pending
+ lastSeekedTime = currentTime;
+
+ // determine the requested segment
+ this.mediaIndex =
+ getMediaIndexByTime(this.playlists.media(), currentTime);
+
+ // abort any segments still being decoded
+ this.sourceBuffer.abort();
+
+ // cancel outstanding requests and buffer appends
+ if (segmentXhr) {
+ segmentXhr.abort();
+ }
+
+ // begin filling the buffer at the new position
+ fillBuffer(currentTime * 1000);
+ };
+
+ /**
+ * Update the player duration
+ */
+ updateDuration = function(playlist) {
+ var oldDuration = player.duration(),
+ newDuration = totalDuration(playlist);
+
+ // if the duration has changed, invalidate the cached value
+ if (oldDuration !== newDuration) {
+ player.trigger('durationchange');
+ }
+ };
+
+ /**
+ * Chooses the appropriate media playlist based on the current
+ * bandwidth estimate and the player size.
+ * @return the highest bitrate playlist less than the currently detected
+ * bandwidth, accounting for some amount of bandwidth variance
+ */
+ player.hls.selectPlaylist = function () {
+ var
+ effectiveBitrate,
+ sortedPlaylists = player.hls.playlists.master.playlists.slice(),
+ bandwidthPlaylists = [],
+ i = sortedPlaylists.length,
+ variant,
+ bandwidthBestVariant,
+ resolutionBestVariant;
+
+ sortedPlaylists.sort(playlistBandwidth);
+
+ // filter out any variant that has greater effective bitrate
+ // than the current estimated bandwidth
+ while (i--) {
+ variant = sortedPlaylists[i];
+
+ // ignore playlists without bandwidth information
+ if (!variant.attributes || !variant.attributes.BANDWIDTH) {
+ continue;
+ }
+
+ effectiveBitrate = variant.attributes.BANDWIDTH * bandwidthVariance;
+
+ if (effectiveBitrate < player.hls.bandwidth) {
+ bandwidthPlaylists.push(variant);
+
+ // since the playlists are sorted in ascending order by
+ // bandwidth, the first viable variant is the best
+ if (!bandwidthBestVariant) {
+ bandwidthBestVariant = variant;
+ }
+ }
+ }
+
+ i = bandwidthPlaylists.length;
+
+ // sort variants by resolution
+ bandwidthPlaylists.sort(playlistResolution);
+
+ // iterate through the bandwidth-filtered playlists and find
+ // best rendition by player dimension
+ while (i--) {
+ variant = bandwidthPlaylists[i];
+
+ // ignore playlists without resolution information
+ if (!variant.attributes ||
+ !variant.attributes.RESOLUTION ||
+ !variant.attributes.RESOLUTION.width ||
+ !variant.attributes.RESOLUTION.height) {
+ continue;
+ }
+
+ // since the playlists are sorted, the first variant that has
+ // dimensions less than or equal to the player size is the
+ // best
+ if (variant.attributes.RESOLUTION.width <= player.width() &&
+ variant.attributes.RESOLUTION.height <= player.height()) {
+ resolutionBestVariant = variant;
+ break;
+ }
+ }
+
+ // fallback chain of variants
+ return resolutionBestVariant || bandwidthBestVariant || sortedPlaylists[0];
+ };
+
+ /**
+ * Determines whether there is enough video data currently in the buffer
+ * and downloads a new segment if the buffered time is less than the goal.
+ * @param offset (optional) {number} the offset into the downloaded segment
+ * to seek to, in milliseconds
+ */
+ fillBuffer = function(offset) {
+ var
+ buffered = player.buffered(),
+ bufferedTime = 0,
+ segment,
+ segmentUri,
+ startTime;
+
+ // if there is a request already in flight, do nothing
+ if (segmentXhr) {
+ return;
+ }
+
+ // if no segments are available, do nothing
+ if (player.hls.playlists.state === "HAVE_NOTHING" ||
+ !player.hls.playlists.media().segments) {
+ return;
+ }
+
+ // if the video has finished downloading, stop trying to buffer
+ segment = player.hls.playlists.media().segments[player.hls.mediaIndex];
+ if (!segment) {
+ return;
+ }
+
+ if (buffered) {
+ // assuming a single, contiguous buffer region
+ bufferedTime = player.buffered().end(0) - player.currentTime();
+ }
+
+ // if there is plenty of content in the buffer and we're not
+ // seeking, relax for awhile
+ if (typeof offset !== 'number' && bufferedTime >= goalBufferLength) {
+ return;
+ }
+
+ // resolve the segment URL relative to the playlist
+ if (player.hls.playlists.media().uri === srcUrl) {
+ segmentUri = resolveUrl(srcUrl, segment.uri);
+ } else {
+ segmentUri = resolveUrl(resolveUrl(srcUrl, player.hls.playlists.media().uri || ''),
+ segment.uri);
+ }
+
+ startTime = +new Date();
+
+ // request the next segment
+ segmentXhr = xhr({
+ url: segmentUri,
+ responseType: 'arraybuffer',
+ withCredentials: settings.withCredentials
+ }, function(error, url) {
+ // the segment request is no longer outstanding
+ segmentXhr = null;
+
+ if (error) {
+ player.hls.error = {
+ status: this.status,
+ message: 'HLS segment request error at URL: ' + url,
+ code: (this.status >= 500) ? 4 : 2
+ };
+
+ // try moving on to the next segment
+ player.hls.mediaIndex++;
+ return;
+ }
+
+ // stop processing if the request was aborted
+ if (!this.response) {
+ return;
+ }
+
+ // calculate the download bandwidth
+ player.hls.segmentXhrTime = (+new Date()) - startTime;
+ player.hls.bandwidth = (this.response.byteLength / player.hls.segmentXhrTime) * 8 * 1000;
+
+ // transmux the segment data from MP2T to FLV
+ segmentParser.parseSegmentBinaryData(new Uint8Array(this.response));
+ segmentParser.flushTags();
+
+ // if we're refilling the buffer after a seek, scan through the muxed
+ // FLV tags until we find the one that is closest to the desired
+ // playback time
+ if (typeof offset === 'number') {
+ (function() {
+ var tag = segmentParser.getTags()[0];
+
+ for (; tag.pts < offset; tag = segmentParser.getTags()[0]) {
+ segmentParser.getNextTag();
+ }
+
+ // tell the SWF where we will be seeking to
+ player.hls.el().vjs_setProperty('currentTime', tag.pts * 0.001);
+ lastSeekedTime = null;
+ })();
+ }
+
+ while (segmentParser.tagsAvailable()) {
+ // queue up the bytes to be appended to the SourceBuffer
+ // the queue gives control back to the browser between tags
+ // so that large segments don't cause a "hiccup" in playback
+
+ player.hls.sourceBuffer.appendBuffer(segmentParser.getNextTag().bytes,
+ player);
+
+ }
+
+ player.hls.mediaIndex++;
+
+ if (player.hls.mediaIndex === player.hls.playlists.media().segments.length) {
+ mediaSource.endOfStream();
+ }
+
+ // figure out what stream the next segment should be downloaded from
+ // with the updated bandwidth information
+ player.hls.playlists.media(player.hls.selectPlaylist());
+ });
+ };
+
+ // load the MediaSource into the player
+ mediaSource.addEventListener('sourceopen', function() {
+ // construct the video data buffer and set the appropriate MIME type
+ var
+ sourceBuffer = mediaSource.addSourceBuffer('video/flv; codecs="vp6,aac"'),
+ oldMediaPlaylist;
+
+ player.hls.sourceBuffer = sourceBuffer;
+ sourceBuffer.appendBuffer(segmentParser.getFlvHeader());
+
+ player.hls.mediaIndex = 0;
+ player.hls.playlists =
+ new videojs.Hls.PlaylistLoader(srcUrl, settings.withCredentials);
+ player.hls.playlists.on('loadedmetadata', function() {
+ oldMediaPlaylist = player.hls.playlists.media();
+
+ // periodicaly check if the buffer needs to be refilled
+ fillBuffer();
+ player.on('timeupdate', fillBuffer);
+
+ player.trigger('loadedmetadata');
+ });
+ player.hls.playlists.on('error', function() {
+ player.error(player.hls.playlists.error);
+ });
+ player.hls.playlists.on('loadedplaylist', function() {
+ var updatedPlaylist = player.hls.playlists.media();
+
+ if (!updatedPlaylist) {
+ // do nothing before an initial media playlist has been activated
+ return;
+ }
+
+ updateDuration(player.hls.playlists.media());
+ player.hls.mediaIndex = translateMediaIndex(player.hls.mediaIndex,
+ oldMediaPlaylist,
+ updatedPlaylist);
+ oldMediaPlaylist = updatedPlaylist;
+ });
+ });
+ };
+
+var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i;
+
+videojs.Hls = videojs.Flash.extend({
+ init: function(player, options, ready) {
+ var
+ source = options.source,
+ settings = player.options();
+
+ player.hls = this;
+ delete options.source;
+ options.swf = settings.flash.swf;
+ videojs.Flash.call(this, player, options, ready);
+ options.source = source;
+ videojs.Hls.prototype.src.call(this, options.source && options.source.src);
+ }
+});
+
+videojs.Hls.prototype.src = function(src) {
+ var
+ player = this.player(),
+ self = this,
+ mediaSource,
+ source;
+
+ if (src) {
+ mediaSource = new videojs.MediaSource();
+ source = {
+ src: videojs.URL.createObjectURL(mediaSource),
+ type: "video/flv"
+ };
+ this.mediaSource = mediaSource;
+ initSource(player, mediaSource, src);
+ this.player().ready(function() {
+ self.el().vjs_src(source.src);
+ });
+ }
+};
+
+videojs.Hls.prototype.duration = function() {
+ var playlists = this.playlists;
+ if (playlists) {
+ return totalDuration(playlists.media());
+ }
+ return 0;
+};
+
+videojs.Hls.prototype.dispose = function() {
+ if (this.playlists) {
+ this.playlists.dispose();
+ }
+ videojs.Flash.prototype.dispose.call(this);
+};
+
+videojs.Hls.isSupported = function() {
+ return videojs.Flash.isSupported() && videojs.MediaSource;
+};
+
+videojs.Hls.canPlaySource = function(srcObj) {
+ return mpegurlRE.test(srcObj.type);
+};
+
+/**
+ * Creates and sends an XMLHttpRequest.
+ * @param options {string | object} if this argument is a string, it
+ * is intrepreted as a URL and a simple GET request is
+ * inititated. If it is an object, it should contain a `url`
+ * property that indicates the URL to request and optionally a
+ * `method` which is the type of HTTP request to send.
+ * @param callback (optional) {function} a function to call when the
+ * request completes. If the request was not successful, the first
+ * argument will be falsey.
+ * @return {object} the XMLHttpRequest that was initiated.
+ */
+xhr = videojs.Hls.xhr = function(url, callback) {
+ var
+ options = {
+ method: 'GET',
+ timeout: 45 * 1000
+ },
+ request,
+ abortTimeout;
+
+ if (typeof callback !== 'function') {
+ callback = function() {};
+ }
+
+ if (typeof url === 'object') {
+ options = videojs.util.mergeOptions(options, url);
+ url = options.url;
+ }
+
+ request = new window.XMLHttpRequest();
+ request.open(options.method, url);
+ request.url = url;
+
+ if (options.responseType) {
+ request.responseType = options.responseType;
+ }
+ if (options.withCredentials) {
+ request.withCredentials = true;
+ }
+ if (options.timeout) {
+ if (request.timeout === 0) {
+ request.timeout = options.timeout;
+ } else {
+ // polyfill XHR2 by aborting after the timeout
+ abortTimeout = window.setTimeout(function() {
+ if (request.readystate !== 4) {
+ request.abort();
+ }
+ }, options.timeout);
+ }
+ }
+
+ request.onreadystatechange = function() {
+ // wait until the request completes
+ if (this.readyState !== 4) {
+ return;
+ }
+
+ // clear outstanding timeouts
+ window.clearTimeout(abortTimeout);
+
+ // request error
+ if (this.status >= 400 || this.status === 0) {
+ return callback.call(this, true, url);
+ }
+
+ return callback.call(this, false, url);
+ };
+ request.send(null);
+ return request;
+};
+
+/**
+ * Constructs a new URI by interpreting a path relative to another
+ * URI.
+ * @param basePath {string} a relative or absolute URI
+ * @param path {string} a path part to combine with the base
+ * @return {string} a URI that is equivalent to composing `base`
+ * with `path`
+ * @see http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue
+ */
+resolveUrl = videojs.Hls.resolveUrl = function(basePath, path) {
+ // use the base element to get the browser to handle URI resolution
+ var
+ oldBase = document.querySelector('base'),
+ docHead = document.querySelector('head'),
+ a = document.createElement('a'),
+ base = oldBase,
+ oldHref,
+ result;
+
+ // prep the document
+ if (oldBase) {
+ oldHref = oldBase.href;
+ } else {
+ base = docHead.appendChild(document.createElement('base'));
+ }
+
+ base.href = basePath;
+ a.href = path;
+ result = a.href;
+
+ // clean up
+ if (oldBase) {
+ oldBase.href = oldHref;
+ } else {
+ docHead.removeChild(base);
+ }
+ return result;
+};
+
+})(window, window.videojs, document);
+
+(function(window) {
+
+window.videojs = window.videojs || {};
+window.videojs.Hls = window.videojs.Hls || {};
+
+var hls = window.videojs.Hls;
+
+// (type:uint, extraData:Boolean = false) extends ByteArray
+hls.FlvTag = function(type, extraData) {
+ var
+ // Counter if this is a metadata tag, nal start marker if this is a video
+ // tag. unused if this is an audio tag
+ adHoc = 0, // :uint
+
+ // checks whether the FLV tag has enough capacity to accept the proposed
+ // write and re-allocates the internal buffers if necessary
+ prepareWrite = function(flv, count) {
+ var
+ bytes,
+ minLength = flv.position + count;
+ if (minLength < flv.bytes.byteLength) {
+ // there's enough capacity so do nothing
+ return;
+ }
+
+ // allocate a new buffer and copy over the data that will not be modified
+ bytes = new Uint8Array(minLength * 2);
+ bytes.set(flv.bytes.subarray(0, flv.position), 0);
+ flv.bytes = bytes;
+ flv.view = new DataView(flv.bytes.buffer);
+ },
+
+ // commonly used metadata properties
+ widthBytes = hls.FlvTag.widthBytes || new Uint8Array('width'.length),
+ heightBytes = hls.FlvTag.heightBytes || new Uint8Array('height'.length),
+ videocodecidBytes = hls.FlvTag.videocodecidBytes || new Uint8Array('videocodecid'.length),
+ i;
+
+ if (!hls.FlvTag.widthBytes) {
+ // calculating the bytes of common metadata names ahead of time makes the
+ // corresponding writes faster because we don't have to loop over the
+ // characters
+ // re-test with test/perf.html if you're planning on changing this
+ for (i in 'width') {
+ widthBytes[i] = 'width'.charCodeAt(i);
+ }
+ for (i in 'height') {
+ heightBytes[i] = 'height'.charCodeAt(i);
+ }
+ for (i in 'videocodecid') {
+ videocodecidBytes[i] = 'videocodecid'.charCodeAt(i);
+ }
+
+ hls.FlvTag.widthBytes = widthBytes;
+ hls.FlvTag.heightBytes = heightBytes;
+ hls.FlvTag.videocodecidBytes = videocodecidBytes;
+ }
+
+ this.keyFrame = false; // :Boolean
+
+ switch(type) {
+ case hls.FlvTag.VIDEO_TAG:
+ this.length = 16;
+ break;
+ case hls.FlvTag.AUDIO_TAG:
+ this.length = 13;
+ this.keyFrame = true;
+ break;
+ case hls.FlvTag.METADATA_TAG:
+ this.length = 29;
+ this.keyFrame = true;
+ break;
+ default:
+ throw("Error Unknown TagType");
+ }
+
+ this.bytes = new Uint8Array(16384);
+ this.view = new DataView(this.bytes.buffer);
+ this.bytes[0] = type;
+ this.position = this.length;
+ this.keyFrame = extraData; // Defaults to false
+
+ // presentation timestamp
+ this.pts = 0;
+ // decoder timestamp
+ this.dts = 0;
+
+ // ByteArray#writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0)
+ this.writeBytes = function(bytes, offset, length) {
+ var
+ start = offset || 0,
+ end;
+ length = length || bytes.byteLength;
+ end = start + length;
+
+ prepareWrite(this, length);
+ this.bytes.set(bytes.subarray(start, end), this.position);
+
+ this.position += length;
+ this.length = Math.max(this.length, this.position);
+ };
+
+ // ByteArray#writeByte(value:int):void
+ this.writeByte = function(byte) {
+ prepareWrite(this, 1);
+ this.bytes[this.position] = byte;
+ this.position++;
+ this.length = Math.max(this.length, this.position);
+ };
+
+ // ByteArray#writeShort(value:int):void
+ this.writeShort = function(short) {
+ prepareWrite(this, 2);
+ this.view.setUint16(this.position, short);
+ this.position += 2;
+ this.length = Math.max(this.length, this.position);
+ };
+
+ // Negative index into array
+ // (pos:uint):int
+ this.negIndex = function(pos) {
+ return this.bytes[this.length - pos];
+ };
+
+ // The functions below ONLY work when this[0] == VIDEO_TAG.
+ // We are not going to check for that because we dont want the overhead
+ // (nal:ByteArray = null):int
+ this.nalUnitSize = function() {
+ if (adHoc === 0) {
+ return 0;
+ }
+
+ return this.length - (adHoc + 4);
+ };
+
+ this.startNalUnit = function() {
+ // remember position and add 4 bytes
+ if (adHoc > 0) {
+ throw new Error("Attempted to create new NAL wihout closing the old one");
+ }
+
+ // reserve 4 bytes for nal unit size
+ adHoc = this.length;
+ this.length += 4;
+ this.position = this.length;
+ };
+
+ // (nal:ByteArray = null):void
+ this.endNalUnit = function(nalContainer) {
+ var
+ nalStart, // :uint
+ nalLength; // :uint
+
+ // Rewind to the marker and write the size
+ if (this.length === adHoc + 4) {
+ // we started a nal unit, but didnt write one, so roll back the 4 byte size value
+ this.length -= 4;
+ } else if (adHoc > 0) {
+ nalStart = adHoc + 4;
+ nalLength = this.length - nalStart;
+
+ this.position = adHoc;
+ this.view.setUint32(this.position, nalLength);
+ this.position = this.length;
+
+ if (nalContainer) {
+ // Add the tag to the NAL unit
+ nalContainer.push(this.bytes.subarray(nalStart, nalStart + nalLength));
+ }
+ }
+
+ adHoc = 0;
+ };
+
+ /**
+ * Write out a 64-bit floating point valued metadata property. This method is
+ * called frequently during a typical parse and needs to be fast.
+ */
+ // (key:String, val:Number):void
+ this.writeMetaDataDouble = function(key, val) {
+ var i;
+ prepareWrite(this, 2 + key.length + 9);
+
+ // write size of property name
+ this.view.setUint16(this.position, key.length);
+ this.position += 2;
+
+ // this next part looks terrible but it improves parser throughput by
+ // 10kB/s in my testing
+
+ // write property name
+ if (key === 'width') {
+ this.bytes.set(widthBytes, this.position);
+ this.position += 5;
+ } else if (key === 'height') {
+ this.bytes.set(heightBytes, this.position);
+ this.position += 6;
+ } else if (key === 'videocodecid') {
+ this.bytes.set(videocodecidBytes, this.position);
+ this.position += 12;
+ } else {
+ for (i in key) {
+ this.bytes[this.position] = key.charCodeAt(i);
+ this.position++;
+ }
+ }
+
+ // skip null byte
+ this.position++;
+
+ // write property value
+ this.view.setFloat64(this.position, val);
+ this.position += 8;
+
+ // update flv tag length
+ this.length = Math.max(this.length, this.position);
+ ++adHoc;
+ };
+
+ // (key:String, val:Boolean):void
+ this.writeMetaDataBoolean = function(key, val) {
+ var i;
+ prepareWrite(this, 2);
+ this.view.setUint16(this.position, key.length);
+ this.position += 2;
+ for (i in key) {
+ console.assert(key.charCodeAt(i) < 255);
+ prepareWrite(this, 1);
+ this.bytes[this.position] = key.charCodeAt(i);
+ this.position++;
+ }
+ prepareWrite(this, 2);
+ this.view.setUint8(this.position, 0x01);
+ this.position++;
+ this.view.setUint8(this.position, val ? 0x01 : 0x00);
+ this.position++;
+ this.length = Math.max(this.length, this.position);
+ ++adHoc;
+ };
+
+ // ():ByteArray
+ this.finalize = function() {
+ var
+ dtsDelta, // :int
+ len; // :int
+
+ switch(this.bytes[0]) {
+ // Video Data
+ case hls.FlvTag.VIDEO_TAG:
+ this.bytes[11] = ((this.keyFrame || extraData) ? 0x10 : 0x20 ) | 0x07; // We only support AVC, 1 = key frame (for AVC, a seekable frame), 2 = inter frame (for AVC, a non-seekable frame)
+ this.bytes[12] = extraData ? 0x00 : 0x01;
+
+ dtsDelta = this.pts - this.dts;
+ this.bytes[13] = (dtsDelta & 0x00FF0000) >>> 16;
+ this.bytes[14] = (dtsDelta & 0x0000FF00) >>> 8;
+ this.bytes[15] = (dtsDelta & 0x000000FF) >>> 0;
+ break;
+
+ case hls.FlvTag.AUDIO_TAG:
+ this.bytes[11] = 0xAF; // 44 kHz, 16-bit stereo
+ this.bytes[12] = extraData ? 0x00 : 0x01;
+ break;
+
+ case hls.FlvTag.METADATA_TAG:
+ this.position = 11;
+ this.view.setUint8(this.position, 0x02); // String type
+ this.position++;
+ this.view.setUint16(this.position, 0x0A); // 10 Bytes
+ this.position += 2;
+ // set "onMetaData"
+ this.bytes.set([0x6f, 0x6e, 0x4d, 0x65,
+ 0x74, 0x61, 0x44, 0x61,
+ 0x74, 0x61], this.position);
+ this.position += 10;
+ this.bytes[this.position] = 0x08; // Array type
+ this.position++;
+ this.view.setUint32(this.position, adHoc);
+ this.position = this.length;
+ this.bytes.set([0, 0, 9], this.position);
+ this.position += 3; // End Data Tag
+ this.length = this.position;
+ break;
+ }
+
+ len = this.length - 11;
+
+ // write the DataSize field
+ this.bytes[ 1] = (len & 0x00FF0000) >>> 16;
+ this.bytes[ 2] = (len & 0x0000FF00) >>> 8;
+ this.bytes[ 3] = (len & 0x000000FF) >>> 0;
+ // write the Timestamp
+ this.bytes[ 4] = (this.pts & 0x00FF0000) >>> 16;
+ this.bytes[ 5] = (this.pts & 0x0000FF00) >>> 8;
+ this.bytes[ 6] = (this.pts & 0x000000FF) >>> 0;
+ this.bytes[ 7] = (this.pts & 0xFF000000) >>> 24;
+ // write the StreamID
+ this.bytes[ 8] = 0;
+ this.bytes[ 9] = 0;
+ this.bytes[10] = 0;
+
+ this.view.setUint32(this.length, this.length);
+ this.length += 4;
+ this.position += 4;
+
+ // trim down the byte buffer to what is actually being used
+ this.bytes = this.bytes.subarray(0, this.length);
+ this.frameTime = hls.FlvTag.frameTime(this.bytes);
+ console.assert(this.bytes.byteLength === this.length);
+ return this;
+ };
+};
+
+hls.FlvTag.AUDIO_TAG = 0x08; // == 8, :uint
+hls.FlvTag.VIDEO_TAG = 0x09; // == 9, :uint
+hls.FlvTag.METADATA_TAG = 0x12; // == 18, :uint
+
+// (tag:ByteArray):Boolean {
+hls.FlvTag.isAudioFrame = function(tag) {
+ return hls.FlvTag.AUDIO_TAG === tag[0];
+};
+
+// (tag:ByteArray):Boolean {
+hls.FlvTag.isVideoFrame = function(tag) {
+ return hls.FlvTag.VIDEO_TAG === tag[0];
+};
+
+// (tag:ByteArray):Boolean {
+hls.FlvTag.isMetaData = function(tag) {
+ return hls.FlvTag.METADATA_TAG === tag[0];
+};
+
+// (tag:ByteArray):Boolean {
+hls.FlvTag.isKeyFrame = function(tag) {
+ if (hls.FlvTag.isVideoFrame(tag)) {
+ return tag[11] === 0x17;
+ }
+
+ if (hls.FlvTag.isAudioFrame(tag)) {
+ return true;
+ }
+
+ if (hls.FlvTag.isMetaData(tag)) {
+ return true;
+ }
+
+ return false;
+};
+
+// (tag:ByteArray):uint {
+hls.FlvTag.frameTime = function(tag) {
+ var pts = tag[ 4] << 16; // :uint
+ pts |= tag[ 5] << 8;
+ pts |= tag[ 6] << 0;
+ pts |= tag[ 7] << 24;
+ return pts;
+};
+
+})(this);
+
+(function(window) {
+
+/**
+ * Parser for exponential Golomb codes, a variable-bitwidth number encoding
+ * scheme used by h264.
+ */
+window.videojs.Hls.ExpGolomb = function(workingData) {
+ var
+ // the number of bytes left to examine in workingData
+ workingBytesAvailable = workingData.byteLength,
+
+ // the current word being examined
+ workingWord = 0, // :uint
+
+ // the number of bits left to examine in the current word
+ workingBitsAvailable = 0; // :uint;
+
+ // ():uint
+ this.length = function() {
+ return (8 * workingBytesAvailable);
+ };
+
+ // ():uint
+ this.bitsAvailable = function() {
+ return (8 * workingBytesAvailable) + workingBitsAvailable;
+ };
+
+ // ():void
+ this.loadWord = function() {
+ var
+ position = workingData.byteLength - workingBytesAvailable,
+ workingBytes = new Uint8Array(4),
+ availableBytes = Math.min(4, workingBytesAvailable);
+
+ if (availableBytes === 0) {
+ throw new Error('no bytes available');
+ }
+
+ workingBytes.set(workingData.subarray(position,
+ position + availableBytes));
+ workingWord = new DataView(workingBytes.buffer).getUint32(0);
+
+ // track the amount of workingData that has been processed
+ workingBitsAvailable = availableBytes * 8;
+ workingBytesAvailable -= availableBytes;
+ };
+
+ // (count:int):void
+ this.skipBits = function(count) {
+ var skipBytes; // :int
+ if (workingBitsAvailable > count) {
+ workingWord <<= count;
+ workingBitsAvailable -= count;
+ } else {
+ count -= workingBitsAvailable;
+ skipBytes = count / 8;
+
+ count -= (skipBytes * 8);
+ workingBytesAvailable -= skipBytes;
+
+ this.loadWord();
+
+ workingWord <<= count;
+ workingBitsAvailable -= count;
+ }
+ };
+
+ // (size:int):uint
+ this.readBits = function(size) {
+ var
+ bits = Math.min(workingBitsAvailable, size), // :uint
+ valu = workingWord >>> (32 - bits); // :uint
+
+ console.assert(size < 32, 'Cannot read more than 32 bits at a time');
+
+ workingBitsAvailable -= bits;
+ if (workingBitsAvailable > 0) {
+ workingWord <<= bits;
+ } else if (workingBytesAvailable > 0) {
+ this.loadWord();
+ }
+
+ bits = size - bits;
+ if (bits > 0) {
+ return valu << bits | this.readBits(bits);
+ } else {
+ return valu;
+ }
+ };
+
+ // ():uint
+ this.skipLeadingZeros = function() {
+ var leadingZeroCount; // :uint
+ for (leadingZeroCount = 0 ; leadingZeroCount < workingBitsAvailable ; ++leadingZeroCount) {
+ if (0 !== (workingWord & (0x80000000 >>> leadingZeroCount))) {
+ // the first bit of working word is 1
+ workingWord <<= leadingZeroCount;
+ workingBitsAvailable -= leadingZeroCount;
+ return leadingZeroCount;
+ }
+ }
+
+ // we exhausted workingWord and still have not found a 1
+ this.loadWord();
+ return leadingZeroCount + this.skipLeadingZeros();
+ };
+
+ // ():void
+ this.skipUnsignedExpGolomb = function() {
+ this.skipBits(1 + this.skipLeadingZeros());
+ };
+
+ // ():void
+ this.skipExpGolomb = function() {
+ this.skipBits(1 + this.skipLeadingZeros());
+ };
+
+ // ():uint
+ this.readUnsignedExpGolomb = function() {
+ var clz = this.skipLeadingZeros(); // :uint
+ return this.readBits(clz + 1) - 1;
+ };
+
+ // ():int
+ this.readExpGolomb = function() {
+ var valu = this.readUnsignedExpGolomb(); // :int
+ if (0x01 & valu) {
+ // the number is odd if the low order bit is set
+ return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
+ } else {
+ return -1 * (valu >>> 1); // divide by two then make it negative
+ }
+ };
+
+ // Some convenience functions
+ // :Boolean
+ this.readBoolean = function() {
+ return 1 === this.readBits(1);
+ };
+
+ // ():int
+ this.readUnsignedByte = function() {
+ return this.readBits(8);
+ };
+
+ this.loadWord();
+
+};
+})(this);
+
+(function(window) {
+ var
+ ExpGolomb = window.videojs.Hls.ExpGolomb,
+ FlvTag = window.videojs.Hls.FlvTag,
+
+ H264ExtraData = function() {
+ this.sps = []; // :Array
+ this.pps = []; // :Array
+
+ this.extraDataExists = function() { // :Boolean
+ return this.sps.length > 0;
+ };
+
+ // (sizeOfScalingList:int, expGolomb:ExpGolomb):void
+ this.scaling_list = function(sizeOfScalingList, expGolomb) {
+ var
+ lastScale = 8, // :int
+ nextScale = 8, // :int
+ j,
+ delta_scale; // :int
+
+ for (j = 0; j < sizeOfScalingList; ++j) {
+ if (0 !== nextScale) {
+ delta_scale = expGolomb.readExpGolomb();
+ nextScale = (lastScale + delta_scale + 256) % 256;
+ //useDefaultScalingMatrixFlag = ( j = = 0 && nextScale = = 0 )
+ }
+
+ lastScale = (nextScale === 0) ? lastScale : nextScale;
+ // scalingList[ j ] = ( nextScale == 0 ) ? lastScale : nextScale;
+ // lastScale = scalingList[ j ]
+ }
+ };
+
+ /**
+ * RBSP: raw bit-stream payload. The actual encoded video data.
+ *
+ * SPS: sequence parameter set. Part of the RBSP. Metadata to be applied
+ * to a complete video sequence, like width and height.
+ */
+ this.getSps0Rbsp = function() { // :ByteArray
+ var
+ sps = this.sps[0],
+ offset = 1,
+ start = 1,
+ written = 0,
+ end = sps.byteLength - 2,
+ result = new Uint8Array(sps.byteLength);
+
+ // In order to prevent 0x0000 01 from being interpreted as a
+ // NAL start code, occurences of that byte sequence in the
+ // RBSP are escaped with an "emulation byte". That turns
+ // sequences of 0x0000 01 into 0x0000 0301. When interpreting
+ // a NAL payload, they must be filtered back out.
+ while (offset < end) {
+ if (sps[offset] === 0x00 &&
+ sps[offset + 1] === 0x00 &&
+ sps[offset + 2] === 0x03) {
+ result.set(sps.subarray(start, offset + 1), written);
+ written += offset + 1 - start;
+ start = offset + 3;
+ }
+ offset++;
+ }
+ result.set(sps.subarray(start), written);
+ return result.subarray(0, written + (sps.byteLength - start));
+ };
+
+ // (pts:uint):FlvTag
+ this.metaDataTag = function(pts) {
+ var
+ tag = new FlvTag(FlvTag.METADATA_TAG), // :FlvTag
+ expGolomb, // :ExpGolomb
+ profile_idc, // :int
+ chroma_format_idc, // :int
+ imax, // :int
+ i, // :int
+
+ pic_order_cnt_type, // :int
+ num_ref_frames_in_pic_order_cnt_cycle, // :uint
+
+ pic_width_in_mbs_minus1, // :int
+ pic_height_in_map_units_minus1, // :int
+
+ frame_mbs_only_flag, // :int
+ frame_cropping_flag, // :Boolean
+
+ frame_crop_left_offset = 0, // :int
+ frame_crop_right_offset = 0, // :int
+ frame_crop_top_offset = 0, // :int
+ frame_crop_bottom_offset = 0, // :int
+
+ width,
+ height;
+
+ tag.dts = pts;
+ tag.pts = pts;
+ expGolomb = new ExpGolomb(this.getSps0Rbsp());
+
+ // :int = expGolomb.readUnsignedByte(); // profile_idc u(8)
+ profile_idc = expGolomb.readUnsignedByte();
+
+ // constraint_set[0-5]_flag, u(1), reserved_zero_2bits u(2), level_idc u(8)
+ expGolomb.skipBits(16);
+
+ // seq_parameter_set_id
+ expGolomb.skipUnsignedExpGolomb();
+
+ if (profile_idc === 100 ||
+ profile_idc === 110 ||
+ profile_idc === 122 ||
+ profile_idc === 244 ||
+ profile_idc === 44 ||
+ profile_idc === 83 ||
+ profile_idc === 86 ||
+ profile_idc === 118 ||
+ profile_idc === 128) {
+ chroma_format_idc = expGolomb.readUnsignedExpGolomb();
+ if (3 === chroma_format_idc) {
+ expGolomb.skipBits(1); // separate_colour_plane_flag
+ }
+ expGolomb.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
+ expGolomb.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
+ expGolomb.skipBits(1); // qpprime_y_zero_transform_bypass_flag
+ if (expGolomb.readBoolean()) { // seq_scaling_matrix_present_flag
+ imax = (chroma_format_idc !== 3) ? 8 : 12;
+ for (i = 0 ; i < imax ; ++i) {
+ if (expGolomb.readBoolean()) { // seq_scaling_list_present_flag[ i ]
+ if (i < 6) {
+ this.scaling_list(16, expGolomb);
+ } else {
+ this.scaling_list(64, expGolomb);
+ }
+ }
+ }
+ }
+ }
+
+ expGolomb.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
+ pic_order_cnt_type = expGolomb.readUnsignedExpGolomb();
+
+ if ( 0 === pic_order_cnt_type ) {
+ expGolomb.readUnsignedExpGolomb(); //log2_max_pic_order_cnt_lsb_minus4
+ } else if ( 1 === pic_order_cnt_type ) {
+ expGolomb.skipBits(1); // delta_pic_order_always_zero_flag
+ expGolomb.skipExpGolomb(); // offset_for_non_ref_pic
+ expGolomb.skipExpGolomb(); // offset_for_top_to_bottom_field
+ num_ref_frames_in_pic_order_cnt_cycle = expGolomb.readUnsignedExpGolomb();
+ for(i = 0 ; i < num_ref_frames_in_pic_order_cnt_cycle ; ++i) {
+ expGolomb.skipExpGolomb(); // offset_for_ref_frame[ i ]
+ }
+ }
+
+ expGolomb.skipUnsignedExpGolomb(); // max_num_ref_frames
+ expGolomb.skipBits(1); // gaps_in_frame_num_value_allowed_flag
+ pic_width_in_mbs_minus1 = expGolomb.readUnsignedExpGolomb();
+ pic_height_in_map_units_minus1 = expGolomb.readUnsignedExpGolomb();
+
+ frame_mbs_only_flag = expGolomb.readBits(1);
+ if (0 === frame_mbs_only_flag) {
+ expGolomb.skipBits(1); // mb_adaptive_frame_field_flag
+ }
+
+ expGolomb.skipBits(1); // direct_8x8_inference_flag
+ frame_cropping_flag = expGolomb.readBoolean();
+ if (frame_cropping_flag) {
+ frame_crop_left_offset = expGolomb.readUnsignedExpGolomb();
+ frame_crop_right_offset = expGolomb.readUnsignedExpGolomb();
+ frame_crop_top_offset = expGolomb.readUnsignedExpGolomb();
+ frame_crop_bottom_offset = expGolomb.readUnsignedExpGolomb();
+ }
+
+ width = ((pic_width_in_mbs_minus1 + 1) * 16) - frame_crop_left_offset * 2 - frame_crop_right_offset * 2;
+ height = ((2 - frame_mbs_only_flag) * (pic_height_in_map_units_minus1 + 1) * 16) - (frame_crop_top_offset * 2) - (frame_crop_bottom_offset * 2);
+
+ tag.writeMetaDataDouble("videocodecid", 7);
+ tag.writeMetaDataDouble("width", width);
+ tag.writeMetaDataDouble("height", height);
+ // tag.writeMetaDataDouble("videodatarate", 0 );
+ // tag.writeMetaDataDouble("framerate", 0);
+
+ return tag;
+ };
+
+ // (pts:uint):FlvTag
+ this.extraDataTag = function(pts) {
+ var
+ i,
+ tag = new FlvTag(FlvTag.VIDEO_TAG, true);
+
+ tag.dts = pts;
+ tag.pts = pts;
+
+ tag.writeByte(0x01);// version
+ tag.writeByte(this.sps[0][1]);// profile
+ tag.writeByte(this.sps[0][2]);// compatibility
+ tag.writeByte(this.sps[0][3]);// level
+ tag.writeByte(0xFC | 0x03); // reserved (6 bits), NULA length size - 1 (2 bits)
+ tag.writeByte(0xE0 | 0x01 ); // reserved (3 bits), num of SPS (5 bits)
+ tag.writeShort( this.sps[0].length ); // data of SPS
+ tag.writeBytes( this.sps[0] ); // SPS
+
+ tag.writeByte( this.pps.length ); // num of PPS (will there ever be more that 1 PPS?)
+ for (i = 0 ; i < this.pps.length ; ++i) {
+ tag.writeShort(this.pps[i].length); // 2 bytes for length of PPS
+ tag.writeBytes(this.pps[i]); // data of PPS
+ }
+
+ return tag;
+ };
+ },
+
+ NALUnitType;
+
+ /**
+ * Network Abstraction Layer (NAL) units are the packets of an H264
+ * stream. NAL units are divided into types based on their payload
+ * data. Each type has a unique numeric identifier.
+ *
+ * NAL unit
+ * |- NAL header -|------ RBSP ------|
+ *
+ * NAL unit: Network abstraction layer unit. The combination of a NAL
+ * header and an RBSP.
+ * NAL header: the encapsulation unit for transport-specific metadata in
+ * an h264 stream. Exactly one byte.
+ */
+ // incomplete, see Table 7.1 of ITU-T H.264 for 12-32
+ window.videojs.Hls.NALUnitType = NALUnitType = {
+ unspecified: 0,
+ slice_layer_without_partitioning_rbsp_non_idr: 1,
+ slice_data_partition_a_layer_rbsp: 2,
+ slice_data_partition_b_layer_rbsp: 3,
+ slice_data_partition_c_layer_rbsp: 4,
+ slice_layer_without_partitioning_rbsp_idr: 5,
+ sei_rbsp: 6,
+ seq_parameter_set_rbsp: 7,
+ pic_parameter_set_rbsp: 8,
+ access_unit_delimiter_rbsp: 9,
+ end_of_seq_rbsp: 10,
+ end_of_stream_rbsp: 11
+ };
+
+ window.videojs.Hls.H264Stream = function() {
+ var
+ next_pts, // :uint;
+ next_dts, // :uint;
+ pts_offset, // :int
+
+ h264Frame, // :FlvTag
+
+ oldExtraData = new H264ExtraData(), // :H264ExtraData
+ newExtraData = new H264ExtraData(), // :H264ExtraData
+
+ nalUnitType = -1, // :int
+
+ state; // :uint;
+
+ this.tags = [];
+
+ //(pts:uint, dts:uint, dataAligned:Boolean):void
+ this.setNextTimeStamp = function(pts, dts, dataAligned) {
+ // on the first invocation, capture the starting PTS value
+ pts_offset = pts;
+
+ // on subsequent invocations, calculate the PTS based on the starting offset
+ this.setNextTimeStamp = function(pts, dts, dataAligned) {
+ // We could end up with a DTS less than 0 here. We need to deal with that!
+ next_pts = pts - pts_offset;
+ next_dts = dts - pts_offset;
+
+ // If data is aligned, flush all internal buffers
+ if (dataAligned) {
+ this.finishFrame();
+ }
+ };
+
+ this.setNextTimeStamp(pts, dts, dataAligned);
+ };
+
+ this.finishFrame = function() {
+ if (h264Frame) {
+ // Push SPS before EVERY IDR frame for seeking
+ if (newExtraData.extraDataExists()) {
+ oldExtraData = newExtraData;
+ newExtraData = new H264ExtraData();
+ }
+
+ if (h264Frame.keyFrame) {
+ // Push extra data on every IDR frame in case we did a stream change + seek
+ this.tags.push(oldExtraData.metaDataTag(h264Frame.pts));
+ this.tags.push(oldExtraData.extraDataTag(h264Frame.pts));
+ }
+
+ h264Frame.endNalUnit();
+ this.tags.push(h264Frame);
+ }
+
+ h264Frame = null;
+ nalUnitType = -1;
+ state = 0;
+ };
+
+ // (data:ByteArray, o:int, l:int):void
+ this.writeBytes = function(data, offset, length) {
+ var
+ nalUnitSize, // :uint
+ start, // :uint
+ end, // :uint
+ t; // :int
+
+ // default argument values
+ offset = offset || 0;
+ length = length || 0;
+
+ if (length <= 0) {
+ // data is empty so there's nothing to write
+ return;
+ }
+
+ // scan through the bytes until we find the start code (0x000001) for a
+ // NAL unit and then begin writing it out
+ // strip NAL start codes as we go
+ switch (state) {
+ default:
+ /* falls through */
+ case 0:
+ state = 1;
+ /* falls through */
+ case 1:
+ // A NAL unit may be split across two TS packets. Look back a bit to
+ // make sure the prefix of the start code wasn't already written out.
+ if (data[offset] <= 1) {
+ nalUnitSize = h264Frame ? h264Frame.nalUnitSize() : 0;
+ if (nalUnitSize >= 1 && h264Frame.negIndex(1) === 0) {
+ // ?? ?? 00 | O[01] ?? ??
+ if (data[offset] === 1 &&
+ nalUnitSize >= 2 &&
+ h264Frame.negIndex(2) === 0) {
+ // ?? 00 00 : 01
+ if (3 <= nalUnitSize && 0 === h264Frame.negIndex(3)) {
+ h264Frame.length -= 3; // 00 00 00 : 01
+ } else {
+ h264Frame.length -= 2; // 00 00 : 01
+ }
+
+ state = 3;
+ return this.writeBytes(data, offset + 1, length - 1);
+ }
+
+ if (length > 1 && data[offset] === 0 && data[offset + 1] === 1) {
+ // ?? 00 | 00 01
+ if (nalUnitSize >= 2 && h264Frame.negIndex(2) === 0) {
+ h264Frame.length -= 2; // 00 00 : 00 01
+ } else {
+ h264Frame.length -= 1; // 00 : 00 01
+ }
+
+ state = 3;
+ return this.writeBytes(data, offset + 2, length - 2);
+ }
+
+ if (length > 2 &&
+ data[offset] === 0 &&
+ data[offset + 1] === 0 &&
+ data[offset + 2] === 1) {
+ // 00 : 00 00 01
+ // h264Frame.length -= 1;
+ state = 3;
+ return this.writeBytes(data, offset + 3, length - 3);
+ }
+ }
+ }
+ // allow fall through if the above fails, we may end up checking a few
+ // bytes a second time. But that case will be VERY rare
+ state = 2;
+ /* falls through */
+ case 2:
+ // Look for start codes in the data from the current offset forward
+ start = offset;
+ end = start + length;
+ for (t = end - 3; offset < t;) {
+ if (data[offset + 2] > 1) {
+ // if data[offset + 2] is greater than 1, there is no way a start
+ // code can begin before offset + 3
+ offset += 3;
+ } else if (data[offset + 1] !== 0) {
+ offset += 2;
+ } else if (data[offset] !== 0) {
+ offset += 1;
+ } else {
+ // If we get here we have 00 00 00 or 00 00 01
+ if (data[offset + 2] === 1) {
+ if (offset > start) {
+ h264Frame.writeBytes(data, start, offset - start);
+ }
+ state = 3;
+ offset += 3;
+ return this.writeBytes(data, offset, end - offset);
+ }
+
+ if (end - offset >= 4 &&
+ data[offset + 2] === 0 &&
+ data[offset + 3] === 1) {
+ if (offset > start) {
+ h264Frame.writeBytes(data, start, offset - start);
+ }
+ state = 3;
+ offset += 4;
+ return this.writeBytes(data, offset, end - offset);
+ }
+
+ // We are at the end of the buffer, or we have 3 NULLS followed by
+ // something that is not a 1, either way we can step forward by at
+ // least 3
+ offset += 3;
+ }
+ }
+
+ // We did not find any start codes. Try again next packet
+ state = 1;
+ h264Frame.writeBytes(data, start, length);
+ return;
+ case 3:
+ // The next byte is the first byte of a NAL Unit
+
+ if (h264Frame) {
+ // we've come to a new NAL unit so finish up the one we've been
+ // working on
+
+ switch (nalUnitType) {
+ case NALUnitType.seq_parameter_set_rbsp:
+ h264Frame.endNalUnit(newExtraData.sps);
+ break;
+ case NALUnitType.pic_parameter_set_rbsp:
+ h264Frame.endNalUnit(newExtraData.pps);
+ break;
+ case NALUnitType.slice_layer_without_partitioning_rbsp_idr:
+ h264Frame.endNalUnit();
+ break;
+ default:
+ h264Frame.endNalUnit();
+ break;
+ }
+ }
+
+ // setup to begin processing the new NAL unit
+ nalUnitType = data[offset] & 0x1F;
+ if (h264Frame) {
+ if (nalUnitType === NALUnitType.access_unit_delimiter_rbsp) {
+ // starting a new access unit, flush the previous one
+ this.finishFrame();
+ } else if (nalUnitType === NALUnitType.slice_layer_without_partitioning_rbsp_idr) {
+ h264Frame.keyFrame = true;
+ }
+ }
+
+ // finishFrame may render h264Frame null, so we must test again
+ if (!h264Frame) {
+ h264Frame = new FlvTag(FlvTag.VIDEO_TAG);
+ h264Frame.pts = next_pts;
+ h264Frame.dts = next_dts;
+ }
+
+ h264Frame.startNalUnit();
+ // We know there will not be an overlapping start code, so we can skip
+ // that test
+ state = 2;
+ return this.writeBytes(data, offset, length);
+ } // switch
+ };
+ };
+})(this);
+
+(function(window) {
+var
+ FlvTag = window.videojs.Hls.FlvTag,
+ adtsSampleingRates = [
+ 96000, 88200,
+ 64000, 48000,
+ 44100, 32000,
+ 24000, 22050,
+ 16000, 12000
+ ];
+
+window.videojs.Hls.AacStream = function() {
+ var
+ next_pts, // :uint
+ pts_offset, // :int
+ state, // :uint
+ pes_length, // :int
+
+ adtsProtectionAbsent, // :Boolean
+ adtsObjectType, // :int
+ adtsSampleingIndex, // :int
+ adtsChanelConfig, // :int
+ adtsFrameSize, // :int
+ adtsSampleCount, // :int
+ adtsDuration, // :int
+
+ aacFrame, // :FlvTag = null;
+ extraData; // :uint;
+
+ this.tags = [];
+
+ // (pts:uint, pes_size:int, dataAligned:Boolean):void
+ this.setNextTimeStamp = function(pts, pes_size, dataAligned) {
+
+ // on the first invocation, capture the starting PTS value
+ pts_offset = pts;
+
+ // on subsequent invocations, calculate the PTS based on the starting offset
+ this.setNextTimeStamp = function(pts, pes_size, dataAligned) {
+ next_pts = pts - pts_offset;
+ pes_length = pes_size;
+
+ // If data is aligned, flush all internal buffers
+ if (dataAligned) {
+ state = 0;
+ }
+ };
+
+ this.setNextTimeStamp(pts, pes_size, dataAligned);
+ };
+
+ // (data:ByteArray, o:int = 0, l:int = 0):void
+ this.writeBytes = function(data, offset, length) {
+ var
+ end, // :int
+ newExtraData, // :uint
+ bytesToCopy; // :int
+
+ // default arguments
+ offset = offset || 0;
+ length = length || 0;
+
+ // Do not allow more than 'pes_length' bytes to be written
+ length = (pes_length < length ? pes_length : length);
+ pes_length -= length;
+ end = offset + length;
+ while (offset < end) {
+ switch (state) {
+ default:
+ state = 0;
+ break;
+ case 0:
+ if (offset >= end) {
+ return;
+ }
+ if (0xFF !== data[offset]) {
+ console.assert(false, 'Error no ATDS header found');
+ offset += 1;
+ state = 0;
+ return;
+ }
+
+ offset += 1;
+ state = 1;
+ break;
+ case 1:
+ if (offset >= end) {
+ return;
+ }
+ if (0xF0 !== (data[offset] & 0xF0)) {
+ console.assert(false, 'Error no ATDS header found');
+ offset +=1;
+ state = 0;
+ return;
+ }
+
+ adtsProtectionAbsent = !!(data[offset] & 0x01);
+
+ offset += 1;
+ state = 2;
+ break;
+ case 2:
+ if (offset >= end) {
+ return;
+ }
+ adtsObjectType = ((data[offset] & 0xC0) >>> 6) + 1;
+ adtsSampleingIndex = ((data[offset] & 0x3C) >>> 2);
+ adtsChanelConfig = ((data[offset] & 0x01) << 2);
+
+ offset += 1;
+ state = 3;
+ break;
+ case 3:
+ if (offset >= end) {
+ return;
+ }
+ adtsChanelConfig |= ((data[offset] & 0xC0) >>> 6);
+ adtsFrameSize = ((data[offset] & 0x03) << 11);
+
+ offset += 1;
+ state = 4;
+ break;
+ case 4:
+ if (offset >= end) {
+ return;
+ }
+ adtsFrameSize |= (data[offset] << 3);
+
+ offset += 1;
+ state = 5;
+ break;
+ case 5:
+ if(offset >= end) {
+ return;
+ }
+ adtsFrameSize |= ((data[offset] & 0xE0) >>> 5);
+ adtsFrameSize -= (adtsProtectionAbsent ? 7 : 9);
+
+ offset += 1;
+ state = 6;
+ break;
+ case 6:
+ if (offset >= end) {
+ return;
+ }
+ adtsSampleCount = ((data[offset] & 0x03) + 1) * 1024;
+ adtsDuration = (adtsSampleCount * 1000) / adtsSampleingRates[adtsSampleingIndex];
+
+ newExtraData = (adtsObjectType << 11) |
+ (adtsSampleingIndex << 7) |
+ (adtsChanelConfig << 3);
+ if (newExtraData !== extraData) {
+ aacFrame = new FlvTag(FlvTag.METADATA_TAG);
+ aacFrame.pts = next_pts;
+ aacFrame.dts = next_pts;
+
+ // AAC is always 10
+ aacFrame.writeMetaDataDouble("audiocodecid", 10);
+ aacFrame.writeMetaDataBoolean("stereo", 2 === adtsChanelConfig);
+ aacFrame.writeMetaDataDouble ("audiosamplerate", adtsSampleingRates[adtsSampleingIndex]);
+ // Is AAC always 16 bit?
+ aacFrame.writeMetaDataDouble ("audiosamplesize", 16);
+
+ this.tags.push(aacFrame);
+
+ extraData = newExtraData;
+ aacFrame = new FlvTag(FlvTag.AUDIO_TAG, true);
+ aacFrame.pts = aacFrame.dts;
+ // For audio, DTS is always the same as PTS. We want to set the DTS
+ // however so we can compare with video DTS to determine approximate
+ // packet order
+ aacFrame.pts = next_pts;
+ aacFrame.view.setUint16(aacFrame.position, newExtraData);
+ aacFrame.position += 2;
+ aacFrame.length = Math.max(aacFrame.length, aacFrame.position);
+
+ this.tags.push(aacFrame);
+ }
+
+ // Skip the checksum if there is one
+ offset += 1;
+ state = 7;
+ break;
+ case 7:
+ if (!adtsProtectionAbsent) {
+ if (2 > (end - offset)) {
+ return;
+ } else {
+ offset += 2;
+ }
+ }
+
+ aacFrame = new FlvTag(FlvTag.AUDIO_TAG);
+ aacFrame.pts = next_pts;
+ aacFrame.dts = next_pts;
+ state = 8;
+ break;
+ case 8:
+ while (adtsFrameSize) {
+ if (offset >= end) {
+ return;
+ }
+ bytesToCopy = (end - offset) < adtsFrameSize ? (end - offset) : adtsFrameSize;
+ aacFrame.writeBytes(data, offset, bytesToCopy);
+ offset += bytesToCopy;
+ adtsFrameSize -= bytesToCopy;
+ }
+
+ this.tags.push(aacFrame);
+
+ // finished with this frame
+ state = 0;
+ next_pts += adtsDuration;
+ }
+ }
+ };
+};
+
+})(this);
+
+(function(window) {
+ var
+ videojs = window.videojs,
+ FlvTag = videojs.Hls.FlvTag,
+ H264Stream = videojs.Hls.H264Stream,
+ AacStream = videojs.Hls.AacStream,
+ MP2T_PACKET_LENGTH,
+ STREAM_TYPES;
+
+ /**
+ * An object that incrementally transmuxes MPEG2 Trasport Stream
+ * chunks into an FLV.
+ */
+ videojs.Hls.SegmentParser = function() {
+ var
+ self = this,
+ parseTSPacket,
+ streamBuffer = new Uint8Array(MP2T_PACKET_LENGTH),
+ streamBufferByteCount = 0,
+ h264Stream = new H264Stream(),
+ aacStream = new AacStream();
+
+ // expose the stream metadata
+ self.stream = {
+ // the mapping between transport stream programs and the PIDs
+ // that form their elementary streams
+ programMapTable: {}
+ };
+
+ // For information on the FLV format, see
+ // http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf.
+ // Technically, this function returns the header and a metadata FLV tag
+ // if duration is greater than zero
+ // duration in seconds
+ // @return {object} the bytes of the FLV header as a Uint8Array
+ self.getFlvHeader = function(duration, audio, video) { // :ByteArray {
+ var
+ headBytes = new Uint8Array(3 + 1 + 1 + 4),
+ head = new DataView(headBytes.buffer),
+ metadata,
+ result;
+
+ // default arguments
+ duration = duration || 0;
+ audio = audio === undefined? true : audio;
+ video = video === undefined? true : video;
+
+ // signature
+ head.setUint8(0, 0x46); // 'F'
+ head.setUint8(1, 0x4c); // 'L'
+ head.setUint8(2, 0x56); // 'V'
+
+ // version
+ head.setUint8(3, 0x01);
+
+ // flags
+ head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));
+
+ // data offset, should be 9 for FLV v1
+ head.setUint32(5, headBytes.byteLength);
+
+ // init the first FLV tag
+ if (duration <= 0) {
+ // no duration available so just write the first field of the first
+ // FLV tag
+ result = new Uint8Array(headBytes.byteLength + 4);
+ result.set(headBytes);
+ result.set([0, 0, 0, 0], headBytes.byteLength);
+ return result;
+ }
+
+ // write out the duration metadata tag
+ metadata = new FlvTag(FlvTag.METADATA_TAG);
+ metadata.pts = metadata.dts = 0;
+ metadata.writeMetaDataDouble("duration", duration);
+ result = new Uint8Array(headBytes.byteLength + metadata.byteLength);
+ result.set(head);
+ result.set(head.bytesLength, metadata.finalize());
+
+ return result;
+ };
+
+ self.flushTags = function() {
+ h264Stream.finishFrame();
+ };
+
+ /**
+ * Returns whether a call to `getNextTag()` will be successful.
+ * @return {boolean} whether there is at least one transmuxed FLV
+ * tag ready
+ */
+ self.tagsAvailable = function() { // :int {
+ return h264Stream.tags.length + aacStream.tags.length;
+ };
+
+ /**
+ * Returns the next tag in decoder-timestamp (DTS) order.
+ * @returns {object} the next tag to decoded.
+ */
+ self.getNextTag = function() {
+ var tag;
+
+ if (!h264Stream.tags.length) {
+ // only audio tags remain
+ tag = aacStream.tags.shift();
+ } else if (!aacStream.tags.length) {
+ // only video tags remain
+ tag = h264Stream.tags.shift();
+ } else if (aacStream.tags[0].dts < h264Stream.tags[0].dts) {
+ // audio should be decoded next
+ tag = aacStream.tags.shift();
+ } else {
+ // video should be decoded next
+ tag = h264Stream.tags.shift();
+ }
+
+ return tag.finalize();
+ };
+
+ self.parseSegmentBinaryData = function(data) { // :ByteArray) {
+ var
+ dataPosition = 0,
+ dataSlice;
+
+ // To avoid an extra copy, we will stash overflow data, and only
+ // reconstruct the first packet. The rest of the packets will be
+ // parsed directly from data
+ if (streamBufferByteCount > 0) {
+ if (data.byteLength + streamBufferByteCount < MP2T_PACKET_LENGTH) {
+ // the current data is less than a single m2ts packet, so stash it
+ // until we receive more
+
+ // ?? this seems to append streamBuffer onto data and then just give up. I'm not sure why that would be interesting.
+ videojs.log('data.length + streamBuffer.length < MP2T_PACKET_LENGTH ??');
+ streamBuffer.readBytes(data, data.length, streamBuffer.length);
+ return;
+ } else {
+ // we have enough data for an m2ts packet
+ // process it immediately
+ dataSlice = data.subarray(0, MP2T_PACKET_LENGTH - streamBufferByteCount);
+ streamBuffer.set(dataSlice, streamBufferByteCount);
+
+ parseTSPacket(streamBuffer);
+
+ // reset the buffer
+ streamBuffer = new Uint8Array(MP2T_PACKET_LENGTH);
+ streamBufferByteCount = 0;
+ }
+ }
+
+ while (true) {
+ // Make sure we are TS aligned
+ while(dataPosition < data.byteLength && data[dataPosition] !== 0x47) {
+ // If there is no sync byte skip forward until we find one
+ // TODO if we find a sync byte, look 188 bytes in the future (if
+ // possible). If there is not a sync byte there, keep looking
+ dataPosition++;
+ }
+
+ // base case: not enough data to parse a m2ts packet
+ if (data.byteLength - dataPosition < MP2T_PACKET_LENGTH) {
+ if (data.byteLength - dataPosition > 0) {
+ // there are bytes remaining, save them for next time
+ streamBuffer.set(data.subarray(dataPosition),
+ streamBufferByteCount);
+ streamBufferByteCount += data.byteLength - dataPosition;
+ }
+ return;
+ }
+
+ // attempt to parse a m2ts packet
+ if (parseTSPacket(data.subarray(dataPosition, dataPosition + MP2T_PACKET_LENGTH))) {
+ dataPosition += MP2T_PACKET_LENGTH;
+ } else {
+ // If there was an error parsing a TS packet. it could be
+ // because we are not TS packet aligned. Step one forward by
+ // one byte and allow the code above to find the next
+ videojs.log('error parsing m2ts packet, attempting to re-align');
+ dataPosition++;
+ }
+ }
+ };
+
+ /**
+ * Parses a video/mp2t packet and appends the underlying video and
+ * audio data onto h264stream and aacStream, respectively.
+ * @param data {Uint8Array} the bytes of an MPEG2-TS packet,
+ * including the sync byte.
+ * @return {boolean} whether a valid packet was encountered
+ */
+ // TODO add more testing to make sure we dont walk past the end of a TS
+ // packet!
+ parseTSPacket = function(data) { // :ByteArray):Boolean {
+ var
+ offset = 0, // :uint
+ end = offset + MP2T_PACKET_LENGTH, // :uint
+
+ // Payload Unit Start Indicator
+ pusi = !!(data[offset + 1] & 0x40), // mask: 0100 0000
+
+ // packet identifier (PID), a unique identifier for the elementary
+ // stream this packet describes
+ pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2], // mask: 0001 1111
+
+ // adaptation_field_control, whether this header is followed by an
+ // adaptation field, a payload, or both
+ afflag = (data[offset + 3] & 0x30 ) >>> 4,
+
+ patTableId, // :int
+ patCurrentNextIndicator, // Boolean
+ patSectionLength, // :uint
+
+ pesPacketSize, // :int,
+ dataAlignmentIndicator, // :Boolean,
+ ptsDtsIndicator, // :int
+ pesHeaderLength, // :int
+
+ pts, // :uint
+ dts, // :uint
+
+ pmtCurrentNextIndicator, // :Boolean
+ pmtProgramDescriptorsLength,
+ pmtSectionLength, // :uint
+
+ streamType, // :int
+ elementaryPID, // :int
+ ESInfolength; // :int
+
+ // Continuity Counter we could use this for sanity check, and
+ // corrupt stream detection
+ // cc = (data[offset + 3] & 0x0F);
+
+ // move past the header
+ offset += 4;
+
+ // if an adaption field is present, its length is specified by
+ // the fifth byte of the PES header. The adaptation field is
+ // used to specify some forms of timing and control data that we
+ // do not currently use.
+ if (afflag > 0x01) {
+ offset += data[offset] + 1;
+ }
+
+ // Handle a Program Association Table (PAT). PATs map PIDs to
+ // individual programs. If this transport stream was being used
+ // for television broadcast, a program would probably be
+ // equivalent to a channel. In HLS, it would be very unusual to
+ // create an mp2t stream with multiple programs.
+ if (0x0000 === pid) {
+ // The PAT may be split into multiple sections and those
+ // sections may be split into multiple packets. If a PAT
+ // section starts in this packet, PUSI will be true and the
+ // first byte of the playload will indicate the offset from
+ // the current position to the start of the section.
+ if (pusi) {
+ offset += 1 + data[offset];
+ }
+ patTableId = data[offset];
+
+ if (patTableId !== 0x00) {
+ videojs.log('the table_id of the PAT should be 0x00 but was' +
+ patTableId.toString(16));
+ }
+
+ // the current_next_indicator specifies whether this PAT is
+ // currently applicable or is part of the next table to become
+ // active
+ patCurrentNextIndicator = !!(data[offset + 5] & 0x01);
+ if (patCurrentNextIndicator) {
+ // section_length specifies the number of bytes following
+ // its position to the end of this section
+ patSectionLength = (data[offset + 1] & 0x0F) << 8 | data[offset + 2];
+ // move past the rest of the PSI header to the first program
+ // map table entry
+ offset += 8;
+
+ // we don't handle streams with more than one program, so
+ // raise an exception if we encounter one
+ // section_length = rest of header + (n * entry length) + CRC
+ // = 5 + (n * 4) + 4
+ if ((patSectionLength - 5 - 4) / 4 !== 1) {
+ throw new Error("TS has more that 1 program");
+ }
+
+ // the Program Map Table (PMT) associates the underlying
+ // video and audio streams with a unique PID
+ self.stream.pmtPid = (data[offset + 2] & 0x1F) << 8 | data[offset + 3];
+ }
+ } else if (pid === self.stream.programMapTable[STREAM_TYPES.h264] ||
+ pid === self.stream.programMapTable[STREAM_TYPES.adts]) {
+ if (pusi) {
+ // comment out for speed
+ if (0x00 !== data[offset + 0] || 0x00 !== data[offset + 1] || 0x01 !== data[offset + 2]) {
+ // look for PES start code
+ throw new Error("PES did not begin with start code");
+ }
+
+ // var sid:int = data[offset+3]; // StreamID
+ pesPacketSize = (data[offset + 4] << 8) | data[offset + 5];
+ dataAlignmentIndicator = (data[offset + 6] & 0x04) !== 0;
+ ptsDtsIndicator = data[offset + 7];
+ pesHeaderLength = data[offset + 8]; // TODO sanity check header length
+ offset += 9; // Skip past PES header
+
+ // PTS and DTS are normially stored as a 33 bit number.
+ // JavaScript does not have a integer type larger than 32 bit
+ // BUT, we need to convert from 90ns to 1ms time scale anyway.
+ // so what we are going to do instead, is drop the least
+ // significant bit (the same as dividing by two) then we can
+ // divide by 45 (45 * 2 = 90) to get ms.
+ if (ptsDtsIndicator & 0xC0) {
+ // the PTS and DTS are not written out directly. For information on
+ // how they are encoded, see
+ // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
+ pts = (data[offset + 0] & 0x0E) << 28
+ | (data[offset + 1] & 0xFF) << 21
+ | (data[offset + 2] & 0xFE) << 13
+ | (data[offset + 3] & 0xFF) << 6
+ | (data[offset + 4] & 0xFE) >>> 2;
+ pts /= 45;
+ dts = pts;
+ if (ptsDtsIndicator & 0x40) {// DTS
+ dts = (data[offset + 5] & 0x0E ) << 28
+ | (data[offset + 6] & 0xFF ) << 21
+ | (data[offset + 7] & 0xFE ) << 13
+ | (data[offset + 8] & 0xFF ) << 6
+ | (data[offset + 9] & 0xFE ) >>> 2;
+ dts /= 45;
+ }
+ }
+ // Skip past "optional" portion of PTS header
+ offset += pesHeaderLength;
+
+ if (pid === self.stream.programMapTable[STREAM_TYPES.h264]) {
+ h264Stream.setNextTimeStamp(pts,
+ dts,
+ dataAlignmentIndicator);
+ } else if (pid === self.stream.programMapTable[STREAM_TYPES.adts]) {
+ aacStream.setNextTimeStamp(pts,
+ pesPacketSize,
+ dataAlignmentIndicator);
+ }
+ }
+
+ if (pid === self.stream.programMapTable[STREAM_TYPES.adts]) {
+ aacStream.writeBytes(data, offset, end - offset);
+ } else if (pid === self.stream.programMapTable[STREAM_TYPES.h264]) {
+ h264Stream.writeBytes(data, offset, end - offset);
+ }
+ } else if (self.stream.pmtPid === pid) {
+ // similarly to the PAT, jump to the first byte of the section
+ if (pusi) {
+ offset += 1 + data[offset];
+ }
+ if (data[offset] !== 0x02) {
+ videojs.log('The table_id of a PMT should be 0x02 but was ' +
+ data[offset].toString(16));
+ }
+
+ // whether this PMT is currently applicable or is part of the
+ // next table to become active
+ pmtCurrentNextIndicator = !!(data[offset + 5] & 0x01);
+ if (pmtCurrentNextIndicator) {
+ // overwrite any existing program map table
+ self.stream.programMapTable = {};
+ // section_length specifies the number of bytes following
+ // its position to the end of this section
+ pmtSectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
+ // subtract the length of the program info descriptors
+ pmtProgramDescriptorsLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
+ pmtSectionLength -= pmtProgramDescriptorsLength;
+ // skip CRC and PSI data we dont care about
+ // rest of header + CRC = 9 + 4
+ pmtSectionLength -= 13;
+
+ // align offset to the first entry in the PMT
+ offset += 12 + pmtProgramDescriptorsLength;
+
+ // iterate through the entries
+ while (0 < pmtSectionLength) {
+ // the type of data carried in the PID this entry describes
+ streamType = data[offset + 0];
+ // the PID for this entry
+ elementaryPID = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
+
+ if (streamType === STREAM_TYPES.h264) {
+ if (self.stream.programMapTable[streamType] &&
+ self.stream.programMapTable[streamType] !== elementaryPID) {
+ throw new Error("Program has more than 1 video stream");
+ }
+ self.stream.programMapTable[streamType] = elementaryPID;
+ } else if (streamType === STREAM_TYPES.adts) {
+ if (self.stream.programMapTable[streamType] &&
+ self.stream.programMapTable[streamType] !== elementaryPID) {
+ throw new Error("Program has more than 1 audio Stream");
+ }
+ self.stream.programMapTable[streamType] = elementaryPID;
+ }
+ // TODO add support for MP3 audio
+
+ // the length of the entry descriptor
+ ESInfolength = (data[offset + 3] & 0x0F) << 8 | data[offset + 4];
+ // move to the first byte after the end of this entry
+ offset += 5 + ESInfolength;
+ pmtSectionLength -= 5 + ESInfolength;
+ }
+ }
+ // We could test the CRC here to detect corruption with extra CPU cost
+ } else if (0x0011 === pid) {
+ // Service Description Table
+ } else if (0x1FFF === pid) {
+ // NULL packet
+ } else {
+ videojs.log("Unknown PID parsing TS packet: " + pid);
+ }
+
+ return true;
+ };
+
+ self.getTags = function() {
+ return h264Stream.tags;
+ };
+
+ self.stats = {
+ h264Tags: function() {
+ return h264Stream.tags.length;
+ },
+ aacTags: function() {
+ return aacStream.tags.length;
+ }
+ };
+ };
+
+ // MPEG2-TS constants
+ videojs.Hls.SegmentParser.MP2T_PACKET_LENGTH = MP2T_PACKET_LENGTH = 188;
+ videojs.Hls.SegmentParser.STREAM_TYPES = STREAM_TYPES = {
+ h264: 0x1b,
+ adts: 0x0f
+ };
+
+})(window);
+
+(function(videojs, undefined) {
+ var Stream = function() {
+ this.init = function() {
+ var listeners = {};
+ /**
+ * Add a listener for a specified event type.
+ * @param type {string} the event name
+ * @param listener {function} the callback to be invoked when an event of
+ * the specified type occurs
+ */
+ this.on = function(type, listener) {
+ if (!listeners[type]) {
+ listeners[type] = [];
+ }
+ listeners[type].push(listener);
+ };
+ /**
+ * Remove a listener for a specified event type.
+ * @param type {string} the event name
+ * @param listener {function} a function previously registered for this
+ * type of event through `on`
+ */
+ this.off = function(type, listener) {
+ var index;
+ if (!listeners[type]) {
+ return false;
+ }
+ index = listeners[type].indexOf(listener);
+ listeners[type].splice(index, 1);
+ return index > -1;
+ };
+ /**
+ * Trigger an event of the specified type on this stream. Any additional
+ * arguments to this function are passed as parameters to event listeners.
+ * @param type {string} the event name
+ */
+ this.trigger = function(type) {
+ var callbacks, i, length, args;
+ callbacks = listeners[type];
+ if (!callbacks) {
+ return;
+ }
+ args = Array.prototype.slice.call(arguments, 1);
+ length = callbacks.length;
+ for (i = 0; i < length; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ };
+ /**
+ * Destroys the stream and cleans up.
+ */
+ this.dispose = function() {
+ listeners = {};
+ };
+ };
+ };
+ /**
+ * Forwards all `data` events on this stream to the destination stream. The
+ * destination stream should provide a method `push` to receive the data
+ * events as they arrive.
+ * @param destination {stream} the stream that will receive all `data` events
+ * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
+ */
+ Stream.prototype.pipe = function(destination) {
+ this.on('data', function(data) {
+ destination.push(data);
+ });
+ };
+
+ videojs.Hls.Stream = Stream;
+})(window.videojs);
+
+(function(videojs, parseInt, isFinite, mergeOptions, undefined) {
+ var
+ noop = function() {},
+ parseAttributes = function(attributes) {
+ var
+ attrs = attributes.split(','),
+ i = attrs.length,
+ result = {},
+ attr;
+
+ while (i--) {
+ attr = attrs[i].split('=');
+ attr[0] = attr[0].replace(/^\s+|\s+$/g, '');
+
+ // This is not sexy, but gives us the resulting object we want.
+ if (attr[1]) {
+ attr[1] = attr[1].replace(/^\s+|\s+$/g, '');
+ if (attr[1].indexOf('"') !== -1) {
+ attr[1] = attr[1].split('"')[1];
+ }
+ result[attr[0]] = attr[1];
+ } else {
+ attrs[i - 1] = attrs[i - 1] + ',' + attr[0];
+ }
+ }
+ return result;
+ },
+ Stream = videojs.Hls.Stream,
+ LineStream,
+ ParseStream,
+ Parser;
+
+ /**
+ * A stream that buffers string input and generates a `data` event for each
+ * line.
+ */
+ LineStream = function() {
+ var buffer = '';
+ LineStream.prototype.init.call(this);
+
+ /**
+ * Add new data to be parsed.
+ * @param data {string} the text to process
+ */
+ this.push = function(data) {
+ var nextNewline;
+
+ buffer += data;
+ nextNewline = buffer.indexOf('\n');
+
+ for (; nextNewline > -1; nextNewline = buffer.indexOf('\n')) {
+ this.trigger('data', buffer.substring(0, nextNewline));
+ buffer = buffer.substring(nextNewline + 1);
+ }
+ };
+ };
+ LineStream.prototype = new Stream();
+
+ /**
+ * A line-level M3U8 parser event stream. It expects to receive input one
+ * line at a time and performs a context-free parse of its contents. A stream
+ * interpretation of a manifest can be useful if the manifest is expected to
+ * be too large to fit comfortably into memory or the entirety of the input
+ * is not immediately available. Otherwise, it's probably much easier to work
+ * with a regular `Parser` object.
+ *
+ * Produces `data` events with an object that captures the parser's
+ * interpretation of the input. That object has a property `tag` that is one
+ * of `uri`, `comment`, or `tag`. URIs only have a single additional
+ * property, `line`, which captures the entirety of the input without
+ * interpretation. Comments similarly have a single additional property
+ * `text` which is the input without the leading `#`.
+ *
+ * Tags always have a property `tagType` which is the lower-cased version of
+ * the M3U8 directive without the `#EXT` or `#EXT-X-` prefix. For instance,
+ * `#EXT-X-MEDIA-SEQUENCE` becomes `media-sequence` when parsed. Unrecognized
+ * tags are given the tag type `unknown` and a single additional property
+ * `data` with the remainder of the input.
+ */
+ ParseStream = function() {
+ ParseStream.prototype.init.call(this);
+ };
+ ParseStream.prototype = new Stream();
+ /**
+ * Parses an additional line of input.
+ * @param line {string} a single line of an M3U8 file to parse
+ */
+ ParseStream.prototype.push = function(line) {
+ var match, event;
+ if (line.length === 0) {
+ // ignore empty lines
+ return;
+ }
+
+ // URIs
+ if (line[0] !== '#') {
+ this.trigger('data', {
+ type: 'uri',
+ uri: line
+ });
+ return;
+ }
+
+ // Comments
+ if (line.indexOf('#EXT') !== 0) {
+ this.trigger('data', {
+ type: 'comment',
+ text: line.slice(1)
+ });
+ return;
+ }
+
+ //strip off any carriage returns here so the regex matching
+ //doesn't have to account for them.
+ line = line.replace('\r','');
+
+ // Tags
+ match = /^#EXTM3U/.exec(line);
+ if (match) {
+ this.trigger('data', {
+ type: 'tag',
+ tagType: 'm3u'
+ });
+ return;
+ }
+ match = (/^#EXTINF:?([0-9\.]*)?,?(.*)?$/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'inf'
+ };
+ if (match[1]) {
+ event.duration = parseFloat(match[1], 10);
+ }
+ if (match[2]) {
+ event.title = match[2];
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-TARGETDURATION:?([0-9.]*)?/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'targetduration'
+ };
+ if (match[1]) {
+ event.duration = parseInt(match[1], 10);
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#ZEN-TOTAL-DURATION:?([0-9.]*)?/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'totalduration'
+ };
+ if (match[1]) {
+ event.duration = parseInt(match[1], 10);
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-VERSION:?([0-9.]*)?/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'version'
+ };
+ if (match[1]) {
+ event.version = parseInt(match[1], 10);
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'media-sequence'
+ };
+ if (match[1]) {
+ event.number = parseInt(match[1], 10);
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-PLAYLIST-TYPE:?(.*)?$/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'playlist-type'
+ };
+ if (match[1]) {
+ event.playlistType = match[1];
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-BYTERANGE:?([0-9.]*)?@?([0-9.]*)?/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'byterange'
+ };
+ if (match[1]) {
+ event.length = parseInt(match[1], 10);
+ }
+ if (match[2]) {
+ event.offset = parseInt(match[2], 10);
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-ALLOW-CACHE:?(YES|NO)?/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'allow-cache'
+ };
+ if (match[1]) {
+ event.allowed = !(/NO/).test(match[1]);
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-STREAM-INF:?(.*)$/).exec(line);
+ if (match) {
+ event = {
+ type: 'tag',
+ tagType: 'stream-inf'
+ };
+ if (match[1]) {
+ event.attributes = parseAttributes(match[1]);
+
+ if (event.attributes.RESOLUTION) {
+ (function() {
+ var
+ split = event.attributes.RESOLUTION.split('x'),
+ resolution = {};
+ if (split[0]) {
+ resolution.width = parseInt(split[0], 10);
+ }
+ if (split[1]) {
+ resolution.height = parseInt(split[1], 10);
+ }
+ event.attributes.RESOLUTION = resolution;
+ })();
+ }
+ if (event.attributes.BANDWIDTH) {
+ event.attributes.BANDWIDTH = parseInt(event.attributes.BANDWIDTH, 10);
+ }
+ if (event.attributes['PROGRAM-ID']) {
+ event.attributes['PROGRAM-ID'] = parseInt(event.attributes['PROGRAM-ID'], 10);
+ }
+ }
+ this.trigger('data', event);
+ return;
+ }
+ match = (/^#EXT-X-ENDLIST/).exec(line);
+ if (match) {
+ this.trigger('data', {
+ type: 'tag',
+ tagType: 'endlist'
+ });
+ return;
+ }
+
+ // unknown tag type
+ this.trigger('data', {
+ type: 'tag',
+ data: line.slice(4, line.length)
+ });
+ };
+
+ /**
+ * A parser for M3U8 files. The current interpretation of the input is
+ * exposed as a property `manifest` on parser objects. It's just two lines to
+ * create and parse a manifest once you have the contents available as a string:
+ *
+ * ```js
+ * var parser = new videojs.m3u8.Parser();
+ * parser.push(xhr.responseText);
+ * ```
+ *
+ * New input can later be applied to update the manifest object by calling
+ * `push` again.
+ *
+ * The parser attempts to create a usable manifest object even if the
+ * underlying input is somewhat nonsensical. It emits `info` and `warning`
+ * events during the parse if it encounters input that seems invalid or
+ * requires some property of the manifest object to be defaulted.
+ */
+ Parser = function() {
+ var
+ self = this,
+ uris = [],
+ currentUri = {};
+ Parser.prototype.init.call(this);
+
+ this.lineStream = new LineStream();
+ this.parseStream = new ParseStream();
+ this.lineStream.pipe(this.parseStream);
+
+ // the manifest is empty until the parse stream begins delivering data
+ this.manifest = {
+ allowCache: true
+ };
+
+ // update the manifest with the m3u8 entry from the parse stream
+ this.parseStream.on('data', function(entry) {
+ ({
+ tag: function() {
+ // switch based on the tag type
+ (({
+ 'allow-cache': function() {
+ this.manifest.allowCache = entry.allowed;
+ if (!('allowed' in entry)) {
+ this.trigger('info', {
+ message: 'defaulting allowCache to YES'
+ });
+ this.manifest.allowCache = true;
+ }
+ },
+ 'byterange': function() {
+ var byterange = {};
+ if ('length' in entry) {
+ currentUri.byterange = byterange;
+ byterange.length = entry.length;
+
+ if (!('offset' in entry)) {
+ this.trigger('info', {
+ message: 'defaulting offset to zero'
+ });
+ entry.offset = 0;
+ }
+ }
+ if ('offset' in entry) {
+ currentUri.byterange = byterange;
+ byterange.offset = entry.offset;
+ }
+ },
+ 'endlist': function() {
+ this.manifest.endList = true;
+ },
+ 'inf': function() {
+ if (!('mediaSequence' in this.manifest)) {
+ this.manifest.mediaSequence = 0;
+ this.trigger('info', {
+ message: 'defaulting media sequence to zero'
+ });
+ }
+ if (entry.duration >= 0) {
+ currentUri.duration = entry.duration;
+ }
+
+ this.manifest.segments = uris;
+
+ },
+ 'media-sequence': function() {
+ if (!isFinite(entry.number)) {
+ this.trigger('warn', {
+ message: 'ignoring invalid media sequence: ' + entry.number
+ });
+ return;
+ }
+ this.manifest.mediaSequence = entry.number;
+ },
+ 'playlist-type': function() {
+ if (!(/VOD|EVENT/).test(entry.playlistType)) {
+ this.trigger('warn', {
+ message: 'ignoring unknown playlist type: ' + entry.playlist
+ });
+ return;
+ }
+ this.manifest.playlistType = entry.playlistType;
+ },
+ 'stream-inf': function() {
+ this.manifest.playlists = uris;
+
+ if (!entry.attributes) {
+ this.trigger('warn', {
+ message: 'ignoring empty stream-inf attributes'
+ });
+ return;
+ }
+
+ if (!currentUri.attributes) {
+ currentUri.attributes = {};
+ }
+ currentUri.attributes = mergeOptions(currentUri.attributes,
+ entry.attributes);
+ },
+ 'targetduration': function() {
+ if (!isFinite(entry.duration) || entry.duration < 0) {
+ this.trigger('warn', {
+ message: 'ignoring invalid target duration: ' + entry.duration
+ });
+ return;
+ }
+ this.manifest.targetDuration = entry.duration;
+ },
+ 'totalduration': function() {
+ if (!isFinite(entry.duration) || entry.duration < 0) {
+ this.trigger('warn', {
+ message: 'ignoring invalid total duration: ' + entry.duration
+ });
+ return;
+ }
+ this.manifest.totalDuration = entry.duration;
+ }
+ })[entry.tagType] || noop).call(self);
+ },
+ uri: function() {
+ currentUri.uri = entry.uri;
+ uris.push(currentUri);
+
+ // if no explicit duration was declared, use the target duration
+ if (this.manifest.targetDuration &&
+ !('duration' in currentUri)) {
+ this.trigger('warn', {
+ message: 'defaulting segment duration to the target duration'
+ });
+ currentUri.duration = this.manifest.targetDuration;
+ }
+
+ // prepare for the next URI
+ currentUri = {};
+ },
+ comment: function() {
+ // comments are not important for playback
+ }
+ })[entry.type].call(self);
+ });
+ };
+ Parser.prototype = new Stream();
+ /**
+ * Parse the input string and update the manifest object.
+ * @param chunk {string} a potentially incomplete portion of the manifest
+ */
+ Parser.prototype.push = function(chunk) {
+ this.lineStream.push(chunk);
+ };
+ /**
+ * Flush any remaining input. This can be handy if the last line of an M3U8
+ * manifest did not contain a trailing newline but the file has been
+ * completely received.
+ */
+ Parser.prototype.end = function() {
+ // flush any buffered input
+ this.lineStream.push('\n');
+ };
+
+ window.videojs.m3u8 = {
+ LineStream: LineStream,
+ ParseStream: ParseStream,
+ Parser: Parser
+ };
+})(window.videojs, window.parseInt, window.isFinite, window.videojs.util.mergeOptions);
+
+(function(window, videojs) {
+ 'use strict';
+ var
+ resolveUrl = videojs.Hls.resolveUrl,
+ xhr = videojs.Hls.xhr,
+
+ /**
+ * Returns a new master playlist that is the result of merging an
+ * updated media playlist into the original version. If the
+ * updated media playlist does not match any of the playlist
+ * entries in the original master playlist, null is returned.
+ * @param master {object} a parsed master M3U8 object
+ * @param media {object} a parsed media M3U8 object
+ * @return {object} a new object that represents the original
+ * master playlist with the updated media playlist merged in, or
+ * null if the merge produced no change.
+ */
+ updateMaster = function(master, media) {
+ var
+ changed = false,
+ result = videojs.util.mergeOptions(master, {}),
+ i,
+ playlist;
+
+ i = master.playlists.length;
+ while (i--) {
+ playlist = result.playlists[i];
+ if (playlist.uri === media.uri) {
+ // consider the playlist unchanged if the number of segments
+ // are equal and the media sequence number is unchanged
+ if (playlist.segments &&
+ media.segments &&
+ playlist.segments.length === media.segments.length &&
+ playlist.mediaSequence === media.mediaSequence) {
+ continue;
+ }
+
+ result.playlists[i] = videojs.util.mergeOptions(playlist, media);
+ result.playlists[media.uri] = result.playlists[i];
+ changed = true;
+ }
+ }
+ return changed ? result : null;
+ },
+
+ PlaylistLoader = function(srcUrl, withCredentials) {
+ var
+ loader = this,
+ dispose,
+ media,
+ mediaUpdateTimeout,
+ request,
+
+ haveMetadata = function(error, xhr, url) {
+ var parser, refreshDelay, update;
+
+ // any in-flight request is now finished
+ request = null;
+
+ if (error) {
+ loader.error = {
+ status: xhr.status,
+ message: 'HLS playlist request error at URL: ' + url,
+ code: (xhr.status >= 500) ? 4 : 2
+ };
+ return loader.trigger('error');
+ }
+
+ loader.state = 'HAVE_METADATA';
+
+ parser = new videojs.m3u8.Parser();
+ parser.push(xhr.responseText);
+ parser.manifest.uri = url;
+
+ // merge this playlist into the master
+ update = updateMaster(loader.master, parser.manifest);
+ refreshDelay = (parser.manifest.targetDuration || 10) * 1000;
+ if (update) {
+ loader.master = update;
+ media = loader.master.playlists[url];
+ } else {
+ // if the playlist is unchanged since the last reload,
+ // try again after half the target duration
+ refreshDelay /= 2;
+ }
+
+ // refresh live playlists after a target duration passes
+ if (!loader.media().endList) {
+ mediaUpdateTimeout = window.setTimeout(function() {
+ loader.trigger('mediaupdatetimeout');
+ }, refreshDelay);
+ }
+
+ loader.trigger('loadedplaylist');
+ };
+
+ PlaylistLoader.prototype.init.call(this);
+
+ if (!srcUrl) {
+ throw new Error('A non-empty playlist URL is required');
+ }
+
+ loader.state = 'HAVE_NOTHING';
+
+ // capture the prototype dispose function
+ dispose = this.dispose;
+
+ /**
+ * Abort any outstanding work and clean up.
+ */
+ loader.dispose = function() {
+ if (request) {
+ request.abort();
+ }
+ window.clearTimeout(mediaUpdateTimeout);
+ dispose.call(this);
+ };
+
+ /**
+ * When called without any arguments, returns the currently
+ * active media playlist. When called with a single argument,
+ * triggers the playlist loader to asynchronously switch to the
+ * specified media playlist. Calling this method while the
+ * loader is in the HAVE_NOTHING or HAVE_MASTER states causes an
+ * error to be emitted but otherwise has no effect.
+ * @param playlist (optional) {object} the parsed media playlist
+ * object to switch to
+ */
+ loader.media = function(playlist) {
+ // getter
+ if (!playlist) {
+ return media;
+ }
+
+ // setter
+ if (loader.state === 'HAVE_NOTHING' || loader.state === 'HAVE_MASTER') {
+ throw new Error('Cannot switch media playlist from ' + loader.state);
+ }
+
+ // find the playlist object if the target playlist has been
+ // specified by URI
+ if (typeof playlist === 'string') {
+ if (!loader.master.playlists[playlist]) {
+ throw new Error('Unknown playlist URI: ' + playlist);
+ }
+ playlist = loader.master.playlists[playlist];
+ }
+
+ if (playlist.uri === media.uri) {
+ // switching to the currently active playlist is a no-op
+ return;
+ }
+
+
+
+ loader.state = 'SWITCHING_MEDIA';
+
+ // there is already an outstanding playlist request
+ if (request) {
+ if (resolveUrl(loader.master.uri, playlist.uri) === request.url) {
+ // requesting to switch to the same playlist multiple times
+ // has no effect after the first
+ return;
+ }
+ request.abort();
+ request = null;
+ }
+
+ // request the new playlist
+ request = xhr({
+ url: resolveUrl(loader.master.uri, playlist.uri),
+ withCredentials: withCredentials
+ }, function(error) {
+ haveMetadata(error, this, playlist.uri);
+ });
+ };
+
+ // live playlist staleness timeout
+ loader.on('mediaupdatetimeout', function() {
+ if (loader.state !== 'HAVE_METADATA') {
+ // only refresh the media playlist if no other activity is going on
+ return;
+ }
+
+ loader.state = 'HAVE_CURRENT_METADATA';
+ request = xhr({
+ url: resolveUrl(loader.master.uri, loader.media().uri),
+ withCredentials: withCredentials
+ }, function(error) {
+ haveMetadata(error, this, loader.media().uri);
+ });
+ });
+
+ // request the specified URL
+ xhr({
+ url: srcUrl,
+ withCredentials: withCredentials
+ }, function(error) {
+ var parser, i;
+
+ if (error) {
+ loader.error = {
+ status: this.status,
+ message: 'HLS playlist request error at URL: ' + srcUrl,
+ code: 2 // MEDIA_ERR_NETWORK
+ };
+ return loader.trigger('error');
+ }
+
+ parser = new videojs.m3u8.Parser();
+ parser.push(this.responseText);
+
+ loader.state = 'HAVE_MASTER';
+
+ parser.manifest.uri = srcUrl;
+
+ // loaded a master playlist
+ if (parser.manifest.playlists) {
+ loader.master = parser.manifest;
+
+ // setup by-URI lookups
+ i = loader.master.playlists.length;
+ while (i--) {
+ loader.master.playlists[loader.master.playlists[i].uri] = loader.master.playlists[i];
+ }
+
+ request = xhr({
+ url: resolveUrl(srcUrl, parser.manifest.playlists[0].uri),
+ withCredentials: withCredentials
+ }, function(error) {
+ // pass along the URL specified in the master playlist
+ haveMetadata(error,
+ this,
+ parser.manifest.playlists[0].uri);
+ if (!error) {
+ loader.trigger('loadedmetadata');
+ }
+ });
+ return loader.trigger('loadedplaylist');
+ }
+
+ // loaded a media playlist
+ // infer a master playlist if none was previously requested
+ loader.master = {
+ uri: window.location.href,
+ playlists: [{
+ uri: srcUrl
+ }]
+ };
+ loader.master.playlists[srcUrl] = loader.master.playlists[0];
+ haveMetadata(null, this, srcUrl);
+ return loader.trigger('loadedmetadata');
+ });
+ };
+ PlaylistLoader.prototype = new videojs.Hls.Stream();
+
+ videojs.Hls.PlaylistLoader = PlaylistLoader;
+})(window, window.videojs);
diff --git a/assets/videojs.hls.min.js b/assets/videojs.hls.min.js
new file mode 100644
index 0000000..9b3e049
--- /dev/null
+++ b/assets/videojs.hls.min.js
@@ -0,0 +1,3 @@
+/*! videojs-contrib-hls - v0.7.2 - 2014-06-13
+* Copyright (c) 2014 Brightcove; Licensed */
+!function(a,b,c){var d,e,f=5,g=1.1,h=function(b,c){var d,e;return b.attributes&&b.attributes.BANDWIDTH&&(d=b.attributes.BANDWIDTH),d=d||a.Number.MAX_VALUE,c.attributes&&c.attributes.BANDWIDTH&&(e=c.attributes.BANDWIDTH),e=e||a.Number.MAX_VALUE,d-e},i=function(b,c){var d,e;return b.attributes&&b.attributes.RESOLUTION&&b.attributes.RESOLUTION.width&&(d=b.attributes.RESOLUTION.width),d=d||a.Number.MAX_VALUE,c.attributes&&c.attributes.RESOLUTION&&c.attributes.RESOLUTION.width&&(e=c.attributes.RESOLUTION.width),e=e||a.Number.MAX_VALUE,d===e&&b.attributes.BANDWIDTH&&c.attributes.BANDWIDTH?b.attributes.BANDWIDTH-c.attributes.BANDWIDTH:d-e},j=function(a,b){var c,d,e,f;for(e=[],c=0;c=e[d].start&&b=f||(h=a.hls.playlists.media().uri===m?e(m,g.uri):e(e(m,a.hls.playlists.media().uri||""),g.uri),i=+new Date,o=d({url:h,responseType:"arraybuffer",withCredentials:s.withCredentials},function(d,e){if(o=null,d)return a.hls.error={status:this.status,message:"HLS segment request error at URL: "+e,code:this.status>=500?4:2},void a.hls.mediaIndex++;if(this.response){for(a.hls.segmentXhrTime=+new Date-i,a.hls.bandwidth=this.response.byteLength/a.hls.segmentXhrTime*8*1e3,r.parseSegmentBinaryData(new Uint8Array(this.response)),r.flushTags(),"number"==typeof b&&!function(){for(var c=r.getTags()[0];c.pts=400||0===this.status?d.call(this,!0,c):d.call(this,!1,c)):void 0},e.send(null),e},e=b.Hls.resolveUrl=function(a,b){var d,e,f=c.querySelector("base"),g=c.querySelector("head"),h=c.createElement("a"),i=f;return f?d=f.href:i=g.appendChild(c.createElement("base")),i.href=a,h.href=b,e=h.href,f?f.href=d:g.removeChild(i),e}}(window,window.videojs,document),function(a){a.videojs=a.videojs||{},a.videojs.Hls=a.videojs.Hls||{};var b=a.videojs.Hls;b.FlvTag=function(a,c){var d,e=0,f=function(a,b){var c,d=a.position+b;d0)throw new Error("Attempted to create new NAL wihout closing the old one");e=this.length,this.length+=4,this.position=this.length},this.endNalUnit=function(a){var b,c;this.length===e+4?this.length-=4:e>0&&(b=e+4,c=this.length-b,this.position=e,this.view.setUint32(this.position,c),this.position=this.length,a&&a.push(this.bytes.subarray(b,b+c))),e=0},this.writeMetaDataDouble=function(a,b){var c;if(f(this,2+a.length+9),this.view.setUint16(this.position,a.length),this.position+=2,"width"===a)this.bytes.set(g,this.position),this.position+=5;else if("height"===a)this.bytes.set(h,this.position),this.position+=6;else if("videocodecid"===a)this.bytes.set(i,this.position),this.position+=12;else for(c in a)this.bytes[this.position]=a.charCodeAt(c),this.position++;this.position++,this.view.setFloat64(this.position,b),this.position+=8,this.length=Math.max(this.length,this.position),++e},this.writeMetaDataBoolean=function(a,b){var c;f(this,2),this.view.setUint16(this.position,a.length),this.position+=2;for(c in a)console.assert(a.charCodeAt(c)<255),f(this,1),this.bytes[this.position]=a.charCodeAt(c),this.position++;f(this,2),this.view.setUint8(this.position,1),this.position++,this.view.setUint8(this.position,b?1:0),this.position++,this.length=Math.max(this.length,this.position),++e},this.finalize=function(){var a,d;switch(this.bytes[0]){case b.FlvTag.VIDEO_TAG:this.bytes[11]=7|(this.keyFrame||c?16:32),this.bytes[12]=c?0:1,a=this.pts-this.dts,this.bytes[13]=(16711680&a)>>>16,this.bytes[14]=(65280&a)>>>8,this.bytes[15]=(255&a)>>>0;break;case b.FlvTag.AUDIO_TAG:this.bytes[11]=175,this.bytes[12]=c?0:1;break;case b.FlvTag.METADATA_TAG:this.position=11,this.view.setUint8(this.position,2),this.position++,this.view.setUint16(this.position,10),this.position+=2,this.bytes.set([111,110,77,101,116,97,68,97,116,97],this.position),this.position+=10,this.bytes[this.position]=8,this.position++,this.view.setUint32(this.position,e),this.position=this.length,this.bytes.set([0,0,9],this.position),this.position+=3,this.length=this.position}return d=this.length-11,this.bytes[1]=(16711680&d)>>>16,this.bytes[2]=(65280&d)>>>8,this.bytes[3]=(255&d)>>>0,this.bytes[4]=(16711680&this.pts)>>>16,this.bytes[5]=(65280&this.pts)>>>8,this.bytes[6]=(255&this.pts)>>>0,this.bytes[7]=(4278190080&this.pts)>>>24,this.bytes[8]=0,this.bytes[9]=0,this.bytes[10]=0,this.view.setUint32(this.length,this.length),this.length+=4,this.position+=4,this.bytes=this.bytes.subarray(0,this.length),this.frameTime=b.FlvTag.frameTime(this.bytes),console.assert(this.bytes.byteLength===this.length),this}},b.FlvTag.AUDIO_TAG=8,b.FlvTag.VIDEO_TAG=9,b.FlvTag.METADATA_TAG=18,b.FlvTag.isAudioFrame=function(a){return b.FlvTag.AUDIO_TAG===a[0]},b.FlvTag.isVideoFrame=function(a){return b.FlvTag.VIDEO_TAG===a[0]},b.FlvTag.isMetaData=function(a){return b.FlvTag.METADATA_TAG===a[0]},b.FlvTag.isKeyFrame=function(a){return b.FlvTag.isVideoFrame(a)?23===a[11]:b.FlvTag.isAudioFrame(a)?!0:b.FlvTag.isMetaData(a)?!0:!1},b.FlvTag.frameTime=function(a){var b=a[4]<<16;return b|=a[5]<<8,b|=a[6]<<0,b|=a[7]<<24}}(this),function(a){a.videojs.Hls.ExpGolomb=function(a){var b=a.byteLength,c=0,d=0;this.length=function(){return 8*b},this.bitsAvailable=function(){return 8*b+d},this.loadWord=function(){var e=a.byteLength-b,f=new Uint8Array(4),g=Math.min(4,b);if(0===g)throw new Error("no bytes available");f.set(a.subarray(e,e+g)),c=new DataView(f.buffer).getUint32(0),d=8*g,b-=g},this.skipBits=function(a){var e;d>a?(c<<=a,d-=a):(a-=d,e=a/8,a-=8*e,b-=e,this.loadWord(),c<<=a,d-=a)},this.readBits=function(a){var e=Math.min(d,a),f=c>>>32-e;return console.assert(32>a,"Cannot read more than 32 bits at a time"),d-=e,d>0?c<<=e:b>0&&this.loadWord(),e=a-e,e>0?f<a;++a)if(0!==(c&2147483648>>>a))return c<<=a,d-=a,a;return this.loadWord(),a+this.skipLeadingZeros()},this.skipUnsignedExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.skipExpGolomb=function(){this.skipBits(1+this.skipLeadingZeros())},this.readUnsignedExpGolomb=function(){var a=this.skipLeadingZeros();return this.readBits(a+1)-1},this.readExpGolomb=function(){var a=this.readUnsignedExpGolomb();return 1&a?1+a>>>1:-1*(a>>>1)},this.readBoolean=function(){return 1===this.readBits(1)},this.readUnsignedByte=function(){return this.readBits(8)},this.loadWord()}}(this),function(a){var b,c=a.videojs.Hls.ExpGolomb,d=a.videojs.Hls.FlvTag,e=function(){this.sps=[],this.pps=[],this.extraDataExists=function(){return this.sps.length>0},this.scaling_list=function(a,b){var c,d,e=8,f=8;for(c=0;a>c;++c)0!==f&&(d=b.readExpGolomb(),f=(e+d+256)%256),e=0===f?e:f},this.getSps0Rbsp=function(){for(var a=this.sps[0],b=1,c=1,d=0,e=a.byteLength-2,f=new Uint8Array(a.byteLength);e>b;)0===a[b]&&0===a[b+1]&&3===a[b+2]&&(f.set(a.subarray(c,b+1),d),d+=b+1-c,c=b+3),b++;return f.set(a.subarray(c),d),f.subarray(0,d+(a.byteLength-c))},this.metaDataTag=function(a){var b,e,f,g,h,i,j,k,l,m,n,o,p,q=new d(d.METADATA_TAG),r=0,s=0,t=0,u=0;if(q.dts=a,q.pts=a,b=new c(this.getSps0Rbsp()),e=b.readUnsignedByte(),b.skipBits(16),b.skipUnsignedExpGolomb(),(100===e||110===e||122===e||244===e||44===e||83===e||86===e||118===e||128===e)&&(f=b.readUnsignedExpGolomb(),3===f&&b.skipBits(1),b.skipUnsignedExpGolomb(),b.skipUnsignedExpGolomb(),b.skipBits(1),b.readBoolean()))for(g=3!==f?8:12,h=0;g>h;++h)b.readBoolean()&&(6>h?this.scaling_list(16,b):this.scaling_list(64,b));if(b.skipUnsignedExpGolomb(),i=b.readUnsignedExpGolomb(),0===i)b.readUnsignedExpGolomb();else if(1===i)for(b.skipBits(1),b.skipExpGolomb(),b.skipExpGolomb(),j=b.readUnsignedExpGolomb(),h=0;j>h;++h)b.skipExpGolomb();return b.skipUnsignedExpGolomb(),b.skipBits(1),k=b.readUnsignedExpGolomb(),l=b.readUnsignedExpGolomb(),m=b.readBits(1),0===m&&b.skipBits(1),b.skipBits(1),n=b.readBoolean(),n&&(r=b.readUnsignedExpGolomb(),s=b.readUnsignedExpGolomb(),t=b.readUnsignedExpGolomb(),u=b.readUnsignedExpGolomb()),o=16*(k+1)-2*r-2*s,p=(2-m)*(l+1)*16-2*t-2*u,q.writeMetaDataDouble("videocodecid",7),q.writeMetaDataDouble("width",o),q.writeMetaDataDouble("height",p),q},this.extraDataTag=function(a){var b,c=new d(d.VIDEO_TAG,!0);for(c.dts=a,c.pts=a,c.writeByte(1),c.writeByte(this.sps[0][1]),c.writeByte(this.sps[0][2]),c.writeByte(this.sps[0][3]),c.writeByte(255),c.writeByte(225),c.writeShort(this.sps[0].length),c.writeBytes(this.sps[0]),c.writeByte(this.pps.length),b=0;b=i))switch(h){default:case 0:h=1;case 1:if(e[f]<=1&&(l=g?g.nalUnitSize():0,l>=1&&0===g.negIndex(1))){if(1===e[f]&&l>=2&&0===g.negIndex(2))return g.length-=l>=3&&0===g.negIndex(3)?3:2,h=3,this.writeBytes(e,f+1,i-1);if(i>1&&0===e[f]&&1===e[f+1])return g.length-=l>=2&&0===g.negIndex(2)?2:1,h=3,this.writeBytes(e,f+2,i-2);if(i>2&&0===e[f]&&0===e[f+1]&&1===e[f+2])return h=3,this.writeBytes(e,f+3,i-3)}h=2;case 2:for(m=f,n=m+i,o=n-3;o>f;)if(e[f+2]>1)f+=3;else if(0!==e[f+1])f+=2;else if(0!==e[f])f+=1;else{if(1===e[f+2])return f>m&&g.writeBytes(e,m,f-m),h=3,f+=3,this.writeBytes(e,f,n-f);if(n-f>=4&&0===e[f+2]&&1===e[f+3])return f>m&&g.writeBytes(e,m,f-m),h=3,f+=4,this.writeBytes(e,f,n-f);f+=3}return h=1,void g.writeBytes(e,m,i);case 3:if(g)switch(k){case b.seq_parameter_set_rbsp:g.endNalUnit(j.sps);break;case b.pic_parameter_set_rbsp:g.endNalUnit(j.pps);break;case b.slice_layer_without_partitioning_rbsp_idr:g.endNalUnit();break;default:g.endNalUnit()}return k=31&e[f],g&&(k===b.access_unit_delimiter_rbsp?this.finishFrame():k===b.slice_layer_without_partitioning_rbsp_idr&&(g.keyFrame=!0)),g||(g=new d(d.VIDEO_TAG),g.pts=a,g.dts=c),g.startNalUnit(),h=2,this.writeBytes(e,f,i)}}}}(this),function(a){var b=a.videojs.Hls.FlvTag,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3];a.videojs.Hls.AacStream=function(){var a,d,e,f,g,h,i,j,k,l,m,n,o;this.tags=[],this.setNextTimeStamp=function(b,c,g){d=b,this.setNextTimeStamp=function(b,c,g){a=b-d,f=c,g&&(e=0)},this.setNextTimeStamp(b,c,g)},this.writeBytes=function(d,p,q){var r,s,t;for(p=p||0,q=q||0,q=q>f?f:q,f-=q,r=p+q;r>p;)switch(e){default:e=0;break;case 0:if(p>=r)return;if(255!==d[p])return console.assert(!1,"Error no ATDS header found"),p+=1,void(e=0);p+=1,e=1;break;case 1:if(p>=r)return;if(240!==(240&d[p]))return console.assert(!1,"Error no ATDS header found"),p+=1,void(e=0);g=!!(1&d[p]),p+=1,e=2;break;case 2:if(p>=r)return;h=((192&d[p])>>>6)+1,i=(60&d[p])>>>2,j=(1&d[p])<<2,p+=1,e=3;break;case 3:if(p>=r)return;j|=(192&d[p])>>>6,k=(3&d[p])<<11,p+=1,e=4;break;case 4:if(p>=r)return;k|=d[p]<<3,p+=1,e=5;break;case 5:if(p>=r)return;k|=(224&d[p])>>>5,k-=g?7:9,p+=1,e=6;break;case 6:if(p>=r)return;l=1024*((3&d[p])+1),m=1e3*l/c[i],s=h<<11|i<<7|j<<3,s!==o&&(n=new b(b.METADATA_TAG),n.pts=a,n.dts=a,n.writeMetaDataDouble("audiocodecid",10),n.writeMetaDataBoolean("stereo",2===j),n.writeMetaDataDouble("audiosamplerate",c[i]),n.writeMetaDataDouble("audiosamplesize",16),this.tags.push(n),o=s,n=new b(b.AUDIO_TAG,!0),n.pts=n.dts,n.pts=a,n.view.setUint16(n.position,s),n.position+=2,n.length=Math.max(n.length,n.position),this.tags.push(n)),p+=1,e=7;break;case 7:if(!g){if(2>r-p)return;p+=2}n=new b(b.AUDIO_TAG),n.pts=a,n.dts=a,e=8;break;case 8:for(;k;){if(p>=r)return;t=k>r-p?r-p:k,n.writeBytes(d,p,t),p+=t,k-=t}this.tags.push(n),e=0,a+=m}}}}(this),function(a){var b,c,d=a.videojs,e=d.Hls.FlvTag,f=d.Hls.H264Stream,g=d.Hls.AacStream;d.Hls.SegmentParser=function(){var a,h=this,i=new Uint8Array(b),j=0,k=new f,l=new g;h.stream={programMapTable:{}},h.getFlvHeader=function(a,b,c){var d,f,g=new Uint8Array(9),h=new DataView(g.buffer);return a=a||0,b=void 0===b?!0:b,c=void 0===c?!0:c,h.setUint8(0,70),h.setUint8(1,76),h.setUint8(2,86),h.setUint8(3,1),h.setUint8(4,(b?4:0)|(c?1:0)),h.setUint32(5,g.byteLength),0>=a?(f=new Uint8Array(g.byteLength+4),f.set(g),f.set([0,0,0,0],g.byteLength),f):(d=new e(e.METADATA_TAG),d.pts=d.dts=0,d.writeMetaDataDouble("duration",a),f=new Uint8Array(g.byteLength+d.byteLength),f.set(h),f.set(h.bytesLength,d.finalize()),f)},h.flushTags=function(){k.finishFrame()},h.tagsAvailable=function(){return k.tags.length+l.tags.length},h.getNextTag=function(){var a;return a=k.tags.length?l.tags.length&&l.tags[0].dts0){if(c.byteLength+j0&&(i.set(c.subarray(f),j),j+=c.byteLength-f));a(c.subarray(f,f+b))?f+=b:(d.log("error parsing m2ts packet, attempting to re-align"),f++)}},a=function(a){var e,f,g,i,j,m,n,o,p,q,r,s,t,u,v,w=0,x=w+b,y=!!(64&a[w+1]),z=(31&a[w+1])<<8|a[w+2],A=(48&a[w+3])>>>4;if(w+=4,A>1&&(w+=a[w]+1),0===z){if(y&&(w+=1+a[w]),e=a[w],0!==e&&d.log("the table_id of the PAT should be 0x00 but was"+e.toString(16)),f=!!(1&a[w+5])){if(g=(15&a[w+1])<<8|a[w+2],w+=8,(g-5-4)/4!==1)throw new Error("TS has more that 1 program");h.stream.pmtPid=(31&a[w+2])<<8|a[w+3]}}else if(z===h.stream.programMapTable[c.h264]||z===h.stream.programMapTable[c.adts]){if(y){if(0!==a[w+0]||0!==a[w+1]||1!==a[w+2])throw new Error("PES did not begin with start code");i=a[w+4]<<8|a[w+5],j=0!==(4&a[w+6]),m=a[w+7],n=a[w+8],w+=9,192&m&&(o=(14&a[w+0])<<28|(255&a[w+1])<<21|(254&a[w+2])<<13|(255&a[w+3])<<6|(254&a[w+4])>>>2,o/=45,p=o,64&m&&(p=(14&a[w+5])<<28|(255&a[w+6])<<21|(254&a[w+7])<<13|(255&a[w+8])<<6|(254&a[w+9])>>>2,p/=45)),w+=n,z===h.stream.programMapTable[c.h264]?k.setNextTimeStamp(o,p,j):z===h.stream.programMapTable[c.adts]&&l.setNextTimeStamp(o,i,j)}z===h.stream.programMapTable[c.adts]?l.writeBytes(a,w,x-w):z===h.stream.programMapTable[c.h264]&&k.writeBytes(a,w,x-w)}else if(h.stream.pmtPid===z){if(y&&(w+=1+a[w]),2!==a[w]&&d.log("The table_id of a PMT should be 0x02 but was "+a[w].toString(16)),q=!!(1&a[w+5]))for(h.stream.programMapTable={},s=(15&a[w+1])<<8|a[w+2],r=(15&a[w+10])<<8|a[w+11],s-=r,s-=13,w+=12+r;s>0;){if(t=a[w+0],u=(31&a[w+1])<<8|a[w+2],t===c.h264){if(h.stream.programMapTable[t]&&h.stream.programMapTable[t]!==u)throw new Error("Program has more than 1 video stream");h.stream.programMapTable[t]=u}else if(t===c.adts){if(h.stream.programMapTable[t]&&h.stream.programMapTable[t]!==u)throw new Error("Program has more than 1 audio Stream");h.stream.programMapTable[t]=u}v=(15&a[w+3])<<8|a[w+4],w+=5+v,s-=5+v}}else 17===z||8191===z||d.log("Unknown PID parsing TS packet: "+z);return!0},h.getTags=function(){return k.tags},h.stats={h264Tags:function(){return k.tags.length},aacTags:function(){return l.tags.length}}},d.Hls.SegmentParser.MP2T_PACKET_LENGTH=b=188,d.Hls.SegmentParser.STREAM_TYPES=c={h264:27,adts:15}}(window),function(a){var b=function(){this.init=function(){var a={};this.on=function(b,c){a[b]||(a[b]=[]),a[b].push(c)},this.off=function(b,c){var d;return a[b]?(d=a[b].indexOf(c),a[b].splice(d,1),d>-1):!1},this.trigger=function(b){var c,d,e,f;if(c=a[b])for(f=Array.prototype.slice.call(arguments,1),e=c.length,d=0;e>d;++d)c[d].apply(this,f)},this.dispose=function(){a={}}}};b.prototype.pipe=function(a){this.on("data",function(b){a.push(b)})},a.Hls.Stream=b}(window.videojs),function(a,b,c,d){var e,f,g,h=function(){},i=function(a){for(var b,c=a.split(","),d=c.length,e={};d--;)b=c[d].split("="),b[0]=b[0].replace(/^\s+|\s+$/g,""),b[1]?(b[1]=b[1].replace(/^\s+|\s+$/g,""),-1!==b[1].indexOf('"')&&(b[1]=b[1].split('"')[1]),e[b[0]]=b[1]):c[d-1]=c[d-1]+","+b[0];return e},j=a.Hls.Stream;e=function(){var a="";e.prototype.init.call(this),this.push=function(b){var c;for(a+=b,c=a.indexOf("\n");c>-1;c=a.indexOf("\n"))this.trigger("data",a.substring(0,c)),a=a.substring(c+1)}},e.prototype=new j,f=function(){f.prototype.init.call(this)},f.prototype=new j,f.prototype.push=function(a){var c,d;if(0!==a.length)return"#"!==a[0]?void this.trigger("data",{type:"uri",uri:a}):0!==a.indexOf("#EXT")?void this.trigger("data",{type:"comment",text:a.slice(1)}):(a=a.replace("\r",""),(c=/^#EXTM3U/.exec(a))?void this.trigger("data",{type:"tag",tagType:"m3u"}):(c=/^#EXTINF:?([0-9\.]*)?,?(.*)?$/.exec(a))?(d={type:"tag",tagType:"inf"},c[1]&&(d.duration=parseFloat(c[1],10)),c[2]&&(d.title=c[2]),void this.trigger("data",d)):(c=/^#EXT-X-TARGETDURATION:?([0-9.]*)?/.exec(a))?(d={type:"tag",tagType:"targetduration"},c[1]&&(d.duration=b(c[1],10)),void this.trigger("data",d)):(c=/^#ZEN-TOTAL-DURATION:?([0-9.]*)?/.exec(a))?(d={type:"tag",tagType:"totalduration"},c[1]&&(d.duration=b(c[1],10)),void this.trigger("data",d)):(c=/^#EXT-X-VERSION:?([0-9.]*)?/.exec(a))?(d={type:"tag",tagType:"version"},c[1]&&(d.version=b(c[1],10)),void this.trigger("data",d)):(c=/^#EXT-X-MEDIA-SEQUENCE:?(\-?[0-9.]*)?/.exec(a))?(d={type:"tag",tagType:"media-sequence"},c[1]&&(d.number=b(c[1],10)),void this.trigger("data",d)):(c=/^#EXT-X-PLAYLIST-TYPE:?(.*)?$/.exec(a))?(d={type:"tag",tagType:"playlist-type"},c[1]&&(d.playlistType=c[1]),void this.trigger("data",d)):(c=/^#EXT-X-BYTERANGE:?([0-9.]*)?@?([0-9.]*)?/.exec(a))?(d={type:"tag",tagType:"byterange"},c[1]&&(d.length=b(c[1],10)),c[2]&&(d.offset=b(c[2],10)),void this.trigger("data",d)):(c=/^#EXT-X-ALLOW-CACHE:?(YES|NO)?/.exec(a))?(d={type:"tag",tagType:"allow-cache"},c[1]&&(d.allowed=!/NO/.test(c[1])),void this.trigger("data",d)):(c=/^#EXT-X-STREAM-INF:?(.*)$/.exec(a))?(d={type:"tag",tagType:"stream-inf"},c[1]&&(d.attributes=i(c[1]),d.attributes.RESOLUTION&&!function(){var a=d.attributes.RESOLUTION.split("x"),c={};a[0]&&(c.width=b(a[0],10)),a[1]&&(c.height=b(a[1],10)),d.attributes.RESOLUTION=c}(),d.attributes.BANDWIDTH&&(d.attributes.BANDWIDTH=b(d.attributes.BANDWIDTH,10)),d.attributes["PROGRAM-ID"]&&(d.attributes["PROGRAM-ID"]=b(d.attributes["PROGRAM-ID"],10))),void this.trigger("data",d)):(c=/^#EXT-X-ENDLIST/.exec(a))?void this.trigger("data",{type:"tag",tagType:"endlist"}):void this.trigger("data",{type:"tag",data:a.slice(4,a.length)}))},g=function(){var a=this,b=[],i={};g.prototype.init.call(this),this.lineStream=new e,this.parseStream=new f,this.lineStream.pipe(this.parseStream),this.manifest={allowCache:!0},this.parseStream.on("data",function(e){({tag:function(){(({"allow-cache":function(){this.manifest.allowCache=e.allowed,"allowed"in e||(this.trigger("info",{message:"defaulting allowCache to YES"}),this.manifest.allowCache=!0)},byterange:function(){var a={};"length"in e&&(i.byterange=a,a.length=e.length,"offset"in e||(this.trigger("info",{message:"defaulting offset to zero"}),e.offset=0)),"offset"in e&&(i.byterange=a,a.offset=e.offset)},endlist:function(){this.manifest.endList=!0},inf:function(){"mediaSequence"in this.manifest||(this.manifest.mediaSequence=0,this.trigger("info",{message:"defaulting media sequence to zero"})),e.duration>=0&&(i.duration=e.duration),this.manifest.segments=b},"media-sequence":function(){return c(e.number)?void(this.manifest.mediaSequence=e.number):void this.trigger("warn",{message:"ignoring invalid media sequence: "+e.number})},"playlist-type":function(){return/VOD|EVENT/.test(e.playlistType)?void(this.manifest.playlistType=e.playlistType):void this.trigger("warn",{message:"ignoring unknown playlist type: "+e.playlist})},"stream-inf":function(){return this.manifest.playlists=b,e.attributes?(i.attributes||(i.attributes={}),void(i.attributes=d(i.attributes,e.attributes))):void this.trigger("warn",{message:"ignoring empty stream-inf attributes"})},targetduration:function(){return!c(e.duration)||e.duration<0?void this.trigger("warn",{message:"ignoring invalid target duration: "+e.duration}):void(this.manifest.targetDuration=e.duration)},totalduration:function(){return!c(e.duration)||e.duration<0?void this.trigger("warn",{message:"ignoring invalid total duration: "+e.duration}):void(this.manifest.totalDuration=e.duration)}})[e.tagType]||h).call(a)},uri:function(){i.uri=e.uri,b.push(i),!this.manifest.targetDuration||"duration"in i||(this.trigger("warn",{message:"defaulting segment duration to the target duration"}),i.duration=this.manifest.targetDuration),i={}},comment:function(){}})[e.type].call(a)})},g.prototype=new j,g.prototype.push=function(a){this.lineStream.push(a)},g.prototype.end=function(){this.lineStream.push("\n")},window.videojs.m3u8={LineStream:e,ParseStream:f,Parser:g}}(window.videojs,window.parseInt,window.isFinite,window.videojs.util.mergeOptions),function(a,b){"use strict";var c=b.Hls.resolveUrl,d=b.Hls.xhr,e=function(a,c){var d,e,f=!1,g=b.util.mergeOptions(a,{});for(d=a.playlists.length;d--;)if(e=g.playlists[d],e.uri===c.uri){if(e.segments&&c.segments&&e.segments.length===c.segments.length&&e.mediaSequence===c.mediaSequence)continue;g.playlists[d]=b.util.mergeOptions(e,c),g.playlists[c.uri]=g.playlists[d],f=!0}return f?g:null},f=function(g,h){var i,j,k,l,m=this,n=function(c,d,f){var g,h,i;return l=null,c?(m.error={status:d.status,message:"HLS playlist request error at URL: "+f,code:d.status>=500?4:2},m.trigger("error")):(m.state="HAVE_METADATA",g=new b.m3u8.Parser,g.push(d.responseText),g.manifest.uri=f,i=e(m.master,g.manifest),h=1e3*(g.manifest.targetDuration||10),i?(m.master=i,j=m.master.playlists[f]):h/=2,m.media().endList||(k=a.setTimeout(function(){m.trigger("mediaupdatetimeout")},h)),void m.trigger("loadedplaylist"))};if(f.prototype.init.call(this),!g)throw new Error("A non-empty playlist URL is required");m.state="HAVE_NOTHING",i=this.dispose,m.dispose=function(){l&&l.abort(),a.clearTimeout(k),i.call(this)},m.media=function(a){if(!a)return j;if("HAVE_NOTHING"===m.state||"HAVE_MASTER"===m.state)throw new Error("Cannot switch media playlist from "+m.state);if("string"==typeof a){if(!m.master.playlists[a])throw new Error("Unknown playlist URI: "+a);a=m.master.playlists[a]}if(a.uri!==j.uri){if(m.state="SWITCHING_MEDIA",l){if(c(m.master.uri,a.uri)===l.url)return;l.abort(),l=null}l=d({url:c(m.master.uri,a.uri),withCredentials:h},function(b){n(b,this,a.uri)})}},m.on("mediaupdatetimeout",function(){"HAVE_METADATA"===m.state&&(m.state="HAVE_CURRENT_METADATA",l=d({url:c(m.master.uri,m.media().uri),withCredentials:h},function(a){n(a,this,m.media().uri)}))}),d({url:g,withCredentials:h},function(e){var f,i;if(e)return m.error={status:this.status,message:"HLS playlist request error at URL: "+g,code:2},m.trigger("error");if(f=new b.m3u8.Parser,f.push(this.responseText),m.state="HAVE_MASTER",f.manifest.uri=g,f.manifest.playlists){for(m.master=f.manifest,i=m.master.playlists.length;i--;)m.master.playlists[m.master.playlists[i].uri]=m.master.playlists[i];return l=d({url:c(g,f.manifest.playlists[0].uri),withCredentials:h},function(a){n(a,this,f.manifest.playlists[0].uri),a||m.trigger("loadedmetadata")}),m.trigger("loadedplaylist")}return m.master={uri:a.location.href,playlists:[{uri:g}]},m.master.playlists[g]=m.master.playlists[0],n(null,this,g),m.trigger("loadedmetadata")})};f.prototype=new b.Hls.Stream,b.Hls.PlaylistLoader=f}(window,window.videojs);
\ No newline at end of file
diff --git a/composer.json b/composer.json
new file mode 100644
index 0000000..c79c968
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,24 @@
+{
+ "name": "wbraganca/yii2-videojs-widget",
+ "description": "The yii2-videojs-widget is a Yii 2 wrapper for the [video.js](http://www.videojs.com/). A JavaScript and CSS library that makes it easier to work with and build on HTML5 video. This is also known as an HTML5 Video Player.",
+ "keywords": ["yii2", "extension", "yii2-extension", "yii2-videojs-widget", "yii2-videojs", "videojs", "html5 video", "video", "player"],
+ "type": "yii2-extension",
+ "license": "BSD-3-Clause",
+ "support": {
+ "issues": "https://github.com/wbraganca/yii2-videojs-widget/issues",
+ "wiki": "https://github.com/wbraganca/yii2-videojs-widget/wiki/",
+ "source": "https://github.com/wbraganca/yii2-videojs-widget"
+ },
+ "authors": [
+ {
+ "name": "Wanderson Bragança",
+ "email": "wanderson.wbc@gmail.com"
+ }
+ ],
+ "require": {
+ "yiisoft/yii2": "*"
+ },
+ "autoload": {
+ "psr-4": { "wbraganca\\": "" }
+ }
+}
diff --git a/videojs/VideoJsAsset.php b/videojs/VideoJsAsset.php
new file mode 100644
index 0000000..9e3a924
--- /dev/null
+++ b/videojs/VideoJsAsset.php
@@ -0,0 +1,64 @@
+
+ */
+class VideoJsAsset extends \yii\web\AssetBundle
+{
+ /**
+ * @inheritdoc
+ */
+ public $depends = [
+ 'yii\web\JqueryAsset',
+ ];
+
+ /**
+ * Set up CSS and JS asset arrays based on the base-file names
+ *
+ * @param string $type whether 'css' or 'js'
+ * @param array $files the list of 'css' or 'js' basefile names
+ */
+ protected function setupAssets($type, $files = [])
+ {
+ $srcFiles = [];
+ $minFiles = [];
+ foreach ($files as $file) {
+ $srcFiles[] = "{$file}.{$type}";
+ $minFiles[] = "{$file}.min.{$type}";
+ }
+ if (empty($this->$type)) {
+ $this->$type = YII_DEBUG ? $srcFiles : $minFiles;
+ }
+ }
+
+ /**
+ * @inheritdoc
+ */
+ public function init()
+ {
+ $this->setSourcePath(__DIR__ . '/../assets');
+ $this->setupAssets('css', ['video-js']);
+ $this->setupAssets('js', ['video', 'videojs-media-sources', 'videojs.hls']);
+ parent::init();
+ }
+
+ /**
+ * Sets the source path if empty
+ * @param string $path the path to be set
+ */
+ protected function setSourcePath($path)
+ {
+ if (empty($this->sourcePath)) {
+ $this->sourcePath = $path;
+ }
+ }
+}
diff --git a/videojs/VideoJsWidget.php b/videojs/VideoJsWidget.php
new file mode 100644
index 0000000..9735b85
--- /dev/null
+++ b/videojs/VideoJsWidget.php
@@ -0,0 +1,87 @@
+
+ */
+class VideoJsWidget extends \yii\base\Widget
+{
+ /**
+ * @var array
+ */
+ public $options = [];
+ /**
+ * @var array
+ */
+ public $jsOptions = [];
+ /**
+ * @var array
+ */
+ public $tags = [];
+
+ /**
+ * @inheritdoc
+ */
+ public function init()
+ {
+ parent::init();
+ $this->initOptions();
+ $this->registerAssets();
+ }
+
+ /**
+ * Initializes the widget options
+ */
+ protected function initOptions()
+ {
+ if (!isset($this->options['id'])) {
+ $this->options['id'] = 'videojs-' . $this->getId();
+ }
+ }
+
+ /**
+ * Registers the needed assets
+ */
+ public function registerAssets()
+ {
+ $view = $this->getView();
+ $obj = VideoJsAsset::register($view);
+
+ echo "\n" . Html::beginTag('video', $this->options);
+ if (!empty($this->tags) && is_array($this->tags)) {
+ foreach ($this->tags as $tagName => $tags) {
+ if (is_array($this->tags[$tagName])) {
+ foreach ($tags as $tagOptions) {
+ $tagContent = '';
+ if (isset($tagOptions['content'])) {
+ $tagContent = $tagOptions['content'];
+ unset($tagOptions['content']);
+ }
+ echo "\n" . Html::tag($tagName, $tagContent, $tagOptions);
+ }
+ } else {
+ throw new InvalidConfigException("Invalid config for 'tags' property.");
+ }
+ }
+ }
+ echo "\n" .Html::endTag('video');
+
+ if (!empty($this->jsOptions)) {
+ $js = 'videojs("#' . $this->options['id'] . '").ready(' . Json::encode($this->jsOptions). ');';
+ $view->registerJs($js);
+ }
+ }
+}