mpvVideoPlayer.js 20 KB

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