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