mpvVideoPlayer.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. /* eslint-disable indent */
  2. function getMediaStreamAudioTracks(mediaSource) {
  3. return mediaSource.MediaStreams.filter(function (s) {
  4. return s.Type === 'Audio';
  5. });
  6. }
  7. class mpvVideoPlayer {
  8. constructor({ events, loading, appRouter, globalize, appHost, appSettings }) {
  9. this.events = events;
  10. this.loading = loading;
  11. this.appRouter = appRouter;
  12. this.globalize = globalize;
  13. this.appHost = appHost;
  14. this.appSettings = appSettings;
  15. /**
  16. * @type {string}
  17. */
  18. this.name = 'MPV Video Player';
  19. /**
  20. * @type {string}
  21. */
  22. this.type = 'mediaplayer';
  23. /**
  24. * @type {string}
  25. */
  26. this.id = 'mpvvideoplayer';
  27. this.syncPlayWrapAs = 'htmlvideoplayer';
  28. this.priority = -1;
  29. this.useFullSubtitleUrls = true;
  30. /**
  31. * @type {boolean}
  32. */
  33. this.isFetching = false;
  34. /**
  35. * @type {HTMLDivElement | null | undefined}
  36. */
  37. this._videoDialog = undefined;
  38. /**
  39. * @type {number | undefined}
  40. */
  41. this._subtitleTrackIndexToSetOnPlaying = undefined;
  42. /**
  43. * @type {number | null}
  44. */
  45. this._audioTrackIndexToSetOnPlaying = undefined;
  46. /**
  47. * @type {boolean | undefined}
  48. */
  49. this._showTrackOffset = undefined;
  50. /**
  51. * @type {number | undefined}
  52. */
  53. this._currentTrackOffset = undefined;
  54. /**
  55. * @type {string[] | undefined}
  56. */
  57. this._supportedFeatures = undefined;
  58. /**
  59. * @type {string | undefined}
  60. */
  61. this._currentSrc = undefined;
  62. /**
  63. * @type {boolean | undefined}
  64. */
  65. this._started = undefined;
  66. /**
  67. * @type {boolean | undefined}
  68. */
  69. this._timeUpdated = undefined;
  70. /**
  71. * @type {number | null | undefined}
  72. */
  73. this._currentTime = undefined;
  74. /**
  75. * @private (used in other files)
  76. * @type {any | undefined}
  77. */
  78. this._currentPlayOptions = undefined;
  79. /**
  80. * @type {any | undefined}
  81. */
  82. this._lastProfile = undefined;
  83. /**
  84. * @type {number | undefined}
  85. */
  86. this._duration = undefined;
  87. /**
  88. * @type {boolean}
  89. */
  90. this._paused = false;
  91. /**
  92. * @type {int}
  93. */
  94. this._volume = 100;
  95. /**
  96. * @type {boolean}
  97. */
  98. this._muted = false;
  99. /**
  100. * @type {float}
  101. */
  102. this._playRate = 1;
  103. /**
  104. * @type {boolean}
  105. */
  106. this._hasConnection = false;
  107. /**
  108. * @private
  109. */
  110. this.onEnded = () => {
  111. this.onEndedInternal();
  112. };
  113. /**
  114. * @private
  115. */
  116. this.onTimeUpdate = (time) => {
  117. if (time && !this._timeUpdated) {
  118. this._timeUpdated = true;
  119. }
  120. this._currentTime = time;
  121. this.events.trigger(this, 'timeupdate');
  122. };
  123. /**
  124. * @private
  125. */
  126. this.onNavigatedToOsd = () => {
  127. const dlg = this._videoDialog;
  128. if (dlg) {
  129. dlg.style.zIndex = 'unset';
  130. }
  131. };
  132. /**
  133. * @private
  134. */
  135. this.onPlaying = () => {
  136. if (!this._started) {
  137. this._started = true;
  138. this.loading.hide();
  139. const volume = this.getSavedVolume() * 100;
  140. this.setVolume(volume, false);
  141. this.setPlaybackRate(1);
  142. this.setMute(false, false);
  143. if (this._currentPlayOptions.fullscreen) {
  144. this.appRouter.showVideoOsd().then(this.onNavigatedToOsd);
  145. } else {
  146. this.appRouter.setTransparency('backdrop');
  147. this._videoDialog.dlg.style.zIndex = 'unset';
  148. }
  149. // Need to override default style.
  150. this._videoDialog.style.setProperty('background', 'transparent', 'important');
  151. }
  152. if (this._paused) {
  153. this._paused = false;
  154. this.events.trigger(this, 'unpause');
  155. }
  156. this.events.trigger(this, 'playing');
  157. };
  158. /**
  159. * @private
  160. */
  161. this.onPause = () => {
  162. this._paused = true;
  163. // For Syncplay ready notification
  164. this.events.trigger(this, 'pause');
  165. };
  166. this.onWaiting = () => {
  167. this.events.trigger(this, 'waiting');
  168. };
  169. /**
  170. * @private
  171. * @param e {Event} The event received from the `<video>` element
  172. */
  173. this.onError = (error) => {
  174. console.error(`media element error: ${error}`);
  175. this.events.trigger(this, 'error', [
  176. {
  177. type: 'mediadecodeerror'
  178. }
  179. ]);
  180. };
  181. this.onDuration = (duration) => {
  182. this._duration = duration;
  183. };
  184. }
  185. currentSrc() {
  186. return this._currentSrc;
  187. }
  188. async play(options) {
  189. this._started = false;
  190. this._timeUpdated = false;
  191. this._currentTime = null;
  192. this.resetSubtitleOffset();
  193. this.loading.show();
  194. window.api.power.setScreensaverEnabled(false);
  195. const elem = await this.createMediaElement(options);
  196. return await this.setCurrentSrc(elem, options);
  197. }
  198. getSavedVolume() {
  199. return this.appSettings.get('volume') || 1;
  200. }
  201. /**
  202. * @private
  203. */
  204. getSubtitleParam() {
  205. const options = this._currentPlayOptions;
  206. if (this._subtitleTrackIndexToSetOnPlaying != null && this._subtitleTrackIndexToSetOnPlaying >= 0) {
  207. const initialSubtitleStream = options.mediaSource.MediaStreams[this._subtitleTrackIndexToSetOnPlaying];
  208. if (!initialSubtitleStream || initialSubtitleStream.DeliveryMethod === 'Encode') {
  209. this._subtitleTrackIndexToSetOnPlaying = -1;
  210. } else if (initialSubtitleStream.DeliveryMethod === 'External') {
  211. return '#,' + initialSubtitleStream.DeliveryUrl;
  212. }
  213. }
  214. if (this._subtitleTrackIndexToSetOnPlaying == -1 || this._subtitleTrackIndexToSetOnPlaying == null) {
  215. return '';
  216. }
  217. return '#' + this._subtitleTrackIndexToSetOnPlaying;
  218. }
  219. tryGetFramerate(options) {
  220. if (options.mediaSource && options.mediaSource.MediaStreams) {
  221. for (let stream of options.mediaSource.MediaStreams) {
  222. if (stream.Type == "Video") {
  223. return stream.RealFrameRate || stream.AverageFrameRate || null;
  224. }
  225. }
  226. }
  227. }
  228. /**
  229. * @private
  230. */
  231. setCurrentSrc(elem, options) {
  232. return new Promise((resolve) => {
  233. const val = options.url;
  234. this._currentSrc = val;
  235. console.debug(`playing url: ${val}`);
  236. // Convert to seconds
  237. const ms = (options.playerStartPositionTicks || 0) / 10000;
  238. this._currentPlayOptions = options;
  239. this._subtitleTrackIndexToSetOnPlaying = options.mediaSource.DefaultSubtitleStreamIndex == null ? -1 : options.mediaSource.DefaultSubtitleStreamIndex;
  240. this._audioTrackIndexToSetOnPlaying = options.playMethod === 'Transcode' ? null : options.mediaSource.DefaultAudioStreamIndex;
  241. const streamdata = {type: 'video', headers: {'User-Agent': 'JellyfinMediaPlayer'}, metadata: options.item, media: {}};
  242. const fps = this.tryGetFramerate(options);
  243. if (fps) {
  244. streamdata.frameRate = fps;
  245. }
  246. const player = window.api.player;
  247. player.load(val,
  248. { startMilliseconds: ms, autoplay: true },
  249. streamdata,
  250. (this._audioTrackIndexToSetOnPlaying != null)
  251. ? '#' + this._audioTrackIndexToSetOnPlaying : '#1',
  252. this.getSubtitleParam(),
  253. resolve);
  254. });
  255. }
  256. setSubtitleStreamIndex(index) {
  257. this._subtitleTrackIndexToSetOnPlaying = index;
  258. window.api.player.setSubtitleStream(this.getSubtitleParam());
  259. }
  260. resetSubtitleOffset() {
  261. this._currentTrackOffset = 0;
  262. this._showTrackOffset = false;
  263. window.api.player.setSubtitleDelay(0);
  264. }
  265. enableShowingSubtitleOffset() {
  266. this._showTrackOffset = true;
  267. }
  268. disableShowingSubtitleOffset() {
  269. this._showTrackOffset = false;
  270. }
  271. isShowingSubtitleOffsetEnabled() {
  272. return this._showTrackOffset;
  273. }
  274. setSubtitleOffset(offset) {
  275. const offsetValue = parseFloat(offset);
  276. this._currentTrackOffset = offsetValue;
  277. window.api.player.setSubtitleDelay(Math.round(offsetValue * 1000));
  278. }
  279. getSubtitleOffset() {
  280. return this._currentTrackOffset;
  281. }
  282. /**
  283. * @private
  284. */
  285. isAudioStreamSupported() {
  286. return true;
  287. }
  288. /**
  289. * @private
  290. */
  291. getSupportedAudioStreams() {
  292. const profile = this._lastProfile;
  293. return getMediaStreamAudioTracks(this._currentPlayOptions.mediaSource).filter((stream) => {
  294. return this.isAudioStreamSupported(stream, profile);
  295. });
  296. }
  297. setAudioStreamIndex(index) {
  298. this._audioTrackIndexToSetOnPlaying = index;
  299. const streams = this.getSupportedAudioStreams();
  300. if (streams.length < 2) {
  301. // If there's only one supported stream then trust that the player will handle it on it's own
  302. return;
  303. }
  304. window.api.player.setAudioStream(index != -1 ? '#' + index : '');
  305. }
  306. onEndedInternal() {
  307. const stopInfo = {
  308. src: this._currentSrc
  309. };
  310. this.events.trigger(this, 'stopped', [stopInfo]);
  311. this._currentTime = null;
  312. this._currentSrc = null;
  313. this._currentPlayOptions = null;
  314. }
  315. stop(destroyPlayer) {
  316. window.api.player.stop();
  317. window.api.power.setScreensaverEnabled(true);
  318. this.onEndedInternal();
  319. if (destroyPlayer) {
  320. this.destroy();
  321. }
  322. return Promise.resolve();
  323. }
  324. destroy() {
  325. window.api.player.stop();
  326. window.api.power.setScreensaverEnabled(true);
  327. this.appRouter.setTransparency('none');
  328. document.body.classList.remove('hide-scroll');
  329. const player = window.api.player;
  330. this._hasConnection = false;
  331. player.playing.disconnect(this.onPlaying);
  332. player.positionUpdate.disconnect(this.onTimeUpdate);
  333. player.finished.disconnect(this.onEnded);
  334. this._duration = undefined;
  335. player.updateDuration.disconnect(this.onDuration);
  336. player.error.disconnect(this.onError);
  337. player.paused.disconnect(this.onPause);
  338. const dlg = this._videoDialog;
  339. if (dlg) {
  340. this._videoDialog = null;
  341. dlg.parentNode.removeChild(dlg);
  342. }
  343. // Only supporting QtWebEngine here
  344. if (document.webkitIsFullScreen && document.webkitExitFullscreen) {
  345. document.webkitExitFullscreen();
  346. }
  347. }
  348. /**
  349. * @private
  350. */
  351. createMediaElement(options) {
  352. const dlg = document.querySelector('.videoPlayerContainer');
  353. if (!dlg) {
  354. this.loading.show();
  355. const dlg = document.createElement('div');
  356. dlg.classList.add('videoPlayerContainer');
  357. dlg.style.position = 'fixed';
  358. dlg.style.top = 0;
  359. dlg.style.bottom = 0;
  360. dlg.style.left = 0;
  361. dlg.style.right = 0;
  362. dlg.style.display = 'flex';
  363. dlg.style.alignItems = 'center';
  364. if (options.fullscreen) {
  365. dlg.style.zIndex = 1000;
  366. }
  367. const html = '';
  368. dlg.innerHTML = html;
  369. document.body.insertBefore(dlg, document.body.firstChild);
  370. this._videoDialog = dlg;
  371. const player = window.api.player;
  372. if (!this._hasConnection) {
  373. this._hasConnection = true;
  374. player.playing.connect(this.onPlaying);
  375. player.positionUpdate.connect(this.onTimeUpdate);
  376. player.finished.connect(this.onEnded);
  377. player.updateDuration.connect(this.onDuration);
  378. player.error.connect(this.onError);
  379. player.paused.connect(this.onPause);
  380. }
  381. if (options.fullscreen) {
  382. // At this point, we must hide the scrollbar placeholder, so it's not being displayed while the item is being loaded
  383. document.body.classList.add('hide-scroll');
  384. }
  385. return Promise.resolve();
  386. } else {
  387. // we need to hide scrollbar when starting playback from page with animated background
  388. if (options.fullscreen) {
  389. document.body.classList.add('hide-scroll');
  390. }
  391. return Promise.resolve();
  392. }
  393. }
  394. /**
  395. * @private
  396. */
  397. canPlayMediaType(mediaType) {
  398. return (mediaType || '').toLowerCase() === 'video';
  399. }
  400. /**
  401. * @private
  402. */
  403. supportsPlayMethod() {
  404. return true;
  405. }
  406. /**
  407. * @private
  408. */
  409. getDeviceProfile(item, options) {
  410. if (this.appHost.getDeviceProfile) {
  411. return this.appHost.getDeviceProfile(item, options);
  412. }
  413. return Promise.resolve({});
  414. }
  415. /**
  416. * @private
  417. */
  418. static getSupportedFeatures() {
  419. return ['PlaybackRate'];
  420. }
  421. supports(feature) {
  422. if (!this._supportedFeatures) {
  423. this._supportedFeatures = mpvVideoPlayer.getSupportedFeatures();
  424. }
  425. return this._supportedFeatures.includes(feature);
  426. }
  427. // Save this for when playback stops, because querying the time at that point might return 0
  428. currentTime(val) {
  429. if (val != null) {
  430. window.api.player.seekTo(val);
  431. return;
  432. }
  433. return this._currentTime;
  434. }
  435. currentTimeAsync() {
  436. return new Promise((resolve) => {
  437. window.api.player.getPosition(resolve);
  438. });
  439. }
  440. duration() {
  441. if (this._duration) {
  442. return this._duration;
  443. }
  444. return null;
  445. }
  446. canSetAudioStreamIndex() {
  447. return true;
  448. }
  449. static onPictureInPictureError(err) {
  450. console.error(`Picture in picture error: ${err}`);
  451. }
  452. setPictureInPictureEnabled() {}
  453. isPictureInPictureEnabled() {
  454. return false;
  455. }
  456. isAirPlayEnabled() {
  457. return false;
  458. }
  459. setAirPlayEnabled() {}
  460. setBrightness() {}
  461. getBrightness() {
  462. return 100;
  463. }
  464. seekable() {
  465. return Boolean(this._duration);
  466. }
  467. pause() {
  468. window.api.player.pause();
  469. }
  470. // This is a retry after error
  471. resume() {
  472. this._paused = false;
  473. window.api.player.play();
  474. }
  475. unpause() {
  476. window.api.player.play();
  477. }
  478. paused() {
  479. return this._paused;
  480. }
  481. setPlaybackRate(value) {
  482. this._playRate = value;
  483. window.api.player.setPlaybackRate(value * 1000);
  484. }
  485. getPlaybackRate() {
  486. return this._playRate;
  487. }
  488. getSupportedPlaybackRates() {
  489. return [{
  490. name: '0.5x',
  491. id: 0.5
  492. }, {
  493. name: '0.75x',
  494. id: 0.75
  495. }, {
  496. name: '1x',
  497. id: 1.0
  498. }, {
  499. name: '1.25x',
  500. id: 1.25
  501. }, {
  502. name: '1.5x',
  503. id: 1.5
  504. }, {
  505. name: '1.75x',
  506. id: 1.75
  507. }, {
  508. name: '2x',
  509. id: 2.0
  510. }];
  511. }
  512. saveVolume(value) {
  513. if (value) {
  514. this.appSettings.set('volume', value);
  515. }
  516. }
  517. setVolume(val, save = true) {
  518. this._volume = val;
  519. if (save) {
  520. this.saveVolume((val || 100) / 100);
  521. this.events.trigger(this, 'volumechange');
  522. }
  523. window.api.player.setVolume(val);
  524. }
  525. getVolume() {
  526. return this._volume;
  527. }
  528. volumeUp() {
  529. this.setVolume(Math.min(this.getVolume() + 2, 100));
  530. }
  531. volumeDown() {
  532. this.setVolume(Math.max(this.getVolume() - 2, 0));
  533. }
  534. setMute(mute, triggerEvent = true) {
  535. this._muted = mute;
  536. window.api.player.setMuted(mute);
  537. if (triggerEvent) {
  538. this.events.trigger(this, 'volumechange');
  539. }
  540. }
  541. isMuted() {
  542. return this._muted;
  543. }
  544. setAspectRatio() {
  545. }
  546. getAspectRatio() {
  547. return this._currentAspectRatio || 'auto';
  548. }
  549. getSupportedAspectRatios() {
  550. return [{
  551. name: this.globalize.translate('Auto'),
  552. id: 'auto'
  553. }];
  554. }
  555. togglePictureInPicture() {
  556. }
  557. toggleAirPlay() {
  558. }
  559. getBufferedRanges() {
  560. return [];
  561. }
  562. getStats() {
  563. const playOptions = this._currentPlayOptions || [];
  564. const categories = [];
  565. if (!this._currentPlayOptions) {
  566. return Promise.resolve({
  567. categories: categories
  568. });
  569. }
  570. const mediaCategory = {
  571. stats: [],
  572. type: 'media'
  573. };
  574. categories.push(mediaCategory);
  575. if (playOptions.url) {
  576. // create an anchor element (note: no need to append this element to the document)
  577. let link = document.createElement('a');
  578. // set href to any path
  579. link.setAttribute('href', playOptions.url);
  580. const protocol = (link.protocol || '').replace(':', '');
  581. if (protocol) {
  582. mediaCategory.stats.push({
  583. label: this.globalize.translate('LabelProtocol'),
  584. value: protocol
  585. });
  586. }
  587. link = null;
  588. }
  589. mediaCategory.stats.push({
  590. label: this.globalize.translate('LabelStreamType'),
  591. value: 'Video'
  592. });
  593. const videoCategory = {
  594. stats: [],
  595. type: 'video'
  596. };
  597. categories.push(videoCategory);
  598. const audioCategory = {
  599. stats: [],
  600. type: 'audio'
  601. };
  602. categories.push(audioCategory);
  603. return Promise.resolve({
  604. categories: categories
  605. });
  606. }
  607. }
  608. /* eslint-enable indent */
  609. window._mpvVideoPlayer = mpvVideoPlayer;