aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/plugins
diff options
context:
space:
mode:
Diffstat (limited to 'src/js/plugins')
-rw-r--r--src/js/plugins/ads.js1114
-rw-r--r--src/js/plugins/preview-thumbnails.js1159
-rw-r--r--src/js/plugins/vimeo.js726
-rw-r--r--src/js/plugins/youtube.js790
4 files changed, 1913 insertions, 1876 deletions
diff --git a/src/js/plugins/ads.js b/src/js/plugins/ads.js
index 6b4fca10..1a52ebce 100644
--- a/src/js/plugins/ads.js
+++ b/src/js/plugins/ads.js
@@ -11,626 +11,634 @@ import { triggerEvent } from '../utils/events';
import i18n from '../utils/i18n';
import is from '../utils/is';
import loadScript from '../utils/load-script';
+import { silencePromise } from '../utils/promise';
import { formatTime } from '../utils/time';
import { buildUrlParams } from '../utils/urls';
const destroy = instance => {
- // Destroy our adsManager
- if (instance.manager) {
- instance.manager.destroy();
- }
+ // Destroy our adsManager
+ if (instance.manager) {
+ instance.manager.destroy();
+ }
- // Destroy our adsManager
- if (instance.elements.displayContainer) {
- instance.elements.displayContainer.destroy();
- }
+ // Destroy our adsManager
+ if (instance.elements.displayContainer) {
+ instance.elements.displayContainer.destroy();
+ }
- instance.elements.container.remove();
+ instance.elements.container.remove();
};
class Ads {
- /**
- * Ads constructor.
- * @param {Object} player
- * @return {Ads}
- */
- constructor(player) {
- 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();
+ /**
+ * Ads constructor.
+ * @param {Object} player
+ * @return {Ads}
+ */
+ constructor(player) {
+ 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))
+ );
+ }
+
+ /**
+ * Load the IMA SDK
+ */
+ load() {
+ if (!this.enabled) {
+ return;
}
- get enabled() {
- const { config } = this;
-
- return (
- this.player.isHTML5 &&
- this.player.isVideo &&
- config.enabled &&
- (!is.empty(config.publisherId) || is.url(config.tagUrl))
- );
- }
-
- /**
- * Load the IMA SDK
- */
- 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
- */
- 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()');
+ // 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'));
});
-
- // Set listeners on the Plyr instance
- this.listeners();
-
- // Setup the IMA SDK
- this.setupIMA();
+ } else {
+ this.ready();
}
-
- // 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)}`;
+ }
+
+ /**
+ * Get the ads instance ready
+ */
+ ready() {
+ // Double check we're enabled
+ if (!this.enabled) {
+ destroy(this);
}
- /**
- * 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.
- */
- 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);
+ // Start ticking our safety timer. If the whole advertisement
+ // thing doesn't resolve within our set time; we bail
+ this.startSafetyTimer(12000, 'ready()');
- // So we can run VPAID2
- google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);
+ // Clear the safety timer
+ this.managerPromise.then(() => {
+ this.clearSafetyTimer('onAdsManagerLoaded()');
+ });
- // Set language
- google.ima.settings.setLocale(this.player.config.ads.language);
+ // Set listeners on the Plyr instance
+ this.listeners();
- // Set playback for iOS10+
- google.ima.settings.setDisableCustomPlaybackForIOS10Plus(this.player.config.playsinline);
+ // Setup the IMA SDK
+ this.setupIMA();
+ }
- // 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);
+ // Build the tag URL
+ get tagUrl() {
+ const { config } = this;
- // Request video ads to be pre-loaded
- this.requestAds();
+ if (is.url(config.tagUrl)) {
+ return config.tagUrl;
}
- /**
- * Request advertisements
- */
- requestAds() {
- const { container } = this.player.elements;
-
- try {
- // 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
- 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 (e) {
- this.onAdError(e);
- }
+ 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)}`;
+ }
+
+ /**
+ * 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.
+ */
+ 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
+ */
+ 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 (e) {
+ this.onAdError(e);
+ }
+ }
+
+ /**
+ * Update the ad countdown
+ * @param {Boolean} start
+ */
+ pollCountdown(start = false) {
+ if (!start) {
+ clearInterval(this.countdownTimer);
+ this.elements.container.removeAttribute('data-badge-text');
+ return;
}
- /**
- * Update the ad countdown
- * @param {Boolean} start
- */
- 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);
+ 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} adsManagerLoadedEvent
+ */
+ onAdsManagerLoaded(event) {
+ // Load could occur after a source change (race condition)
+ if (!this.enabled) {
+ return;
}
- /**
- * This method is called whenever the ads are ready inside the AdDisplayContainer
- * @param {Event} adsManagerLoadedEvent
- */
- 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();
- // 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;
- // 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);
- // 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();
- // 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));
- // 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));
+ });
- // 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');
+ }
- // Resolve our adsManager
- this.trigger('loaded');
- }
+ 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;
- 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);
- }
- }
+ if (is.element(seekElement)) {
+ const cuePercentage = (100 / this.player.duration) * cuePoint;
+ const cue = createElement('span', {
+ class: this.player.config.classNames.cues,
});
- }
- }
- /**
- * 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
- */
- 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
-
- this.loadAds();
-
- 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;
-
- default:
- break;
+ 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
+ */
+ 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');
- /**
- * Any ad error handling comes through here
- * @param {Event} event
- */
- 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
- */
- listeners() {
- const { container } = this.player.elements;
- let time;
-
- this.player.on('canplay', () => {
- this.addCuePoints();
- });
+ // Start countdown
+ this.pollCountdown(true);
- this.player.on('ended', () => {
- this.loader.contentComplete();
- });
+ if (!ad.isLinear()) {
+ // Position AdDisplayContainer correctly for overlay
+ ad.width = container.offsetWidth;
+ ad.height = container.offsetHeight;
+ }
- this.player.on('timeupdate', () => {
- time = this.player.currentTime;
- });
+ // 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();
+ }
- this.player.on('seeked', () => {
- const seekedTime = this.player.currentTime;
+ break;
- if (is.empty(this.cuePoints)) {
- return;
- }
+ 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.cuePoints.forEach((cuePoint, index) => {
- if (time < cuePoint && cuePoint < seekedTime) {
- this.manager.discardAdBreak();
- this.cuePoints.splice(index, 1);
- }
- });
- });
+ this.pauseContent();
- // 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);
- }
- });
- }
+ break;
- /**
- * Initialize the adsManager and start playing advertisements
- */
- play() {
- const { container } = this.player.elements;
+ 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
- if (!this.managerPromise) {
- this.resumeContent();
- }
+ this.pollCountdown();
- // 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(() => {});
- }
+ this.resumeContent();
- /**
- * Resume our video
- */
- resumeContent() {
- // Hide the advertisement container
- this.elements.container.style.zIndex = '';
+ break;
- // Ad is stopped
- this.playing = false;
-
- // Play video
- this.player.media.play();
- }
-
- /**
- * Pause our video
- */
- pauseContent() {
- // Show the advertisement container
- this.elements.container.style.zIndex = 3;
+ case google.ima.AdEvent.Type.LOG:
+ if (adData.adError) {
+ this.player.debug.warn(`Non-fatal ad error: ${adData.adError.getMessage()}`);
+ }
- // Ad is playing
- this.playing = true;
+ break;
- // Pause our video.
- this.player.media.pause();
+ default:
+ break;
}
-
- /**
- * 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
- */
- cancel() {
- // Pause our video
- if (this.initialized) {
- this.resumeContent();
+ }
+
+ /**
+ * Any ad error handling comes through here
+ * @param {Event} event
+ */
+ 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
+ */
+ 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);
}
-
- // Tell our instance that we're done for now
- this.trigger('error');
-
- // Re-create our adsManager
- this.loadAds();
+ });
+ });
+
+ // 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
+ */
+ play() {
+ const { container } = this.player.elements;
+
+ if (!this.managerPromise) {
+ this.resumeContent();
}
- /**
- * Re-create our adsManager
- */
- 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 request some new advertisements
- this.requestAds();
- })
- .catch(() => {});
- }
+ // Play the requested advertisement whenever the adsManager is ready
+ this.managerPromise
+ .then(() => {
+ // Set volume to match player
+ this.manager.setVolume(this.player.volume);
- /**
- * Handles callbacks after an ad event was invoked
- * @param {String} event - Event type
- */
- trigger(event, ...args) {
- const handlers = this.events[event];
-
- if (is.array(handlers)) {
- handlers.forEach(handler => {
- if (is.function(handler)) {
- handler.apply(this, args);
- }
- });
+ // 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
+ */
+ 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
+ */
+ 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
+ */
+ cancel() {
+ // Pause our video
+ if (this.initialized) {
+ this.resumeContent();
}
- /**
- * Add event listeners
- * @param {String} event - Event type
- * @param {Function} callback - Callback for when event occurs
- * @return {Ads}
- */
- on(event, callback) {
- if (!is.array(this.events[event])) {
- this.events[event] = [];
+ // Tell our instance that we're done for now
+ this.trigger('error');
+
+ // Re-create our adsManager
+ this.loadAds();
+ }
+
+ /**
+ * Re-create our adsManager
+ */
+ loadAds() {
+ // Tell our adsManager to go bye bye
+ this.managerPromise
+ .then(() => {
+ // Destroy our adsManager
+ if (this.manager) {
+ this.manager.destroy();
}
- this.events[event].push(callback);
+ // 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;
- return this;
+ // Now request some new advertisements
+ this.requestAds();
+ })
+ .catch(() => {});
+ }
+
+ /**
+ * Handles callbacks after an ad event was invoked
+ * @param {String} event - Event type
+ */
+ trigger(event, ...args) {
+ const handlers = this.events[event];
+
+ if (is.array(handlers)) {
+ handlers.forEach(handler => {
+ if (is.function(handler)) {
+ handler.apply(this, args);
+ }
+ });
}
-
- /**
- * 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
- */
- startSafetyTimer(time, from) {
- this.player.debug.log(`Safety timer invoked from: ${from}`);
-
- this.safetyTimer = setTimeout(() => {
- this.cancel();
- this.clearSafetyTimer('startSafetyTimer()');
- }, time);
+ }
+
+ /**
+ * Add event listeners
+ * @param {String} event - Event type
+ * @param {Function} callback - Callback for when event occurs
+ * @return {Ads}
+ */
+ on(event, callback) {
+ if (!is.array(this.events[event])) {
+ this.events[event] = [];
}
- /**
- * Clear our safety timer(s)
- * @param {String} from
- */
- clearSafetyTimer(from) {
- if (!is.nullOrUndefined(this.safetyTimer)) {
- this.player.debug.log(`Safety timer cleared from: ${from}`);
-
- clearTimeout(this.safetyTimer);
- this.safetyTimer = null;
- }
+ 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
+ */
+ 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
+ */
+ clearSafetyTimer(from) {
+ if (!is.nullOrUndefined(this.safetyTimer)) {
+ this.player.debug.log(`Safety timer cleared from: ${from}`);
+
+ clearTimeout(this.safetyTimer);
+ this.safetyTimer = null;
}
+ }
}
export default Ads;
diff --git a/src/js/plugins/preview-thumbnails.js b/src/js/plugins/preview-thumbnails.js
index 86eeebc8..6ce53f28 100644
--- a/src/js/plugins/preview-thumbnails.js
+++ b/src/js/plugins/preview-thumbnails.js
@@ -6,50 +6,50 @@ import { formatTime } from '../utils/time';
// 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(',');
- }
- }
- });
+ const processedList = [];
+ const frames = vttDataString.split(/\r\n\r\n|\n\n|\r\r/);
- if (result.text) {
- processedList.push(result);
- }
+ 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(',');
+ }
+ }
});
- return processedList;
+ if (result.text) {
+ processedList.push(result);
+ }
+ });
+
+ return processedList;
};
/**
@@ -64,629 +64,646 @@ const parseVtt = vttDataString => {
*/
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;
+ 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) {
- 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;
- }
-
- load() {
- // Toggle the regular seek tooltip
- if (this.player.elements.display.seekTooltip) {
- this.player.elements.display.seekTooltip.hidden = this.enabled;
- }
-
- if (!this.enabled) {
- return;
- }
+ /**
+ * PreviewThumbnails constructor.
+ * @param {Plyr} player
+ * @return {PreviewThumbnails}
+ */
+ constructor(player) {
+ this.player = player;
+ this.thumbnails = [];
+ this.loaded = false;
+ this.lastMouseMoveTime = Date.now();
+ this.mouseDown = false;
+ this.loadedImages = [];
- this.getThumbnails().then(() => {
- if (!this.enabled) {
- return;
- }
+ this.elements = {
+ thumb: {},
+ scrubbing: {},
+ };
- // Render DOM elements
- this.render();
+ this.load();
+ }
- // Check to see if thumb container size was specified manually in CSS
- this.determineContainerAutoSizing();
+ get enabled() {
+ return this.player.isHTML5 && this.player.isVideo && this.player.config.previewThumbnails.enabled;
+ }
- this.loaded = true;
- });
+ load() {
+ // Toggle the regular seek tooltip
+ if (this.player.elements.display.seekTooltip) {
+ this.player.elements.display.seekTooltip.hidden = this.enabled;
}
- // Download VTT files and parse them
- getThumbnails() {
- return new Promise(resolve => {
- const { src } = this.player.config.previewThumbnails;
-
- if (is.empty(src)) {
- throw new Error('Missing previewThumbnails.src config attribute');
- }
-
- // 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));
+ if (!this.enabled) {
+ return;
+ }
- Promise.all(promises).then(() => {
- // Sort smallest to biggest (e.g., [120p, 480p, 1080p])
- this.thumbnails.sort((x, y) => x.height - y.height);
+ this.getThumbnails().then(() => {
+ if (!this.enabled) {
+ return;
+ }
- this.player.debug.log('Preview thumbnails', this.thumbnails);
+ // Render DOM elements
+ this.render();
- resolve();
- });
- });
- }
+ // Check to see if thumb container size was specified manually in CSS
+ this.determineContainerAutoSizing();
- // Process individual VTT file
- getThumbnail(url) {
- return new Promise(resolve => {
- fetch(url).then(response => {
- const thumbnail = {
- frames: parseVtt(response),
- height: null,
- urlPrefix: '',
- };
+ this.loaded = true;
+ });
+ }
- // 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 VTT files and parse them
+ getThumbnails() {
+ return new Promise(resolve => {
+ const { src } = this.player.config.previewThumbnails;
- // Download the first frame, so that we can determine/set the height of this thumbnailsDef
- const tempImage = new Image();
+ if (is.empty(src)) {
+ throw new Error('Missing previewThumbnails.src config attribute');
+ }
- tempImage.onload = () => {
- thumbnail.height = tempImage.naturalHeight;
- thumbnail.width = tempImage.naturalWidth;
+ // Resolve promise
+ const sortAndResolve = () => {
+ // Sort smallest to biggest (e.g., [120p, 480p, 1080p])
+ this.thumbnails.sort((x, y) => x.height - y.height);
- this.thumbnails.push(thumbnail);
+ this.player.debug.log('Preview thumbnails', this.thumbnails);
- resolve();
- };
+ resolve();
+ };
- tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;
- });
+ // Via callback()
+ if (is.function(src)) {
+ src(thumbnails => {
+ this.thumbnails = thumbnails;
+ sortAndResolve();
});
- }
-
- startMove(event) {
- if (!this.loaded) {
- return;
- }
-
- if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {
- return;
- }
+ }
+ // 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
+ getThumbnail(url) {
+ return new Promise(resolve => {
+ fetch(url).then(response => {
+ const thumbnail = {
+ frames: parseVtt(response),
+ height: null,
+ urlPrefix: '',
+ };
- // Wait until media has a duration
- if (!this.player.media.duration) {
- return;
+ // 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);
}
- 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 {
- // 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;
- }
+ // Download the first frame, so that we can determine/set the height of this thumbnailsDef
+ const tempImage = new Image();
- 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;
- }
+ tempImage.onload = () => {
+ thumbnail.height = tempImage.naturalHeight;
+ thumbnail.width = tempImage.naturalWidth;
- this.mousePosX = event.pageX;
+ this.thumbnails.push(thumbnail);
- // Set time text inside image container
- this.elements.thumb.time.innerText = formatTime(this.seekTime);
- }
+ resolve();
+ };
- // Download and show image
- this.showImageAtCurrentTime();
- }
+ tempImage.src = thumbnail.urlPrefix + thumbnail.frames[0].text;
+ });
+ });
+ }
- endMove() {
- this.toggleThumbContainer(false, true);
+ startMove(event) {
+ if (!this.loaded) {
+ return;
}
- 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();
- }
- }
+ if (!is.event(event) || !['touchmove', 'mousemove'].includes(event.type)) {
+ return;
}
- 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);
- }
- });
- }
+ // Wait until media has a duration
+ if (!this.player.media.duration) {
+ return;
}
- /**
- * Setup hooks for Plyr and window events
- */
- 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;
- });
- }
+ 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 {
+ // 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);
- /**
- * Create HTML elements for image containers
- */
- render() {
- // Create HTML element: plyr__preview-thumbnail-container
- this.elements.thumb.container = createElement('div', {
- class: this.player.config.classNames.previewThumbnails.thumbContainer,
- });
+ if (this.seekTime < 0) {
+ // The mousemove fires for 10+px out to the left
+ this.seekTime = 0;
+ }
- // 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);
+ 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;
+ }
- // Create HTML element, parent+span: time text (e.g., 01:32:00)
- const timeContainer = createElement('div', {
- class: this.player.config.classNames.previewThumbnails.timeContainer,
- });
+ this.mousePosX = event.pageX;
- this.elements.thumb.time = createElement('span', {}, '00:00');
- timeContainer.appendChild(this.elements.thumb.time);
+ // Set time text inside image container
+ this.elements.thumb.time.innerText = formatTime(this.seekTime);
+ }
- this.elements.thumb.container.appendChild(timeContainer);
+ // Download and show image
+ this.showImageAtCurrentTime();
+ }
- // Inject the whole thumb
- if (is.element(this.player.elements.progress)) {
- this.player.elements.progress.appendChild(this.elements.thumb.container);
- }
+ endMove() {
+ this.toggleThumbContainer(false, true);
+ }
- // Create HTML element: plyr__preview-scrubbing-container
- this.elements.scrubbing.container = createElement('div', {
- class: this.player.config.classNames.previewThumbnails.scrubbingContainer,
- });
+ 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;
- this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);
- }
+ // Wait until media has a duration
+ if (this.player.media.duration) {
+ this.toggleScrubbingContainer(true);
+ this.toggleThumbContainer(false, true);
- destroy() {
- if (this.elements.thumb.container) {
- this.elements.thumb.container.remove();
- }
- if (this.elements.scrubbing.container) {
- this.elements.scrubbing.container.remove();
- }
+ // Download and show image
+ this.showImageAtCurrentTime();
+ }
}
+ }
- 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;
+ endScrubbing() {
+ this.mouseDown = false;
- // Show the thumb container if we're not scrubbing
+ // 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.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 thumbnum or thumbfilename has changed
- if (thumbNum !== this.showingThumb) {
- this.showingThumb = thumbNum;
- this.loadImage(qualityIndex);
+ this.toggleScrubbingContainer(false);
}
+ });
}
+ }
- // Show the image that's currently specified in this.showingThumb
- 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;
- }
+ /**
+ * Setup hooks for Plyr and window events
+ */
+ 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);
+ });
- // 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);
- }
- }
+ this.player.on('seeked', () => {
+ this.toggleThumbContainer(false);
+ });
- 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);
+ this.player.on('timeupdate', () => {
+ this.lastTime = this.player.media.currentTime;
+ });
+ }
+
+ /**
+ * Create HTML elements for image containers
+ */
+ render() {
+ // Create HTML element: plyr__preview-thumbnail-container
+ this.elements.thumb.container = createElement('div', {
+ class: this.player.config.classNames.previewThumbnails.thumbContainer,
+ });
- if (newImage) {
- this.currentImageContainer.appendChild(previewImage);
- this.currentImageElement = previewImage;
+ // 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);
- if (!this.loadedImages.includes(thumbFilename)) {
- this.loadedImages.push(thumbFilename);
- }
- }
+ // Create HTML element, parent+span: time text (e.g., 01:32:00)
+ const timeContainer = createElement('div', {
+ class: this.player.config.classNames.previewThumbnails.timeContainer,
+ });
- // 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));
- }
+ this.elements.thumb.time = createElement('span', {}, '00:00');
+ timeContainer.appendChild(this.elements.thumb.time);
- // Remove all preview images that aren't the designated current image
- 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;
- }
+ this.elements.thumb.container.appendChild(timeContainer);
- const removeDelay = this.usingSprites ? 500 : 1000;
+ // Inject the whole thumb
+ if (is.element(this.player.elements.progress)) {
+ this.player.elements.progress.appendChild(this.elements.thumb.container);
+ }
- 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;
+ // Create HTML element: plyr__preview-scrubbing-container
+ this.elements.scrubbing.container = createElement('div', {
+ class: this.player.config.classNames.previewThumbnails.scrubbingContainer,
+ });
- // This has to be set before the timeout - to prevent issues switching between hover and scrub
- const { currentImageContainer } = this;
+ this.player.elements.wrapper.appendChild(this.elements.scrubbing.container);
+ }
- setTimeout(() => {
- currentImageContainer.removeChild(image);
- this.player.debug.log(`Removing thumb: ${image.dataset.filename}`);
- }, removeDelay);
- }
- });
+ destroy() {
+ if (this.elements.thumb.container) {
+ this.elements.thumb.container.remove();
}
-
- // 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
- 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 (this.elements.scrubbing.container) {
+ this.elements.scrubbing.container.remove();
}
+ }
- // If user has been hovering current image for half a second, look for a higher quality one
- 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);
- }
- }
+ showImageAtCurrentTime() {
+ if (this.mouseDown) {
+ this.setScrubbingContainerSize();
+ } else {
+ this.setThumbContainerSizeAndPos();
}
- get currentImageContainer() {
- if (this.mouseDown) {
- return this.elements.scrubbing.container;
- }
+ // 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;
- return this.elements.thumb.imageContainer;
+ // Show the thumb container if we're not scrubbing
+ if (!this.mouseDown) {
+ this.toggleThumbContainer(hasThumb);
}
- get usingSprites() {
- return Object.keys(this.thumbnails[0].frames[0]).includes('w');
+ // No matching thumb found
+ if (!hasThumb) {
+ return;
}
- 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;
- }
+ // 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;
+ }
+ });
- get thumbContainerHeight() {
- if (this.mouseDown) {
- const { height } = fitRatio(this.thumbAspectRatio, {
- width: this.player.media.clientWidth,
- height: this.player.media.clientHeight,
- });
- return height;
- }
+ // Only proceed if either thumbnum or thumbfilename has changed
+ if (thumbNum !== this.showingThumb) {
+ this.showingThumb = thumbNum;
+ this.loadImage(qualityIndex);
+ }
+ }
+
+ // Show the image that's currently specified in this.showingThumb
+ 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);
+ }
+ }
+
+ 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
+ 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;
- // 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;
- }
+ // This has to be set before the timeout - to prevent issues switching between hover and scrub
+ const { currentImageContainer } = this;
- return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);
- }
+ 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
+ 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();
+ };
+ }
+ }
+ });
- get currentImageElement() {
- if (this.mouseDown) {
- return this.currentScrubbingImageElement;
+ // If there are none to preload then we want to resolve immediately
+ if (!foundOne) {
+ resolve();
+ }
}
+ }, 300);
+ });
+ }
- return this.currentThumbnailImageElement;
- }
+ // If user has been hovering current image for half a second, look for a higher quality one
+ 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;
- set currentImageElement(element) {
- if (this.mouseDown) {
- this.currentScrubbingImageElement = element;
- } else {
- this.currentThumbnailImageElement = element;
- }
- }
+ if (this.usingSprites) {
+ previewImageHeight = frame.h;
+ }
- 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;
- }
+ 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);
+ }
}
+ }
- 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;
- }
+ get currentImageContainer() {
+ if (this.mouseDown) {
+ return this.elements.scrubbing.container;
}
- 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;
- }
- }
+ return this.elements.thumb.imageContainer;
+ }
- // 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
- setThumbContainerSizeAndPos() {
- if (!this.sizeSpecifiedInCSS) {
- const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);
- this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;
- this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;
- } else if (this.elements.thumb.imageContainer.clientHeight > 20 && this.elements.thumb.imageContainer.clientWidth < 20) {
- const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);
- this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;
- } else if (this.elements.thumb.imageContainer.clientHeight < 20 && this.elements.thumb.imageContainer.clientWidth > 20) {
- const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);
- this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;
- }
+ get usingSprites() {
+ return Object.keys(this.thumbnails[0].frames[0]).includes('w');
+ }
- this.setThumbContainerPos();
+ get thumbAspectRatio() {
+ if (this.usingSprites) {
+ return this.thumbnails[0].frames[0].w / this.thumbnails[0].frames[0].h;
}
- setThumbContainerPos() {
- const seekbarRect = this.player.elements.progress.getBoundingClientRect();
- const plyrRect = 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 minVal = plyrRect.left - seekbarRect.left + 10;
- const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10;
- // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth
- let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;
-
- if (previewPos < minVal) {
- previewPos = minVal;
- }
+ return this.thumbnails[0].width / this.thumbnails[0].height;
+ }
- if (previewPos > maxVal) {
- previewPos = maxVal;
- }
-
- container.style.left = `${previewPos}px`;
+ get thumbContainerHeight() {
+ if (this.mouseDown) {
+ const { height } = fitRatio(this.thumbAspectRatio, {
+ width: this.player.media.clientWidth,
+ height: this.player.media.clientHeight,
+ });
+ return height;
}
- // Can't use 100% width, in case the video is a different aspect ratio to the video container
- 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`;
+ // 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;
}
- // Sprites need to be offset to the correct location
- setImageSizeAndOffset(previewImage, frame) {
- if (!this.usingSprites) {
- return;
- }
-
- // Find difference between height and preview container height
- const multiplier = this.thumbContainerHeight / frame.h;
+ return Math.floor(this.player.media.clientWidth / this.thumbAspectRatio / 4);
+ }
- // 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`;
+ get currentImageElement() {
+ if (this.mouseDown) {
+ return this.currentScrubbingImageElement;
}
+
+ return this.currentThumbnailImageElement;
+ }
+
+ set currentImageElement(element) {
+ if (this.mouseDown) {
+ this.currentScrubbingImageElement = element;
+ } else {
+ this.currentThumbnailImageElement = element;
+ }
+ }
+
+ 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;
+ }
+ }
+
+ 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;
+ }
+ }
+
+ 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
+ setThumbContainerSizeAndPos() {
+ if (!this.sizeSpecifiedInCSS) {
+ const thumbWidth = Math.floor(this.thumbContainerHeight * this.thumbAspectRatio);
+ this.elements.thumb.imageContainer.style.height = `${this.thumbContainerHeight}px`;
+ this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;
+ } else if (
+ this.elements.thumb.imageContainer.clientHeight > 20 &&
+ this.elements.thumb.imageContainer.clientWidth < 20
+ ) {
+ const thumbWidth = Math.floor(this.elements.thumb.imageContainer.clientHeight * this.thumbAspectRatio);
+ this.elements.thumb.imageContainer.style.width = `${thumbWidth}px`;
+ } else if (
+ this.elements.thumb.imageContainer.clientHeight < 20 &&
+ this.elements.thumb.imageContainer.clientWidth > 20
+ ) {
+ const thumbHeight = Math.floor(this.elements.thumb.imageContainer.clientWidth / this.thumbAspectRatio);
+ this.elements.thumb.imageContainer.style.height = `${thumbHeight}px`;
+ }
+
+ this.setThumbContainerPos();
+ }
+
+ setThumbContainerPos() {
+ const seekbarRect = this.player.elements.progress.getBoundingClientRect();
+ const plyrRect = 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 minVal = plyrRect.left - seekbarRect.left + 10;
+ const maxVal = plyrRect.right - seekbarRect.left - container.clientWidth - 10;
+ // Set preview container position to: mousepos, minus seekbar.left, minus half of previewContainer.clientWidth
+ let previewPos = this.mousePosX - seekbarRect.left - container.clientWidth / 2;
+
+ if (previewPos < minVal) {
+ previewPos = minVal;
+ }
+
+ if (previewPos > maxVal) {
+ previewPos = maxVal;
+ }
+
+ container.style.left = `${previewPos}px`;
+ }
+
+ // Can't use 100% width, in case the video is a different aspect ratio to the video container
+ 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
+ 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`;
+ }
}
export default PreviewThumbnails;
diff --git a/src/js/plugins/vimeo.js b/src/js/plugins/vimeo.js
index fa965d8e..d098fe96 100644
--- a/src/js/plugins/vimeo.js
+++ b/src/js/plugins/vimeo.js
@@ -10,393 +10,405 @@ import { triggerEvent } from '../utils/events';
import fetch from '../utils/fetch';
import is from '../utils/is';
import loadScript from '../utils/load-script';
-import { extend } from '../utils/objects';
import { format, stripHTML } from '../utils/strings';
import { setAspectRatio } from '../utils/style';
import { buildUrlParams } from '../utils/urls';
// Parse Vimeo ID from URL
function parseId(url) {
- if (is.empty(url)) {
- return null;
- }
+ if (is.empty(url)) {
+ return null;
+ }
- if (is.number(Number(url))) {
- return url;
- }
+ if (is.number(Number(url))) {
+ return url;
+ }
- const regex = /^.*(vimeo.com\/|video\/)(\d+).*/;
- return url.match(regex) ? RegExp.$2 : url;
+ const regex = /^.*(vimeo.com\/|video\/)(\d+).*/;
+ return url.match(regex) ? RegExp.$2 : url;
}
// Set playback state and trigger change (only on actual change)
function assurePlaybackState(play) {
- if (play && !this.embed.hasPlayed) {
- this.embed.hasPlayed = true;
- }
- if (this.media.paused === play) {
- this.media.paused = !play;
- triggerEvent.call(this, this.media, play ? 'play' : 'pause');
- }
+ if (play && !this.embed.hasPlayed) {
+ this.embed.hasPlayed = true;
+ }
+ if (this.media.paused === play) {
+ this.media.paused = !play;
+ triggerEvent.call(this, this.media, play ? 'play' : 'pause');
+ }
}
const vimeo = {
- setup() {
- const player = this;
-
- // Add embed class for responsive
- toggleClass(player.elements.wrapper, player.config.classNames.embed, true);
-
- // Set speed options from config
- player.options.speed = player.config.speed.options;
-
- // Set intial ratio
- setAspectRatio.call(player);
-
- // Load the SDK if not already
- if (!is.object(window.Vimeo)) {
- loadScript(player.config.urls.vimeo.sdk)
- .then(() => {
- vimeo.ready.call(player);
- })
- .catch(error => {
- player.debug.warn('Vimeo SDK (player.js) failed to load', error);
- });
- } else {
- vimeo.ready.call(player);
- }
- },
-
- // API Ready
- ready() {
- const player = this;
- const config = player.config.vimeo;
-
- // Get Vimeo params for the iframe
- const params = buildUrlParams(
- extend(
- {},
- {
- loop: player.config.loop.active,
- autoplay: player.autoplay,
- muted: player.muted,
- gesture: 'media',
- playsinline: !this.config.fullscreen.iosNative,
- },
- config,
- ),
- );
-
- // Get the source URL or ID
- let source = player.media.getAttribute('src');
-
- // Get from <div> if needed
- if (is.empty(source)) {
- source = player.media.getAttribute(player.config.attributes.embed.id);
- }
-
- const id = parseId(source);
- // Build an iframe
- const iframe = createElement('iframe');
- const src = format(player.config.urls.vimeo.iframe, id, params);
- iframe.setAttribute('src', src);
- iframe.setAttribute('allowfullscreen', '');
- iframe.setAttribute('allowtransparency', '');
- iframe.setAttribute('allow', 'autoplay');
-
- // Set the referrer policy if required
- if (!is.empty(config.referrerPolicy)) {
- iframe.setAttribute('referrerPolicy', config.referrerPolicy);
- }
-
- // Get poster, if already set
- const { poster } = player;
- // Inject the package
- const wrapper = createElement('div', { poster, class: player.config.classNames.embedContainer });
- wrapper.appendChild(iframe);
- player.media = replaceElement(wrapper, player.media);
-
- // Get poster image
- fetch(format(player.config.urls.vimeo.api, id), 'json').then(response => {
- if (is.empty(response)) {
- return;
- }
-
- // Get the URL for thumbnail
- const url = new URL(response[0].thumbnail_large);
-
- // Get original image
- url.pathname = `${url.pathname.split('_')[0]}.jpg`;
-
- // Set and show poster
- ui.setPoster.call(player, url.href).catch(() => {});
- });
-
- // Setup instance
- // https://github.com/vimeo/player.js
- player.embed = new window.Vimeo.Player(iframe, {
- autopause: player.config.autopause,
- muted: player.muted,
- });
-
- player.media.paused = true;
- player.media.currentTime = 0;
-
- // Disable native text track rendering
- if (player.supported.ui) {
- player.embed.disableTextTrack();
- }
-
- // Create a faux HTML5 API using the Vimeo API
- player.media.play = () => {
- assurePlaybackState.call(player, true);
- return player.embed.play();
- };
-
- player.media.pause = () => {
- assurePlaybackState.call(player, false);
- return player.embed.pause();
- };
-
- player.media.stop = () => {
- player.pause();
- player.currentTime = 0;
- };
-
- // Seeking
- let { currentTime } = player.media;
- Object.defineProperty(player.media, 'currentTime', {
- get() {
- return currentTime;
- },
- set(time) {
- // Vimeo will automatically play on seek if the video hasn't been played before
-
- // Get current paused state and volume etc
- const { embed, media, paused, volume } = player;
- const restorePause = paused && !embed.hasPlayed;
-
- // Set seeking state and trigger event
- media.seeking = true;
- triggerEvent.call(player, media, 'seeking');
-
- // If paused, mute until seek is complete
- Promise.resolve(restorePause && embed.setVolume(0))
- // Seek
- .then(() => embed.setCurrentTime(time))
- // Restore paused
- .then(() => restorePause && embed.pause())
- // Restore volume
- .then(() => restorePause && embed.setVolume(volume))
- .catch(() => {
- // Do nothing
- });
- },
- });
-
- // Playback speed
- let speed = player.config.speed.selected;
- Object.defineProperty(player.media, 'playbackRate', {
- get() {
- return speed;
- },
- set(input) {
- player.embed.setPlaybackRate(input).then(() => {
- speed = input;
- triggerEvent.call(player, player.media, 'ratechange');
- });
- },
- });
-
- // Volume
- let { volume } = player.config;
- Object.defineProperty(player.media, 'volume', {
- get() {
- return volume;
- },
- set(input) {
- player.embed.setVolume(input).then(() => {
- volume = input;
- 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 : false;
-
- player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {
- muted = toggle;
- triggerEvent.call(player, player.media, 'volumechange');
- });
- },
- });
-
- // Loop
- let { loop } = player.config;
- Object.defineProperty(player.media, 'loop', {
- get() {
- return loop;
- },
- set(input) {
- const toggle = is.boolean(input) ? input : player.config.loop.active;
-
- player.embed.setLoop(toggle).then(() => {
- loop = toggle;
- });
- },
- });
-
- // Source
- let currentSrc;
- player.embed
- .getVideoUrl()
- .then(value => {
- currentSrc = value;
- controls.setDownloadUrl.call(player);
- })
- .catch(error => {
- this.debug.warn(error);
- });
-
- Object.defineProperty(player.media, 'currentSrc', {
- get() {
- return currentSrc;
- },
- });
-
- // Ended
- Object.defineProperty(player.media, 'ended', {
- get() {
- return player.currentTime === player.duration;
- },
- });
-
- // Set aspect ratio based on video size
- Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => {
- const [width, height] = dimensions;
- player.embed.ratio = [width, height];
- setAspectRatio.call(this);
- });
-
- // Set autopause
- player.embed.setAutopause(player.config.autopause).then(state => {
- player.config.autopause = state;
- });
-
- // Get title
- player.embed.getVideoTitle().then(title => {
- player.config.title = title;
- ui.setTitle.call(this);
- });
-
- // Get current time
- player.embed.getCurrentTime().then(value => {
- currentTime = value;
- triggerEvent.call(player, player.media, 'timeupdate');
+ setup() {
+ const player = this;
+
+ // Add embed class for responsive
+ toggleClass(player.elements.wrapper, player.config.classNames.embed, true);
+
+ // Set speed options from config
+ player.options.speed = player.config.speed.options;
+
+ // Set intial ratio
+ setAspectRatio.call(player);
+
+ // Load the SDK if not already
+ if (!is.object(window.Vimeo)) {
+ loadScript(player.config.urls.vimeo.sdk)
+ .then(() => {
+ vimeo.ready.call(player);
+ })
+ .catch(error => {
+ player.debug.warn('Vimeo SDK (player.js) failed to load', error);
});
+ } else {
+ vimeo.ready.call(player);
+ }
+ },
+
+ // API Ready
+ ready() {
+ const player = this;
+ const config = player.config.vimeo;
+ const { premium, referrerPolicy, ...frameParams } = config;
+
+ // If the owner has a pro or premium account then we can hide controls etc
+ if (premium) {
+ Object.assign(frameParams, {
+ controls: false,
+ sidedock: false,
+ });
+ }
- // Get duration
- player.embed.getDuration().then(value => {
- player.media.duration = value;
- triggerEvent.call(player, player.media, 'durationchange');
- });
+ // Get Vimeo params for the iframe
+ const params = buildUrlParams({
+ loop: player.config.loop.active,
+ autoplay: player.autoplay,
+ muted: player.muted,
+ gesture: 'media',
+ playsinline: !this.config.fullscreen.iosNative,
+ ...frameParams,
+ });
+
+ // Get the source URL or ID
+ let source = player.media.getAttribute('src');
+
+ // Get from <div> if needed
+ if (is.empty(source)) {
+ source = player.media.getAttribute(player.config.attributes.embed.id);
+ }
- // Get captions
- player.embed.getTextTracks().then(tracks => {
- player.media.textTracks = tracks;
- captions.setup.call(player);
- });
+ const id = parseId(source);
+ // Build an iframe
+ const iframe = createElement('iframe');
+ const src = format(player.config.urls.vimeo.iframe, id, params);
+ iframe.setAttribute('src', src);
+ iframe.setAttribute('allowfullscreen', '');
+ iframe.setAttribute('allow', 'autoplay,fullscreen,picture-in-picture');
+
+ // Set the referrer policy if required
+ if (!is.empty(referrerPolicy)) {
+ iframe.setAttribute('referrerPolicy', referrerPolicy);
+ }
- player.embed.on('cuechange', ({ cues = [] }) => {
- const strippedCues = cues.map(cue => stripHTML(cue.text));
- captions.updateCues.call(player, strippedCues);
- });
+ // Inject the package
+ const { poster } = player;
+ if (premium) {
+ iframe.setAttribute('data-poster', poster);
+ player.media = replaceElement(iframe, player.media);
+ } else {
+ const wrapper = createElement('div', { class: player.config.classNames.embedContainer, 'data-poster': poster });
+ wrapper.appendChild(iframe);
+ player.media = replaceElement(wrapper, player.media);
+ }
- player.embed.on('loaded', () => {
- // Assure state and events are updated on autoplay
- player.embed.getPaused().then(paused => {
- assurePlaybackState.call(player, !paused);
- if (!paused) {
- triggerEvent.call(player, player.media, 'playing');
- }
- });
-
- if (is.element(player.embed.element) && player.supported.ui) {
- const frame = player.embed.element;
-
- // Fix keyboard focus issues
- // https://github.com/sampotts/plyr/issues/317
- frame.setAttribute('tabindex', -1);
- }
- });
+ // Get poster image
+ fetch(format(player.config.urls.vimeo.api, id), 'json').then(response => {
+ if (is.empty(response)) {
+ return;
+ }
- player.embed.on('bufferstart', () => {
- triggerEvent.call(player, player.media, 'waiting');
- });
+ // Get the URL for thumbnail
+ const url = new URL(response[0].thumbnail_large);
- player.embed.on('bufferend', () => {
- triggerEvent.call(player, player.media, 'playing');
- });
+ // Get original image
+ url.pathname = `${url.pathname.split('_')[0]}.jpg`;
- player.embed.on('play', () => {
- assurePlaybackState.call(player, true);
- triggerEvent.call(player, player.media, 'playing');
- });
+ // Set and show poster
+ ui.setPoster.call(player, url.href).catch(() => {});
+ });
- player.embed.on('pause', () => {
- assurePlaybackState.call(player, false);
- });
+ // Setup instance
+ // https://github.com/vimeo/player.js
+ player.embed = new window.Vimeo.Player(iframe, {
+ autopause: player.config.autopause,
+ muted: player.muted,
+ });
- player.embed.on('timeupdate', data => {
- player.media.seeking = false;
- currentTime = data.seconds;
- triggerEvent.call(player, player.media, 'timeupdate');
- });
+ player.media.paused = true;
+ player.media.currentTime = 0;
- player.embed.on('progress', data => {
- player.media.buffered = data.percent;
- triggerEvent.call(player, player.media, 'progress');
-
- // Check all loaded
- if (parseInt(data.percent, 10) === 1) {
- triggerEvent.call(player, player.media, 'canplaythrough');
- }
-
- // Get duration as if we do it before load, it gives an incorrect value
- // https://github.com/sampotts/plyr/issues/891
- player.embed.getDuration().then(value => {
- if (value !== player.media.duration) {
- player.media.duration = value;
- triggerEvent.call(player, player.media, 'durationchange');
- }
- });
- });
+ // Disable native text track rendering
+ if (player.supported.ui) {
+ player.embed.disableTextTrack();
+ }
- player.embed.on('seeked', () => {
- player.media.seeking = false;
- triggerEvent.call(player, player.media, 'seeked');
+ // Create a faux HTML5 API using the Vimeo API
+ player.media.play = () => {
+ assurePlaybackState.call(player, true);
+ return player.embed.play();
+ };
+
+ player.media.pause = () => {
+ assurePlaybackState.call(player, false);
+ return player.embed.pause();
+ };
+
+ player.media.stop = () => {
+ player.pause();
+ player.currentTime = 0;
+ };
+
+ // Seeking
+ let { currentTime } = player.media;
+ Object.defineProperty(player.media, 'currentTime', {
+ get() {
+ return currentTime;
+ },
+ set(time) {
+ // Vimeo will automatically play on seek if the video hasn't been played before
+
+ // Get current paused state and volume etc
+ const { embed, media, paused, volume } = player;
+ const restorePause = paused && !embed.hasPlayed;
+
+ // Set seeking state and trigger event
+ media.seeking = true;
+ triggerEvent.call(player, media, 'seeking');
+
+ // If paused, mute until seek is complete
+ Promise.resolve(restorePause && embed.setVolume(0))
+ // Seek
+ .then(() => embed.setCurrentTime(time))
+ // Restore paused
+ .then(() => restorePause && embed.pause())
+ // Restore volume
+ .then(() => restorePause && embed.setVolume(volume))
+ .catch(() => {
+ // Do nothing
+ });
+ },
+ });
+
+ // Playback speed
+ let speed = player.config.speed.selected;
+ Object.defineProperty(player.media, 'playbackRate', {
+ get() {
+ return speed;
+ },
+ set(input) {
+ player.embed
+ .setPlaybackRate(input)
+ .then(() => {
+ speed = input;
+ triggerEvent.call(player, player.media, 'ratechange');
+ })
+ .catch(() => {
+ // Cannot set Playback Rate, Video is probably not on Pro account
+ player.options.speed = [1];
+ });
+ },
+ });
+
+ // Volume
+ let { volume } = player.config;
+ Object.defineProperty(player.media, 'volume', {
+ get() {
+ return volume;
+ },
+ set(input) {
+ player.embed.setVolume(input).then(() => {
+ volume = input;
+ triggerEvent.call(player, player.media, 'volumechange');
});
-
- player.embed.on('ended', () => {
- player.media.paused = true;
- triggerEvent.call(player, player.media, 'ended');
+ },
+ });
+
+ // Muted
+ let { muted } = player.config;
+ Object.defineProperty(player.media, 'muted', {
+ get() {
+ return muted;
+ },
+ set(input) {
+ const toggle = is.boolean(input) ? input : false;
+
+ player.embed.setVolume(toggle ? 0 : player.config.volume).then(() => {
+ muted = toggle;
+ triggerEvent.call(player, player.media, 'volumechange');
});
-
- player.embed.on('error', detail => {
- player.media.error = detail;
- triggerEvent.call(player, player.media, 'error');
+ },
+ });
+
+ // Loop
+ let { loop } = player.config;
+ Object.defineProperty(player.media, 'loop', {
+ get() {
+ return loop;
+ },
+ set(input) {
+ const toggle = is.boolean(input) ? input : player.config.loop.active;
+
+ player.embed.setLoop(toggle).then(() => {
+ loop = toggle;
});
-
- // Rebuild UI
- setTimeout(() => ui.build.call(player), 0);
- },
+ },
+ });
+
+ // Source
+ let currentSrc;
+ player.embed
+ .getVideoUrl()
+ .then(value => {
+ currentSrc = value;
+ controls.setDownloadUrl.call(player);
+ })
+ .catch(error => {
+ this.debug.warn(error);
+ });
+
+ Object.defineProperty(player.media, 'currentSrc', {
+ get() {
+ return currentSrc;
+ },
+ });
+
+ // Ended
+ Object.defineProperty(player.media, 'ended', {
+ get() {
+ return player.currentTime === player.duration;
+ },
+ });
+
+ // Set aspect ratio based on video size
+ Promise.all([player.embed.getVideoWidth(), player.embed.getVideoHeight()]).then(dimensions => {
+ const [width, height] = dimensions;
+ player.embed.ratio = [width, height];
+ setAspectRatio.call(this);
+ });
+
+ // Set autopause
+ player.embed.setAutopause(player.config.autopause).then(state => {
+ player.config.autopause = state;
+ });
+
+ // Get title
+ player.embed.getVideoTitle().then(title => {
+ player.config.title = title;
+ ui.setTitle.call(this);
+ });
+
+ // Get current time
+ player.embed.getCurrentTime().then(value => {
+ currentTime = value;
+ triggerEvent.call(player, player.media, 'timeupdate');
+ });
+
+ // Get duration
+ player.embed.getDuration().then(value => {
+ player.media.duration = value;
+ triggerEvent.call(player, player.media, 'durationchange');
+ });
+
+ // Get captions
+ player.embed.getTextTracks().then(tracks => {
+ player.media.textTracks = tracks;
+ captions.setup.call(player);
+ });
+
+ player.embed.on('cuechange', ({ cues = [] }) => {
+ const strippedCues = cues.map(cue => stripHTML(cue.text));
+ captions.updateCues.call(player, strippedCues);
+ });
+
+ player.embed.on('loaded', () => {
+ // Assure state and events are updated on autoplay
+ player.embed.getPaused().then(paused => {
+ assurePlaybackState.call(player, !paused);
+ if (!paused) {
+ triggerEvent.call(player, player.media, 'playing');
+ }
+ });
+
+ if (is.element(player.embed.element) && player.supported.ui) {
+ const frame = player.embed.element;
+
+ // Fix keyboard focus issues
+ // https://github.com/sampotts/plyr/issues/317
+ frame.setAttribute('tabindex', -1);
+ }
+ });
+
+ player.embed.on('bufferstart', () => {
+ triggerEvent.call(player, player.media, 'waiting');
+ });
+
+ player.embed.on('bufferend', () => {
+ triggerEvent.call(player, player.media, 'playing');
+ });
+
+ player.embed.on('play', () => {
+ assurePlaybackState.call(player, true);
+ triggerEvent.call(player, player.media, 'playing');
+ });
+
+ player.embed.on('pause', () => {
+ assurePlaybackState.call(player, false);
+ });
+
+ player.embed.on('timeupdate', data => {
+ player.media.seeking = false;
+ currentTime = data.seconds;
+ triggerEvent.call(player, player.media, 'timeupdate');
+ });
+
+ player.embed.on('progress', data => {
+ player.media.buffered = data.percent;
+ triggerEvent.call(player, player.media, 'progress');
+
+ // Check all loaded
+ if (parseInt(data.percent, 10) === 1) {
+ triggerEvent.call(player, player.media, 'canplaythrough');
+ }
+
+ // Get duration as if we do it before load, it gives an incorrect value
+ // https://github.com/sampotts/plyr/issues/891
+ player.embed.getDuration().then(value => {
+ if (value !== player.media.duration) {
+ player.media.duration = value;
+ triggerEvent.call(player, player.media, 'durationchange');
+ }
+ });
+ });
+
+ player.embed.on('seeked', () => {
+ player.media.seeking = false;
+ triggerEvent.call(player, player.media, 'seeked');
+ });
+
+ player.embed.on('ended', () => {
+ player.media.paused = true;
+ triggerEvent.call(player, player.media, 'ended');
+ });
+
+ player.embed.on('error', detail => {
+ player.media.error = detail;
+ triggerEvent.call(player, player.media, 'error');
+ });
+
+ // Rebuild UI
+ setTimeout(() => ui.build.call(player), 0);
+ },
};
export default vimeo;
diff --git a/src/js/plugins/youtube.js b/src/js/plugins/youtube.js
index 8c65b1dc..89a75d89 100644
--- a/src/js/plugins/youtube.js
+++ b/src/js/plugins/youtube.js
@@ -15,426 +15,426 @@ import { setAspectRatio } from '../utils/style';
// Parse YouTube ID from URL
function parseId(url) {
- if (is.empty(url)) {
- return null;
- }
+ if (is.empty(url)) {
+ return null;
+ }
- const regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
- return url.match(regex) ? RegExp.$2 : url;
+ const regex = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/;
+ return url.match(regex) ? RegExp.$2 : url;
}
// Set playback state and trigger change (only on actual change)
function assurePlaybackState(play) {
- if (play && !this.embed.hasPlayed) {
- this.embed.hasPlayed = true;
- }
- if (this.media.paused === play) {
- this.media.paused = !play;
- triggerEvent.call(this, this.media, play ? 'play' : 'pause');
- }
+ if (play && !this.embed.hasPlayed) {
+ this.embed.hasPlayed = true;
+ }
+ if (this.media.paused === play) {
+ this.media.paused = !play;
+ triggerEvent.call(this, this.media, play ? 'play' : 'pause');
+ }
}
function getHost(config) {
- if (config.noCookie) {
- return 'https://www.youtube-nocookie.com';
- }
+ if (config.noCookie) {
+ return 'https://www.youtube-nocookie.com';
+ }
- if (window.location.protocol === 'http:') {
- return 'http://www.youtube.com';
- }
+ if (window.location.protocol === 'http:') {
+ return 'http://www.youtube.com';
+ }
- // Use YouTube's default
- return undefined;
+ // Use YouTube's default
+ return undefined;
}
const youtube = {
- setup() {
- // Add embed class for responsive
- toggleClass(this.elements.wrapper, this.config.classNames.embed, true);
-
- // Setup API
- if (is.object(window.YT) && is.function(window.YT.Player)) {
- youtube.ready.call(this);
- } else {
- // Reference current global callback
- const callback = window.onYouTubeIframeAPIReady;
-
- // Set callback to process queue
- window.onYouTubeIframeAPIReady = () => {
- // Call global callback if set
- if (is.function(callback)) {
- callback();
- }
-
- youtube.ready.call(this);
- };
-
- // Load the SDK
- loadScript(this.config.urls.youtube.sdk).catch(error => {
- this.debug.warn('YouTube API failed to load', error);
- });
+ setup() {
+ // Add embed class for responsive
+ toggleClass(this.elements.wrapper, this.config.classNames.embed, true);
+
+ // Setup API
+ if (is.object(window.YT) && is.function(window.YT.Player)) {
+ youtube.ready.call(this);
+ } else {
+ // Reference current global callback
+ const callback = window.onYouTubeIframeAPIReady;
+
+ // Set callback to process queue
+ window.onYouTubeIframeAPIReady = () => {
+ // Call global callback if set
+ if (is.function(callback)) {
+ callback();
}
- },
- // Get the media title
- getTitle(videoId) {
- const url = format(this.config.urls.youtube.api, videoId);
+ youtube.ready.call(this);
+ };
- fetch(url)
- .then(data => {
- if (is.object(data)) {
- const { title, height, width } = data;
+ // Load the SDK
+ loadScript(this.config.urls.youtube.sdk).catch(error => {
+ this.debug.warn('YouTube API failed to load', error);
+ });
+ }
+ },
- // Set title
- this.config.title = title;
- ui.setTitle.call(this);
+ // Get the media title
+ getTitle(videoId) {
+ const url = format(this.config.urls.youtube.api, videoId);
- // Set aspect ratio
- this.embed.ratio = [width, height];
- }
+ fetch(url)
+ .then(data => {
+ if (is.object(data)) {
+ const { title, height, width } = data;
- setAspectRatio.call(this);
- })
- .catch(() => {
- // Set aspect ratio
- setAspectRatio.call(this);
- });
- },
-
- // API ready
- ready() {
- const player = this;
- // Ignore already setup (race condition)
- const currentId = player.media && player.media.getAttribute('id');
- if (!is.empty(currentId) && currentId.startsWith('youtube-')) {
- return;
+ // Set title
+ this.config.title = title;
+ ui.setTitle.call(this);
+
+ // Set aspect ratio
+ this.embed.ratio = [width, height];
}
- // Get the source URL or ID
- let source = player.media.getAttribute('src');
+ setAspectRatio.call(this);
+ })
+ .catch(() => {
+ // Set aspect ratio
+ setAspectRatio.call(this);
+ });
+ },
+
+ // API ready
+ ready() {
+ const player = this;
+ // Ignore already setup (race condition)
+ const currentId = player.media && player.media.getAttribute('id');
+ if (!is.empty(currentId) && currentId.startsWith('youtube-')) {
+ return;
+ }
+
+ // Get the source URL or ID
+ let source = player.media.getAttribute('src');
+
+ // Get from <div> if needed
+ if (is.empty(source)) {
+ source = player.media.getAttribute(this.config.attributes.embed.id);
+ }
- // Get from <div> if needed
- if (is.empty(source)) {
- source = player.media.getAttribute(this.config.attributes.embed.id);
+ // Replace the <iframe> with a <div> due to YouTube API issues
+ const videoId = parseId(source);
+ const id = generateId(player.provider);
+ // Get poster, if already set
+ const { poster } = player;
+ // Replace media element
+ const container = createElement('div', { id, 'data-poster': poster });
+ player.media = replaceElement(container, player.media);
+
+ // Id to poster wrapper
+ 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) // Higest quality and unpadded
+ .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(() => {});
+
+ const config = player.config.youtube;
+
+ // Setup instance
+ // https://developers.google.com/youtube/iframe_api_reference
+ player.embed = new window.YT.Player(id, {
+ videoId,
+ host: getHost(config),
+ playerVars: extend(
+ {},
+ {
+ autoplay: player.config.autoplay ? 1 : 0, // Autoplay
+ hl: player.config.hl, // iframe interface language
+ controls: player.supported.ui ? 0 : 1, // Only show controls if not fully supported
+ disablekb: 1, // Disable keyboard as we handle it
+ playsinline: !player.config.fullscreen.iosNative ? 1 : 0, // Allow iOS inline playback
+ // 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 occured';
+
+ 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);
+ },
+ });
- // Replace the <iframe> with a <div> due to YouTube API issues
- const videoId = parseId(source);
- const id = generateId(player.provider);
- // Get poster, if already set
- const { poster } = player;
- // Replace media element
- const container = createElement('div', { id, poster });
- player.media = replaceElement(container, player.media);
-
- // Id to poster wrapper
- 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) // Higest quality and unpadded
- .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(() => {});
-
- const config = player.config.youtube;
-
- // Setup instance
- // https://developers.google.com/youtube/iframe_api_reference
- player.embed = new window.YT.Player(id, {
- videoId,
- host: getHost(config),
- playerVars: extend(
- {},
- {
- autoplay: player.config.autoplay ? 1 : 0, // Autoplay
- hl: player.config.hl, // iframe interface language
- controls: player.supported.ui ? 0 : 1, // Only show controls if not fully supported
- disablekb: 1, // Disable keyboard as we handle it
- playsinline: !player.config.fullscreen.iosNative ? 1 : 0, // Allow iOS inline playback
- // 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 occured';
-
- 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']();
- 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) {
- 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
- 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 (!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;
-
- default:
- break;
- }
-
- triggerEvent.call(player, player.elements.container, 'statechange', false, {
- code: event.data,
- });
- },
+ // 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']();
+ 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) {
+ 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
+ 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 (!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;
+
+ default:
+ break;
+ }
+
+ triggerEvent.call(player, player.elements.container, 'statechange', false, {
+ code: event.data,
+ });
+ },
+ },
+ });
+ },
};
export default youtube;