due to YouTube API issues
const videoId = parseId(source);
const id = generateId(player.provider);
// Replace media element
const container = createElement('div', {
id,
'data-poster': config.customControls ? player.poster : undefined
});
player.media = replaceElement(container, player.media);
// Only load the poster when using custom controls
if (config.customControls) {
const posterSrc = s => `https://i.ytimg.com/vi/${videoId}/${s}default.jpg`;
// Check thumbnail images in order of quality, but reject fallback thumbnails (120px wide)
loadImage(posterSrc('maxres'), 121) // Highest quality and un-padded
.catch(() => loadImage(posterSrc('sd'), 121)) // 480p padded 4:3
.catch(() => loadImage(posterSrc('hq'))) // 360p padded 4:3. Always exists
.then(image => ui.setPoster.call(player, image.src)).then(src => {
// If the image is padded, use background-size "cover" instead (like youtube does too with their posters)
if (!src.includes('maxres')) {
player.elements.poster.style.backgroundSize = 'cover';
}
}).catch(() => {});
}
// Setup instance
// https://developers.google.com/youtube/iframe_api_reference
player.embed = new window.YT.Player(player.media, {
videoId,
host: getHost(config),
playerVars: extend({}, {
// Autoplay
autoplay: player.config.autoplay ? 1 : 0,
// iframe interface language
hl: player.config.hl,
// Only show controls if not fully supported or opted out
controls: player.supported.ui && config.customControls ? 0 : 1,
// Disable keyboard as we handle it
disablekb: 1,
// Allow iOS inline playback
playsinline: player.config.playsinline && !player.config.fullscreen.iosNative ? 1 : 0,
// Captions are flaky on YouTube
cc_load_policy: player.captions.active ? 1 : 0,
cc_lang_pref: player.config.captions.language,
// Tracking for stats
widget_referrer: window ? window.location.href : null
}, config),
events: {
onError(event) {
// YouTube may fire onError twice, so only handle it once
if (!player.media.error) {
const code = event.data;
// Messages copied from https://developers.google.com/youtube/iframe_api_reference#onError
const message = {
2: 'The request contains an invalid parameter value. For example, this error occurs if you specify a video ID that does not have 11 characters, or if the video ID contains invalid characters, such as exclamation points or asterisks.',
5: 'The requested content cannot be played in an HTML5 player or another error related to the HTML5 player has occurred.',
100: 'The video requested was not found. This error occurs when a video has been removed (for any reason) or has been marked as private.',
101: 'The owner of the requested video does not allow it to be played in embedded players.',
150: 'The owner of the requested video does not allow it to be played in embedded players.'
}[code] || 'An unknown error occurred';
player.media.error = {
code,
message
};
triggerEvent.call(player, player.media, 'error');
}
},
onPlaybackRateChange(event) {
// Get the instance
const instance = event.target;
// Get current speed
player.media.playbackRate = instance.getPlaybackRate();
triggerEvent.call(player, player.media, 'ratechange');
},
onReady(event) {
// Bail if onReady has already been called. See issue #1108
if (is.function(player.media.play)) {
return;
}
// Get the instance
const instance = event.target;
// Get the title
youtube.getTitle.call(player, videoId);
// Create a faux HTML5 API using the YouTube API
player.media.play = () => {
assurePlaybackState.call(player, true);
instance.playVideo();
};
player.media.pause = () => {
assurePlaybackState.call(player, false);
instance.pauseVideo();
};
player.media.stop = () => {
instance.stopVideo();
};
player.media.duration = instance.getDuration();
player.media.paused = true;
// Seeking
player.media.currentTime = 0;
Object.defineProperty(player.media, 'currentTime', {
get() {
return Number(instance.getCurrentTime());
},
set(time) {
// If paused and never played, mute audio preventively (YouTube starts playing on seek if the video hasn't been played yet).
if (player.paused && !player.embed.hasPlayed) {
player.embed.mute();
}
// Set seeking state and trigger event
player.media.seeking = true;
triggerEvent.call(player, player.media, 'seeking');
// Seek after events sent
instance.seekTo(time);
}
});
// Playback speed
Object.defineProperty(player.media, 'playbackRate', {
get() {
return instance.getPlaybackRate();
},
set(input) {
instance.setPlaybackRate(input);
}
});
// Volume
let {
volume
} = player.config;
Object.defineProperty(player.media, 'volume', {
get() {
return volume;
},
set(input) {
volume = input;
instance.setVolume(volume * 100);
triggerEvent.call(player, player.media, 'volumechange');
}
});
// Muted
let {
muted
} = player.config;
Object.defineProperty(player.media, 'muted', {
get() {
return muted;
},
set(input) {
const toggle = is.boolean(input) ? input : muted;
muted = toggle;
instance[toggle ? 'mute' : 'unMute']();
instance.setVolume(volume * 100);
triggerEvent.call(player, player.media, 'volumechange');
}
});
// Source
Object.defineProperty(player.media, 'currentSrc', {
get() {
return instance.getVideoUrl();
}
});
// Ended
Object.defineProperty(player.media, 'ended', {
get() {
return player.currentTime === player.duration;
}
});
// Get available speeds
const speeds = instance.getAvailablePlaybackRates();
// Filter based on config
player.options.speed = speeds.filter(s => player.config.speed.options.includes(s));
// Set the tabindex to avoid focus entering iframe
if (player.supported.ui && config.customControls) {
player.media.setAttribute('tabindex', -1);
}
triggerEvent.call(player, player.media, 'timeupdate');
triggerEvent.call(player, player.media, 'durationchange');
// Reset timer
clearInterval(player.timers.buffering);
// Setup buffering
player.timers.buffering = setInterval(() => {
// Get loaded % from YouTube
player.media.buffered = instance.getVideoLoadedFraction();
// Trigger progress only when we actually buffer something
if (player.media.lastBuffered === null || player.media.lastBuffered < player.media.buffered) {
triggerEvent.call(player, player.media, 'progress');
}
// Set last buffer point
player.media.lastBuffered = player.media.buffered;
// Bail if we're at 100%
if (player.media.buffered === 1) {
clearInterval(player.timers.buffering);
// Trigger event
triggerEvent.call(player, player.media, 'canplaythrough');
}
}, 200);
// Rebuild UI
if (config.customControls) {
setTimeout(() => ui.build.call(player), 50);
}
},
onStateChange(event) {
// Get the instance
const instance = event.target;
// Reset timer
clearInterval(player.timers.playing);
const seeked = player.media.seeking && [1, 2].includes(event.data);
if (seeked) {
// Unset seeking and fire seeked event
player.media.seeking = false;
triggerEvent.call(player, player.media, 'seeked');
}
// Handle events
// -1 Unstarted
// 0 Ended
// 1 Playing
// 2 Paused
// 3 Buffering
// 5 Video cued
switch (event.data) {
case -1:
// Update scrubber
triggerEvent.call(player, player.media, 'timeupdate');
// Get loaded % from YouTube
player.media.buffered = instance.getVideoLoadedFraction();
triggerEvent.call(player, player.media, 'progress');
break;
case 0:
assurePlaybackState.call(player, false);
// YouTube doesn't support loop for a single video, so mimick it.
if (player.media.loop) {
// YouTube needs a call to `stopVideo` before playing again
instance.stopVideo();
instance.playVideo();
} else {
triggerEvent.call(player, player.media, 'ended');
}
break;
case 1:
// Restore paused state (YouTube starts playing on seek if the video hasn't been played yet)
if (config.customControls && !player.config.autoplay && player.media.paused && !player.embed.hasPlayed) {
player.media.pause();
} else {
assurePlaybackState.call(player, true);
triggerEvent.call(player, player.media, 'playing');
// Poll to get playback progress
player.timers.playing = setInterval(() => {
triggerEvent.call(player, player.media, 'timeupdate');
}, 50);
// Check duration again due to YouTube bug
// https://github.com/sampotts/plyr/issues/374
// https://code.google.com/p/gdata-issues/issues/detail?id=8690
if (player.media.duration !== instance.getDuration()) {
player.media.duration = instance.getDuration();
triggerEvent.call(player, player.media, 'durationchange');
}
}
break;
case 2:
// Restore audio (YouTube starts playing on seek if the video hasn't been played yet)
if (!player.muted) {
player.embed.unMute();
}
assurePlaybackState.call(player, false);
break;
case 3:
// Trigger waiting event to add loading classes to container as the video buffers.
triggerEvent.call(player, player.media, 'waiting');
break;
}
triggerEvent.call(player, player.elements.container, 'statechange', false, {
code: event.data
});
}
}
});
}
};
// ==========================================================================
const media = {
// Setup media
setup() {
// If there's no media, bail
if (!this.media) {
this.debug.warn('No media element found!');
return;
}
// Add type class
toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', this.type), true);
// Add provider class
toggleClass(this.elements.container, this.config.classNames.provider.replace('{0}', this.provider), true);
// Add video class for embeds
// This will require changes if audio embeds are added
if (this.isEmbed) {
toggleClass(this.elements.container, this.config.classNames.type.replace('{0}', 'video'), true);
}
// Inject the player wrapper
if (this.isVideo) {
// Create the wrapper div
this.elements.wrapper = createElement('div', {
class: this.config.classNames.video
});
// Wrap the video in a container
wrap(this.media, this.elements.wrapper);
// Poster image container
this.elements.poster = createElement('div', {
class: this.config.classNames.poster
});
this.elements.wrapper.appendChild(this.elements.poster);
}
if (this.isHTML5) {
html5.setup.call(this);
} else if (this.isYouTube) {
youtube.setup.call(this);
} else if (this.isVimeo) {
vimeo.setup.call(this);
}
}
};
const destroy = instance => {
// Destroy our adsManager
if (instance.manager) {
instance.manager.destroy();
}
// Destroy our adsManager
if (instance.elements.displayContainer) {
instance.elements.displayContainer.destroy();
}
instance.elements.container.remove();
};
class Ads {
/**
* Ads constructor.
* @param {Object} player
* @return {Ads}
*/
constructor(player) {
/**
* Load the IMA SDK
*/
_defineProperty$1(this, "load", () => {
if (!this.enabled) {
return;
}
// Check if the Google IMA3 SDK is loaded or load it ourselves
if (!is.object(window.google) || !is.object(window.google.ima)) {
loadScript(this.player.config.urls.googleIMA.sdk).then(() => {
this.ready();
}).catch(() => {
// Script failed to load or is blocked
this.trigger('error', new Error('Google IMA SDK failed to load'));
});
} else {
this.ready();
}
});
/**
* Get the ads instance ready
*/
_defineProperty$1(this, "ready", () => {
// Double check we're enabled
if (!this.enabled) {
destroy(this);
}
// Start ticking our safety timer. If the whole advertisement
// thing doesn't resolve within our set time; we bail
this.startSafetyTimer(12000, 'ready()');
// Clear the safety timer
this.managerPromise.then(() => {
this.clearSafetyTimer('onAdsManagerLoaded()');
});
// Set listeners on the Plyr instance
this.listeners();
// Setup the IMA SDK
this.setupIMA();
});
/**
* In order for the SDK to display ads for our video, we need to tell it where to put them,
* so here we define our ad container. This div is set up to render on top of the video player.
* Using the code below, we tell the SDK to render ads within that div. We also provide a
* handle to the content video player - the SDK will poll the current time of our player to
* properly place mid-rolls. After we create the ad display container, we initialize it. On
* mobile devices, this initialization is done as the result of a user action.
*/
_defineProperty$1(this, "setupIMA", () => {
// Create the container for our advertisements
this.elements.container = createElement('div', {
class: this.player.config.classNames.ads
});
this.player.elements.container.appendChild(this.elements.container);
// So we can run VPAID2
google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
// Set language
google.ima.settings.setLocale(this.player.config.ads.language);
// Set playback for iOS10+
google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);
// We assume the adContainer is the video container of the plyr element that will house the ads
this.elements.displayContainer = new google.ima.AdDisplayContainer(this.elements.container, this.player.media);
// Create ads loader
this.loader = new google.ima.AdsLoader(this.elements.displayContainer);
// Listen and respond to ads loaded and error events
this.loader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, event => this.onAdsManagerLoaded(event), false);
this.loader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error), false);
// Request video ads to be pre-loaded
this.requestAds();
});
/**
* Request advertisements
*/
_defineProperty$1(this, "requestAds", () => {
const {
container
} = this.player.elements;
try {
// Request video ads
const request = new google.ima.AdsRequest();
request.adTagUrl = this.tagUrl;
// Specify the linear and nonlinear slot sizes. This helps the SDK
// to select the correct creative if multiple are returned
request.linearAdSlotWidth = container.offsetWidth;
request.linearAdSlotHeight = container.offsetHeight;
request.nonLinearAdSlotWidth = container.offsetWidth;
request.nonLinearAdSlotHeight = container.offsetHeight;
// We only overlay ads as we only support video.
request.forceNonLinearFullSlot = false;
// Mute based on current state
request.setAdWillPlayMuted(!this.player.muted);
this.loader.requestAds(request);
} catch (error) {
this.onAdError(error);
}
});
/**
* Update the ad countdown
* @param {Boolean} start
*/
_defineProperty$1(this, "pollCountdown", (start = false) => {
if (!start) {
clearInterval(this.countdownTimer);
this.elements.container.removeAttribute('data-badge-text');
return;
}
const update = () => {
const time = formatTime(Math.max(this.manager.getRemainingTime(), 0));
const label = `${i18n.get('advertisement', this.player.config)} - ${time}`;
this.elements.container.setAttribute('data-badge-text', label);
};
this.countdownTimer = setInterval(update, 100);
});
/**
* This method is called whenever the ads are ready inside the AdDisplayContainer
* @param {Event} event - adsManagerLoadedEvent
*/
_defineProperty$1(this, "onAdsManagerLoaded", event => {
// Load could occur after a source change (race condition)
if (!this.enabled) {
return;
}
// Get the ads manager
const settings = new google.ima.AdsRenderingSettings();
// Tell the SDK to save and restore content video state on our behalf
settings.restoreCustomPlaybackStateOnAdBreakComplete = true;
settings.enablePreloading = true;
// The SDK is polling currentTime on the contentPlayback. And needs a duration
// so it can determine when to start the mid- and post-roll
this.manager = event.getAdsManager(this.player, settings);
// Get the cue points for any mid-rolls by filtering out the pre- and post-roll
this.cuePoints = this.manager.getCuePoints();
// Add listeners to the required events
// Advertisement error events
this.manager.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, error => this.onAdError(error));
// Advertisement regular events
Object.keys(google.ima.AdEvent.Type).forEach(type => {
this.manager.addEventListener(google.ima.AdEvent.Type[type], e => this.onAdEvent(e));
});
// Resolve our adsManager
this.trigger('loaded');
});
_defineProperty$1(this, "addCuePoints", () => {
// Add advertisement cue's within the time line if available
if (!is.empty(this.cuePoints)) {
this.cuePoints.forEach(cuePoint => {
if (cuePoint !== 0 && cuePoint !== -1 && cuePoint < this.player.duration) {
const seekElement = this.player.elements.progress;
if (is.element(seekElement)) {
const cuePercentage = 100 / this.player.duration * cuePoint;
const cue = createElement('span', {
class: this.player.config.classNames.cues
});
cue.style.left = `${cuePercentage.toString()}%`;
seekElement.appendChild(cue);
}
}
});
}
});
/**
* This is where all the event handling takes place. Retrieve the ad from the event. Some
* events (e.g. ALL_ADS_COMPLETED) don't have the ad object associated
* https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdEvent.Type
* @param {Event} event
*/
_defineProperty$1(this, "onAdEvent", event => {
const {
container
} = this.player.elements;
// Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
// don't have ad object associated
const ad = event.getAd();
const adData = event.getAdData();
// Proxy event
const dispatchEvent = type => {
triggerEvent.call(this.player, this.player.media, `ads${type.replace(/_/g, '').toLowerCase()}`);
};
// Bubble the event
dispatchEvent(event.type);
switch (event.type) {
case google.ima.AdEvent.Type.LOADED:
// This is the first event sent for an ad - it is possible to determine whether the
// ad is a video ad or an overlay
this.trigger('loaded');
// Start countdown
this.pollCountdown(true);
if (!ad.isLinear()) {
// Position AdDisplayContainer correctly for overlay
ad.width = container.offsetWidth;
ad.height = container.offsetHeight;
}
// console.info('Ad type: ' + event.getAd().getAdPodInfo().getPodIndex());
// console.info('Ad time: ' + event.getAd().getAdPodInfo().getTimeOffset());
break;
case google.ima.AdEvent.Type.STARTED:
// Set volume to match player
this.manager.setVolume(this.player.volume);
break;
case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
// All ads for the current videos are done. We can now request new advertisements
// in case the video is re-played
// TODO: Example for what happens when a next video in a playlist would be loaded.
// So here we load a new video when all ads are done.
// Then we load new ads within a new adsManager. When the video
// Is started - after - the ads are loaded, then we get ads.
// You can also easily test cancelling and reloading by running
// player.ads.cancel() and player.ads.play from the console I guess.
// this.player.source = {
// type: 'video',
// title: 'View From A Blue Moon',
// sources: [{
// src:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.mp4', type:
// 'video/mp4', }], poster:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.jpg', tracks:
// [ { kind: 'captions', label: 'English', srclang: 'en', src:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.en.vtt',
// default: true, }, { kind: 'captions', label: 'French', srclang: 'fr', src:
// 'https://cdn.plyr.io/static/demo/View_From_A_Blue_Moon_Trailer-HD.fr.vtt', }, ],
// };
// TODO: So there is still this thing where a video should only be allowed to start
// playing when the IMA SDK is ready or has failed
if (this.player.ended) {
this.loadAds();
} else {
// The SDK won't allow new ads to be called without receiving a contentComplete()
this.loader.contentComplete();
}
break;
case google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED:
// This event indicates the ad has started - the video player can adjust the UI,
// for example display a pause button and remaining time. Fired when content should
// be paused. This usually happens right before an ad is about to cover the content
this.pauseContent();
break;
case google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED:
// This event indicates the ad has finished - the video player can perform
// appropriate UI actions, such as removing the timer for remaining time detection.
// Fired when content should be resumed. This usually happens when an ad finishes
// or collapses
this.pollCountdown();
this.resumeContent();
break;
case google.ima.AdEvent.Type.LOG:
if (adData.adError) {
this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);
}
break;
}
});
/**
* Any ad error handling comes through here
* @param {Event} event
*/
_defineProperty$1(this, "onAdError", event => {
this.cancel();
this.player.debug.warn('Ads error', event);
});
/**
* Setup hooks for Plyr and window events. This ensures
* the mid- and post-roll launch at the correct time. And
* resize the advertisement when the player resizes
*/
_defineProperty$1(this, "listeners", () => {
const {
container
} = this.player.elements;
let time;
this.player.on('canplay', () => {
this.addCuePoints();
});
this.player.on('ended', () => {
this.loader.contentComplete();
});
this.player.on('timeupdate', () => {
time = this.player.currentTime;
});
this.player.on('seeked', () => {
const seekedTime = this.player.currentTime;
if (is.empty(this.cuePoints)) {
return;
}
this.cuePoints.forEach((cuePoint, index) => {
if (time < cuePoint && cuePoint < seekedTime) {
this.manager.discardAdBreak();
this.cuePoints.splice(index, 1);
}
});
});
// Listen to the resizing of the window. And resize ad accordingly
// TODO: eventually implement ResizeObserver
window.addEventListener('resize', () => {
if (this.manager) {
this.manager.resize(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
}
});
});
/**
* Initialize the adsManager and start playing advertisements
*/
_defineProperty$1(this, "play", () => {
const {
container
} = this.player.elements;
if (!this.managerPromise) {
this.resumeContent();
}
// Play the requested advertisement whenever the adsManager is ready
this.managerPromise.then(() => {
// Set volume to match player
this.manager.setVolume(this.player.volume);
// Initialize the container. Must be done via a user action on mobile devices
this.elements.displayContainer.initialize();
try {
if (!this.initialized) {
// Initialize the ads manager. Ad rules playlist will start at this time
this.manager.init(container.offsetWidth, container.offsetHeight, google.ima.ViewMode.NORMAL);
// Call play to start showing the ad. Single video and overlay ads will
// start at this time; the call will be ignored for ad rules
this.manager.start();
}
this.initialized = true;
} catch (adError) {
// An error may be thrown if there was a problem with the
// VAST response
this.onAdError(adError);
}
}).catch(() => {});
});
/**
* Resume our video
*/
_defineProperty$1(this, "resumeContent", () => {
// Hide the advertisement container
this.elements.container.style.zIndex = '';
// Ad is stopped
this.playing = false;
// Play video
silencePromise(this.player.media.play());
});
/**
* Pause our video
*/
_defineProperty$1(this, "pauseContent", () => {
// Show the advertisement container
this.elements.container.style.zIndex = 3;
// Ad is playing
this.playing = true;
// Pause our video.
this.player.media.pause();
});
/**
* Destroy the adsManager so we can grab new ads after this. If we don't then we're not
* allowed to call new ads based on google policies, as they interpret this as an accidental
* video requests. https://developers.google.com/interactive-
* media-ads/docs/sdks/android/faq#8
*/
_defineProperty$1(this, "cancel", () => {
// Pause our video
if (this.initialized) {
this.resumeContent();
}
// Tell our instance that we're done for now
this.trigger('error');
// Re-create our adsManager
this.loadAds();
});
/**
* Re-create our adsManager
*/
_defineProperty$1(this, "loadAds", () => {
// Tell our adsManager to go bye bye
this.managerPromise.then(() => {
// Destroy our adsManager
if (this.manager) {
this.manager.destroy();
}
// Re-set our adsManager promises
this.managerPromise = new Promise(resolve => {
this.on('loaded', resolve);
this.player.debug.log(this.manager);
});
// Now that the manager has been destroyed set it to also be un-initialized
this.initialized = false;
// Now request some new advertisements
this.requestAds();
}).catch(() => {});
});
/**
* Handles callbacks after an ad event was invoked
* @param {String} event - Event type
* @param args
*/
_defineProperty$1(this, "trigger", (event, ...args) => {
const handlers = this.events[event];
if (is.array(handlers)) {
handlers.forEach(handler => {
if (is.function(handler)) {
handler.apply(this, args);
}
});
}
});
/**
* Add event listeners
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
* @return {Ads}
*/
_defineProperty$1(this, "on", (event, callback) => {
if (!is.array(this.events[event])) {
this.events[event] = [];
}
this.events[event].push(callback);
return this;
});
/**
* Setup a safety timer for when the ad network doesn't respond for whatever reason.
* The advertisement has 12 seconds to get its things together. We stop this timer when the
* advertisement is playing, or when a user action is required to start, then we clear the
* timer on ad ready
* @param {Number} time
* @param {String} from
*/
_defineProperty$1(this, "startSafetyTimer", (time, from) => {
this.player.debug.log(`Safety timer invoked from: ${from}`);
this.safetyTimer = setTimeout(() => {
this.cancel();
this.clearSafetyTimer('startSafetyTimer()');
}, time);
});
/**
* Clear our safety timer(s)
* @param {String} from
*/
_defineProperty$1(this, "clearSafetyTimer", from => {
if (!is.nullOrUndefined(this.safetyTimer)) {
this.player.debug.log(`Safety timer cleared from: ${from}`);
clearTimeout(this.safetyTimer);
this.safetyTimer = null;
}
});
this.player = player;
this.config = player.config.ads;
this.playing = false;
this.initialized = false;
this.elements = {
container: null,
displayContainer: null
};
this.manager = null;
this.loader = null;
this.cuePoints = null;
this.events = {};
this.safetyTimer = null;
this.countdownTimer = null;
// Setup a promise to resolve when the IMA manager is ready
this.managerPromise = new Promise((resolve, reject) => {
// The ad is loaded and ready
this.on('loaded', resolve);
// Ads failed
this.on('error', reject);
});
this.load();
}
get enabled() {
const {
config
} = this;
return this.player.isHTML5 && this.player.isVideo && config.enabled && (!is.empty(config.publisherId) || is.url(config.tagUrl));
}
// Build the tag URL
get tagUrl() {
const {
config
} = this;
if (is.url(config.tagUrl)) {
return config.tagUrl;
}
const params = {
AV_PUBLISHERID: '58c25bb0073ef448b1087ad6',
AV_CHANNELID: '5a0458dc28a06145e4519d21',
AV_URL: window.location.hostname,
cb: Date.now(),
AV_WIDTH: 640,
AV_HEIGHT: 480,
AV_CDIM2: config.publisherId
};
const base = 'https://go.aniview.com/api/adserver6/vast/';
return `${base}?${buildUrlParams(params)}`;
}
}
/**
* Returns a number whose value is limited to the given range.
*
* Example: limit the output of this computation to between 0 and 255
* (x * 255).clamp(0, 255)
*
* @param {Number} input
* @param {Number} min The lower boundary of the output range
* @param {Number} max The upper boundary of the output range
* @returns A number within the bounds of min and max
* @type Number
*/
function clamp(input = 0, min = 0, max = 255) {
return Math.min(Math.max(input, min), max);
}
// Arg: vttDataString example: "WEBVTT\n\n1\n00:00:05.000 --> 00:00:10.000\n1080p-00001.jpg"
const parseVtt = vttDataString => {
const processedList = [];
const frames = vttDataString.split(/\r\n\r\n|\n\n|\r\r/);
frames.forEach(frame => {
const result = {};
const lines = frame.split(/\r\n|\n|\r/);
lines.forEach(line => {
if (!is.number(result.startTime)) {
// The line with start and end times on it is the first line of interest
const matchTimes = line.match(/([0-9]{2})?:?([0-9]{2}):([0-9]{2}).([0-9]{2,3})( ?--> ?)([0-9]{2})?:?([0-9]{2}):([0-9]{2}).([0-9]{2,3})/); // Note that this currently ignores caption formatting directives that are optionally on the end of this line - fine for non-captions VTT
if (matchTimes) {
result.startTime = Number(matchTimes[1] || 0) * 60 * 60 + Number(matchTimes[2]) * 60 + Number(matchTimes[3]) + Number(`0.${matchTimes[4]}`);
result.endTime = Number(matchTimes[6] || 0) * 60 * 60 + Number(matchTimes[7]) * 60 + Number(matchTimes[8]) + Number(`0.${matchTimes[9]}`);
}
} else if (!is.empty(line.trim()) && is.empty(result.text)) {
// If we already have the startTime, then we're definitely up to the text line(s)
const lineSplit = line.trim().split('#xywh=');
[result.text] = lineSplit;
// If there's content in lineSplit[1], then we have sprites. If not, then it's just one frame per image
if (lineSplit[1]) {
[result.x, result.y, result.w, result.h] = lineSplit[1].split(',');
}
}
});
if (result.text) {
processedList.push(result);
}
});
return processedList;
};
/**
* Preview thumbnails for seek hover and scrubbing
* Seeking: Hover over the seek bar (desktop only): shows a small preview container above the seek bar
* Scrubbing: Click and drag the seek bar (desktop and mobile): shows the preview image over the entire video, as if the video is scrubbing at very high speed
*
* Notes:
* - Thumbs are set via JS settings on Plyr init, not HTML5 'track' property. Using the track property would be a bit gross, because it doesn't support custom 'kinds'. kind=metadata might be used for something else, and we want to allow multiple thumbnails tracks. Tracks must have a unique combination of 'kind' and 'label'. We would have to do something like kind=metadata,label=thumbnails1 / kind=metadata,label=thumbnails2. Square peg, round hole
* - VTT info: the image URL is relative to the VTT, not the current document. But if the url starts with a slash, it will naturally be relative to the current domain. https://support.jwplayer.com/articles/how-to-add-preview-thumbnails
* - This implementation uses multiple separate img elements. Other implementations use background-image on one element. This would be nice and simple, but Firefox and Safari have flickering issues with replacing backgrounds of larger images. It seems that YouTube perhaps only avoids this because they don't have the option for high-res previews (even the fullscreen ones, when mousedown/seeking). Images appear over the top of each other, and previous ones are discarded once the new ones have been rendered
*/
const fitRatio = (ratio, outer) => {
const targetRatio = outer.width / outer.height;
const result = {};
if (ratio > targetRatio) {
result.width = outer.width;
result.height = 1 / ratio * outer.width;
} else {
result.height = outer.height;
result.width = ratio * outer.height;
}
return result;
};
class PreviewThumbnails {
/**
* PreviewThumbnails constructor.
* @param {Plyr} player
* @return {PreviewThumbnails}
*/
constructor(player) {
_defineProperty$1(this, "load", () => {
// Toggle the regular seek tooltip
if (this.player.elements.display.seekTooltip) {
this.player.elements.display.seekTooltip.hidden = this.enabled;
}
if (!this.enabled) return;
this.getThumbnails().then(() => {
if (!this.enabled) {
return;
}
// Render DOM elements
this.render();
// Check to see if thumb container size was specified manually in CSS
this.determineContainerAutoSizing();
// Set up listeners
this.listeners();
this.loaded = true;
});
});
// Download VTT files and parse them
_defineProperty$1(this, "getThumbnails", () => {
return new Promise(resolve => {
const {
src
} = this.player.config.previewThumbnails;
if (is.empty(src)) {
throw new Error('Missing previewThumbnails.src config attribute');
}
// Resolve promise
const sortAndResolve = () => {
// Sort smallest to biggest (e.g., [120p, 480p, 1080p])
this.thumbnails.sort((x, y) => x.height - y.height);
this.player.debug.log('Preview thumbnails', this.thumbnails);
resolve();
};
// Via callback()
if (is.function(src)) {
src(thumbnails => {
this.thumbnails = thumbnails;
sortAndResolve();
});
}
// VTT urls
else {
// If string, convert into single-element list
const urls = is.string(src) ? [src] : src;
// Loop through each src URL. Download and process the VTT file, storing the resulting data in this.thumbnails
const promises = urls.map(u => this.getThumbnail(u));
// Resolve
Promise.all(promises).then(sortAndResolve);
}
});
});
// Process individual VTT file
_defineProperty$1(this, "getThumbnail", url => {
return new Promise(resolve => {
fetch(url).then(response => {
const thumbnail = {
frames: parseVtt(response),
height: null,
urlPrefix: ''
};
// If the URLs don't start with '/', then we need to set their relative path to be the location of the VTT file
// If the URLs do start with '/', then they obviously don't need a prefix, so it will remain blank
// If the thumbnail URLs start with with none of '/', 'http://' or 'https://', then we need to set their relative path to be the location of the VTT file
if (!thumbnail.frames[0].text.startsWith('/') && !thumbnail.frames[0].text.startsWith('http://') && !thumbnail.frames[0].text.startsWith('https://')) {
thumbnail.urlPrefix = url.substring(0, url.lastIndexOf('/') + 1);
}
// Download the first frame, so that we can determine/set the height of this thumbnailsDef
const tempImage = new Image();
tempImage.onload = () => {
thumbnail.height = tempImage.naturalHeight;
thumbnail.width = tempImage.naturalWidth;
this.thumbnails.push(thumbnail);
resolve();
};
tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;
});
});
});
_defineProperty$1(this, "startMove", event => {
if (!this.loaded) return;
if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) return;
// Wait until media has a duration
if (!this.player.media.duration) return;
if (event.type === 'touchmove') {
// Calculate seek hover position as approx video seconds
this.seekTime = this.player.media.duration * (this.player.elements.inputs.seek.value / 100);
} else {
var _this$player$config$m, _this$player$config$m2;
// Calculate seek hover position as approx video seconds
const clientRect = this.player.elements.progress.getBoundingClientRect();
const percentage = 100 / clientRect.width * (event.pageX - clientRect.left);
this.seekTime = this.player.media.duration * (percentage / 100);
if (this.seekTime < 0) {
// The mousemove fires for 10+px out to the left
this.seekTime = 0;
}
if (this.seekTime > this.player.media.duration - 1) {
// Took 1 second off the duration for safety, because different players can disagree on the real duration of a video
this.seekTime = this.player.media.duration - 1;
}
this.mousePosX = event.pageX;
// Set time text inside image container
this.elements.thumb.time.innerText = formatTime(this.seekTime);
// Get marker point for time
const point = (_this$player$config$m = this.player.config.markers) === null || _this$player$config$m === void 0 ? void 0 : (_this$player$config$m2 = _this$player$config$m.points) === null || _this$player$config$m2 === void 0 ? void 0 : _this$player$config$m2.find(({
time: t
}) => t === Math.round(this.seekTime));
// Append the point label to the tooltip
if (point) {
// this.elements.thumb.time.innerText.concat('\n');
this.elements.thumb.time.insertAdjacentHTML('afterbegin', `${point.label}
`);
}
}
// Download and show image
this.showImageAtCurrentTime();
});
_defineProperty$1(this, "endMove", () => {
this.toggleThumbContainer(false, true);
});
_defineProperty$1(this, "startScrubbing", event => {
// Only act on left mouse button (0), or touch device (event.button does not exist or is false)
if (is.nullOrUndefined(event.button) || event.button === false || event.button === 0) {
this.mouseDown = true;
// Wait until media has a duration
if (this.player.media.duration) {
this.toggleScrubbingContainer(true);
this.toggleThumbContainer(false, true);
// Download and show image
this.showImageAtCurrentTime();
}
}
});
_defineProperty$1(this, "endScrubbing", () => {
this.mouseDown = false;
// Hide scrubbing preview. But wait until the video has successfully seeked before hiding the scrubbing preview
if (Math.ceil(this.lastTime) === Math.ceil(this.player.media.currentTime)) {
// The video was already seeked/loaded at the chosen time - hide immediately
this.toggleScrubbingContainer(false);
} else {
// The video hasn't seeked yet. Wait for that
once.call(this.player, this.player.media, 'timeupdate', () => {
// Re-check mousedown - we might have already started scrubbing again
if (!this.mouseDown) {
this.toggleScrubbingContainer(false);
}
});
}
});
/**
* Setup hooks for Plyr and window events
*/
_defineProperty$1(this, "listeners", () => {
// Hide thumbnail preview - on mouse click, mouse leave (in listeners.js for now), and video play/seek. All four are required, e.g., for buffering
this.player.on('play', () => {
this.toggleThumbContainer(false, true);
});
this.player.on('seeked', () => {
this.toggleThumbContainer(false);
});
this.player.on('timeupdate', () => {
this.lastTime = this.player.media.currentTime;
});
});
/**
* Create HTML elements for image containers
*/
_defineProperty$1(this, "render", () => {
// Create HTML element: plyr__preview-thumbnail-container
this.elements.thumb.container = createElement('div', {
class: this.player.config.classNames.previewThumbnails.thumbContainer
});
// Wrapper for the image for styling
this.elements.thumb.imageContainer = createElement('div', {
class: this.player.config.classNames.previewThumbnails.imageContainer
});
this.elements.thumb.container.appendChild(this.elements.thumb.imageContainer);
// Create HTML element, parent+span: time text (e.g., 01:32:00)
const timeContainer = createElement('div', {
class: this.player.config.classNames.previewThumbnails.timeContainer
});
this.elements.thumb.time = createElement('span', {}, '00:00');
timeContainer.appendChild(this.elements.thumb.time);
this.elements.thumb.imageContainer.appendChild(timeContainer);
// Inject the whole thumb
if (is.element(this.player.elements.progress)) {
this.player.elements.progress.appendChild(this.elements.thumb.container);
}
// Create HTML element: plyr__preview-scrubbing-container
this.elements.scrubbing.container = createElement('div', {
class: this.player.config.classNames.previewThumbnails.scrubbingContainer
});
this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);
});
_defineProperty$1(this, "destroy", () => {
if (this.elements.thumb.container) {
this.elements.thumb.container.remove();
}
if (this.elements.scrubbing.container) {
this.elements.scrubbing.container.remove();
}
});
_defineProperty$1(this, "showImageAtCurrentTime", () => {
if (this.mouseDown) {
this.setScrubbingContainerSize();
} else {
this.setThumbContainerSizeAndPos();
}
// Find the desired thumbnail index
// TODO: Handle a video longer than the thumbs where thumbNum is null
const thumbNum = this.thumbnails[0].frames.findIndex(frame => this.seekTime >= frame.startTime && this.seekTime <= frame.endTime);
const hasThumb = thumbNum >= 0;
let qualityIndex = 0;
// Show the thumb container if we're not scrubbing
if (!this.mouseDown) {
this.toggleThumbContainer(hasThumb);
}
// No matching thumb found
if (!hasThumb) {
return;
}
// Check to see if we've already downloaded higher quality versions of this image
this.thumbnails.forEach((thumbnail, index) => {
if (this.loadedImages.includes(thumbnail.frames[thumbNum].text)) {
qualityIndex = index;
}
});
// Only proceed if either thumb num or thumbfilename has changed
if (thumbNum !== this.showingThumb) {
this.showingThumb = thumbNum;
this.loadImage(qualityIndex);
}
});
// Show the image that's currently specified in this.showingThumb
_defineProperty$1(this, "loadImage", (qualityIndex = 0) => {
const thumbNum = this.showingThumb;
const thumbnail = this.thumbnails[qualityIndex];
const {
urlPrefix
} = thumbnail;
const frame = thumbnail.frames[thumbNum];
const thumbFilename = thumbnail.frames[thumbNum].text;
const thumbUrl = urlPrefix + thumbFilename;
if (!this.currentImageElement || this.currentImageElement.dataset.filename !== thumbFilename) {
// If we're already loading a previous image, remove its onload handler - we don't want it to load after this one
// Only do this if not using sprites. Without sprites we really want to show as many images as possible, as a best-effort
if (this.loadingImage && this.usingSprites) {
this.loadingImage.onload = null;
}
// We're building and adding a new image. In other implementations of similar functionality (YouTube), background image
// is instead used. But this causes issues with larger images in Firefox and Safari - switching between background
// images causes a flicker. Putting a new image over the top does not
const previewImage = new Image();
previewImage.src = thumbUrl;
previewImage.dataset.index = thumbNum;
previewImage.dataset.filename = thumbFilename;
this.showingThumbFilename = thumbFilename;
this.player.debug.log(`Loading image: ${thumbUrl}`);
// For some reason, passing the named function directly causes it to execute immediately. So I've wrapped it in an anonymous function...
previewImage.onload = () => this.showImage(previewImage, frame, qualityIndex, thumbNum, thumbFilename, true);
this.loadingImage = previewImage;
this.removeOldImages(previewImage);
} else {
// Update the existing image
this.showImage(this.currentImageElement, frame, qualityIndex, thumbNum, thumbFilename, false);
this.currentImageElement.dataset.index = thumbNum;
this.removeOldImages(this.currentImageElement);
}
});
_defineProperty$1(this, "showImage", (previewImage, frame, qualityIndex, thumbNum, thumbFilename, newImage = true) => {
this.player.debug.log(`Showing thumb: ${thumbFilename}. num: ${thumbNum}. qual: ${qualityIndex}. newimg: ${newImage}`);
this.setImageSizeAndOffset(previewImage, frame);
if (newImage) {
this.currentImageContainer.appendChild(previewImage);
this.currentImageElement = previewImage;
if (!this.loadedImages.includes(thumbFilename)) {
this.loadedImages.push(thumbFilename);
}
}
// Preload images before and after the current one
// Show higher quality of the same frame
// Each step here has a short time delay, and only continues if still hovering/seeking the same spot. This is to protect slow connections from overloading
this.preloadNearby(thumbNum, true).then(this.preloadNearby(thumbNum, false)).then(this.getHigherQuality(qualityIndex, previewImage, frame, thumbFilename));
});
// Remove all preview images that aren't the designated current image
_defineProperty$1(this, "removeOldImages", currentImage => {
// Get a list of all images, convert it from a DOM list to an array
Array.from(this.currentImageContainer.children).forEach(image => {
if (image.tagName.toLowerCase() !== 'img') {
return;
}
const removeDelay = this.usingSprites ? 500 : 1000;
if (image.dataset.index !== currentImage.dataset.index && !image.dataset.deleting) {
// Wait 200ms, as the new image can take some time to show on certain browsers (even though it was downloaded before showing). This will prevent flicker, and show some generosity towards slower clients
// First set attribute 'deleting' to prevent multi-handling of this on repeat firing of this function
// eslint-disable-next-line no-param-reassign
image.dataset.deleting = true;
// This has to be set before the timeout - to prevent issues switching between hover and scrub
const {
currentImageContainer
} = this;
setTimeout(() => {
currentImageContainer.removeChild(image);
this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);
}, removeDelay);
}
});
});
// Preload images before and after the current one. Only if the user is still hovering/seeking the same frame
// This will only preload the lowest quality
_defineProperty$1(this, "preloadNearby", (thumbNum, forward = true) => {
return new Promise(resolve => {
setTimeout(() => {
const oldThumbFilename = this.thumbnails[0].frames[thumbNum].text;
if (this.showingThumbFilename === oldThumbFilename) {
// Find the nearest thumbs with different filenames. Sometimes it'll be the next index, but in the case of sprites, it might be 100+ away
let thumbnailsClone;
if (forward) {
thumbnailsClone = this.thumbnails[0].frames.slice(thumbNum);
} else {
thumbnailsClone = this.thumbnails[0].frames.slice(0, thumbNum).reverse();
}
let foundOne = false;
thumbnailsClone.forEach(frame => {
const newThumbFilename = frame.text;
if (newThumbFilename !== oldThumbFilename) {
// Found one with a different filename. Make sure it hasn't already been loaded on this page visit
if (!this.loadedImages.includes(newThumbFilename)) {
foundOne = true;
this.player.debug.log(`Preloading thumb filename: ${newThumbFilename}`);
const {
urlPrefix
} = this.thumbnails[0];
const thumbURL = urlPrefix + newThumbFilename;
const previewImage = new Image();
previewImage.src = thumbURL;
previewImage.onload = () => {
this.player.debug.log(`Preloaded thumb filename: ${newThumbFilename}`);
if (!this.loadedImages.includes(newThumbFilename)) this.loadedImages.push(newThumbFilename);
// We don't resolve until the thumb is loaded
resolve();
};
}
}
});
// If there are none to preload then we want to resolve immediately
if (!foundOne) {
resolve();
}
}
}, 300);
});
});
// If user has been hovering current image for half a second, look for a higher quality one
_defineProperty$1(this, "getHigherQuality", (currentQualityIndex, previewImage, frame, thumbFilename) => {
if (currentQualityIndex < this.thumbnails.length - 1) {
// Only use the higher quality version if it's going to look any better - if the current thumb is of a lower pixel density than the thumbnail container
let previewImageHeight = previewImage.naturalHeight;
if (this.usingSprites) {
previewImageHeight = frame.h;
}
if (previewImageHeight < this.thumbContainerHeight) {
// Recurse back to the loadImage function - show a higher quality one, but only if the viewer is on this frame for a while
setTimeout(() => {
// Make sure the mouse hasn't already moved on and started hovering at another image
if (this.showingThumbFilename === thumbFilename) {
this.player.debug.log(`Showing higher quality thumb for: ${thumbFilename}`);
this.loadImage(currentQualityIndex + 1);
}
}, 300);
}
}
});
_defineProperty$1(this, "toggleThumbContainer", (toggle = false, clearShowing = false) => {
const className = this.player.config.classNames.previewThumbnails.thumbContainerShown;
this.elements.thumb.container.classList.toggle(className, toggle);
if (!toggle && clearShowing) {
this.showingThumb = null;
this.showingThumbFilename = null;
}
});
_defineProperty$1(this, "toggleScrubbingContainer", (toggle = false) => {
const className = this.player.config.classNames.previewThumbnails.scrubbingContainerShown;
this.elements.scrubbing.container.classList.toggle(className, toggle);
if (!toggle) {
this.showingThumb = null;
this.showingThumbFilename = null;
}
});
_defineProperty$1(this, "determineContainerAutoSizing", () => {
if (this.elements.thumb.imageContainer.clientHeight > 20 || this.elements.thumb.imageContainer.clientWidth > 20) {
// This will prevent auto sizing in this.setThumbContainerSizeAndPos()
this.sizeSpecifiedInCSS = true;
}
});
// Set the size to be about a quarter of the size of video. Unless option dynamicSize === false, in which case it needs to be set in CSS
_defineProperty$1(this, "setThumbContainerSizeAndPos", () => {
const {
imageContainer
} = this.elements.thumb;
if (!this.sizeSpecifiedInCSS) {
const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);
imageContainer.style.height = `${this.thumbContainerHeight}px`;
imageContainer.style.width = `${thumbWidth}px`;
} else if (imageContainer.clientHeight > 20 && imageContainer.clientWidth < 20) {
const thumbWidth = Math.floor(imageContainer.clientHeight * this.thumbAspectRatio);
imageContainer.style.width = `${thumbWidth}px`;
} else if (imageContainer.clientHeight < 20 && imageContainer.clientWidth > 20) {
const thumbHeight = Math.floor(imageContainer.clientWidth / this.thumbAspectRatio);
imageContainer.style.height = `${thumbHeight}px`;
}
this.setThumbContainerPos();
});
_defineProperty$1(this, "setThumbContainerPos", () => {
const scrubberRect = this.player.elements.progress.getBoundingClientRect();
const containerRect = this.player.elements.container.getBoundingClientRect();
const {
container
} = this.elements.thumb;
// Find the lowest and highest desired left-position, so we don't slide out the side of the video container
const min = containerRect.left - scrubberRect.left + 10;
const max = containerRect.right - scrubberRect.left - container.clientWidth - 10;
// Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth
const position = this.mousePosX - scrubberRect.left - container.clientWidth / 2;
const clamped = clamp(position, min, max);
// Move the popover position
container.style.left = `${clamped}px`;
// The arrow can follow the cursor
container.style.setProperty('--preview-arrow-offset', `${position - clamped}px`);
});
// Can't use 100% width, in case the video is a different aspect ratio to the video container
_defineProperty$1(this, "setScrubbingContainerSize", () => {
const {
width,
height
} = fitRatio(this.thumbAspectRatio, {
width: this.player.media.clientWidth,
height: this.player.media.clientHeight
});
this.elements.scrubbing.container.style.width = `${width}px`;
this.elements.scrubbing.container.style.height = `${height}px`;
});
// Sprites need to be offset to the correct location
_defineProperty$1(this, "setImageSizeAndOffset", (previewImage, frame) => {
if (!this.usingSprites) return;
// Find difference between height and preview container height
const multiplier = this.thumbContainerHeight / frame.h;
// eslint-disable-next-line no-param-reassign
previewImage.style.height = `${previewImage.naturalHeight * multiplier}px`;
// eslint-disable-next-line no-param-reassign
previewImage.style.width = `${previewImage.naturalWidth * multiplier}px`;
// eslint-disable-next-line no-param-reassign
previewImage.style.left = `-${frame.x * multiplier}px`;
// eslint-disable-next-line no-param-reassign
previewImage.style.top = `-${frame.y * multiplier}px`;
});
this.player = player;
this.thumbnails = [];
this.loaded = false;
this.lastMouseMoveTime = Date.now();
this.mouseDown = false;
this.loadedImages = [];
this.elements = {
thumb: {},
scrubbing: {}
};
this.load();
}
get enabled() {
return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;
}
get currentImageContainer() {
return this.mouseDown ? this.elements.scrubbing.container : this.elements.thumb.imageContainer;
}
get usingSprites() {
return Object.keys(this.thumbnails[0].frames[0]).includes('w');
}
get thumbAspectRatio() {
if (this.usingSprites) {
return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;
}
return this.thumbnails[0].width / this.thumbnails[0].height;
}
get thumbContainerHeight() {
if (this.mouseDown) {
const {
height
} = fitRatio(this.thumbAspectRatio, {
width: this.player.media.clientWidth,
height: this.player.media.clientHeight
});
return height;
}
// If css is used this needs to return the css height for sprites to work (see setImageSizeAndOffset)
if (this.sizeSpecifiedInCSS) {
return this.elements.thumb.imageContainer.clientHeight;
}
return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);
}
get currentImageElement() {
return this.mouseDown ? this.currentScrubbingImageElement : this.currentThumbnailImageElement;
}
set currentImageElement(element) {
if (this.mouseDown) {
this.currentScrubbingImageElement = element;
} else {
this.currentThumbnailImageElement = element;
}
}
}
// ==========================================================================
const source = {
// Add elements to HTML5 media (source, tracks, etc)
insertElements(type, attributes) {
if (is.string(attributes)) {
insertElement(type, this.media, {
src: attributes
});
} else if (is.array(attributes)) {
attributes.forEach(attribute => {
insertElement(type, this.media, attribute);
});
}
},
// Update source
// Sources are not checked for support so be careful
change(input) {
if (!getDeep(input, 'sources.length')) {
this.debug.warn('Invalid source format');
return;
}
// Cancel current network requests
html5.cancelRequests.call(this);
// Destroy instance and re-setup
this.destroy.call(this, () => {
// Reset quality options
this.options.quality = [];
// Remove elements
removeElement(this.media);
this.media = null;
// Reset class name
if (is.element(this.elements.container)) {
this.elements.container.removeAttribute('class');
}
// Set the type and provider
const {
sources,
type
} = input;
const [{
provider = providers.html5,
src
}] = sources;
const tagName = provider === 'html5' ? type : 'div';
const attributes = provider === 'html5' ? {} : {
src
};
Object.assign(this, {
provider,
type,
// Check for support
supported: support.check(type, provider, this.config.playsinline),
// Create new element
media: createElement(tagName, attributes)
});
// Inject the new element
this.elements.container.appendChild(this.media);
// Autoplay the new source?
if (is.boolean(input.autoplay)) {
this.config.autoplay = input.autoplay;
}
// Set attributes for audio and video
if (this.isHTML5) {
if (this.config.crossorigin) {
this.media.setAttribute('crossorigin', '');
}
if (this.config.autoplay) {
this.media.setAttribute('autoplay', '');
}
if (!is.empty(input.poster)) {
this.poster = input.poster;
}
if (this.config.loop.active) {
this.media.setAttribute('loop', '');
}
if (this.config.muted) {
this.media.setAttribute('muted', '');
}
if (this.config.playsinline) {
this.media.setAttribute('playsinline', '');
}
}
// Restore class hook
ui.addStyleHook.call(this);
// Set new sources for html5
if (this.isHTML5) {
source.insertElements.call(this, 'source', sources);
}
// Set video title
this.config.title = input.title;
// Set up from scratch
media.setup.call(this);
// HTML5 stuff
if (this.isHTML5) {
// Setup captions
if (Object.keys(input).includes('tracks')) {
source.insertElements.call(this, 'track', input.tracks);
}
}
// If HTML5 or embed but not fully supported, setupInterface and call ready now
if (this.isHTML5 || this.isEmbed && !this.supported.ui) {
// Setup interface
ui.build.call(this);
}
// Load HTML5 sources
if (this.isHTML5) {
this.media.load();
}
// Update previewThumbnails config & reload plugin
if (!is.empty(input.previewThumbnails)) {
Object.assign(this.config.previewThumbnails, input.previewThumbnails);
// Cleanup previewThumbnails plugin if it was loaded
if (this.previewThumbnails && this.previewThumbnails.loaded) {
this.previewThumbnails.destroy();
this.previewThumbnails = null;
}
// Create new instance if it is still enabled
if (this.config.previewThumbnails.enabled) {
this.previewThumbnails = new PreviewThumbnails(this);
}
}
// Update the fullscreen support
this.fullscreen.update();
}, true);
}
};
// Private properties
// TODO: Use a WeakMap for private globals
// const globals = new WeakMap();
// Plyr instance
class Plyr {
constructor(target, options) {
/**
* Play the media, or play the advertisement (if they are not blocked)
*/
_defineProperty$1(this, "play", () => {
if (!is.function(this.media.play)) {
return null;
}
// Intecept play with ads
if (this.ads && this.ads.enabled) {
this.ads.managerPromise.then(() => this.ads.play()).catch(() => silencePromise(this.media.play()));
}
// Return the promise (for HTML5)
return this.media.play();
});
/**
* Pause the media
*/
_defineProperty$1(this, "pause", () => {
if (!this.playing || !is.function(this.media.pause)) {
return null;
}
return this.media.pause();
});
/**
* Toggle playback based on current status
* @param {Boolean} input
*/
_defineProperty$1(this, "togglePlay", input => {
// Toggle based on current state if nothing passed
const toggle = is.boolean(input) ? input : !this.playing;
if (toggle) {
return this.play();
}
return this.pause();
});
/**
* Stop playback
*/
_defineProperty$1(this, "stop", () => {
if (this.isHTML5) {
this.pause();
this.restart();
} else if (is.function(this.media.stop)) {
this.media.stop();
}
});
/**
* Restart playback
*/
_defineProperty$1(this, "restart", () => {
this.currentTime = 0;
});
/**
* Rewind
* @param {Number} seekTime - how far to rewind in seconds. Defaults to the config.seekTime
*/
_defineProperty$1(this, "rewind", seekTime => {
this.currentTime -= is.number(seekTime) ? seekTime : this.config.seekTime;
});
/**
* Fast forward
* @param {Number} seekTime - how far to fast forward in seconds. Defaults to the config.seekTime
*/
_defineProperty$1(this, "forward", seekTime => {
this.currentTime += is.number(seekTime) ? seekTime : this.config.seekTime;
});
/**
* Increase volume
* @param {Boolean} step - How much to decrease by (between 0 and 1)
*/
_defineProperty$1(this, "increaseVolume", step => {
const volume = this.media.muted ? 0 : this.volume;
this.volume = volume + (is.number(step) ? step : 0);
});
/**
* Decrease volume
* @param {Boolean} step - How much to decrease by (between 0 and 1)
*/
_defineProperty$1(this, "decreaseVolume", step => {
this.increaseVolume(-step);
});
/**
* Trigger the airplay dialog
* TODO: update player with state, support, enabled
*/
_defineProperty$1(this, "airplay", () => {
// Show dialog if supported
if (support.airplay) {
this.media.webkitShowPlaybackTargetPicker();
}
});
/**
* Toggle the player controls
* @param {Boolean} [toggle] - Whether to show the controls
*/
_defineProperty$1(this, "toggleControls", toggle => {
// Don't toggle if missing UI support or if it's audio
if (this.supported.ui && !this.isAudio) {
// Get state before change
const isHidden = hasClass(this.elements.container, this.config.classNames.hideControls);
// Negate the argument if not undefined since adding the class to hides the controls
const force = typeof toggle === 'undefined' ? undefined : !toggle;
// Apply and get updated state
const hiding = toggleClass(this.elements.container, this.config.classNames.hideControls, force);
// Close menu
if (hiding && is.array(this.config.controls) && this.config.controls.includes('settings') && !is.empty(this.config.settings)) {
controls.toggleMenu.call(this, false);
}
// Trigger event on change
if (hiding !== isHidden) {
const eventName = hiding ? 'controlshidden' : 'controlsshown';
triggerEvent.call(this, this.media, eventName);
}
return !hiding;
}
return false;
});
/**
* Add event listeners
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
*/
_defineProperty$1(this, "on", (event, callback) => {
on.call(this, this.elements.container, event, callback);
});
/**
* Add event listeners once
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
*/
_defineProperty$1(this, "once", (event, callback) => {
once.call(this, this.elements.container, event, callback);
});
/**
* Remove event listeners
* @param {String} event - Event type
* @param {Function} callback - Callback for when event occurs
*/
_defineProperty$1(this, "off", (event, callback) => {
off(this.elements.container, event, callback);
});
/**
* Destroy an instance
* Event listeners are removed when elements are removed
* http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory
* @param {Function} callback - Callback for when destroy is complete
* @param {Boolean} soft - Whether it's a soft destroy (for source changes etc)
*/
_defineProperty$1(this, "destroy", (callback, soft = false) => {
if (!this.ready) {
return;
}
const done = () => {
// Reset overflow (incase destroyed while in fullscreen)
document.body.style.overflow = '';
// GC for embed
this.embed = null;
// If it's a soft destroy, make minimal changes
if (soft) {
if (Object.keys(this.elements).length) {
// Remove elements
removeElement(this.elements.buttons.play);
removeElement(this.elements.captions);
removeElement(this.elements.controls);
removeElement(this.elements.wrapper);
// Clear for GC
this.elements.buttons.play = null;
this.elements.captions = null;
this.elements.controls = null;
this.elements.wrapper = null;
}
// Callback
if (is.function(callback)) {
callback();
}
} else {
// Unbind listeners
unbindListeners.call(this);
// Cancel current network requests
html5.cancelRequests.call(this);
// Replace the container with the original element provided
replaceElement(this.elements.original, this.elements.container);
// Event
triggerEvent.call(this, this.elements.original, 'destroyed', true);
// Callback
if (is.function(callback)) {
callback.call(this.elements.original);
}
// Reset state
this.ready = false;
// Clear for garbage collection
setTimeout(() => {
this.elements = null;
this.media = null;
}, 200);
}
};
// Stop playback
this.stop();
// Clear timeouts
clearTimeout(this.timers.loading);
clearTimeout(this.timers.controls);
clearTimeout(this.timers.resized);
// Provider specific stuff
if (this.isHTML5) {
// Restore native video controls
ui.toggleNativeControls.call(this, true);
// Clean up
done();
} else if (this.isYouTube) {
// Clear timers
clearInterval(this.timers.buffering);
clearInterval(this.timers.playing);
// Destroy YouTube API
if (this.embed !== null && is.function(this.embed.destroy)) {
this.embed.destroy();
}
// Clean up
done();
} else if (this.isVimeo) {
// Destroy Vimeo API
// then clean up (wait, to prevent postmessage errors)
if (this.embed !== null) {
this.embed.unload().then(done);
}
// Vimeo does not always return
setTimeout(done, 200);
}
});
/**
* Check for support for a mime type (HTML5 only)
* @param {String} type - Mime type
*/
_defineProperty$1(this, "supports", type => support.mime.call(this, type));
this.timers = {};
// State
this.ready = false;
this.loading = false;
this.failed = false;
// Touch device
this.touch = support.touch;
// Set the media element
this.media = target;
// String selector passed
if (is.string(this.media)) {
this.media = document.querySelectorAll(this.media);
}
// jQuery, NodeList or Array passed, use first element
if (window.jQuery && this.media instanceof jQuery || is.nodeList(this.media) || is.array(this.media)) {
// eslint-disable-next-line
this.media = this.media[0];
}
// Set config
this.config = extend({}, defaults, Plyr.defaults, options || {}, (() => {
try {
return JSON.parse(this.media.getAttribute('data-plyr-config'));
} catch (_) {
return {};
}
})());
// Elements cache
this.elements = {
container: null,
fullscreen: null,
captions: null,
buttons: {},
display: {},
progress: {},
inputs: {},
settings: {
popup: null,
menu: null,
panels: {},
buttons: {}
}
};
// Captions
this.captions = {
active: null,
currentTrack: -1,
meta: new WeakMap()
};
// Fullscreen
this.fullscreen = {
active: false
};
// Options
this.options = {
speed: [],
quality: []
};
// Debugging
// TODO: move to globals
this.debug = new Console(this.config.debug);
// Log config options and support
this.debug.log('Config', this.config);
this.debug.log('Support', support);
// We need an element to setup
if (is.nullOrUndefined(this.media) || !is.element(this.media)) {
this.debug.error('Setup failed: no suitable element passed');
return;
}
// Bail if the element is initialized
if (this.media.plyr) {
this.debug.warn('Target already setup');
return;
}
// Bail if not enabled
if (!this.config.enabled) {
this.debug.error('Setup failed: disabled by config');
return;
}
// Bail if disabled or no basic support
// You may want to disable certain UAs etc
if (!support.check().api) {
this.debug.error('Setup failed: no support');
return;
}
// Cache original element state for .destroy()
const clone = this.media.cloneNode(true);
clone.autoplay = false;
this.elements.original = clone;
// Set media type based on tag or data attribute
// Supported: video, audio, vimeo, youtube
const _type = this.media.tagName.toLowerCase();
// Embed properties
let iframe = null;
let url = null;
// Different setup based on type
switch (_type) {
case 'div':
// Find the frame
iframe = this.media.querySelector('iframe');
//