mpvVideoPlayer.js 21 KB

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