Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add mediasession support #8309

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion sandbox/load-media.html.example
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@

<script>
var vid = document.getElementById('vid1');
var player = videojs(vid);
var player = videojs(vid, {
mediaSession: true
});

player.log('window.player created', player);

Expand Down
132 changes: 132 additions & 0 deletions src/js/mediasession.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import window from 'global/window';
import {getMimetype} from './utils/mimetypes';

/**
* @method initMediaSession Sets up media session if supported and configured
* @this { import('./player').default } Player
*/
export const initMediaSession = function() {
if (!this.options_.mediaSession || !('mediaSession' in window.navigator)) {
return;
}
const ms = window.navigator.mediaSession;
const defaultSkipTime = 15;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question, do you think it would be a good idea to use skipButtons values if they are available? This would allow a unified experience between the player and the mediaSession.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that makes sense, yes.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think about keeping this property as it is for now and adding this modification via another PR? Because it would be nice to have the titleBar values as well.


const actionHandlers = [
['play', () => {
this.play();
}],
['pause', () => {
this.pause();
}],
['stop', () => {
this.pause();
this.currentTime(0);
}],
// videojs-contrib-ads
['seekbackward', (details) => {
if (this.usingPlugin('ads') && this.ads.inAdBreak()) {
return;
}
this.currentTime(Math.max(0, this.currentTime() - (details.skipOffset || defaultSkipTime)));
}],
['seekforward', (details) => {
if (this.usingPlugin('ads') && this.ads.inAdBreak()) {
return;
}
this.currentTime(Math.min(this.duration(), this.currentTime() + (details.skipOffset || defaultSkipTime)));
}],
['seekto', (details) => {
if (this.usingPlugin('ads') && this.ads.inAdBreak()) {
return;
}
this.currentTime(details.seekTime);
}]
];

// Using Google's recommendation that expects some handler may not be settable, especially as we
// want to support older Chrome
// https://web.dev/media-session/#let-users-control-whats-playing
for (const [action, handler] of actionHandlers) {
try {
ms.setActionHandler(action, handler);
} catch (error) {
this.log.debug(`Couldn't register media session action "${action}".`);
}
}

const setUpMediaSessionPlaylist = () => {
try {
ms.setActionHandler('previoustrack', () => {
this.playlist.previous();
});
ms.setActionHandler('nexttrack', () => {
this.playlist.next();
});
} catch (error) {
this.log.debug('Couldn\'t register playlist media session actions.');
}
};

// Only setup playlist handlers if / when playlist plugin is present
this.on('pluginsetup:playlist', setUpMediaSessionPlaylist);

/**
*
* Updates the mediaSession metadata. Fires `updatemediasession` as an
* opportunity to modify the metadata
*
* @fires Player#updatemediasession
*/
const updateMediaSession = () => {
const currentMedia = this.getMedia();
const playlistItem = this.usingPlugin('playlist') ? Object.assign({}, this.playlist()[this.playlist.currentItem()]) : {};
const mediaSessionData = {
title: currentMedia.title || playlistItem.name || '',
artist: currentMedia.artist || playlistItem.artist || '',
album: currentMedia.album || playlistItem.album || ''
};

if (currentMedia.artwork) {
mediaSessionData.artwork = currentMedia.artwork;
} else if (playlistItem.artwork) {
mediaSessionData.artwork = playlistItem.artwork;
} else if (this.poster()) {
mediaSessionData.artwork = [{
src: this.poster(),
type: getMimetype(this.poster())
}];
}

// This allows the metadata to be updated before being set, e.g. if loadMedia() is not used.
this.trigger('updatemediasession', mediaSessionData);

ms.metadata = new window.MediaMetadata(mediaSessionData);
};

const updatePositionState = () => {
const dur = parseFloat(this.duration());
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Question, is there a case that requires a parseFloat?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That can probably go

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From a specification perspective (w3c, whatwg), it seems safe to remove the parseFloat, especially as the condition immediately following it prevents any NaN or Infinity. However, if you prefer to keep it, that's fine too.


if (Number.isFinite(dur)) {
ms.setPositionState({
duration: dur,
playbackRate: this.playbackRate(),
position: this.currentTime()
});
}
};

this.on('playing', () => {
// Called on each `playing` rather than `sourceset`, in case of multiple players on a page
updateMediaSession();
ms.playbackState = 'playing';
});

this.on('paused', () => {
mister-ben marked this conversation as resolved.
Show resolved Hide resolved
ms.playbackState = 'paused';
});

if ('setPositionState' in ms) {
this.on('timeupdate', updatePositionState);
}
};
5 changes: 5 additions & 0 deletions src/js/player.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {getMimetype, findMimetype} from './utils/mimetypes';
import {hooks} from './utils/hooks';
import {isObject} from './utils/obj';
import keycode from 'keycode';
import { initMediaSession } from './mediasession.js';
import icons from '../images/icons.svg';

// The following imports are used only to ensure that the corresponding modules
Expand Down Expand Up @@ -603,6 +604,10 @@ class Player extends Component {
this.audioPosterMode(this.options_.audioPosterMode);
this.audioOnlyMode(this.options_.audioOnlyMode);
});

// Set up media session if supported
initMediaSession.call(this);

}

/**
Expand Down