mpvVideoPlayer.js 20 KB

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