YouTube: Audio Only

No Video Streaming

当前为 2025-01-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name YouTube: Audio Only
  3. // @description No Video Streaming
  4. // @namespace UserScript
  5. // @version 2.1.22
  6. // @author CY Fung
  7. // @match https://www.youtube.com/*
  8. // @match https://www.youtube.com/embed/*
  9. // @match https://www.youtube-nocookie.com/embed/*
  10. // @match https://m.youtube.com/*
  11. // @exclude /^https?://\S+\.(txt|png|jpg|jpeg|gif|xml|svg|manifest|log|ini)[^\/]*$/
  12. // @icon https://raw.githubusercontent.com/cyfung1031/userscript-supports/main/icons/YouTube-Audio-Only.png
  13. // @grant GM_registerMenuCommand
  14. // @grant GM.setValue
  15. // @grant GM.getValue
  16. // @grant GM.listValues
  17. // @grant GM.deleteValue
  18. // @run-at document-start
  19. // @require https://cdn.jsdelivr.net/gh/cyfung1031/userscript-supports@5d83d154956057bdde19e24f95b332cb9a78fcda/library/default-trusted-type-policy.js
  20. // @license MIT
  21. // @compatible chrome
  22. // @compatible firefox
  23. // @compatible opera
  24. // @compatible edge
  25. // @compatible safari
  26. // @allFrames true
  27. //
  28. // ==/UserScript==
  29.  
  30. (async function () {
  31. 'use strict';
  32.  
  33.  
  34. const defaultPolicy = (typeof trustedTypes !== 'undefined' && trustedTypes.defaultPolicy) || { createHTML: s => s };
  35. function createHTML(s) {
  36. return defaultPolicy.createHTML(s);
  37. }
  38.  
  39. let trustHTMLErr = null;
  40. try {
  41. document.createElement('div').innerHTML = createHTML('1');
  42. } catch (e) {
  43. trustHTMLErr = e;
  44. }
  45.  
  46. if (trustHTMLErr) {
  47. console.log(`trustHTMLErr`, trustHTMLErr);
  48. trustHTMLErr(); // exit userscript
  49. }
  50.  
  51. /** @type {globalThis.PromiseConstructor} */
  52. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  53.  
  54. if (typeof AbortSignal === 'undefined') throw new DOMException("Please update your browser.", "NotSupportedError");
  55.  
  56. async function confirm(message) {
  57. // Create the HTML for the dialog
  58.  
  59. if (!document.body) return;
  60.  
  61. let dialog = document.getElementById('confirmDialog794');
  62. if (!dialog) {
  63.  
  64. const dialogHTML = `
  65. <div id="confirmDialog794" class="dialog-style" style="display: block;">
  66. <div class="confirm-box">
  67. <p>${message}</p>
  68. <div class="confirm-buttons">
  69. <button id="confirmBtn">Confirm</button>
  70. <button id="cancelBtn">Cancel</button>
  71. </div>
  72. </div>
  73. </div>
  74. `;
  75.  
  76. // Append the dialog to the document body
  77. document.body.insertAdjacentHTML('beforeend', createHTML(dialogHTML));
  78. dialog = document.getElementById('confirmDialog794');
  79.  
  80. }
  81.  
  82. // Return a promise that resolves or rejects based on the user's choice
  83. return new Promise((resolve) => {
  84. document.getElementById('confirmBtn').onclick = () => {
  85. resolve(true);
  86. cleanup();
  87. };
  88.  
  89. document.getElementById('cancelBtn').onclick = () => {
  90. resolve(false);
  91. cleanup();
  92. };
  93.  
  94. function cleanup() {
  95. dialog && dialog.remove();
  96. dialog = null;
  97. }
  98. });
  99. }
  100.  
  101.  
  102.  
  103. if (location.pathname === '/live_chat' || location.pathname === 'live_chat_replay') return;
  104.  
  105. const kEventListener = (evt) => {
  106. if (document.documentElement.hasAttribute('forceRefresh032')) {
  107. evt.stopImmediatePropagation();
  108. evt.stopPropagation();
  109. }
  110. }
  111. window.addEventListener('beforeunload', kEventListener, false);
  112.  
  113. const pageInjectionCode = function () {
  114.  
  115. let debugFlg001 = false;
  116. // let debugFlg002 = false;
  117. // let globalPlayer = null;
  118. const SHOW_VIDEO_STATIC_IMAGE = true;
  119. const PATCH_MEDIA_PUBLISH = true;
  120. const PATCH_MEDIA_PLAYPAUSE = true;
  121.  
  122. if (typeof AbortSignal === 'undefined') throw new DOMException("Please update your browser.", "NotSupportedError");
  123.  
  124. const URL = window.URL || new Function('return URL')();
  125. const createObjectURL = URL.createObjectURL.bind(URL);
  126.  
  127. /** @type {globalThis.PromiseConstructor} */
  128. const Promise = (async () => { })().constructor; // YouTube hacks Promise in WaterFox Classic and "Promise.resolve(0)" nevers resolve.
  129.  
  130. const PromiseExternal = ((resolve_, reject_) => {
  131. const h = (resolve, reject) => { resolve_ = resolve; reject_ = reject };
  132. return class PromiseExternal extends Promise {
  133. constructor(cb = h) {
  134. super(cb);
  135. if (cb === h) {
  136. /** @type {(value: any) => void} */
  137. this.resolve = resolve_;
  138. /** @type {(reason?: any) => void} */
  139. this.reject = reject_;
  140. }
  141. }
  142. };
  143. })();
  144.  
  145. const [setTimeout_, clearTimeout_] = [setTimeout, clearTimeout];
  146.  
  147. /* globals WeakRef:false */
  148.  
  149. /** @type {(o: Object | null) => WeakRef | null} */
  150. const mWeakRef = typeof WeakRef === 'function' ? (o => o ? new WeakRef(o) : null) : (o => o || null);
  151.  
  152. /** @type {(wr: Object | null) => Object | null} */
  153. const kRef = (wr => (wr && wr.deref) ? wr.deref() : wr);
  154.  
  155. const isIterable = (x) => Symbol.iterator in Object(x);
  156.  
  157.  
  158. let byPassSync = false;
  159. let byPassNonFatalError = false;
  160. let skipPlayPause = 0;
  161. let byPassPublishPatch = false;
  162.  
  163. const dmo = {};
  164. const qzk = Symbol();
  165.  
  166.  
  167. const observablePromise = (proc, timeoutPromise) => {
  168. let promise = null;
  169. return {
  170. obtain() {
  171. if (!promise) {
  172. promise = new Promise(resolve => {
  173. let mo = null;
  174. const f = () => {
  175. let t = proc();
  176. if (t) {
  177. mo.disconnect();
  178. mo.takeRecords();
  179. mo = null;
  180. resolve(t);
  181. }
  182. }
  183. mo = new MutationObserver(f);
  184. mo.observe(document, { subtree: true, childList: true })
  185. f();
  186. timeoutPromise && timeoutPromise.then(() => {
  187. resolve(null)
  188. });
  189. });
  190. }
  191. return promise
  192. }
  193. }
  194. }
  195.  
  196.  
  197. const insp = o => o ? (o.polymerController || o.inst || o || 0) : (o || 0);
  198.  
  199. const prototypeInherit = (d, b) => {
  200. const m = Object.getOwnPropertyDescriptors(b);
  201. for (const p in m) {
  202. if (!Object.getOwnPropertyDescriptor(d, p)) {
  203. Object.defineProperty(d, p, m[p]);
  204. }
  205. }
  206. };
  207.  
  208. const delayPn = delay => new Promise((fn => setTimeout_(fn, delay)));
  209.  
  210. const mockEvent = (o, elem) => {
  211. o = o || {};
  212. elem = elem || null;
  213. return {
  214. preventDefault: () => { },
  215. stopPropagation: () => { },
  216. stopImmediatePropagation: () => { },
  217. returnValue: true,
  218. target: elem,
  219. srcElement: elem,
  220. defaultPrevented: false,
  221. cancelable: true,
  222. timeStamp: performance.now(),
  223. ...o
  224. }
  225. };
  226.  
  227.  
  228. const generalRegister = (prop, symbol, checker, pg) => {
  229. const objSet = new Set();
  230. let done = false;
  231. const f = (o) => {
  232. const ct = o.constructor;
  233. const proto = ct.prototype;
  234. if (!done && proto && ct !== Function && ct !== Object && checker(proto)) {
  235. done = true;
  236. delete Object.prototype[prop];
  237. objSet.delete(proto);
  238. objSet.delete(o);
  239. for (const obj of objSet) {
  240. obj[prop] = obj[symbol];
  241. delete obj[symbol];
  242. }
  243. objSet.clear();
  244. Object.defineProperty(proto, prop, pg);
  245. return proto;
  246. }
  247. return false;
  248. };
  249. Object.defineProperty(Object.prototype, prop, {
  250. get() {
  251. const p = f(this);
  252. if (p) {
  253. return p[prop];
  254. } else {
  255. return this[symbol];
  256. }
  257. },
  258. set(nv) {
  259. const p = f(this);
  260. if (p) {
  261. p[prop] = nv;
  262. } else {
  263. objSet.add(this);
  264. this[symbol] = nv;
  265. }
  266. return true;
  267. },
  268. enumerable: false,
  269. configurable: true
  270. });
  271.  
  272. };
  273.  
  274.  
  275. const attachOneTimeEvent = function (eventType, callback) {
  276. let kz = false;
  277. document.addEventListener(eventType, function (evt) {
  278. if (kz) return;
  279. kz = true;
  280. callback(evt);
  281. }, { capture: true, passive: true, once: true });
  282. }
  283.  
  284. const evaluateInternalAppScore = (internalApp) => {
  285.  
  286.  
  287. let r = 0;
  288. if (!internalApp || typeof internalApp !== 'object') {
  289. return -999;
  290. }
  291.  
  292. if (internalApp.app) r -= 100;
  293.  
  294. if (!('mediaElement' in internalApp)) r -= 500;
  295.  
  296. if (!('videoData' in internalApp)) r -= 50;
  297.  
  298. if (!('playerState' in internalApp)) r -= 50;
  299.  
  300. if ('getVisibilityState' in internalApp) r += 20;
  301. if ('visibility' in internalApp) r += 40;
  302. if ('isBackground' in internalApp) r += 40;
  303. if ('publish' in internalApp) r += 10;
  304.  
  305.  
  306. if (('playerType' in internalApp)) r += 10;
  307. if (('playbackRate' in internalApp)) r += 10;
  308. if (('playerState' in internalApp)) r += 10;
  309. if (typeof (internalApp.playerState || 0) === 'object') r += 50;
  310.  
  311.  
  312. return r;
  313.  
  314.  
  315.  
  316. }
  317.  
  318.  
  319. const { remapString } = (() => {
  320.  
  321. function shuffleArray(array) {
  322. for (let i = array.length - 1; i > 0; i--) {
  323. const j = Math.floor(Math.random() * (i + 1));
  324. [array[i], array[j]] = [array[j], array[i]];
  325. }
  326. return array;
  327. }
  328.  
  329. /**
  330. * Create a deterministic "random" mapping from 'a'..'z' -> shuffled letters.
  331. * Returns a Map for O(1) lookups.
  332. */
  333. function createRandomAlphabetMap() {
  334. const baseAlphabet = "abcdefghijklmnopqrstuvwxyz";
  335. const letters = baseAlphabet.split("");
  336.  
  337.  
  338. // Shuffle letters with that seeded generator
  339. const shuffledLetters = shuffleArray(letters);
  340.  
  341. // Build the Map
  342. const map = new Map();
  343. for (let i = 0, l = baseAlphabet.length; i < l; i++) {
  344. map.set(baseAlphabet[i], shuffledLetters[i]);
  345. map.set(baseAlphabet[i].toUpperCase(), shuffledLetters[i].toUpperCase());
  346. }
  347. return map;
  348. }
  349.  
  350. // Create the random map once at initialization
  351. let randomAlphabetMap = null;
  352.  
  353. /**
  354. * Remaps alphabetic letters in a string according to randomAlphabetMap.
  355. * Preserves the case of letters and leaves non-alphabet characters unchanged.
  356. */
  357. function remapString(input) {
  358. if (!randomAlphabetMap) return input;
  359. let result = new Array(input.length);
  360. let i = 0;
  361. for (const char of input) {
  362. result[i++] = randomAlphabetMap.get(char) || char;
  363. }
  364. return result.join('');
  365. }
  366.  
  367. const listA = [
  368. "error",
  369. "internalvideodatachange",
  370. "statechange",
  371. "SEEK_TO",
  372. "videoelementevent",
  373. "onLoadedMetadata",
  374. "progresssync",
  375. "onVideoProgress",
  376. "SEEK_COMPLETE",
  377. "playbackstarted",
  378. "onLoadProgress",
  379. "nonfatalerror",
  380. "internalAbandon",
  381. "internalvideoformatchange",
  382. "internalaudioformatchange",
  383. "playbackready",
  384. "mediasourceattached",
  385. "beginseeking",
  386. "endseeking"
  387. ];
  388.  
  389. const mdA = listA.join('|');
  390.  
  391. loop1:
  392. for (let tryCount = 8; tryCount > 0; tryCount--) {
  393. randomAlphabetMap = createRandomAlphabetMap();
  394. const listB = listA.map(remapString);
  395. const mdB = listB.join('|');
  396. for (const a of listA) {
  397. if (mdB.includes(a)) {
  398. randomAlphabetMap = null;
  399. continue loop1;
  400. }
  401. }
  402. for (const b of listB) {
  403. if (mdA.includes(b)) {
  404. randomAlphabetMap = null;
  405. continue loop1;
  406. }
  407. }
  408. break;
  409. }
  410. if (!randomAlphabetMap) {
  411. console.error('randomAlphabetMap is not available.')
  412. }
  413.  
  414. return { remapString };
  415. })();
  416.  
  417.  
  418. function removeTempObjectProp01() {
  419. delete Object.prototype['kevlar_non_watch_unified_player'];
  420. delete Object.prototype['kevlar_unified_player'];
  421. }
  422.  
  423. function ytConfigFix(config__) {
  424. const config_ = config__;
  425.  
  426. if (config_) {
  427.  
  428. const playerKevlar = ((config_ || 0).WEB_PLAYER_CONTEXT_CONFIGS || 0).WEB_PLAYER_CONTEXT_CONFIG_ID_KEVLAR_WATCH || 0;
  429.  
  430. if (playerKevlar) {
  431.  
  432. // console.log(322, playerKevlar)
  433. playerKevlar.allowWoffleManagement = false;
  434. playerKevlar.cinematicSettingsAvailable = false;
  435. playerKevlar.showMiniplayerButton = false;
  436. playerKevlar.showMiniplayerUiWhenMinimized = false;
  437. playerKevlar.transparentBackground = false;
  438.  
  439. playerKevlar.enableCsiLogging = false;
  440. playerKevlar.externalFullscreen = false;
  441.  
  442. if (typeof playerKevlar.serializedExperimentFlags === 'string') {
  443. playerKevlar.serializedExperimentFlags = '';
  444. // playerKevlar.serializedExperimentFlags = playerKevlar.serializedExperimentFlags.replace(/[-\w]+=(\[\]|[.-\d]+|[_a-z]+|)(&|$)/g,'').replace(/&$/,'')
  445. }
  446.  
  447. if (typeof playerKevlar.serializedExperimentIds === 'string') {
  448. playerKevlar.serializedExperimentIds = '';
  449. // playerKevlar.serializedExperimentIds = playerKevlar.serializedExperimentIds.replace(/\d+\s*(,\s*|$)/g,'')
  450. }
  451.  
  452. }
  453.  
  454. removeTempObjectProp01();
  455.  
  456. let configs = config_.WEB_PLAYER_CONTEXT_CONFIGS || {};
  457. for (const [key, entry] of Object.entries(configs)) {
  458.  
  459. if (entry && typeof entry.serializedExperimentFlags === 'string' && entry.serializedExperimentFlags.length > 16) {
  460. // prevent idle playback failure
  461. entry.serializedExperimentFlags = entry.serializedExperimentFlags.replace(/\b(html5_check_for_idle_network_interval_ms|html5_trigger_loader_when_idle_network|html5_sabr_fetch_on_idle_network_preloaded_players|html5_autonav_cap_idle_secs|html5_autonav_quality_cap|html5_disable_client_autonav_cap_for_onesie|html5_idle_rate_limit_ms|html5_sabr_fetch_on_idle_network_preloaded_players|html5_webpo_idle_priority_job|html5_server_playback_start_policy|html5_check_video_data_errors_before_playback_start|html5_check_unstarted|html5_check_queue_on_data_loaded)=([-_\w]+)(\&|$)/g, (_, a, b, c) => {
  462. return a + '00' + '=' + b + c;
  463. });
  464.  
  465. }
  466.  
  467. }
  468.  
  469. const EXPERIMENT_FLAGS = config_.EXPERIMENT_FLAGS;
  470.  
  471. if (EXPERIMENT_FLAGS) {
  472. EXPERIMENT_FLAGS.kevlar_unified_player = true;
  473. EXPERIMENT_FLAGS.kevlar_non_watch_unified_player = true;
  474. }
  475.  
  476.  
  477. const EXPERIMENTS_FORCED_FLAGS = config_.EXPERIMENTS_FORCED_FLAGS;
  478.  
  479. if (EXPERIMENTS_FORCED_FLAGS) {
  480. EXPERIMENTS_FORCED_FLAGS.kevlar_unified_player = true;
  481. EXPERIMENTS_FORCED_FLAGS.kevlar_non_watch_unified_player = true;
  482. }
  483.  
  484. }
  485. }
  486.  
  487. Object.defineProperty(Object.prototype, 'kevlar_non_watch_unified_player', {
  488. get() {
  489. // console.log(501, this.constructor.prototype)
  490. return true;
  491. },
  492. set(nv) {
  493. return true;
  494. },
  495. enumerable: false,
  496. configurable: true
  497. });
  498.  
  499.  
  500. Object.defineProperty(Object.prototype, 'kevlar_unified_player', {
  501. get() {
  502. // console.log(501, this.constructor.prototype)
  503. return true;
  504. },
  505. set(nv) {
  506. return true;
  507. },
  508. enumerable: false,
  509. configurable: true
  510. });
  511.  
  512. // let prr = new PromiseExternal();
  513. // const prrPipeline = createPipeline();
  514. // let stopAndReload = false;
  515.  
  516. let fa = 0;
  517.  
  518. let cv = null;
  519. let durationchangeForMobile = false;
  520. function fixThumbnailURL(src) {
  521. if (typeof src === 'string' && src.length >= 4) {
  522. let m = /\b[a-z0-9]{4,13}\.jpg\b/.exec(src);
  523. if (m && m[0]) {
  524. const t = m[0];
  525. let idx = src.indexOf(t);
  526. let nSrc = idx >= 0 ? src.substring(0, idx + t.length) : '';
  527. return nSrc;
  528. }
  529. }
  530. return src;
  531. }
  532.  
  533. const isDesktopSite = location.origin === 'https://www.youtube.com' && !location.pathname.startsWith('/embed/');
  534.  
  535. const getThumbnailUrlFromThumbnails = (thumbnails) => {
  536.  
  537. let thumbnailUrl = '';
  538. if (thumbnails && thumbnails.length >= 1) {
  539. const arr = thumbnails.map(e => {
  540. return e.url ? [e.width * e.height, e.url] : typeof e === 'string' ? [0, e] : [0, '']
  541. });
  542. arr.sort((a, b) => b[0] - a[0]);
  543. thumbnailUrl = arr[0][1]
  544. if (typeof thumbnailUrl === 'string') {
  545. thumbnailUrl = fixThumbnailURL(thumbnailUrl);
  546. }
  547. }
  548. return thumbnailUrl;
  549. }
  550.  
  551. const staticImageMap = new Map();
  552.  
  553. const delayedUpdateStaticImage = (target) => {
  554.  
  555. dmo.delayedUpdateStaticImage && dmo.delayedUpdateStaticImage(target);
  556.  
  557.  
  558. }
  559.  
  560. const pmof = () => {
  561.  
  562. if (SHOW_VIDEO_STATIC_IMAGE) {
  563.  
  564. const medias = [...document.querySelectorAll('ytd-watch-flexy #player .html5-video-container .video-stream.html5-main-video')].filter(e => !e.closest('[hidden]'));
  565. if (medias.length !== 1) return;
  566. const mediaElm = medias[0];
  567.  
  568. const container = mediaElm ? mediaElm.closest('.html5-video-container') : null;
  569. if (!container) return;
  570.  
  571. const movie_player = mediaElm.closest('#movie_player, #masthead-player');
  572.  
  573. let videoId = '';
  574. try {
  575. videoId = movie_player && insp(movie_player).getVideoData().video_id;
  576. } catch (e) { }
  577.  
  578. let thumbnailUrl = '';
  579.  
  580. if (videoId) { thumbnailUrl = staticImageMap.get(videoId); }
  581.  
  582. if (!thumbnailUrl) {
  583. const ytdPage = container.closest('ytd-watch-flexy');
  584. if (ytdPage && ytdPage.is === 'ytd-watch-flexy') {
  585. const cnt = insp(ytdPage);
  586. let thumbnails = null;
  587. try {
  588. thumbnails = insp(cnt).__data.playerData.videoDetails.thumbnail.thumbnails
  589. // thumbnails = cnt.__data.watchNextData.playerOverlays.playerOverlayRenderer.autoplay.playerOverlayAutoplayRenderer.background.thumbnails
  590. } catch (e) { }
  591.  
  592. thumbnailUrl = getThumbnailUrlFromThumbnails(thumbnails);
  593.  
  594. if (videoId && thumbnailUrl && typeof thumbnailUrl === 'string') {
  595. staticImageMap.set(videoId, thumbnailUrl);
  596. }
  597.  
  598. }
  599. }
  600.  
  601.  
  602.  
  603. if (thumbnailUrl && typeof thumbnailUrl === 'string') {
  604. container.style.setProperty('--audio-only-thumbnail-image', `url(${thumbnailUrl})`);
  605. } else {
  606. container.style.removeProperty('--audio-only-thumbnail-image')
  607. }
  608.  
  609. }
  610.  
  611.  
  612. }
  613. const pmo = new MutationObserver(pmof);
  614.  
  615. isDesktopSite && document.addEventListener('yt-navigate-finish', () => {
  616. const ytdWatchFlexy = document.querySelector('ytd-watch-flexy');
  617. if (ytdWatchFlexy) {
  618. pmo.observe(ytdWatchFlexy, { attributes: true });
  619. ytdWatchFlexy.setAttribute('ytzNavigateFinish', Date.now());
  620. }
  621. });
  622. document.addEventListener('durationchange', (evt) => {
  623. const target = (evt || 0).target;
  624. if (!(target instanceof HTMLMediaElement)) return;
  625. const targetClassList = target.classList || 0;
  626. const isPlayerVideo = typeof targetClassList.contains === 'function' ? targetClassList.contains('video-stream') && targetClassList.contains('html5-main-video') : false;
  627. dirtyMark = 1 | 2 | 4 | 8;
  628. delayedUpdateStaticImage(target);
  629. if (durationchangeForMobile || isPlayerVideo) {
  630. if (target.readyState !== 1) {
  631. fa = 1;
  632. } else {
  633. fa = 2;
  634. }
  635. }
  636.  
  637. if (isPlayerVideo) {
  638.  
  639. if (target.readyState === 1 && target.networkState === 2) {
  640. target.__spfgs__ = true;
  641. if (cv) {
  642. cv.resolve();
  643. cv = null;
  644. }
  645. } else {
  646. target.__spfgs__ = false;
  647. }
  648.  
  649. if (isDesktopSite) {
  650. const ytdWatchFlexy = document.querySelector('ytd-watch-flexy');
  651. if (ytdWatchFlexy) {
  652. ytdWatchFlexy.setAttribute('ytzMediaDurationChanged', Date.now());
  653. }
  654. }
  655.  
  656. if (onVideoChangeForMobile) {
  657. onVideoChangeForMobile();
  658. }
  659.  
  660. }
  661. }, true);
  662.  
  663.  
  664.  
  665. // XMLHttpRequest.prototype.open299 = XMLHttpRequest.prototype.open;
  666. /*
  667.  
  668. XMLHttpRequest.prototype.open2 = function(method, url, ...args){
  669.  
  670. if (typeof url === 'string' && url.length > 24 && url.includes('/videoplayback?') && url.replace('?', '&').includes('&source=')) {
  671. if (vcc !== vdd) {
  672. vdd = vcc;
  673. window.postMessage({ ZECxh: url.includes('source=yt_live_broadcast') }, "*");
  674. }
  675. }
  676.  
  677. return this.open299(method, url, ...args)
  678. }*/
  679.  
  680.  
  681.  
  682. // desktop only
  683. // document.addEventListener('yt-page-data-fetched', async (evt) => {
  684.  
  685. // const pageFetchedDataLocal = evt.detail;
  686. // let isLiveNow;
  687. // try {
  688. // isLiveNow = pageFetchedDataLocal.pageData.playerResponse.microformat.playerMicroformatRenderer.liveBroadcastDetails.isLiveNow;
  689. // } catch (e) { }
  690. // window.postMessage({ ZECxh: isLiveNow === true }, "*");
  691.  
  692. // }, false);
  693.  
  694. // return;
  695.  
  696. // let clickLockFn = null;
  697.  
  698.  
  699. let onVideoChangeForMobile = null;
  700.  
  701. let removeBottomOverlayForMobile = null;
  702.  
  703. let clickLockFn = null;
  704. let clickTarget = null;
  705. if (location.origin === 'https://m.youtube.com') {
  706.  
  707. EventTarget.prototype.addEventListener322 = EventTarget.prototype.addEventListener;
  708.  
  709. const dummyFn = () => { };
  710. EventTarget.prototype.addEventListener = function (evt, fn, opts) {
  711.  
  712. let hn = fn;
  713.  
  714. // if (evt === 'player-error') {
  715. // } else if (evt === 'player-detailed-error') {
  716. // } else if (evt === 'video-data-change') {
  717. // } else if (evt === 'player-state-change') {
  718. // } else
  719. if (evt === 'player-autonav-pause' || evt === 'visibilitychange') {
  720. evt += 'y'
  721. fn = dummyFn;
  722. } else if (evt === 'click' && (this.id === 'movie_player' || this.id === 'masthead-player')) {
  723. clickLockFn = fn;
  724. clickTarget = this;
  725. }
  726. return this.addEventListener322(evt, hn, opts)
  727.  
  728. }
  729.  
  730. }
  731.  
  732.  
  733.  
  734. (() => {
  735.  
  736. XMLHttpRequest = (() => {
  737. const XMLHttpRequest_ = XMLHttpRequest;
  738. if ('__xmMc8__' in XMLHttpRequest_.prototype) return XMLHttpRequest_;
  739. const url0 = createObjectURL(new Blob([], { type: 'text/plain' }));
  740. const c = class XMLHttpRequest extends XMLHttpRequest_ {
  741. constructor(...args) {
  742. super(...args);
  743. }
  744. open(method, url, ...args) {
  745. let skip = false;
  746. if (!url || typeof url !== 'string') skip = true;
  747. else if (typeof url === 'string') {
  748. let turl = url[0] === '/' ? `.youtube.com${url}` : `${url}`;
  749. if (turl.includes('googleads') || turl.includes('doubleclick.net')) {
  750. skip = true;
  751. } else if (turl.includes('.youtube.com/pagead/')) {
  752. skip = true;
  753. } else if (turl.includes('.youtube.com/ptracking')) {
  754. skip = true;
  755. } else if (turl.includes('.youtube.com/api/stats/')) { // /api/stats/
  756. // skip = true; // for user activity logging e.g. watched videos
  757. } else if (turl.includes('play.google.com/log')) {
  758. skip = true;
  759. } else if (turl.includes('.youtube.com//?')) { // //?cpn=
  760. skip = true;
  761. }
  762. }
  763. if (!skip) {
  764. this.__xmMc8__ = 1;
  765. return super.open(method, url, ...args);
  766. } else {
  767. this.__xmMc8__ = 2;
  768. return super.open('GET', url0);
  769. }
  770. }
  771. send(...args) {
  772. if (this.__xmMc8__ === 1) {
  773. return super.send(...args);
  774. } else if (this.__xmMc8__ === 2) {
  775. return super.send();
  776. } else {
  777. console.log('xhr warning');
  778. return super.send(...args);
  779. }
  780. }
  781. }
  782. c.prototype.__xmMc8__ = 0;
  783. prototypeInherit(c.prototype, XMLHttpRequest_.prototype);
  784. return c;
  785. })();
  786.  
  787. const s7 = Symbol();
  788. const f7 = () => true;
  789.  
  790. !window.canRetry9048 && generalRegister('canRetry', s7, (p) => {
  791. return typeof p.onStateChange === 'function' && typeof p.dispose === 'function' && typeof p.hide === 'undefined' && typeof p.show === 'undefined' && typeof p.isComplete === 'undefined' && typeof p.getDuration === 'undefined'
  792. }, {
  793. get() {
  794. if ('logger' in this && 'policy' in this && 'xhr' && this) {
  795. if (this.errorMessage && typeof this.errorMessage === 'string' && this.errorMessage.includes('XMLHttpRequest') && this.errorMessage.includes('Invalid URL')) { // "SyntaxError_Failed to execute 'open' on 'XMLHttpRequest': Invalid URL"
  796. // OKAY !
  797. console.log('canRetry05 - ', this.errorMessage)
  798. return f7;
  799. }
  800. // console.log(this)
  801. console.log('canRetry02 - ', this.errorMessage, this)
  802. } else {
  803. console.log('canRetry ERR - ', this.errorMessage)
  804. }
  805. return this[s7];
  806. },
  807. set(nv) {
  808. this[s7] = nv;
  809. return true;
  810. },
  811. enumerable: false,
  812. configurable: true
  813. });
  814. window.canRetry9048 = 1;
  815.  
  816. })();
  817.  
  818.  
  819. const updateLastActiveTimeAsync_ = (player_) => {
  820. if (player_ && typeof player_.updateLastActiveTime === 'function') {
  821. player_.updateLastActiveTime();
  822. }
  823. };
  824.  
  825. const updateLastActiveTimeAsync = (evt) => {
  826. Promise.resolve(evt?.updateLastActiveTime ? evt : evt?.target).then(updateLastActiveTimeAsync_);
  827. };
  828.  
  829.  
  830.  
  831. const { setupAudioPlaying, internalAppPTFn, standardAppPTFn, playerDapPTFn } = (() => {
  832.  
  833. // playerApp: external API [ external use ]
  834. // playerDap: internal player ( with this.app and this.state ) [ the internal interface for both app and state ]
  835. // standardApp: .app of internal player [without isBackground, with fn getVideoDate(), etc]
  836. // internalApp: internal controller inside standardApp (normally non-accessible) [with isBackground, data field videoData, etc]
  837.  
  838. // window.gt1 -> playerApp
  839. // window.gt11 -> playerDap
  840. // window.gt2 -> standardApp
  841. // window.gt3 -> internalApp
  842.  
  843. let key_mediaElementT = '';
  844.  
  845. let key_yn = '';
  846. let key_nS = '';
  847.  
  848. let key_L1 = ''; // playerDap -> internalDap
  849.  
  850. let listAllPublish = false;
  851. let promiseSeek = null;
  852.  
  853. let internalAppXT = null;
  854. let standardAppXT = null;
  855. let playerAppXT = null;
  856. let playerDapXT = null;
  857.  
  858.  
  859.  
  860. /*
  861. const __wmObjectRefs__ = new WeakMap();
  862. class WeakRefSet extends Set {
  863. constructor() {
  864. super();
  865. }
  866. add(obj) {
  867. if (typeof (obj || 0) === 'object') {
  868. let ref = __wmObjectRefs__.get(obj);
  869. if (!ref) {
  870. __wmObjectRefs__.set(obj, (ref = mWeakRef(obj)));
  871. }
  872. super.add(ref);
  873. }
  874. return this;
  875. }
  876. delete(obj) {
  877. if (!obj) return null;
  878. const ref = __wmObjectRefs__.get(obj);
  879. if (ref) {
  880. if(kRef(ref)) return super.delete(ref);
  881. super.delete(ref);
  882. return false;
  883. }
  884. return false;
  885. }
  886. *[Symbol.iterator]() {
  887. for (const value of super.values()) {
  888. const obj = (kRef(value) || null);
  889. if (!obj) {
  890. super.delete(value);
  891. continue;
  892. }
  893. yield obj;
  894. }
  895. }
  896. has(obj) {
  897. if (!obj) return null;
  898. const ref = __wmObjectRefs__.get(obj);
  899. if (!ref) return false;
  900. if (kRef(ref)) return super.has(ref);
  901. super.delete(ref);
  902. return false;
  903. }
  904. }
  905. */
  906.  
  907. const internalAppUT = new Set();
  908. const standardAppUT = new Set();
  909. const playerAppUT = new Set();
  910. const playerDapUT = new Set();
  911. let dirtyMark = 1 | 2 | 4 | 8;
  912.  
  913.  
  914. let playerDapPTDone = false;
  915. // let playerAppPTDone = false;
  916. let standardAppPTDone = false;
  917. let internalAppPTDone = false;
  918.  
  919.  
  920. window.gtz = () => {
  921. return {
  922. internalAppUT, standardAppUT, playerAppUT, playerDapUT, dirtyMark
  923. }
  924. }
  925.  
  926. const getMediaElement = () => {
  927.  
  928. const internalApp = internalAppXM();
  929. const standardApp = standardAppXM();
  930.  
  931. let t;
  932.  
  933. if (t = internalApp?.mediaElement?.[key_mediaElementT]) return t;
  934.  
  935.  
  936. if (t = standardApp?.mediaElement?.[key_mediaElementT]) return t;
  937.  
  938. return null;
  939.  
  940.  
  941.  
  942. }
  943.  
  944. const internalApp_ZZ_sync = function () {
  945. if (byPassSync) {
  946. return;
  947. }
  948. return this.sync9383(...arguments)
  949. };
  950.  
  951. const updateInternalAppFn_ = () => {
  952.  
  953. const internalApp = internalAppXT;
  954. if (internalApp && !internalApp.__s4538__) {
  955. if (internalApp.mediaElement) internalApp.__s4538__ = true;
  956.  
  957. const arr = Object.entries(internalApp).filter(e => e[1] && typeof e[1].sync === 'function');
  958. for (const [key, o] of arr) {
  959. const p = o.__proto__ || o;
  960. if (!p.sync9383 && typeof p.sync === 'function') {
  961. p.sync9383 = p.sync;
  962. p.sync = internalApp_ZZ_sync;
  963. }
  964. }
  965.  
  966. if (!key_yn || !key_nS) {
  967.  
  968. for (const [key, value] of Object.entries(internalApp)) {
  969. if (!key_yn && typeof (value || 0) === 'object' && value.experiments && value.experiments.flags && !isIterable(value)) {
  970. key_yn = key;
  971. console.log(1959, 'key_yn', key_yn)
  972. } else if (!key_nS && typeof (value || 0) === 'object' && 'videoTrack' in value && 'audioTrack' in value && 'isSuspended' in value && !isIterable(value)) {
  973. key_nS = key;
  974. console.log(1959, 'key_nS', key_nS)
  975. }
  976. }
  977.  
  978. }
  979.  
  980. if (!key_mediaElementT) {
  981. const iaMedia = internalApp.mediaElement || 0;
  982. // console.log(1959, internalApp, iaMedia)
  983.  
  984. if (internalApp && typeof iaMedia === 'object') {
  985. for (const [key, value] of Object.entries(iaMedia)) {
  986. if (value instanceof HTMLMediaElement) {
  987. key_mediaElementT = key;
  988. console.log(1959, 'key_mediaElementT', key_mediaElementT)
  989. }
  990. }
  991. }
  992.  
  993. }
  994.  
  995. }
  996.  
  997.  
  998. if (!internalAppPTDone) {
  999. const proto = internalApp ? internalApp.__proto__ : null;
  1000. if (proto) {
  1001. internalAppPTDone = true;
  1002. internalAppPTFn(proto);
  1003. }
  1004. }
  1005.  
  1006. }
  1007.  
  1008. const updateInternalAppFn = (x) => {
  1009. if (x !== internalAppXT) {
  1010. dirtyMark = 1 | 2 | 4 | 8;
  1011. internalAppUT.add(x);
  1012. internalAppXT = x;
  1013. // videoData
  1014. // stopVideo
  1015. // pauseVideo
  1016.  
  1017. }
  1018. updateInternalAppFn_();
  1019. }
  1020.  
  1021. window.gt3 = () => internalAppXM();
  1022. window.gt3x = ()=>internalAppUT;
  1023. const internalAppXM = () => {
  1024. if (!(dirtyMark & 4)) return internalAppXT;
  1025. if (!key_mediaElementT) return internalAppXT;
  1026. let result = null;
  1027. const possibleResults = [];
  1028. for (const p of internalAppUT) {
  1029. const iaMediaP = p.mediaElement;
  1030. if (!iaMediaP) {
  1031. // internalAppUT.delete(p);
  1032. } else {
  1033. const element = iaMediaP[key_mediaElementT];
  1034. if (element instanceof Element) {
  1035. if (element instanceof HTMLMediaElement && Number.isNaN(element.duration)) {
  1036.  
  1037. } else if (!element.isConnected) {
  1038. // valid entry but audio is not on the page
  1039.  
  1040. } else if (element.closest('[hidden]')) {
  1041.  
  1042. } else if (result === null && element.duration > 0) {
  1043. possibleResults.push([p, element.duration, (element.paused?1:0)]);
  1044. // 3600 ads might be added
  1045. }
  1046. }
  1047. }
  1048. }
  1049. if (possibleResults.length > 0) {
  1050. if (possibleResults.length === 1) result = possibleResults[0][0];
  1051. else {
  1052. possibleResults.sort((a, b) => {
  1053.  
  1054. if (b[2] && !a[2]) return -1;
  1055. if (!b[2] && a[2]) return 1;
  1056. return (b[1] - a[1]);
  1057.  
  1058. });
  1059. result = possibleResults[0][0];
  1060. }
  1061. possibleResults.length = 0;
  1062. }
  1063. if (!result) return result;
  1064. if (!internalAppUT.has(result)) {
  1065. for (const p of internalAppUT) {
  1066. const iaMediaP = p.mediaElement;
  1067. if (!iaMediaP) {
  1068. internalAppUT.delete(p);
  1069. }
  1070. }
  1071. internalAppUT.add(result);
  1072. }
  1073. internalAppXT = result;
  1074. updateInternalAppFn_();
  1075. if (dirtyMark & 4) dirtyMark -= 4;
  1076. return result;
  1077. }
  1078.  
  1079. const updateStandardAppFn_ = () => {
  1080. const standardAppXT_ = standardAppXT;
  1081. if (!standardAppPTDone) {
  1082. const proto = standardAppXT_ ? standardAppXT_.__proto__ : null;
  1083. if (proto) {
  1084. standardAppPTDone = true;
  1085. standardAppPTFn(proto);
  1086. }
  1087. }
  1088. }
  1089.  
  1090. const updateStandardAppFn = (x) => {
  1091. if (x !== standardAppXT) {
  1092. dirtyMark = 1 | 2 | 4 | 8;
  1093. standardAppUT.add(x);
  1094. standardAppXT = x;
  1095. // isAtLiveHead
  1096. // cancelPlayback
  1097. // stopVideo
  1098. // pauseVideo
  1099. }
  1100. updateStandardAppFn_(x);
  1101. }
  1102. window.gt2 = () => standardAppXM();
  1103.  
  1104. const loadVideoByPlayerVarsP20 = {};
  1105. const loadVideoByPlayerVarsQ20 = new Map();
  1106.  
  1107.  
  1108. const standardAppXM = () => {
  1109.  
  1110. if (!(dirtyMark & 2)) return standardAppXT;
  1111.  
  1112. const internalApp = internalAppXM();
  1113. if (!internalApp) return standardAppXT;
  1114. const iaMedia = internalApp.mediaElement;
  1115.  
  1116.  
  1117. let result = null;
  1118. for (const p of standardAppUT) {
  1119. const iaMediaP = p.mediaElement;
  1120. if (!iaMediaP) {
  1121. // standardAppUT.delete(p);
  1122. } else {
  1123. if (iaMediaP === iaMedia) result = p;
  1124. }
  1125. }
  1126. if (!result) return result;
  1127. if (!standardAppUT.has(result)) {
  1128. for (const p of standardAppUT) {
  1129. const iaMediaP = p.mediaElement;
  1130. if (!iaMediaP) {
  1131. standardAppUT.delete(p);
  1132. }
  1133. }
  1134. standardAppUT.add(result);
  1135. }
  1136. standardAppXT = result;
  1137. updateStandardAppFn_();
  1138. if (dirtyMark & 2) dirtyMark -= 2;
  1139. return result;
  1140.  
  1141. }
  1142.  
  1143. const updatePlayerDapFn_ = () => {
  1144.  
  1145. const playerD_ = playerDapXT;
  1146. if (!playerD_.__onVideoProgressF381__) {
  1147. playerD_.__onVideoProgressF381__ = true;
  1148. try {
  1149. playerD_.removeEventListener('onVideoProgress', updateLastActiveTimeAsync); // desktop
  1150. } catch (e) { }
  1151. playerD_.addEventListener('onVideoProgress', updateLastActiveTimeAsync); // desktop
  1152. }
  1153.  
  1154. if (!playerDapPTDone) {
  1155. const proto = playerD_ ? playerD_.__proto__ : null;
  1156. if (proto) {
  1157. playerDapPTDone = true;
  1158. playerDapPTFn(proto);
  1159. }
  1160. }
  1161.  
  1162. const standardApp_ = playerD_.app || 0;
  1163. if (standardApp_) {
  1164. updateStandardAppFn(standardApp_);
  1165. }
  1166. }
  1167.  
  1168. const updatePlayerDapFn = (x) => {
  1169. if (x !== playerDapXT) {
  1170. dirtyMark = 1 | 2 | 4 | 8;
  1171. // console.log('updatePlayerDapFn')
  1172. playerDapUT.add(x);
  1173. playerDapXT = x;
  1174. }
  1175. updatePlayerDapFn_(x);
  1176.  
  1177. }
  1178.  
  1179. window.gt11 = () => {
  1180. return playerDapXM();
  1181. }
  1182. const playerDapXM = () => {
  1183.  
  1184. if (!(dirtyMark & 8)) return playerDapXT;
  1185. const standardApp = standardAppXM();
  1186. if (!standardApp) return playerDapXT;
  1187. let result = null;
  1188. for (const p of playerDapUT) {
  1189. if (!p.app || !p.app.mediaElement) {
  1190. // playerDapUT.delete(p);
  1191. }
  1192. else if (p.app === standardApp) result = p;
  1193. }
  1194. if (!result) return result;
  1195. playerDapUT.add(result);
  1196. playerDapXT = result;
  1197. updatePlayerDapFn_();
  1198. if (dirtyMark & 8) dirtyMark -= 8;
  1199. return result;
  1200. }
  1201.  
  1202. const updatePlayerAppFn_ = () => {
  1203.  
  1204. const player_ = playerAppXT;
  1205.  
  1206.  
  1207. if (!player_.__s4539__ || !player_.__s4549__) {
  1208. player_.__s4539__ = true;
  1209.  
  1210.  
  1211. if (!player_.__onVideoProgressF381__ && typeof player_.addEventListener === 'function') {
  1212. player_.__onVideoProgressF381__ = true;
  1213. try {
  1214. player_.removeEventListener('onVideoProgress', updateLastActiveTimeAsync); // desktop
  1215. } catch (e) { }
  1216. player_.addEventListener('onVideoProgress', updateLastActiveTimeAsync); // desktop
  1217. }
  1218.  
  1219. const playerPT = player_.__proto__;
  1220. if (playerPT && typeof playerPT.getPlayerStateObject === 'function' && !playerPT.getPlayerStateObject949) {
  1221. playerPT.getPlayerStateObject949 = playerPT.getPlayerStateObject;
  1222. playerPT.getPlayerStateObject = function () {
  1223. updatePlayerAppFn(this);
  1224. return this.getPlayerStateObject949(...arguments);
  1225. }
  1226. } else if (player_ && typeof player_.getPlayerStateObject === 'function' && !player_.getPlayerStateObject949) {
  1227. player_.getPlayerStateObject949 = player_.getPlayerStateObject;
  1228. player_.getPlayerStateObject = function () {
  1229. updatePlayerAppFn(this);
  1230. return this.getPlayerStateObject949(...arguments);
  1231. }
  1232. }
  1233.  
  1234.  
  1235.  
  1236. // globalPlayer = mWeakRef(player_);
  1237. // window.gp3 = player_;
  1238.  
  1239.  
  1240. let playerDap_ = null;
  1241. {
  1242.  
  1243.  
  1244. const objectSets = new Set();
  1245. Function.prototype.apply129 = Function.prototype.apply;
  1246. Function.prototype.apply = function () {
  1247. objectSets.add([this, ...arguments]);
  1248. return this.apply129(...arguments)
  1249. }
  1250. player_.getPlayerState();
  1251.  
  1252. Function.prototype.apply = Function.prototype.apply129;
  1253.  
  1254. console.log(39912, [...objectSets]);
  1255. let filteredObjects = [...objectSets].filter(e => {
  1256. return Object(e[1]).getPlayerState === e[0]
  1257. });
  1258. console.log(39914, filteredObjects);
  1259.  
  1260. if (filteredObjects.length > 1) {
  1261. filteredObjects = filteredObjects.filter((e) => !(e[1] instanceof Node));
  1262. }
  1263.  
  1264. if (filteredObjects.length === 1) {
  1265. playerDap_ = filteredObjects[0][1];
  1266. }
  1267.  
  1268. objectSets.clear();
  1269. filteredObjects.length = 0;
  1270.  
  1271. }
  1272. {
  1273.  
  1274.  
  1275. let internalApp_ = null;
  1276. if (playerDap_ && playerDap_.app && playerDap_.state) {
  1277. const playerDapP_ = playerDap_.__proto__;
  1278. if (playerDapP_ && (playerDapP_.stopVideo || playerDapP_.pauseVideo) && (playerDapP_.playVideo)) {
  1279. if (!key_L1) {
  1280. const listOfPossibles = [];
  1281. for (const [key, value] of Object.entries(playerDapP_)) {
  1282. if (typeof value === 'function' && value.length === 0 && `${value}`.endsWith('(this.app)}')) { // return g.O5(this.app)
  1283. let m = null;
  1284. try {
  1285. m = playerDap_[key]()
  1286. } catch (e) { }
  1287. if (typeof (m || 0) === 'object') {
  1288. listOfPossibles.push([key, m, evaluateInternalAppScore(m)]);
  1289. }
  1290. }
  1291. }
  1292.  
  1293. if (listOfPossibles.length >= 2) {
  1294. listOfPossibles.sort((a, b) => {
  1295. return b[2] - a[2];
  1296. })
  1297. }
  1298. if (listOfPossibles.length >= 1) {
  1299. key_L1 = listOfPossibles[0][0];
  1300. internalApp_ = listOfPossibles[0][1];
  1301. console.log('[yt-audio-only] key_L1', key_L1);
  1302. }
  1303. listOfPossibles.length = 0;
  1304. // key_L1 = '';
  1305. }
  1306. updatePlayerDapFn(playerDap_);
  1307. }
  1308. }
  1309.  
  1310. if (key_L1) {
  1311. const internalApp = internalApp_ || playerDap_[key_L1]();
  1312. if (internalApp) {
  1313. updateInternalAppFn(internalApp);
  1314. player_.__s4549__ = true;
  1315. }
  1316. }
  1317. }
  1318.  
  1319.  
  1320. setupFns();
  1321.  
  1322.  
  1323. }
  1324.  
  1325.  
  1326. }
  1327.  
  1328. // player could be just a DOM element without __proto__
  1329. // will this update fail?
  1330. const updatePlayerAppFn = (x) => {
  1331. if (x !== playerAppXT) {
  1332. dirtyMark = 1 | 2 | 4 | 8;
  1333. // console.log('updatePlayerAppFn')
  1334. playerAppUT.add(x);
  1335. playerAppXT = x;
  1336. }
  1337. updatePlayerAppFn_();
  1338. }
  1339. const playerAppXM = () => {
  1340.  
  1341. if (!(dirtyMark & 1)) return playerAppXT;
  1342.  
  1343. const standardApp = standardAppXM();
  1344. if (!standardApp) return playerAppXT;
  1345.  
  1346. const playerAppUA = [...playerAppUT];
  1347. loadVideoByPlayerVarsQ20.clear();
  1348. for (let i = 0; i < playerAppUA.length; i++) {
  1349. const playerApp = playerAppUA[i];
  1350. loadVideoByPlayerVarsP20.index = i;
  1351. try {
  1352. playerApp.loadVideoByPlayerVars(loadVideoByPlayerVarsP20, 0, 0);
  1353. } catch (e) { }
  1354. loadVideoByPlayerVarsP20.index = -1;
  1355. }
  1356. window.loadVideoByPlayerVarsQ20 = loadVideoByPlayerVarsQ20;
  1357.  
  1358. const j = loadVideoByPlayerVarsQ20.get(standardApp);
  1359.  
  1360. const result = Number.isFinite(j) && j >= 0 ? playerAppUA[j] : null;
  1361.  
  1362. const idxSet = new Set(loadVideoByPlayerVarsQ20.values());
  1363.  
  1364. for (let i = 0; i < playerAppUA.length; i++) {
  1365. if (!idxSet.has(i)) playerAppUT.delete(playerAppUA[i]);
  1366. }
  1367. // loadVideoByPlayerVarsQ20.clear();
  1368. if (!result) return result;
  1369. playerAppUT.add(result);
  1370. playerAppXT = result;
  1371. updatePlayerAppFn_();
  1372. if (dirtyMark & 1) dirtyMark -= 1;
  1373. return result;
  1374.  
  1375. }
  1376. window.gt1 = () => playerAppXM();
  1377.  
  1378.  
  1379.  
  1380.  
  1381.  
  1382. const playerDapPTFn = (playerDapPT_) => {
  1383.  
  1384. const playerDapPT = playerDapPT_;
  1385.  
  1386.  
  1387. if (playerDapPT && typeof playerDapPT.getPlayerStateObject === 'function' && !playerDapPT.getPlayerStateObject949) {
  1388.  
  1389. playerDapPT.getPlayerStateObject949 = playerDapPT.getPlayerStateObject;
  1390. playerDapPT.getPlayerStateObject = function () {
  1391. updatePlayerDapFn(this);
  1392. return this.getPlayerStateObject949(...arguments);
  1393. };
  1394.  
  1395. }
  1396. };
  1397.  
  1398.  
  1399. const standardAppPTFn = (standardAppPT_) => {
  1400.  
  1401. const standardAppPT = standardAppPT_;
  1402.  
  1403. if (standardAppPT && typeof standardAppPT.loadVideoByPlayerVars === 'function' && !standardAppPT.loadVideoByPlayerVars311) {
  1404.  
  1405. let lastRecord = [];
  1406.  
  1407. standardAppPT.loadVideoByPlayerVars311 = standardAppPT.loadVideoByPlayerVars;
  1408.  
  1409. standardAppPT.loadVideoByPlayerVars = function (p, C, V, N, H) {
  1410. if (p === loadVideoByPlayerVarsP20) {
  1411. // console.log('loadVideoByPlayerVarsP20', p, p.index)
  1412. loadVideoByPlayerVarsQ20.set(this, p.index);
  1413. return;
  1414. }
  1415. try {
  1416. // update static image here!
  1417. updateStandardAppFn(this)
  1418. if (p && typeof p === 'object') {
  1419.  
  1420. const { adPlacements, adSlots } = p.raw_player_response || {};
  1421. if (isIterable(adPlacements)) adPlacements.length = 0;
  1422. if (isIterable(adSlots)) adSlots.length = 0;
  1423.  
  1424. lastRecord.length = 0;
  1425. lastRecord.push(...[p, C, V, N, H]);
  1426. console.log('lastRecord 03022', [...lastRecord])
  1427. const videoDetails = ((p || 0).raw_player_response || 0).videoDetails || 0;
  1428. if (videoDetails) {
  1429. const thumbnails = (videoDetails.thumbnail || 0).thumbnails || 0;
  1430. const url = thumbnails ? getThumbnailUrlFromThumbnails(thumbnails) : '';
  1431. const videoId = videoDetails.videoId;
  1432. videoId && url && typeof url === 'string' && typeof videoId === 'string' && staticImageMap.set(videoId, url);
  1433. // console.log('staticImageMap set', videoId, url);
  1434. }
  1435. dirtyMark = 1 | 2 | 4 | 8;
  1436. }
  1437.  
  1438. } catch (e) {
  1439. console.warn(e);
  1440. }
  1441.  
  1442. return this.loadVideoByPlayerVars311(...arguments);
  1443. }
  1444. }
  1445.  
  1446.  
  1447. };
  1448.  
  1449.  
  1450.  
  1451. const { internalAppPTFn } = (() => {
  1452.  
  1453. const flags_ = {}
  1454. let qma = 0;
  1455. const flagOn_ = (flags, key, bool) => {
  1456. flags_[key] = flags[key];
  1457. flags[key] = typeof flags[key] === 'boolean' ? bool : `${bool}`;
  1458. }
  1459. const flagOn = () => {
  1460. // return;
  1461. const internalApp = internalAppXM();
  1462. if (!key_yn) return;
  1463. const flags = internalApp?.[key_yn]?.experiments?.flags || 0;
  1464. if (!flags) return;
  1465. if (qma < 0) return;
  1466. qma++;
  1467. if (qma > 1) return;
  1468. flagOn_(flags, 'html5_enable_ssap_autoplay_debug_logging', false);
  1469. // flagOn_(flags, 'enable_visit_advertiser_support_on_ipad_mweb', false);
  1470. // flagOn_(flags, 'html5_shorts_onesie_mismatched_fix', false);
  1471. // flagOn_(flags, 'html5_early_media_for_drm', false);
  1472. // flagOn_(flags, 'allow_vp9_1080p_mq_enc', false);
  1473. // flagOn_(flags, 'html5_onesie_preload_use_content_owner', false);
  1474. flagOn_(flags, 'html5_exponential_memory_for_sticky', false);
  1475. // flagOn_(flags, 'html5_perf_cap_override_sticky', false);
  1476. // flagOn_(flags, 'html5_perserve_av1_perf_cap', false);
  1477. // flagOn_(flags, 'html5_disable_low_pipeline', false);
  1478. flagOn_(flags, 'html5_publish_all_cuepoints', false);
  1479. flagOn_(flags, 'html5_ultra_low_latency_subsegment_readahead', false);
  1480. // flagOn_(flags, 'html5_disable_move_pssh_to_moov', false);
  1481. flagOn_(flags, 'html5_sunset_aac_high_codec_family', false);
  1482. // flagOn_(flags, 'html5_enable_ssap_seteos', false);
  1483.  
  1484. // flagOn_(flags, 'html5_catch_errors_for_rollback', false);
  1485. // flagOn_(flags, 'html5_sabr_enable_utc_seek_requests', false);
  1486. // flagOn_(flags, 'html5_sabr_enable_live_clock_offset', false);
  1487. // flagOn_(flags, 'html5_disable_client_resume_policy_for_sabr', false);
  1488. flagOn_(flags, 'html5_trigger_loader_when_idle_network', false);
  1489.  
  1490. flagOn_(flags, 'web_key_moments_markers', false);
  1491. flagOn_(flags, 'embeds_use_parent_visibility_in_ve_logging', false);
  1492. flagOn_(flags, 'html5_onesie', false);
  1493. qma = 1;
  1494. }
  1495.  
  1496. const flagOff = () => {
  1497.  
  1498. // return;
  1499. const internalApp = internalAppXM();
  1500. if (!key_yn) return;
  1501. const flags = internalApp?.[key_yn]?.experiments?.flags || 0;
  1502. if (!flags) return;
  1503. if (qma <= 0) return;
  1504. qma--;
  1505. if (qma > 1) return;
  1506. for (const [key, value] of Object.entries(flags_)) {
  1507. flags[key] = value;
  1508. }
  1509. qma = 0;
  1510. }
  1511.  
  1512.  
  1513. const internalAppPTFn = (internalAppPT_) => {
  1514.  
  1515. const internalAppPT = internalAppPT_;
  1516.  
  1517.  
  1518. if (internalAppPT && internalAppPT.playVideo && !internalAppPT.playVideo9391) {
  1519. internalAppPT.playVideo9391 = internalAppPT.playVideo;
  1520.  
  1521. internalAppPT.playVideo = function (p, C) {
  1522. updateInternalAppFn(this);
  1523. console.log(`[yt-audio-only] internalApp.playVideo; skipPlayPause=${skipPlayPause}`);
  1524. try {
  1525. flagOn();
  1526. return this.playVideo9391(...arguments);
  1527. } catch (e) {
  1528. console.warn(e);
  1529. } finally {
  1530. flagOff();
  1531. }
  1532. }
  1533. internalAppPT.playVideo.toString = internalAppPT.playVideo9391.toString.bind(internalAppPT.playVideo9391);
  1534.  
  1535.  
  1536.  
  1537. }
  1538.  
  1539.  
  1540. if (internalAppPT && internalAppPT.pauseVideo && !internalAppPT.pauseVideo9391) {
  1541.  
  1542. internalAppPT.pauseVideo9391 = internalAppPT.pauseVideo;
  1543.  
  1544. internalAppPT.pauseVideo = function (p) {
  1545. updateInternalAppFn(this);
  1546. console.log(`[yt-audio-only] internalApp.pauseVideo; skipPlayPause=${skipPlayPause}`);
  1547. try {
  1548. flagOn();
  1549. return this.pauseVideo9391(...arguments);
  1550. } catch (e) {
  1551. console.warn(e);
  1552. } finally {
  1553. flagOff();
  1554. }
  1555. }
  1556. internalAppPT.pauseVideo.toString = internalAppPT.pauseVideo9391.toString.bind(internalAppPT.pauseVideo9391);
  1557.  
  1558.  
  1559. }
  1560.  
  1561.  
  1562. if (internalAppPT && internalAppPT.stopVideo && !internalAppPT.stopVideo9391) {
  1563.  
  1564. internalAppPT.stopVideo9391 = internalAppPT.stopVideo;
  1565.  
  1566. internalAppPT.stopVideo = function () {
  1567. updateInternalAppFn(this);
  1568. console.log(`[yt-audio-only] internalApp.stopVideo; skipPlayPause=${skipPlayPause ? 1 : 0}`);
  1569. try {
  1570. flagOn();
  1571. return this.stopVideo9391(...arguments);
  1572. } catch (e) {
  1573. console.warn(e);
  1574. } finally {
  1575. flagOff();
  1576. }
  1577. }
  1578. internalAppPT.stopVideo.toString = internalAppPT.stopVideo9391.toString.bind(internalAppPT.stopVideo9391);
  1579.  
  1580.  
  1581. }
  1582.  
  1583. if (internalAppPT && internalAppPT.isBackground && !internalAppPT.isBackground9391) {
  1584. internalAppPT.isBackground9391 = internalAppPT.isBackground;
  1585.  
  1586. const f = () => false;
  1587. internalAppPT.isBackground = function () {
  1588. try {
  1589. if (this.visibility.isBackground !== f) this.visibility.isBackground = f;
  1590. return f();
  1591. } catch (e) {
  1592. }
  1593. return false;
  1594. }
  1595.  
  1596. }
  1597.  
  1598. if (internalAppPT && internalAppPT.sendAbandonmentPing && !internalAppPT.sendAbandonmentPing9391) {
  1599. internalAppPT.sendAbandonmentPing9391 = internalAppPT.sendAbandonmentPing;
  1600.  
  1601. internalAppPT.sendAbandonmentPing = function () {
  1602.  
  1603.  
  1604.  
  1605.  
  1606.  
  1607. console.log('[yt-audio-only] sendAbandonmentPing');
  1608.  
  1609. const internalApp = this;
  1610. const iaMedia = internalApp ? internalApp.mediaElement : null;
  1611. if (iaMedia) {
  1612. iaMedia.__publishStatus17__ = 0;
  1613. iaMedia.__publishStatus18__ = 0;
  1614. }
  1615.  
  1616. byPassSync = false;
  1617. skipPlayPause = 0;
  1618. byPassNonFatalError = true;
  1619. byPassPublishPatch = true;
  1620.  
  1621. dirtyMark = 1 | 2 | 4 | 8;
  1622.  
  1623. return this.sendAbandonmentPing9391(...arguments);
  1624. }
  1625. }
  1626.  
  1627.  
  1628.  
  1629. if (internalAppPT && internalAppPT.publish && !internalAppPT.publish48) {
  1630.  
  1631.  
  1632. internalAppPT.publish48 = internalAppPT.publish;
  1633.  
  1634. if (PATCH_MEDIA_PUBLISH) {
  1635.  
  1636.  
  1637.  
  1638. const printObject = (b) => {
  1639. return JSON.stringify(Object.entries(b || {}).filter(e => typeof (e[1] || 0) !== 'object'));
  1640. };
  1641.  
  1642.  
  1643. const errorRS = remapString('error');
  1644.  
  1645. internalAppPT.publish33 = async function (a, b) {
  1646. // console.log(3888, a,b);
  1647.  
  1648.  
  1649. if (byPassPublishPatch) return;
  1650. const isLoaded = await dmo.isLoadedW();
  1651. if (!isLoaded) return;
  1652.  
  1653. // window.gt6 = this;
  1654. const player_ = dmo.playerDapXM() || dmo.playerAppXM();
  1655. if (!player_) return;
  1656.  
  1657.  
  1658. const stateObject = dmo.getPlayerWrappedStateObject();
  1659.  
  1660.  
  1661.  
  1662. let publishStatus = 0;
  1663. const iaMedia = this.mediaElement;
  1664.  
  1665. if (!stateObject || !iaMedia) return;
  1666.  
  1667. if (stateObject.isUnstarted === true) {
  1668.  
  1669. } else if (iaMedia && iaMedia.__publishStatus17__ >= 100 && iaMedia.__publishStatus17__ < 300) {
  1670.  
  1671. if (iaMedia.__publishStatus18__ < Date.now()) {
  1672. iaMedia.__publishStatus17__ = 0;
  1673. iaMedia.__publishStatus18__ = 0;
  1674. return;
  1675. }
  1676. } else {
  1677. return;
  1678. }
  1679.  
  1680.  
  1681. let kb = false;
  1682.  
  1683. const audio = dmo.getMediaElement();
  1684.  
  1685. if (a === 'internalaudioformatchange' && typeof (b.author || 0) === 'string' && iaMedia) {
  1686.  
  1687. kb = kb ? true : ((dmo.updateAtPublish && dmo.updateAtPublish(this)), true);
  1688.  
  1689. byPassSync = false;
  1690. skipPlayPause = 0;
  1691.  
  1692. // byPassSync = true;
  1693. byPassNonFatalError = true;
  1694. await dmo.clearVideoAndQueue();
  1695. await dmo.refreshAllStaleEntitiesForNonReadyAudio();
  1696. byPassNonFatalError = false;
  1697. // byPassSync = false;
  1698. // await cancelPlayback();
  1699. publishStatus = iaMedia.__publishStatus17__ = 100;
  1700.  
  1701. console.log(`[yt-audio-only] publish (internalaudioformatchange, =>100)`);
  1702. iaMedia.__publishStatus18__ = Date.now() + 240;
  1703. if (audio) {
  1704. if (audio[qzk] > 1e9) audio[qzk] = 9;
  1705. audio[qzk] = (audio[qzk] || 0) + 1;
  1706. }
  1707. }
  1708.  
  1709.  
  1710. if (this.mediaElement && audio && a !== 'internalvideoformatchange') {
  1711.  
  1712.  
  1713.  
  1714. if (a.includes('error') || a.includes(errorRS)) {
  1715.  
  1716. if (!iaMedia.__publishStatus17__ || iaMedia.__publishStatus17__ < 200) {
  1717.  
  1718. kb = kb ? true : ((dmo.updateAtPublish && dmo.updateAtPublish(this)), true);
  1719.  
  1720. byPassSync = false;
  1721. skipPlayPause = 0;
  1722. // byPassSync = true;
  1723. byPassNonFatalError = true;
  1724. await dmo.clearVideoAndQueue(); // avoid error in live streaming
  1725. await dmo.refreshAllStaleEntitiesForNonReadyAudio();
  1726. byPassNonFatalError = false;
  1727. // byPassSync = false;
  1728.  
  1729. console.log(`[yt-audio-only] publish (*error*, <200)`);
  1730. }
  1731.  
  1732.  
  1733. } else {
  1734.  
  1735. iaMedia.__publishStatus17__ = iaMedia.__publishStatus17__ || 100;
  1736. iaMedia.__publishStatus18__ = iaMedia.__publishStatus18__ || (Date.now() + 240);
  1737.  
  1738. // const utv = player_.isAtLiveHead();
  1739.  
  1740.  
  1741. if (iaMedia.__publishStatus17__ === 100) {
  1742. kb = kb ? true : ((dmo.updateAtPublish && dmo.updateAtPublish(this)), true);
  1743. byPassNonFatalError = true;
  1744. await dmo.refreshAllStaleEntitiesForNonReadyAudio();
  1745. byPassNonFatalError = false;
  1746. console.log(`[yt-audio-only] publish (***, =100)`);
  1747. }
  1748. if (iaMedia.__publishStatus17__ === 100 && audio.duration > 0 /* && (dmo.getPlayerStateInt() === 3 || dmo.getPlayerStateInt() === 2) */) {
  1749.  
  1750. iaMedia.__publishStatus17__ = 200
  1751.  
  1752. kb = kb ? true : ((dmo.updateAtPublish && dmo.updateAtPublish(this)), true);
  1753.  
  1754. byPassSync = true;
  1755. skipPlayPause = 3;
  1756. byPassNonFatalError = true;
  1757. await dmo.cancelPlayback();
  1758. await dmo.playVideo();
  1759. byPassNonFatalError = false;
  1760. skipPlayPause = 0;
  1761. byPassSync = false;
  1762. await dmo.seekToLiveHeadForLiveStream();
  1763.  
  1764.  
  1765. await dmo.playVideo();
  1766.  
  1767. console.log(`[yt-audio-only] publish (***, duration>0, stateInt=3, =100, =>200)`);
  1768. iaMedia.__publishStatus18__ = Date.now() + 240;
  1769.  
  1770. }
  1771.  
  1772.  
  1773.  
  1774. if (a === 'onLoadedMetadata' && iaMedia.__publishStatus17__ === 200) {
  1775. iaMedia.__publishStatus17__ = 201;
  1776. console.log(`[yt-audio-only] publish (onLoadedMetadata, =200, =>201)`);
  1777. iaMedia.__publishStatus18__ = Date.now() + 240;
  1778. }
  1779. if (a === 'videoelementevent' && b.type === 'loadedmetadata' && iaMedia.__publishStatus17__ === 201) {
  1780. iaMedia.__publishStatus17__ = 202;
  1781. console.log(`[yt-audio-only] publish (videoelementevent.loadedmetadata, =201, =>202)`);
  1782. iaMedia.__publishStatus18__ = Date.now() + 240;
  1783. }
  1784. if (a === 'videoelementevent' && b.type === 'progress' && iaMedia.__publishStatus17__ === 202) {
  1785.  
  1786. iaMedia.__publishStatus17__ = 203;
  1787. // window.debug_mfk = this;
  1788. // window.debug_mfp = player_;
  1789. console.log(`[yt-audio-only] publish (videoelementevent.progress, =202, =>203)`);
  1790. iaMedia.__publishStatus18__ = Date.now() + 240;
  1791. }
  1792. if (iaMedia.__publishStatus17__ === 203 && audio && audio.readyState === 1) {
  1793.  
  1794. // byPassSync = true;
  1795. iaMedia.__publishStatus17__ = 204;
  1796.  
  1797. kb = kb ? true : ((dmo.updateAtPublish && dmo.updateAtPublish(this)), true);
  1798.  
  1799. byPassSync = true;
  1800. skipPlayPause = 3;
  1801. byPassNonFatalError = true;
  1802. await dmo.pauseVideo();
  1803. await dmo.playVideo();
  1804. byPassNonFatalError = false;
  1805. skipPlayPause = 0;
  1806. byPassSync = false;
  1807. console.log('[yt-audio-only] publish skipPlayPause 10002', iaMedia.__publishStatus17__, skipPlayPause);
  1808. await dmo.seekToLiveHeadForLiveStream();
  1809. // byPassSync = false;
  1810.  
  1811. console.log('[yt-audio-only] publish skipPlayPause 10003', iaMedia.__publishStatus17__, skipPlayPause);
  1812. await dmo.playVideo();
  1813.  
  1814. console.log(`[yt-audio-only] publish (***, audio.readyState=1, =203, =>204)`);
  1815. iaMedia.__publishStatus18__ = Date.now() + 240;
  1816.  
  1817. console.log('[yt-audio-only] publish skipPlayPause 10004', iaMedia.__publishStatus17__, skipPlayPause);
  1818.  
  1819. }
  1820.  
  1821.  
  1822. if (iaMedia.__publishStatus17__ < 300 && iaMedia.__publishStatus17__ >= 200 && a === 'videoelementevent' && b.type === 'timeupdate' && !audio.paused && audio.readyState >= 4 && audio.duration > 0) {
  1823. iaMedia.__publishStatus17__ = 300;
  1824. if (!dmo.isAtLiveHeadW()) {
  1825. kb = kb ? true : ((dmo.updateAtPublish && dmo.updateAtPublish(this)), true);
  1826. await dmo.seekToLiveHeadForLiveStream();
  1827. }
  1828.  
  1829. console.log(`[yt-audio-only] publish (videoelementevent.timeupdate, {audio playing}, [200, 300), =>300)`);
  1830. iaMedia.__publishStatus18__ = Date.now() + 240;
  1831. }
  1832.  
  1833.  
  1834. }
  1835.  
  1836.  
  1837. publishStatus = iaMedia.__publishStatus17__;
  1838.  
  1839. if (debugFlg001) console.log('gkps0 publish | ' + publishStatus, a, printObject(b))
  1840.  
  1841. }
  1842. }
  1843.  
  1844. }
  1845.  
  1846. internalAppPT.publish = function (p, C) {
  1847. if (promiseSeek) {
  1848. if (p === 'videoelementevent' && C && C.type === 'playing') {
  1849. promiseSeek.resolve();
  1850. } else if (p === 'SEEK_COMPLETE') {
  1851. promiseSeek.resolve();
  1852. }
  1853. }
  1854.  
  1855. let qb = false;
  1856. if (byPassSync || (byPassNonFatalError && p === 'nonfatalerror')) {
  1857. qb = true;
  1858. }
  1859. if (qb) {
  1860. arguments[0] = p = typeof p === 'string' ? remapString(p) : p;
  1861. }
  1862.  
  1863.  
  1864. if (listAllPublish) console.log('[yt-audio-only] list publish', p, C)
  1865. if (this.publish33) {
  1866. try {
  1867. if (dmo.ready) this.publish33(p, C);
  1868. } catch (e) {
  1869. console.warn(e);
  1870. }
  1871. }
  1872. return this.publish48(...arguments);
  1873. }
  1874.  
  1875. }
  1876.  
  1877.  
  1878.  
  1879.  
  1880. if (!internalAppPT.setMediaElement661 && typeof internalAppPT.setMediaElement === 'function') {
  1881. internalAppPT.setMediaElement661 = internalAppPT.setMediaElement;
  1882. internalAppPT.setMediaElement = function (p) {
  1883. updateInternalAppFn(this);
  1884. console.log('setMediaElement', p)
  1885. delayedUpdateStaticImage(getMediaElement());
  1886. return this.setMediaElement661(...arguments);
  1887. }
  1888. }
  1889.  
  1890.  
  1891.  
  1892. }
  1893.  
  1894. return { internalAppPTFn }
  1895.  
  1896.  
  1897. })();
  1898.  
  1899.  
  1900.  
  1901. let setupFnsB = false;
  1902. const setupFns = () => {
  1903. if (setupFnsB) return;
  1904. setupFnsB = true;
  1905.  
  1906. try {
  1907.  
  1908. const clearVideoAndQueue = async () => { // avoid error in live streaming
  1909. const player_ = playerAppXM();
  1910. const playerD_ = playerDapXM();
  1911. const standardApp = standardAppXM();
  1912. if (standardApp && standardApp.clearQueue) {
  1913. return await standardApp.clearQueue();
  1914. } else if (playerD_ && playerD_.clearQueue) {
  1915. return await playerD_.clearQueue();
  1916. } else if (player_ && player_.clearQueue) {
  1917. return await player_.clearQueue();
  1918. } else {
  1919. return null;
  1920. }
  1921. }
  1922.  
  1923. const cancelPlayback = async () => {
  1924.  
  1925. const player_ = playerAppXM();
  1926. const playerD_ = playerDapXM();
  1927. const standardApp = standardAppXM();
  1928. const internalApp = internalAppXM();
  1929.  
  1930. if (internalApp && internalApp.stopVideo && internalApp.pauseVideo && !internalApp.cancelPlayback) {
  1931. return await internalApp.stopVideo();
  1932. } else if (standardApp && standardApp.cancelPlayback) {
  1933. return await standardApp.cancelPlayback();
  1934. } else if (playerD_ && playerD_.cancelPlayback) {
  1935. return await playerD_.cancelPlayback();
  1936. } else if (player_ && player_.cancelPlayback) {
  1937. return await player_.cancelPlayback();
  1938. } else {
  1939. return null;
  1940. }
  1941. }
  1942.  
  1943. const pauseVideo = async () => {
  1944.  
  1945.  
  1946. const player_ = playerAppXM();
  1947. const playerD_ = playerDapXM();
  1948. const standardApp = standardAppXM();
  1949. const internalApp = internalAppXM();
  1950.  
  1951. if (internalApp && internalApp.stopVideo && internalApp.pauseVideo && !internalApp.cancelPlayback) {
  1952. return await internalApp.pauseVideo();
  1953. } else if (standardApp && standardApp.pauseVideo) {
  1954. return await standardApp.pauseVideo();
  1955. } else if (playerD_ && playerD_.pauseVideo) {
  1956. return await playerD_.pauseVideo();
  1957. } else if (player_ && player_.pauseVideo) {
  1958. return await player_.pauseVideo();
  1959. } else {
  1960. return null
  1961. }
  1962. }
  1963.  
  1964. const playVideo = async () => {
  1965.  
  1966. const player_ = playerAppXM();
  1967. const playerD_ = playerDapXM();
  1968. const standardApp = standardAppXM();
  1969. const internalApp = internalAppXM();
  1970.  
  1971. if (internalApp && internalApp.stopVideo && internalApp.pauseVideo && !internalApp.cancelPlayback && internalApp.playVideo) {
  1972. return await internalApp.playVideo();
  1973. } else if (standardApp && standardApp.playVideo) {
  1974. return await standardApp.playVideo();
  1975. } else if (playerD_ && playerD_.playVideo) {
  1976. return await playerD_.playVideo();
  1977. } else if (player_ && player_.playVideo) {
  1978. return await player_.playVideo();
  1979. } else {
  1980. return null
  1981. }
  1982. }
  1983.  
  1984. const isAtLiveHeadW = async () => {
  1985.  
  1986. const player_ = playerAppXM();
  1987. const playerD_ = playerDapXM();
  1988. const standardApp = standardAppXM();
  1989. const internalApp = internalAppXM();
  1990.  
  1991.  
  1992. if (internalApp && internalApp.isAtLiveHead) {
  1993. return await internalApp.isAtLiveHead()
  1994. } else if (standardApp && standardApp.isAtLiveHead) {
  1995. return await standardApp.isAtLiveHead()
  1996. } else if (playerD_ && playerD_.isAtLiveHead) {
  1997. return await playerD_.isAtLiveHead()
  1998. } else if (player_ && player_.isAtLiveHead) {
  1999. return await player_.isAtLiveHead()
  2000. } else {
  2001. return null;
  2002. }
  2003. }
  2004.  
  2005. const getInternalVideoData = () => {
  2006.  
  2007. const internalApp = internalAppXM();
  2008. if (internalApp && internalApp.videoData) {
  2009. return internalApp.videoData;
  2010. }
  2011. const standardApp = standardAppXM();
  2012. if (standardApp && typeof standardApp.getVideoData === 'function') {
  2013. return standardApp.getVideoData();
  2014. }
  2015. return null;
  2016.  
  2017. }
  2018.  
  2019.  
  2020. const isAdW = async () => {
  2021.  
  2022. const vd = getInternalVideoData() || 0;
  2023.  
  2024. if (vd && typeof vd.isAd === 'function') {
  2025. return await vd.isAd();
  2026. } else if (vd && typeof vd.isAd === 'boolean') {
  2027.  
  2028. return vd.isAd;
  2029.  
  2030. } else {
  2031. return null;
  2032. }
  2033. }
  2034.  
  2035. const isLoadedW = async () => {
  2036.  
  2037. const vd = getInternalVideoData() || 0;
  2038.  
  2039. if (vd && typeof vd.isLoaded === 'function') {
  2040. return await vd.isLoaded();
  2041. } else if (vd && typeof vd.isLoaded === 'boolean') {
  2042.  
  2043. return vd.isLoaded;
  2044.  
  2045. } else {
  2046. return null;
  2047. }
  2048.  
  2049. }
  2050.  
  2051. const getPlayerWrappedStateObject = () => {
  2052.  
  2053.  
  2054. // g.h.oD = function(p) {
  2055. // p = this.app.getPlayerStateObject(p);
  2056. // return {
  2057. // isBuffering: g.r(p, 1),
  2058. // isCued: p.isCued(),
  2059. // isDomPaused: g.r(p, 1024),
  2060. // isEnded: g.r(p, 2),
  2061. // isError: g.r(p, 128),
  2062. // isOrWillBePlaying: p.isOrWillBePlaying(),
  2063. // isPaused: p.isPaused(),
  2064. // isPlaying: p.isPlaying(),
  2065. // isSeeking: g.r(p, 16),
  2066. // isUiSeeking: g.r(p, 32),
  2067. // isUnstarted: g.r(p, 64)
  2068. // }
  2069. // }
  2070.  
  2071.  
  2072. const standardApp = standardAppXM();
  2073. const playerD_ = playerDapXM();
  2074. const player_ = playerAppXM();
  2075. const app = standardApp || playerD_;
  2076. if (app && typeof app.getPlayerStateObject === 'function') {
  2077. const fo = app.getPlayerStateObject();
  2078. const flag = fo ? (fo.state || 0) : 0;
  2079. return {
  2080. isBuffering: (flag & 1) === 1,
  2081. isCued: (flag & 64) === 64 && (flag & 8) === 0 && (flag & 4) === 0,
  2082. isDomPaused: (flag & 1024) === 1024,
  2083. isEnded: (flag & 2) === 2,
  2084. isError: (flag & 128) === 128,
  2085. isOrWillBePlaying: (flag & 8) === 8 && (flag & 2) === 0 && (flag & 1024) === 0,
  2086. isPaused: (flag & 4) === 4,
  2087. isPlaying: (flag & 8) === 8 && (flag & 512) === 0 && (flag & 64) === 0 && (flag & 2) === 0,
  2088. isSeeking: (flag & 16) === 16,
  2089. isUiSeeking: (flag & 32) === 32,
  2090. isUnstarted: (flag & 64) === 64,
  2091. };
  2092. } else if (player_ && typeof player_.getPlayerStateObject === 'function') {
  2093. return player_.getPlayerStateObject();
  2094. } else {
  2095. return {};
  2096. }
  2097.  
  2098. }
  2099.  
  2100. const getPlayerStateInt = () => {
  2101.  
  2102. const playerD_ = playerDapXM();
  2103. const player_ = playerAppXM();
  2104.  
  2105. if (playerD_ && typeof playerD_.getPlayerState === 'function') {
  2106. return playerD_.getPlayerState();
  2107.  
  2108. } else if (player_ && typeof player_.getPlayerState === 'function') {
  2109. return player_.getPlayerState();
  2110.  
  2111. } else {
  2112. return null;
  2113. }
  2114. }
  2115.  
  2116. const updateAtPublish = (x) => {
  2117. dirtyMark = 1 | 2 | 4 | 8;
  2118. updateInternalAppFn(x);
  2119. }
  2120.  
  2121. const refreshAllStaleEntitiesForNonReadyAudio = async () => {
  2122.  
  2123. const player_ = playerAppXM(); // player or xj
  2124. if (!player_) return;
  2125. const audio = getMediaElement();
  2126. try {
  2127. // byPassSync = true;
  2128. if (audio.readyState == 0 && audio.isConnected === true) await player_.refreshAllStaleEntities();
  2129. // byPassSync = false;
  2130. } catch (e) {
  2131. }
  2132. };
  2133. const seekToLiveHeadForLiveStream = async () => {
  2134. const player_ = playerDapXM() || playerAppXM(); // player or xj
  2135. const audio = getMediaElement();
  2136. try {
  2137. audio.isConnected === true && await player_.seekToLiveHead();
  2138. if (audio.isConnected === true && (await player_.isAtLiveHead()) === true) {
  2139. audio.isConnected === true && await player_.seekToStreamTime();
  2140. return true;
  2141. }
  2142. } catch (e) {
  2143. console.log('error_F7', e);
  2144. }
  2145. };
  2146.  
  2147. const trySeekToLiveHead = async () => {
  2148. const player_ = playerDapXM() || playerAppXM(); // player or xj
  2149. try {
  2150. await player_.seekToLiveHead();
  2151. if ((await player_.isAtLiveHead()) === true) {
  2152. await player_.seekToStreamTime();
  2153. }
  2154. } catch (e) { }
  2155. }
  2156.  
  2157. let u75 = 0;
  2158.  
  2159. const delayedUpdateStaticImage = async (target) => {
  2160.  
  2161. if (u75 > 1e9) u75 = 9;
  2162. const t75 = ++u75;
  2163. await delayPn(40);
  2164. if (t75 !== u75) return;
  2165.  
  2166. const date0 = Date.now();
  2167.  
  2168. const mediaEm = target;
  2169.  
  2170. if (!mediaEm || mediaEm.isConnected === false) return;
  2171.  
  2172. let movie_player, h5vc;
  2173.  
  2174. while (Date.now() - date0 < 800) {
  2175. movie_player = mediaEm.closest('#movie_player, #masthead-player');
  2176. h5vc = mediaEm.closest('.html5-video-container');
  2177. if (movie_player && h5vc) break;
  2178. await delayPn(40);
  2179. if (t75 !== u75) return;
  2180. }
  2181.  
  2182. if (!movie_player || !h5vc) return;
  2183.  
  2184. if (!mediaEm || mediaEm.isConnected === false) return;
  2185.  
  2186. if (movie_player.querySelectorAll('video, audio').length !== 1) return;
  2187. if (h5vc.querySelectorAll('video, audio').length !== 1) return;
  2188.  
  2189. let videoId = '';
  2190. try {
  2191. videoId = movie_player && insp(movie_player).getVideoData().video_id;
  2192. } catch (e) { }
  2193.  
  2194. if (!videoId) return;
  2195. let thumbnailUrl = '';
  2196.  
  2197. if (videoId) { thumbnailUrl = staticImageMap.get(videoId); }
  2198.  
  2199. if (!thumbnailUrl) return;
  2200.  
  2201. const displayImage = `url(${thumbnailUrl})`;
  2202. h5vc.style.setProperty('--audio-only-thumbnail-image', `${displayImage}`);
  2203.  
  2204. }
  2205. Object.assign(dmo, { clearVideoAndQueue, cancelPlayback, pauseVideo, playVideo, isAtLiveHeadW, updateAtPublish, refreshAllStaleEntitiesForNonReadyAudio, seekToLiveHeadForLiveStream, ready: true, isLoadedW, getMediaElement, playerAppXM, standardAppXM, internalAppXM, playerDapXM, getPlayerStateInt, getPlayerWrappedStateObject, getInternalVideoData, delayedUpdateStaticImage });
  2206.  
  2207.  
  2208.  
  2209. const getPublishStatus17 = () => {
  2210.  
  2211. const internalApp = internalAppXM();
  2212. const iaMedia = internalApp ? internalApp.mediaElement : null;
  2213. return iaMedia ? iaMedia.__publishStatus17__ : null;
  2214. }
  2215.  
  2216. const shouldWaitPublish = () => {
  2217. let waitPublish = false;
  2218. const internalApp = internalAppXM();
  2219. const iaMedia = internalApp ? internalApp.mediaElement : null;
  2220. const stateObject = getPlayerWrappedStateObject();
  2221. if (stateObject && stateObject.isUnstarted === true) {
  2222. waitPublish = true;
  2223. } else if (iaMedia && iaMedia.__publishStatus17__ >= 100 && iaMedia.__publishStatus17__ < 300) {
  2224. waitPublish = true;
  2225. } else {
  2226. waitPublish = false;
  2227. }
  2228. return waitPublish;
  2229. }
  2230.  
  2231. let playBusy = 0;
  2232. if (!HTMLAudioElement.prototype.play3828 && !HTMLAudioElement.prototype.pause3828 && PATCH_MEDIA_PLAYPAUSE) {
  2233.  
  2234.  
  2235. HTMLAudioElement.prototype.pause3828 = HTMLAudioElement.prototype.pause;
  2236. HTMLAudioElement.prototype.pause = function () {
  2237. if (skipPlayPause & 2) return;
  2238.  
  2239. if (getMediaElement() === this) {
  2240.  
  2241. const internalApp = internalAppXM();
  2242. const iaMedia = internalApp ? internalApp.mediaElement : null;
  2243. if (iaMedia) {
  2244. iaMedia.__publishStatus17__ = 0;
  2245. iaMedia.__publishStatus18__ = 0;
  2246. }
  2247. }
  2248.  
  2249. if (playBusy > 0) {
  2250.  
  2251. return this.pause3828();
  2252. } else {
  2253. const audio = this;
  2254.  
  2255. if (audio[qzk] > 1e9) audio[qzk] = 9;
  2256. const lzt = audio[qzk] ? ++audio[qzk] : (audio[qzk] = 1);
  2257. return this.pause3828();
  2258. }
  2259.  
  2260.  
  2261. }
  2262.  
  2263.  
  2264. HTMLAudioElement.prototype.play3828 = HTMLAudioElement.prototype.play;
  2265. HTMLAudioElement.prototype.play = async function () {
  2266. if (skipPlayPause & 1) return;
  2267.  
  2268. if (playBusy > 0) return await this.play3828();
  2269.  
  2270. const audio = this;
  2271.  
  2272. if (audio[qzk] > 1e9) audio[qzk] = 9;
  2273. const lzt = audio[qzk] ? ++audio[qzk] : (audio[qzk] = 1);
  2274.  
  2275. console.log(`[yt-audio-only] video.play01 {${lzt}}`);
  2276. if (getMediaElement() !== this) {
  2277. dirtyMark = 1 | 2 | 4 | 8;
  2278. }
  2279.  
  2280. if (getPublishStatus17() === null) {
  2281. // video switching -> ad media 3600
  2282. console.log('wait for mediaElement')
  2283. await delayPn(400);
  2284. if (lzt !== audio[qzk]) return;
  2285. }
  2286.  
  2287. if (audio !== getMediaElement()) {
  2288. // video switching -> ad media 3600
  2289. console.log('wait for correct mediaElement')
  2290. await delayPn(400);
  2291. if (lzt !== audio[qzk]) return;
  2292. }
  2293.  
  2294. console.log(`[yt-audio-only] video.play02 {${lzt}}`, getPublishStatus17())
  2295. // if ((await isAdW()) === true) return;
  2296.  
  2297.  
  2298. const internalApp = internalAppXM();
  2299.  
  2300. let isAtLiveHead = await isAtLiveHeadW();
  2301. // window.dmo = dmo;
  2302. (internalApp || 0).mediaElement && audio === getMediaElement() && Promise.resolve().then(async () => {
  2303.  
  2304. // if(audio.isConnected === false) return;
  2305.  
  2306. if (lzt !== audio[qzk]) return;
  2307. dirtyMark = 1 | 2 | 4 | 8;
  2308.  
  2309. // between play02 and play03, < publish (***, duration>0, stateInt=3, =100, =>200) > should occur
  2310. console.log(`[yt-audio-only] video.play03 {${lzt}}`, getPublishStatus17())
  2311.  
  2312. if (!shouldWaitPublish()) {
  2313. await delayPn(80);
  2314. dirtyMark = 1 | 2 | 4 | 8;
  2315. if (lzt !== audio[qzk]) return;
  2316. }
  2317.  
  2318. if (shouldWaitPublish()) {
  2319. await delayPn(400);
  2320. dirtyMark = 1 | 2 | 4 | 8;
  2321. if (lzt !== audio[qzk]) return;
  2322. }
  2323.  
  2324. // if(audio.isConnected === false) return;
  2325. const publishStatus1701 = getPublishStatus17();
  2326.  
  2327.  
  2328. console.log(`[yt-audio-only] video.play04 {${lzt}}`, publishStatus1701);
  2329.  
  2330. if (getMediaElement() !== this) {
  2331. dirtyMark = 1 | 2 | 4 | 8;
  2332. }
  2333. if (internalApp !== internalAppXM()) return;
  2334. if (!internalApp.mediaElement) return;
  2335. if (audio !== getMediaElement()) return;
  2336. const stateObject = getPlayerWrappedStateObject();
  2337.  
  2338. if (stateObject.isDomPaused && stateObject.isBuffering && !stateObject.isOrWillBePlaying && !stateObject.isPaused && !stateObject.isPlaying && !stateObject.isSeeking && stateObject.isUnstarted) {
  2339. // allow case; would fall into (publishStatus1701 > 200 && publishStatus1701 < 300) case
  2340. } else if (stateObject.isDomPaused && stateObject.isBuffering && !stateObject.isOrWillBePlaying && !stateObject.isPaused && !stateObject.isPlaying && stateObject.isSeeking && stateObject.isUnstarted) {
  2341. // allow case; would fall into (publishStatus1701 > 200 && publishStatus1701 < 300) case
  2342. } else {
  2343. if (stateObject.isOrWillBePlaying === false || stateObject.isPaused === true || stateObject.isEnded === true) {
  2344. console.log('[yt-audio-only] leave', stateObject)
  2345. if (publishStatus1701 === 300 && (await isLoadedW()) === true && !isAtLiveHead && !skipPlayPause && !byPassPublishPatch && !byPassNonFatalError) {
  2346. if (lzt !== audio[qzk]) return;
  2347. // guess - paused before. switching video -> remains paused status
  2348. byPassNonFatalError = true;
  2349. byPassPublishPatch = true;
  2350. skipPlayPause = 3;
  2351. await cancelPlayback();
  2352. await playVideo();
  2353. skipPlayPause = 0;
  2354. byPassNonFatalError = false;
  2355. byPassPublishPatch = false;
  2356. }
  2357. return;
  2358. }
  2359. }
  2360.  
  2361. console.log(`[yt-audio-only] video.play05 {${lzt}}`, publishStatus1701);
  2362.  
  2363. console.log(1293, stateObject);
  2364.  
  2365. let bool = false;
  2366. if (stateObject.isBuffering && !stateObject.isEnded && !stateObject.isError && stateObject.isSeeking && stateObject.isUnstarted && !stateObject.isCued) {
  2367. bool = true;
  2368. } else if (stateObject.isOrWillBePlaying && stateObject.isSeeking && !stateObject.isCued && stateObject.isPlaying) {
  2369. bool = true;
  2370. } else if (publishStatus1701 > 200 && publishStatus1701 < 300) {
  2371. // loadedmetadata done
  2372. bool = true;
  2373. }
  2374.  
  2375.  
  2376. if (!isAtLiveHead && stateObject.isUnstarted === true && stateObject.isOrWillBePlaying) {
  2377. const vd = getInternalVideoData();
  2378. if (vd.isLivePlayback && vd.isLiveHeadPlayable) {
  2379. console.log('isAtLiveHead: false -> true')
  2380. isAtLiveHead = true;
  2381. }
  2382. }
  2383.  
  2384. console.log(3882, bool, isAtLiveHead)
  2385.  
  2386. if (bool) {
  2387.  
  2388. console.log(`[yt-audio-only] video.play06 {${lzt}}`, publishStatus1701);
  2389.  
  2390. if (internalApp !== internalAppXM()) return;
  2391. if (!internalApp.mediaElement) return;
  2392.  
  2393.  
  2394. // if(audio.isConnected === false) return;
  2395.  
  2396. playBusy++;
  2397.  
  2398. console.log(`[yt-audio-only] video.play07 {${lzt}}`, publishStatus1701);
  2399.  
  2400.  
  2401. // if (!audio.closest('ytd-miniplayer')) {
  2402.  
  2403.  
  2404. // byPassSync = true;
  2405. byPassNonFatalError = true;
  2406. byPassPublishPatch = true;
  2407. skipPlayPause = 3;
  2408. if ((await isLoadedW()) === false) {
  2409. console.log(`[yt-audio-only] video.play07.1 {${lzt}}`, "isLoadedW = false");
  2410. await clearVideoAndQueue();
  2411. await cancelPlayback();
  2412. } else {
  2413. console.log(`[yt-audio-only] video.play07.1 {${lzt}}`, "isLoadedW = true");
  2414. await cancelPlayback();
  2415. }
  2416. await delayPn(80); // wait some time for byPassNonFatalError and byPassPublishPatch
  2417. skipPlayPause = 0;
  2418. byPassNonFatalError = false;
  2419. byPassPublishPatch = false;
  2420. // }
  2421.  
  2422. dirtyMark = 1 | 2 | 4 | 8;
  2423.  
  2424. console.log(`[yt-audio-only] video.play08 {${lzt}}`, getPublishStatus17());
  2425.  
  2426.  
  2427. // await delayPn(40);
  2428. // await audio.pause();
  2429.  
  2430. const promiseSeek_ = promiseSeek = new PromiseExternal();
  2431.  
  2432.  
  2433. // listAllPublish = true;
  2434. if (isAtLiveHead) {
  2435. await trySeekToLiveHead();
  2436. }
  2437. const qX = getPlayerWrappedStateObject();
  2438. if (qX.isBuffering || qX.isSeeking || qX.isUnstarted) {
  2439. await playVideo();
  2440. }
  2441. if (isAtLiveHead === true && (await isAtLiveHeadW()) === false) {
  2442. await trySeekToLiveHead();
  2443. }
  2444.  
  2445. await delayPn(80);
  2446.  
  2447. // byPassSync = false;
  2448. playBusy--;
  2449.  
  2450. if (lzt !== audio[qzk]) return; // abnormal
  2451.  
  2452. if (promiseSeek_ !== promiseSeek) return; // abnormal
  2453.  
  2454. console.log(`[yt-audio-only] video.play10 {${lzt}}`, getPublishStatus17());
  2455.  
  2456. const r = await Promise.race([promiseSeek_, delayPn(400).then(() => 123)]);
  2457. promiseSeek = null;
  2458.  
  2459. if (getPlayerWrappedStateObject().isDomPaused) {
  2460. console.log('manual playing is required') // found in Firefox
  2461. return;
  2462. }
  2463.  
  2464. if (lzt !== audio[qzk]) return; // normal
  2465.  
  2466.  
  2467. console.log(`[yt-audio-only] video.play11 {${lzt}}`, getPublishStatus17(), r, isAtLiveHead, await isAtLiveHeadW());
  2468.  
  2469. if (r === 123 && isAtLiveHead === true && (await isAtLiveHeadW()) === false) {
  2470. console.log(`[yt-audio-only] video.play11.1 {${lzt}}`, getPublishStatus17());
  2471. await trySeekToLiveHead();
  2472. dirtyMark = 1 | 2 | 4 | 8;
  2473. console.log(`[yt-audio-only] video.play11.2 {${lzt}}`, getPublishStatus17());
  2474. }
  2475. await delayPn(80); // wait sometime for next checking
  2476.  
  2477. if (lzt !== audio[qzk]) return; // normal
  2478.  
  2479. console.log(`[yt-audio-only] video.play12 {${lzt}}`, getPublishStatus17(), r, isAtLiveHead, await isAtLiveHeadW());
  2480.  
  2481. // ----- play safe ----
  2482.  
  2483. let stateObject = getPlayerWrappedStateObject();
  2484.  
  2485. if (stateObject.isPlaying && stateObject.isOrWillBePlaying && !stateObject.isPaused) return; // normal checking
  2486. if (stateObject.isError || stateObject.isEnded) return; // error checking
  2487.  
  2488. // retry
  2489.  
  2490. console.log(`[yt-audio-only] video.play13 {${lzt}}`, getPublishStatus17(), r, { ...stateObject });
  2491.  
  2492. if (stateObject && !stateObject.isSeeking) {
  2493. if (stateObject.isError || stateObject.isEnded) {
  2494. } else if (stateObject.isOrWillBePlaying && stateObject.isPlaying && !stateObject.isPaused) {
  2495. } else {
  2496.  
  2497. console.log(`[yt-audio-only] video.play13.1 {${lzt}}`, getPublishStatus17(), r, { ...stateObject });
  2498. try {
  2499. // listAllPublish = false;
  2500. dirtyMark = 1 | 2 | 4 | 8;
  2501. await playVideo();
  2502. } catch (e) {
  2503. }
  2504. }
  2505. }
  2506.  
  2507.  
  2508. // ----- play safe ----
  2509.  
  2510.  
  2511. } else if (!stateObject.isDomPaused && stateObject.isBuffering && stateObject.isOrWillBePlaying && !stateObject.isSeeking && !stateObject.isUnstarted) {
  2512. console.log(3883)
  2513. playBusy++;
  2514. await delayPn(80);
  2515. playVideo();
  2516. await delayPn(80);
  2517. if (isAtLiveHead === true && (await isAtLiveHeadW()) === false) {
  2518. console.log(`[yt-audio-only] video.play21.1 {${lzt}}`, getPublishStatus17());
  2519. await trySeekToLiveHead();
  2520. dirtyMark = 1 | 2 | 4 | 8;
  2521. console.log(`[yt-audio-only] video.play21.2 {${lzt}}`, getPublishStatus17());
  2522. await delayPn(80); // wait sometime for playBusy
  2523. }
  2524. playBusy--;
  2525.  
  2526. } else if (!stateObject.isDomPaused && !stateObject.isBuffering && stateObject.isOrWillBePlaying && !stateObject.isSeeking && !stateObject.isUnstarted) {
  2527. console.log(3884)
  2528. playBusy++;
  2529. await delayPn(80);
  2530. playVideo();
  2531. await delayPn(80);
  2532. if (isAtLiveHead === true && (await isAtLiveHeadW()) === false) {
  2533. console.log(`[yt-audio-only] video.play23.1 {${lzt}}`, getPublishStatus17());
  2534. await trySeekToLiveHead();
  2535. dirtyMark = 1 | 2 | 4 | 8;
  2536. console.log(`[yt-audio-only] video.play23.2 {${lzt}}`, getPublishStatus17());
  2537. await delayPn(80); // wait sometime for playBusy
  2538. }
  2539. playBusy--;
  2540. } else {
  2541. console.log(3889, stateObject)
  2542. }
  2543.  
  2544.  
  2545.  
  2546. }).catch(console.warn);
  2547.  
  2548.  
  2549. try {
  2550. dirtyMark = 1 | 2 | 4 | 8;
  2551. playBusy++;
  2552.  
  2553. return await this.play3828();
  2554. } catch (e) {
  2555.  
  2556. } finally {
  2557.  
  2558.  
  2559. playBusy--;
  2560. dirtyMark = 1 | 2 | 4 | 8;
  2561. }
  2562.  
  2563.  
  2564.  
  2565. }
  2566.  
  2567.  
  2568. }
  2569.  
  2570.  
  2571.  
  2572. console.log('[yt-audio-only] DONE')
  2573.  
  2574. } catch (e) {
  2575. console.warn(e);
  2576. }
  2577.  
  2578.  
  2579.  
  2580.  
  2581. }
  2582.  
  2583. const setupAudioPlaying = (player00_) => {
  2584.  
  2585. // console.log(5939,player00_);
  2586.  
  2587. try {
  2588. const player_ = player00_;
  2589. if (!player_) return;
  2590. if (player_.__audio544__) return;
  2591. player_.__audio544__ = 1;
  2592.  
  2593. updatePlayerAppFn(player_);
  2594.  
  2595. } catch (e) {
  2596. console.warn(e);
  2597. }
  2598. }
  2599.  
  2600. if (!window.__ugAtg3747__) {
  2601. window.__ugAtg3747__ = true;
  2602. const updateLastActiveTimeGeneral = () => {
  2603. // player_ -> yuu
  2604. const player_ = playerDapXM() || playerAppXM();
  2605. if (player_) player_.updateLastActiveTime();
  2606. };
  2607. document.addEventListener('timeupdate', updateLastActiveTimeGeneral, true);
  2608. }
  2609.  
  2610. return { setupAudioPlaying, internalAppPTFn, standardAppPTFn, playerDapPTFn };
  2611.  
  2612. })();
  2613.  
  2614.  
  2615. if (location.origin === 'https://www.youtube.com') {
  2616.  
  2617.  
  2618.  
  2619. if (location.pathname.startsWith('/embed/')) {
  2620.  
  2621. // youtube embed
  2622.  
  2623. const ytEmbedReady = observablePromise(() => document.querySelector('#player > .ytp-embed')).obtain();
  2624.  
  2625. const embedConfigFix = (async () => {
  2626. while (true) {
  2627. const config_ = typeof yt !== 'undefined' ? (yt || 0).config_ : 0;
  2628. if (config_) {
  2629. ytConfigFix(config_);
  2630. break;
  2631. }
  2632. await delayPn(60);
  2633. }
  2634. });
  2635.  
  2636. ytEmbedReady.then(async (embedPlayer) => {
  2637.  
  2638. embedConfigFix();
  2639.  
  2640. const player_ = embedPlayer;
  2641. console.log(5919, player_)
  2642.  
  2643. setupAudioPlaying(player_); // dekstop embed
  2644.  
  2645.  
  2646. if (SHOW_VIDEO_STATIC_IMAGE) {
  2647.  
  2648. let displayImage = '';
  2649. let html5Container = null;
  2650.  
  2651.  
  2652. const moviePlayer = document.querySelector('#movie_player .html5-video-container .video-stream.html5-main-video, #masthead-player .html5-video-container .video-stream.html5-main-video');
  2653. if (moviePlayer) {
  2654. html5Container = moviePlayer.closest('.html5-video-container');
  2655. }
  2656.  
  2657. if (html5Container) {
  2658.  
  2659. const overlayImage = document.querySelector('#movie_player .ytp-cued-thumbnail-overlay-image[style], #masthead-player .ytp-cued-thumbnail-overlay-image[style]');
  2660. if (overlayImage) {
  2661.  
  2662. const cStyle = window.getComputedStyle(overlayImage);
  2663. const cssImageValue = cStyle.backgroundImage;
  2664. if (cssImageValue && typeof cssImageValue === 'string' && cssImageValue.startsWith('url(')) {
  2665. displayImage = cssImageValue;
  2666.  
  2667. }
  2668.  
  2669. }
  2670.  
  2671. if (!displayImage) {
  2672.  
  2673. const config_ = typeof yt !== 'undefined' ? (yt || 0).config_ : 0;
  2674. let embedded_player_response = null;
  2675. if (config_) {
  2676. embedded_player_response = ((config_.PLAYER_VARS || 0).embedded_player_response || 0)
  2677. }
  2678. if (embedded_player_response && typeof embedded_player_response === 'string') {
  2679.  
  2680. let idx1 = embedded_player_response.indexOf('"defaultThumbnail"');
  2681. let idx2 = idx1 >= 0 ? embedded_player_response.lastIndexOf('"defaultThumbnail"') : -1;
  2682.  
  2683. if (idx1 === idx2 && idx1 > 0) {
  2684.  
  2685. let bk = 0;
  2686. let j = -1;
  2687. for (let i = idx1; i < embedded_player_response.length; i++) {
  2688. if (i > idx1 + 40 && bk === 0) {
  2689. j = i;
  2690. break;
  2691. }
  2692. let t = embedded_player_response.charAt(i);
  2693. if (t === '{') bk++;
  2694. else if (t === '}') bk--;
  2695. }
  2696.  
  2697. if (j > idx1) {
  2698.  
  2699. let defaultThumbnailString = embedded_player_response.substring(idx1, j);
  2700. let defaultThumbnailObject = null;
  2701.  
  2702. try {
  2703. defaultThumbnailObject = JSON.parse(`{${defaultThumbnailString}}`);
  2704.  
  2705. } catch (e) { }
  2706.  
  2707. const thumbnails = ((defaultThumbnailObject.defaultThumbnail || 0).thumbnails || 0);
  2708.  
  2709. if (thumbnails && thumbnails.length >= 1) {
  2710.  
  2711. let thumbnailUrl = getThumbnailUrlFromThumbnails(thumbnails);
  2712.  
  2713. if (thumbnailUrl && thumbnailUrl.length > 3) {
  2714. displayImage = `url(${thumbnailUrl})`;
  2715. }
  2716. }
  2717. }
  2718.  
  2719. }
  2720.  
  2721.  
  2722. }
  2723.  
  2724.  
  2725. }
  2726.  
  2727. if (displayImage) {
  2728.  
  2729. html5Container.style.setProperty('--audio-only-thumbnail-image', `${displayImage}`);
  2730. } else {
  2731. html5Container.style.removeProperty('--audio-only-thumbnail-image')
  2732. }
  2733.  
  2734. }
  2735.  
  2736.  
  2737. }
  2738.  
  2739. });
  2740.  
  2741.  
  2742. } else {
  2743.  
  2744.  
  2745. // youtube normal
  2746.  
  2747. attachOneTimeEvent('yt-action', () => {
  2748. const config_ = typeof yt !== 'undefined' ? (yt || 0).config_ : 0;
  2749. ytConfigFix(config_);
  2750. });
  2751.  
  2752. let r3 = new PromiseExternal();
  2753. document.addEventListener('yt-action', () => {
  2754. let u = document.querySelector('ytd-watch-flexy');
  2755. if (u && typeof insp(u).calculateCurrentPlayerSize_ === 'function') {
  2756. r3.resolve(u);
  2757. }
  2758.  
  2759. }, true);
  2760.  
  2761. r3.then((watchFlexy) => {
  2762. // for offline video, without audio -> so no size
  2763.  
  2764. if (!watchFlexy) return;
  2765. const cnt = insp(watchFlexy);
  2766. if (typeof cnt.calculateCurrentPlayerSize_ === 'function' && !cnt.calculateCurrentPlayerSize3991_) {
  2767.  
  2768. cnt.calculateCurrentPlayerSize3991_ = cnt.calculateCurrentPlayerSize_;
  2769. cnt.calculateCurrentPlayerSize_ = function () {
  2770. const r = this.calculateCurrentPlayerSize3991_(...arguments);
  2771.  
  2772. if (r && r.width > 10 && !Number.isFinite(r.height)) {
  2773. r.height = Math.round(r.width / 16 * 9);
  2774. }
  2775. return r;
  2776.  
  2777. }
  2778.  
  2779. }
  2780.  
  2781. });
  2782.  
  2783.  
  2784.  
  2785. customElements.whenDefined('ytd-player').then(() => {
  2786. const dummy = document.querySelector('ytd-player') || document.createElement('ytd-player');
  2787. const cnt = insp(dummy);
  2788. const cProto = cnt.constructor.prototype;
  2789. cProto.createMainAppPlayer932_ = cProto.createMainAppPlayer_;
  2790. cProto.initPlayer932_ = cProto.initPlayer_;
  2791. const configFixBeforeCreate = () => {
  2792. try {
  2793. const config_ = typeof yt !== 'undefined' ? (yt || 0).config_ : 0;
  2794. if (config_) {
  2795. ytConfigFix(config_);
  2796. }
  2797. } catch (e) { }
  2798. }
  2799. cProto.createMainAppPlayer_ = function (a, b, c) {
  2800. configFixBeforeCreate();
  2801. let r = this.createMainAppPlayer932_(a, b, c);
  2802. try {
  2803. (async () => {
  2804. const e = await this.mainAppPlayer_.api;
  2805. setupAudioPlaying(e); // desktop normal
  2806. })();
  2807. } finally {
  2808. return r;
  2809. }
  2810. }
  2811. cProto.initPlayer_ = function (a) {
  2812. configFixBeforeCreate();
  2813. let r = this.initPlayer932_(a);
  2814. try {
  2815. (async () => {
  2816. const e = await r;
  2817. setupAudioPlaying(this.player_); // desktop normal
  2818. })();
  2819. } finally {
  2820. return r;
  2821. }
  2822. }
  2823. });
  2824.  
  2825. }
  2826.  
  2827.  
  2828. } else if (location.origin === 'https://m.youtube.com') {
  2829.  
  2830. removeBottomOverlayForMobile = async (delay) => {
  2831.  
  2832.  
  2833. let closeBtnRenderer = document.querySelector('.ytm-bottom-sheet-overlay-renderer-close.icon-close');
  2834. if (closeBtnRenderer) {
  2835.  
  2836. const btn = closeBtnRenderer.querySelector('button');
  2837. const container = closeBtnRenderer.closest('#global-loader ~ .ytm-bottom-sheet-overlay-container');
  2838.  
  2839. if (container) {
  2840. container.style.visibility = 'collapse';
  2841. container.style.zIndex = '-1';
  2842. }
  2843. if (btn) {
  2844. if (delay) {
  2845. await delayPn(delay);
  2846. }
  2847. btn.click();
  2848. }
  2849. }
  2850.  
  2851. }
  2852.  
  2853. const getAppJSON = () => {
  2854. let t;
  2855. t = document.querySelector('player-microformat-renderer.PlayerMicroformatRendererHost script[type="application/ld+json"]');
  2856. if (t) return t;
  2857. t = document.querySelector('player-microformat-renderer.playerMicroformatRendererHost script[type="application/ld+json"]');
  2858. if (t) return t;
  2859.  
  2860. return null;
  2861.  
  2862. }
  2863.  
  2864.  
  2865. let lastPlayerInfoText = '';
  2866. let mz = 0;
  2867. onVideoChangeForMobile = async () => {
  2868.  
  2869.  
  2870. let html5Container = null;
  2871.  
  2872. const moviePlayer = document.querySelector('#player .html5-video-container .video-stream.html5-main-video');
  2873. if (moviePlayer) {
  2874. html5Container = moviePlayer.closest('.html5-video-container');
  2875. }
  2876.  
  2877. console.log('STx00', html5Container)
  2878. if (!html5Container) return;
  2879. let thumbnailUrl = '';
  2880.  
  2881. if (mz > 1e9) mz = 9;
  2882. let mt = ++mz;
  2883.  
  2884. const scriptText = await observablePromise(() => {
  2885. if (mt !== mz) return 1;
  2886. const t = getAppJSON();
  2887. const tt = (t ? t.textContent : '') || '';
  2888. if (tt === lastPlayerInfoText) return;
  2889. return tt;
  2890. }).obtain();
  2891. if (typeof scriptText !== 'string') return; // 1
  2892. lastPlayerInfoText = scriptText;
  2893.  
  2894. if (!scriptText) return;
  2895.  
  2896.  
  2897. if (SHOW_VIDEO_STATIC_IMAGE) {
  2898. console.log('STx01')
  2899.  
  2900. let idx1 = scriptText.indexOf('"thumbnailUrl"');
  2901. let idx2 = idx1 >= 0 ? scriptText.lastIndexOf('"thumbnailUrl"') : -1;
  2902.  
  2903. if (idx1 === idx2 && idx1 > 0) {
  2904.  
  2905. let bk = 0;
  2906. let j = -1;
  2907. for (let i = idx1; i < scriptText.length; i++) {
  2908. if (i > idx1 + 20 && bk === 0) {
  2909. j = i;
  2910. break;
  2911. }
  2912. let t = scriptText.charAt(i);
  2913. if (t === '[') bk++;
  2914. else if (t === ']') bk--;
  2915. else if (t === '{') bk++;
  2916. else if (t === '}') bk--;
  2917. }
  2918.  
  2919.  
  2920. if (j > idx1) {
  2921.  
  2922. let thumbnailUrlString = scriptText.substring(idx1, j);
  2923. let thumbnailUrlObject = null;
  2924.  
  2925. try {
  2926. thumbnailUrlObject = JSON.parse(`{${thumbnailUrlString}}`);
  2927.  
  2928. } catch (e) { }
  2929.  
  2930. const thumbnails = thumbnailUrlObject.thumbnailUrl;
  2931.  
  2932. if (thumbnails && thumbnails.length >= 1 && typeof thumbnails[0] === 'string') {
  2933. if (thumbnails[0] && thumbnails[0].length > 3) {
  2934. thumbnailUrl = thumbnails[0];
  2935. }
  2936. }
  2937. }
  2938.  
  2939. }
  2940. console.log('STx02', thumbnailUrl);
  2941.  
  2942. if (thumbnailUrl && typeof thumbnailUrl === 'string') {
  2943. html5Container.style.setProperty('--audio-only-thumbnail-image', `url(${thumbnailUrl})`);
  2944. } else {
  2945. html5Container.style.removeProperty('--audio-only-thumbnail-image')
  2946. }
  2947.  
  2948. }
  2949.  
  2950.  
  2951. if (removeBottomOverlayForMobile) await removeBottomOverlayForMobile(40);
  2952.  
  2953. await delayPn(80);
  2954. const audio = moviePlayer;
  2955. if (audio && audio.muted === true && audio.isConnected === true && audio.readyState >= 0 && audio.networkState >= 2 && audio.paused === false) {
  2956. await audio.click();
  2957. }
  2958.  
  2959. }
  2960.  
  2961. let player0 = null;
  2962. const mff = function (e) {
  2963. const target = (e || 0).target || 0;
  2964. if (target !== player0 && target && typeof target.getPlayerState === 'function') {
  2965. player0 = target;
  2966. setupAudioPlaying(target); // mobile
  2967. }
  2968. }
  2969.  
  2970. document.addEventListener('player-initialized', mff, true);
  2971. document.addEventListener('player-state-change', mff, true);
  2972. document.addEventListener('player-ad-state-change', mff, true);
  2973. document.addEventListener('player-detailed-error', mff, true);
  2974. document.addEventListener('player-error', mff, true);
  2975. document.addEventListener('on-play-autonav-video', mff, true);
  2976. document.addEventListener('on-play-previous-autonav-video', mff, true);
  2977. document.addEventListener('player-fullscreen-change', mff, true);
  2978. document.addEventListener('player-fullscreen-toggled', mff, true);
  2979. document.addEventListener('player-dom-paused', mff, true);
  2980. document.addEventListener('yt-show-toast', mff, true);
  2981. document.addEventListener('yt-innertube-command', mff, true);
  2982. document.addEventListener('yt-update-c3-companion', mff, true);
  2983. document.addEventListener('video-data-change', mff, true);
  2984. document.addEventListener('video-progress', mff, true);
  2985. document.addEventListener('local-media-change', mff, true);
  2986.  
  2987.  
  2988.  
  2989. document.addEventListener('video-progress', updateLastActiveTimeAsync, true); // mobile
  2990.  
  2991.  
  2992.  
  2993. // document.addEventListener('DOMContentLoaded', (evt) => {
  2994. // const mo = new MutationObserver((mutations)=>{
  2995. // console.log(5899, mutations)
  2996. // });
  2997. // mo.observe(document, {subtree: true, childList: true})
  2998. // })
  2999.  
  3000. // window.addEventListener('onReady', (evt) => {
  3001. // console.log(6811)
  3002. // }, true);
  3003.  
  3004. // window.addEventListener('localmediachange', (evt) => {
  3005. // console.log(6812)
  3006. // }, true);
  3007.  
  3008. // window.addEventListener('onVideoDataChange', (evt) => {
  3009. // console.log(6813)
  3010. // }, true);
  3011.  
  3012. window.addEventListener('state-navigateend', async (evt) => {
  3013.  
  3014. delayPn(200).then(() => {
  3015. if (!getAppJSON()) {
  3016. console.log('[mobile youtube audio only] getAppJSON fails.', document.querySelectorAll('script[type="application/ld+json"]').length);
  3017. }
  3018. });
  3019.  
  3020. const config_ = typeof yt !== 'undefined' ? (yt || 0).config_ : 0;
  3021. ytConfigFix(config_);
  3022.  
  3023. try {
  3024. if (clickLockFn && clickTarget) {
  3025.  
  3026. let a = HTMLElement.prototype.querySelector.call(clickTarget, '.video-stream.html5-main-video');
  3027. if (!a) return;
  3028.  
  3029. if (a.muted === true && a.__spfgs__ !== true && a.paused === true && a.networkState === 0 && a.readyState === 0) {
  3030.  
  3031. const pr = new Promise(resolve => {
  3032.  
  3033. document.addEventListener('player-state-change', resolve, { once: true, passive: true, capture: false });
  3034.  
  3035. }).then();
  3036.  
  3037. clickLockFn.call(clickTarget, mockEvent({ type: 'click', target: clickTarget, detail: 1 }));
  3038. await delayPn(1);
  3039.  
  3040. if (a.muted === false && a.__spfgs__ !== true && a.paused === true && a.networkState === 0 && a.readyState === 0) {
  3041. clickLockFn.call(clickTarget, mockEvent({ type: 'click', target: clickTarget, detail: 1 }));
  3042. await delayPn(1);
  3043. }
  3044.  
  3045. delayRun(pr);
  3046.  
  3047. }
  3048.  
  3049. }
  3050.  
  3051. } catch (e) { console.log('error_F12', e) }
  3052.  
  3053.  
  3054. }, false);
  3055.  
  3056.  
  3057.  
  3058. // document.addEventListener('volumechange', (evt) => {
  3059. // console.log('volumechange')
  3060. // }, true)
  3061. // document.addEventListener('play', (evt) => {
  3062. // console.log('play')
  3063. // }, true)
  3064.  
  3065.  
  3066. // document.addEventListener('player-initialized', (evt) => {
  3067. // console.log(evt.type)
  3068. // }, true)
  3069. // document.addEventListener('renderer-module-load-start', (evt) => {
  3070. // console.log(evt.type)
  3071. // }, true)
  3072. // document.addEventListener('video-data-change', (evt) => {
  3073. // console.log(evt.type)
  3074. // }, true)
  3075. // document.addEventListener('player-state-change', (evt) => {
  3076. // console.log(evt.type)
  3077. // }, true)
  3078. // document.addEventListener('updateui', (evt) => {
  3079. // console.log(evt.type)
  3080. // }, true)
  3081. // document.addEventListener('renderer-module-load-end', (evt) => {
  3082. // console.log(evt.type)
  3083. // }, true)
  3084.  
  3085. // document.addEventListener('player-autonav-pause', (evt) => {
  3086. // console.log(evt.type)
  3087. // }, true)
  3088.  
  3089.  
  3090.  
  3091. // document.addEventListener('player-ad-state-change', (evt) => {
  3092. // console.log(evt.type)
  3093. // }, true)
  3094.  
  3095. // document.addEventListener('player-detailed-error', (evt) => {
  3096. // console.log(evt.type)
  3097. // }, true)
  3098.  
  3099. // document.addEventListener('player-error', (evt) => {
  3100. // console.log(evt.type)
  3101. // }, true)
  3102.  
  3103. // document.addEventListener('on-play-autonav-video', (evt) => {
  3104. // console.log(evt.type)
  3105. // }, true)
  3106.  
  3107. // document.addEventListener('on-play-previous-autonav-video', (evt) => {
  3108. // console.log(evt.type)
  3109. // }, true)
  3110.  
  3111. // document.addEventListener('player-fullscreen-change', (evt) => {
  3112. // console.log(evt.type)
  3113. // }, true)
  3114.  
  3115. // document.addEventListener('player-fullscreen-toggled', (evt) => {
  3116. // console.log(evt.type)
  3117. // }, true)
  3118.  
  3119. // document.addEventListener('player-dom-paused', (evt) => {
  3120. // console.log(evt.type)
  3121. // }, true)
  3122.  
  3123. // document.addEventListener('yt-show-toast', (evt) => {
  3124. // console.log(evt.type)
  3125. // }, true)
  3126. // document.addEventListener('yt-innertube-command', (evt) => {
  3127. // console.log(evt.type)
  3128. // }, true)
  3129. // document.addEventListener('yt-update-c3-companion', (evt) => {
  3130. // console.log(evt.type)
  3131. // }, true)
  3132. // document.addEventListener('video-progress', (evt) => {
  3133. // // console.log(evt.type)
  3134. // }, true)
  3135. // document.addEventListener('localmediachange', (evt) => {
  3136. // console.log(evt.type)
  3137. // }, true)
  3138.  
  3139.  
  3140.  
  3141. // window.addEventListener('player-initialized', (evt) => {
  3142. // console.log(evt.type)
  3143. // }, true)
  3144. // window.addEventListener('renderer-module-load-start', (evt) => {
  3145. // console.log(evt.type)
  3146. // }, true)
  3147. // window.addEventListener('video-data-change', (evt) => {
  3148. // console.log(evt.type)
  3149. // }, true)
  3150. // window.addEventListener('player-state-change', (evt) => {
  3151. // console.log(evt.type)
  3152. // }, true)
  3153. // window.addEventListener('updateui', (evt) => {
  3154. // console.log(evt.type)
  3155. // }, true)
  3156. // window.addEventListener('renderer-module-load-end', (evt) => {
  3157. // console.log(evt.type)
  3158. // }, true)
  3159.  
  3160. // window.addEventListener('player-autonav-pause', (evt) => {
  3161. // console.log(evt.type)
  3162. // }, true)
  3163.  
  3164.  
  3165.  
  3166. // window.addEventListener('player-ad-state-change', (evt) => {
  3167. // console.log(evt.type)
  3168. // }, true)
  3169.  
  3170. // window.addEventListener('player-detailed-error', (evt) => {
  3171. // console.log(evt.type)
  3172. // }, true)
  3173.  
  3174. // window.addEventListener('player-error', (evt) => {
  3175. // console.log(evt.type)
  3176. // }, true)
  3177.  
  3178. // window.addEventListener('on-play-autonav-video', (evt) => {
  3179. // console.log(evt.type)
  3180. // }, true)
  3181.  
  3182. // window.addEventListener('on-play-previous-autonav-video', (evt) => {
  3183. // console.log(evt.type)
  3184. // }, true)
  3185.  
  3186. // window.addEventListener('player-fullscreen-change', (evt) => {
  3187. // console.log(evt.type)
  3188. // }, true)
  3189.  
  3190. // window.addEventListener('player-fullscreen-toggled', (evt) => {
  3191. // console.log(evt.type)
  3192. // }, true)
  3193.  
  3194. // window.addEventListener('player-dom-paused', (evt) => {
  3195. // console.log(evt.type)
  3196. // }, true)
  3197.  
  3198. // window.addEventListener('yt-show-toast', (evt) => {
  3199. // console.log(evt.type)
  3200. // }, true)
  3201. // window.addEventListener('yt-innertube-command', (evt) => {
  3202. // console.log(evt.type)
  3203. // }, true)
  3204. // window.addEventListener('yt-update-c3-companion', (evt) => {
  3205. // console.log(evt.type)
  3206. // }, true)
  3207. // window.addEventListener('video-progress', (evt) => {
  3208. // // console.log(evt.type)
  3209. // }, true)
  3210. // window.addEventListener('localmediachange', (evt) => {
  3211. // console.log(evt.type)
  3212. // }, true)
  3213.  
  3214.  
  3215.  
  3216. // document.addEventListener('player-error', (evt) => {
  3217. // console.log(3001, evt.type, evt)
  3218. // }, true)
  3219. // document.addEventListener('player-detailed-error', (evt) => {
  3220. // console.log(3002, evt.type, evt)
  3221. // }, true)
  3222.  
  3223.  
  3224.  
  3225. async function delayRun(pr) {
  3226.  
  3227. let q = document.querySelector('#movie_player') || document.querySelector('#masthead-player');
  3228. if (!q) return;
  3229. let a = document.querySelector('.video-stream.html5-main-video');
  3230. if (!a) return;
  3231.  
  3232. await pr.then();
  3233.  
  3234. if (fa !== 1) {
  3235. return;
  3236. } else if (a.muted === true) {
  3237. return;
  3238. } else if (a.muted === false && a.readyState === 0 && a.networkState === 2) {
  3239. if (a.paused === false) return;
  3240. } else {
  3241. return;
  3242. }
  3243.  
  3244. if (document.querySelector('.player-controls-content')) return;
  3245.  
  3246. if (a.paused === true && a.muted === false && a.readyState === 0 && a.networkState === 2) {
  3247.  
  3248. clickLockFn.call(clickTarget, mockEvent({ type: 'click', target: clickTarget, detail: 1 }));
  3249.  
  3250. }
  3251.  
  3252. if (a.paused === true && a.muted === false && a.networkState === 2 && a.readyState === 0) {
  3253.  
  3254. if (typeof clickTarget.seekToLiveHead === 'function') await clickTarget.seekToLiveHead();
  3255. if (typeof clickTarget.isAtLiveHead === 'function' && (await clickTarget.isAtLiveHead()) === true) {
  3256. if (typeof clickTarget.seekToStreamTime === 'function') await clickTarget.seekToStreamTime();
  3257. }
  3258. }
  3259.  
  3260. }
  3261.  
  3262. durationchangeForMobile = true;
  3263.  
  3264. }
  3265.  
  3266.  
  3267. attachOneTimeEvent('yt-action', function () {
  3268. const config_ = typeof yt !== 'undefined' ? (yt || 0).config_ : 0;
  3269. ytConfigFix(config_);
  3270. });
  3271.  
  3272. let prepared = false;
  3273. function prepare() {
  3274. if (prepared) return;
  3275. prepared = true;
  3276.  
  3277. if (typeof _yt_player !== 'undefined' && _yt_player && typeof _yt_player === 'object') {
  3278.  
  3279. for (const [k, v] of Object.entries(_yt_player)) {
  3280.  
  3281. const p = typeof v === 'function' ? v.prototype : 0;
  3282.  
  3283. if (p
  3284. && typeof p.clone === 'function'
  3285. && typeof p.get === 'function' && typeof p.set === 'function'
  3286. && typeof p.isEmpty === 'undefined' && typeof p.forEach === 'undefined'
  3287. && typeof p.clear === 'undefined'
  3288. ) {
  3289.  
  3290. key = k;
  3291.  
  3292. }
  3293.  
  3294. }
  3295.  
  3296. }
  3297.  
  3298. if (key) {
  3299.  
  3300. const ClassX = _yt_player[key];
  3301. _yt_player[key] = class extends ClassX {
  3302. constructor(...args) {
  3303.  
  3304. if (typeof args[0] === 'string' && args[0].startsWith('http://')) args[0] = '';
  3305. super(...args);
  3306.  
  3307. }
  3308. }
  3309. _yt_player[key].luX1Y = 1;
  3310. prototypeInherit(_yt_player[key].prototype, ClassX.prototype);
  3311. }
  3312.  
  3313. }
  3314. let s3 = Symbol();
  3315.  
  3316. generalRegister('deviceIsAudioOnly', s3, (p) => {
  3317. return typeof p.getPlayerType === 'function' && typeof p.getVideoEmbedCode === 'function' && typeof p.getVideoUrl === 'function' && !p.onCueRangeEnter && !p.getVideoData && !('ATTRIBUTE_NODE' in p)
  3318. }, {
  3319.  
  3320. get() {
  3321. return this[s3];
  3322. },
  3323. set(nv) {
  3324. if (typeof nv === 'boolean') this[s3] = true;
  3325. else this[s3] = undefined;
  3326. prepare();
  3327. return true;
  3328. },
  3329. enumerable: false,
  3330. configurable: true
  3331.  
  3332. });
  3333.  
  3334.  
  3335. let s1 = Symbol();
  3336. let s2 = Symbol();
  3337. Object.defineProperty(Object.prototype, 'defraggedFromSubfragments', {
  3338. get() {
  3339. // console.log(501, this.constructor.prototype)
  3340. return undefined;
  3341. },
  3342. set(nv) {
  3343. return true;
  3344. },
  3345. enumerable: false,
  3346. configurable: true
  3347. });
  3348.  
  3349. Object.defineProperty(Object.prototype, 'hasSubfragmentedFmp4', {
  3350. get() {
  3351. // console.log(502, this.constructor.prototype)
  3352. return this[s1];
  3353. },
  3354. set(nv) {
  3355. if (typeof nv === 'boolean') this[s1] = false;
  3356. else this[s1] = undefined;
  3357. return true;
  3358. },
  3359. enumerable: false,
  3360. configurable: true
  3361. });
  3362.  
  3363. Object.defineProperty(Object.prototype, 'hasSubfragmentedWebm', {
  3364. get() {
  3365. // console.log(503, this.constructor.prototype)
  3366. return this[s2];
  3367. },
  3368. set(nv) {
  3369. if (typeof nv === 'boolean') this[s2] = false;
  3370. else this[s2] = undefined;
  3371. return true;
  3372. },
  3373. enumerable: false,
  3374. configurable: true
  3375. });
  3376.  
  3377.  
  3378. const supportedFormatsConfig = () => {
  3379.  
  3380. function typeTest(type) {
  3381. if (typeof type === 'string' && type.startsWith('video/')) {
  3382. return false;
  3383. }
  3384. }
  3385.  
  3386. // return a custom MIME type checker that can defer to the original function
  3387. function makeModifiedTypeChecker(origChecker) {
  3388. // Check if a video type is allowed
  3389. return function (type) {
  3390. let res = undefined;
  3391. if (type === undefined) res = false;
  3392. else {
  3393. res = typeTest.call(this, type);
  3394. }
  3395. if (res === undefined) res = origChecker.apply(this, arguments);
  3396. return res;
  3397. };
  3398. }
  3399.  
  3400. // Override video element canPlayType() function
  3401. const proto = (HTMLVideoElement || 0).prototype;
  3402. if (proto && typeof proto.canPlayType == 'function') {
  3403. proto.canPlayType = makeModifiedTypeChecker(proto.canPlayType);
  3404. }
  3405.  
  3406. // Override media source extension isTypeSupported() function
  3407. const mse = window.MediaSource;
  3408. // Check for MSE support before use
  3409. if (mse && typeof mse.isTypeSupported == 'function') {
  3410. mse.isTypeSupported = makeModifiedTypeChecker(mse.isTypeSupported);
  3411. }
  3412.  
  3413. };
  3414.  
  3415. supportedFormatsConfig();
  3416.  
  3417.  
  3418. ; (async () => {
  3419.  
  3420.  
  3421. const _yt_player_observable = observablePromise(() => {
  3422. return (((window || 0)._yt_player || 0) || 0);
  3423. });
  3424.  
  3425.  
  3426. const addProtoToArr = (parent, key, arr) => {
  3427.  
  3428.  
  3429. let isChildProto = false;
  3430. for (const sr of arr) {
  3431. if (parent[key].prototype instanceof parent[sr]) {
  3432. isChildProto = true;
  3433. break;
  3434. }
  3435. }
  3436.  
  3437. if (isChildProto) return;
  3438.  
  3439. arr = arr.filter(sr => {
  3440. if (parent[sr].prototype instanceof parent[key]) {
  3441. return false;
  3442. }
  3443. return true;
  3444. });
  3445.  
  3446. arr.push(key);
  3447.  
  3448. return arr;
  3449.  
  3450.  
  3451. };
  3452.  
  3453. const getEntriesForPlayerInterfaces = (_yt_player) => {
  3454.  
  3455. const entries = Object.entries(_yt_player);
  3456.  
  3457. const arr = new Array(entries.length);
  3458. let arrI = 0;
  3459.  
  3460. for (const entry of entries) {
  3461. const [k, v] = entry;
  3462.  
  3463. const p = typeof v === 'function' ? v.prototype : 0;
  3464. if (p) {
  3465.  
  3466. const b = (
  3467. typeof p.cancelPlayback === 'function' ||
  3468. typeof p.stopVideo === 'function' ||
  3469. typeof p.pauseVideo === 'function' ||
  3470. typeof p.playVideo === 'function' ||
  3471. typeof p.getPlayerStateObject === 'function'
  3472. );
  3473. if (b) arr[arrI++] = entry;
  3474. }
  3475. }
  3476.  
  3477. arr.length = arrI;
  3478. return arr;
  3479.  
  3480.  
  3481. }
  3482.  
  3483.  
  3484. const getKeyPlayerDap = (_yt_player, filteredEntries) => {
  3485. // one is quu (this.app.getPlayerStateObject(p))
  3486. // one is standardApp (return this.getPresentingPlayerType()===3?R$(this.C7).g7:g.O5(this,p).getPlayerState())
  3487.  
  3488.  
  3489. const w = 'keyPlayerDap';
  3490.  
  3491. let arr = [];
  3492. let brr = new Map();
  3493.  
  3494. for (const [k, v] of filteredEntries) {
  3495.  
  3496. const p = typeof v === 'function' ? v.prototype : 0;
  3497. if (p) {
  3498.  
  3499. let q = 0;
  3500.  
  3501. if (typeof p.cancelPlayback === 'function') q += 50;
  3502. if (typeof p.stopVideo === 'function') q += 50;
  3503. if (typeof p.pauseVideo === 'function') q += 50;
  3504. if (typeof p.playVideo === 'function') q += 50;
  3505. if (typeof p.getPlayerStateObject === 'function') q += 50;
  3506.  
  3507. if (q < 250) continue;
  3508.  
  3509. if (typeof p.cancelPlayback === 'function' && p.cancelPlayback.length === 0) q += 20;
  3510. if (typeof p.stopVideo === 'function' && p.stopVideo.length === 1) q += 20;
  3511. if (typeof p.pauseVideo === 'function' && p.pauseVideo.length === 1) q += 20;
  3512. if (typeof p.playVideo === 'function' && p.playVideo.length === 2) q += 20;
  3513. if (typeof p.getPlayerStateObject === 'function' && p.getPlayerStateObject.length === 1) q += 20;
  3514.  
  3515.  
  3516. if (typeof p.isBackground === 'function') q -= 5;
  3517. if (typeof p.isBackground === 'function' && p.isBackground.length === 0) q -= 2;
  3518.  
  3519. if (typeof p.getPlaybackRate === 'function') q += 25;
  3520. if (typeof p.getPlaybackRate === 'function' && p.getPlaybackRate.length === 0) q += 15;
  3521.  
  3522. if (typeof p.publish === 'function') q += 25;
  3523. if (typeof p.publish === 'function' && p.publish.length === 1) q += 15;
  3524.  
  3525. if (typeof p.addEventListener === 'function') q += 40;
  3526. if (typeof p.addEventListener === 'function' && p.addEventListener.length === 2) q += 25;
  3527. if (typeof p.removeEventListener === 'function') q += 40;
  3528. if (typeof p.removeEventListener === 'function' && p.removeEventListener.length === 2) q += 25;
  3529.  
  3530. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  3531.  
  3532. if (q > 0) brr.set(k, q);
  3533.  
  3534. }
  3535.  
  3536.  
  3537. }
  3538.  
  3539. if (arr.length === 0) {
  3540.  
  3541. console.warn(`[yt-audio-only] (key-extraction) Key does not exist (1). [${w}]`);
  3542. } else {
  3543.  
  3544. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  3545.  
  3546. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  3547.  
  3548. let match = null;
  3549. for (const [key, _] of arr) {
  3550. const p = _yt_player[key].prototype
  3551. const f = (p ? p.getPlayerStateObject : null) || 0;
  3552. if (f) {
  3553. const o = {};
  3554. const w = new Proxy({}, {
  3555. get(target, p) {
  3556. o[p] = 1;
  3557. return w;
  3558. },
  3559. set(target, p, v) {
  3560. return true;
  3561. }
  3562. });
  3563. try {
  3564. f.call(w)
  3565. } catch (e) { }
  3566. if (o.app) {
  3567. match = key;
  3568. }
  3569. }
  3570. }
  3571.  
  3572.  
  3573. if (!match) {
  3574.  
  3575. console.warn(`[yt-audio-only] (key-extraction) Key does not exist (2). [${w}]`);
  3576.  
  3577. } else {
  3578. return match;
  3579. }
  3580.  
  3581. }
  3582.  
  3583.  
  3584.  
  3585. }
  3586.  
  3587. const getKeyStandardApp = (_yt_player, filteredEntries) => {
  3588. // one is quu (this.app.getPlayerStateObject(p))
  3589. // one is standardApp (return this.getPresentingPlayerType()===3?R$(this.C7).g7:g.O5(this,p).getPlayerState())
  3590.  
  3591.  
  3592. const w = 'keyStandardApp';
  3593.  
  3594. let arr = [];
  3595. let brr = new Map();
  3596.  
  3597. for (const [k, v] of filteredEntries) {
  3598.  
  3599. const p = typeof v === 'function' ? v.prototype : 0;
  3600. if (p) {
  3601.  
  3602. let q = 0;
  3603.  
  3604. if (typeof p.cancelPlayback === 'function') q += 50;
  3605. if (typeof p.stopVideo === 'function') q += 50;
  3606. if (typeof p.pauseVideo === 'function') q += 50;
  3607. if (typeof p.playVideo === 'function') q += 50;
  3608. if (typeof p.getPlayerStateObject === 'function') q += 50;
  3609.  
  3610. if (q < 250) continue;
  3611.  
  3612. if (typeof p.cancelPlayback === 'function' && p.cancelPlayback.length === 2) q += 20;
  3613. if (typeof p.stopVideo === 'function' && p.stopVideo.length === 1) q += 20;
  3614. if (typeof p.pauseVideo === 'function' && p.pauseVideo.length === 2) q += 20;
  3615. if (typeof p.playVideo === 'function' && p.playVideo.length === 2) q += 20;
  3616. if (typeof p.getPlayerStateObject === 'function' && p.getPlayerStateObject.length === 1) q += 20;
  3617.  
  3618.  
  3619. if (typeof p.isBackground === 'function') q -= 5;
  3620. if (typeof p.isBackground === 'function' && p.isBackground.length === 0) q -= 2;
  3621.  
  3622. if (typeof p.getPlaybackRate === 'function') q -= 5;
  3623. if (typeof p.getPlaybackRate === 'function' && p.getPlaybackRate.length === 0) q -= 2;
  3624.  
  3625. if (typeof p.publish === 'function') q -= 5;
  3626. if (typeof p.publish === 'function' && p.publish.length === 2) q -= 2;
  3627.  
  3628. if (typeof p.addEventListener === 'function') q -= 5;
  3629. if (typeof p.addEventListener === 'function' && p.addEventListener.length === 2) q -= 2;
  3630. if (typeof p.removeEventListener === 'function') q -= 5;
  3631. if (typeof p.removeEventListener === 'function' && p.removeEventListener.length === 2) q -= 2;
  3632.  
  3633.  
  3634. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  3635.  
  3636. if (q > 0) brr.set(k, q);
  3637.  
  3638. }
  3639.  
  3640.  
  3641. }
  3642.  
  3643. if (arr.length === 0) {
  3644.  
  3645. console.warn(`[yt-audio-only] (key-extraction) Key does not exist (1). [${w}]`);
  3646. } else {
  3647.  
  3648. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  3649.  
  3650. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  3651.  
  3652. let match = null;
  3653. for (const [key, _] of arr) {
  3654. const p = _yt_player[key].prototype
  3655. const f = (p ? p.getPlayerStateObject : null) || 0;
  3656. if (f) {
  3657. const o = {};
  3658. const w = new Proxy({}, {
  3659. get(target, p) {
  3660. o[p] = 1;
  3661. return w;
  3662. },
  3663. set(target, p, v) {
  3664. return true;
  3665. }
  3666. });
  3667. try {
  3668. f.call(w)
  3669. } catch (e) { }
  3670. if (!o.app) {
  3671. match = key;
  3672. }
  3673. }
  3674. }
  3675.  
  3676.  
  3677. if (!match) {
  3678.  
  3679. console.warn(`[yt-audio-only] (key-extraction) Key does not exist (2). [${w}]`);
  3680.  
  3681. } else {
  3682. return match;
  3683. }
  3684.  
  3685. }
  3686.  
  3687.  
  3688.  
  3689. }
  3690.  
  3691.  
  3692. const getKeyInternalApp = (_yt_player, filteredEntries) => {
  3693. // internalApp
  3694.  
  3695. const w = 'keyInternalApp';
  3696.  
  3697. let arr = [];
  3698. let brr = new Map();
  3699.  
  3700. for (const [k, v] of filteredEntries) {
  3701.  
  3702. const p = typeof v === 'function' ? v.prototype : 0;
  3703. if (p) {
  3704.  
  3705. let q = 0;
  3706.  
  3707. if (typeof p.stopVideo === 'function') q += 1;
  3708. if (typeof p.playVideo === 'function') q += 1;
  3709. if (typeof p.pauseVideo === 'function') q += 1;
  3710.  
  3711. if (q < 2) continue;
  3712.  
  3713. if (typeof p.isBackground === 'function') q += 120;
  3714. if (typeof p.getPlaybackRate === 'function') q += 50;
  3715. // if (typeof p.publish === 'function') q += 50;
  3716. if (typeof p.isAtLiveHead === 'function') q += 50;
  3717. if (typeof p.getVideoData === 'function') q += 10;
  3718. if (typeof p.getVolume === 'function') q += 10;
  3719. if (typeof p.getStreamTimeOffset === 'function') q += 10;
  3720. if (typeof p.getPlayerType === 'function') q += 10;
  3721. if (typeof p.getPlayerState === 'function') q += 10;
  3722. if (typeof p.getPlayerSize === 'function') q += 10;
  3723. if (typeof p.cancelPlayback === 'function') q -= 4;
  3724.  
  3725. if (q < 10) continue;
  3726.  
  3727. if ('mediaElement' in p) q += 50;
  3728. if ('videoData' in p) q += 50;
  3729. if ('visibility' in p) q += 50;
  3730.  
  3731. if (typeof p.isBackground === 'function' && p.isBackground.length === 0) q += 20;
  3732. if (typeof p.getPlaybackRate === 'function' && p.getPlaybackRate.length === 0) q += 20;
  3733. if (typeof p.publish === 'function' && p.publish.length === 2) q += 18;
  3734. if (typeof p.isAtLiveHead === 'function' && p.isAtLiveHead.length === 2) q += 18;
  3735.  
  3736. if (q > 0) arr = addProtoToArr(_yt_player, k, arr) || arr;
  3737.  
  3738. if (q > 0) brr.set(k, q);
  3739.  
  3740. }
  3741.  
  3742.  
  3743. }
  3744.  
  3745. if (arr.length === 0) {
  3746.  
  3747. console.warn(`[yt-audio-only] (key-extraction) Key does not exist. [${w}]`);
  3748. } else {
  3749.  
  3750. arr = arr.map(key => [key, (brr.get(key) || 0)]);
  3751.  
  3752. if (arr.length > 1) arr.sort((a, b) => b[1] - a[1]);
  3753.  
  3754. if (arr.length > 2) console.log(`[yt-audio-only] (key-extraction) [${w}]`, arr);
  3755. return arr[0][0];
  3756. }
  3757.  
  3758.  
  3759.  
  3760. };
  3761.  
  3762.  
  3763. (async () => {
  3764. // rAf scheduling
  3765.  
  3766. const _yt_player = await _yt_player_observable.obtain();
  3767.  
  3768. if (!_yt_player || typeof _yt_player !== 'object') return;
  3769.  
  3770. window.ktg = _yt_player;
  3771.  
  3772. // console.log(keys0)
  3773.  
  3774. const entriesForPlayerInterfaces = getEntriesForPlayerInterfaces(_yt_player);
  3775.  
  3776. const keyPlayerDap = getKeyPlayerDap(_yt_player, entriesForPlayerInterfaces)
  3777. const keyStandardApp = getKeyStandardApp(_yt_player, entriesForPlayerInterfaces)
  3778. const keyInternalApp = getKeyInternalApp(_yt_player, entriesForPlayerInterfaces);
  3779.  
  3780. console.log('[yt-audio-only] key obtained', [keyPlayerDap, keyStandardApp, keyInternalApp]);
  3781.  
  3782. if (!keyPlayerDap || !keyStandardApp || !keyInternalApp) {
  3783. console.warn('[yt-audio-only] key failure', [keyPlayerDap, keyStandardApp, keyInternalApp]);
  3784. }
  3785.  
  3786.  
  3787. if (keyPlayerDap) {
  3788. const playerDapCT = _yt_player[keyPlayerDap];
  3789. if (typeof playerDapCT === 'function') {
  3790. const playerDapPT = playerDapCT.prototype;
  3791. playerDapPTFn(playerDapPT);
  3792. }
  3793. }
  3794.  
  3795.  
  3796. if (keyStandardApp) {
  3797. const standardAppCT = _yt_player[keyStandardApp];
  3798. if (typeof standardAppCT === 'function') {
  3799. const standardAppPT = standardAppCT.prototype;
  3800. standardAppPTFn(standardAppPT);
  3801. }
  3802. }
  3803.  
  3804. if (keyInternalApp) {
  3805. const internalAppCT = _yt_player[keyInternalApp];
  3806. if (typeof internalAppCT === 'function') {
  3807. const internalAppPT = internalAppCT.prototype;
  3808. internalAppPTFn(internalAppPT);
  3809. }
  3810. }
  3811.  
  3812.  
  3813.  
  3814. })();
  3815.  
  3816. })();
  3817.  
  3818.  
  3819. //# sourceURL=debug://userscript/yt-audio-only.js
  3820.  
  3821.  
  3822. }
  3823.  
  3824. const getVideoIdByURL = () => {
  3825. // It's almost certainly going to stay at 11 characters. The individual characters come from a set of 64 possibilities (A-Za-z0-9_-).
  3826. // base64 form; 26+26+10+2; 64^len
  3827. // Math.pow(64,11) = 73786976294838210000
  3828.  
  3829. const url = new URL(location.href);
  3830. let m;
  3831.  
  3832. if (m = /^\/watch\?v=([A-Za-z0-9_-]+)/.exec(`${url.pathname}?v=${url.searchParams.get('v')}`)) return `${m[1]}`;
  3833. if (m = /^\/live\/([A-Za-z0-9_-]+)/.exec(url.pathname)) return `${m[1]}`;
  3834.  
  3835. if (m = /^\/embed\/live_stream\?channel=([A-Za-z0-9_-]+)/.exec(`${url.pathname}?channel=${url.searchParams.get('channel')}`)) return `L:${m[1]}`;
  3836. if (m = /^\/embed\/([A-Za-z0-9_-]+)/.exec(url.pathname)) return `${m[1]}`;
  3837.  
  3838. if (m = /^\/channel\/([A-Za-z0-9_-]+)\/live\b/.exec(url.pathname)) return `L:${m[1]}`;
  3839. if (url.hostname === 'youtu.be' && (m = /\/([A-Za-z0-9_-]+)/.exec(url.pathname))) return `${m[1]}`;
  3840.  
  3841. return '';
  3842.  
  3843. };
  3844.  
  3845. const getVideoIdByElement = () => {
  3846. const videoIdElements = [...document.querySelectorAll('[video-id]')].filter(v => !v.closest('[hidden]'));
  3847. const videoId = videoIdElements.length > 0 ? videoIdElements[0].getAttribute('video-id') : null;
  3848. return videoId || '';
  3849. };
  3850.  
  3851. const getEnableValue = async () => {
  3852. const videoId = getVideoIdByURL() || getVideoIdByElement();
  3853. const siteVal = videoId ? await GM.getValue(`isEnable_aWsjF_${videoId}`, null) : null;
  3854. return (siteVal !== null) ? siteVal : await GM.getValue("isEnable_aWsjF", true);
  3855. };
  3856.  
  3857. const setEnableVal = async (val) => {
  3858. const videoId = getVideoIdByURL() || getVideoIdByElement();
  3859. if (videoId) {
  3860. try {
  3861. const cv = await GM.getValue(`isEnable_aWsjF_${videoId}`, null);
  3862. if (typeof cv === typeof val) await GM.setValue(`isEnable_aWsjF_${videoId}`, val);
  3863. } catch (e) { }
  3864. }
  3865. await GM.setValue("isEnable_aWsjF", val);
  3866. }
  3867.  
  3868. const isEnable = (typeof GM !== 'undefined' && typeof GM.getValue === 'function') ? await getEnableValue() : null;
  3869. if (typeof isEnable !== 'boolean') throw new DOMException("Please Update your browser", "NotSupportedError");
  3870. if (isEnable) {
  3871. const element = document.createElement('button');
  3872. element.setAttribute('onclick', createHTML(`(${pageInjectionCode})()`));
  3873. element.click();
  3874. }
  3875.  
  3876. GM_registerMenuCommand(`Turn ${isEnable ? 'OFF' : 'ON'} YouTube Audio Mode`, async function () {
  3877. await setEnableVal(!isEnable);
  3878. await GM.setValue('lastCheck_bWsm5', Date.now());
  3879. document.documentElement.setAttribute('forceRefresh032', '');
  3880. location.reload();
  3881. });
  3882.  
  3883. let messageCount = 0;
  3884. let busy = false;
  3885. window.addEventListener('message', (evt) => {
  3886.  
  3887. const v = ((evt || 0).data || 0).ZECxh;
  3888. if (typeof v === 'boolean') {
  3889. if (messageCount > 1e9) messageCount = 9;
  3890. const t = ++messageCount;
  3891. if (v && isEnable) {
  3892. requestAnimationFrame(async () => {
  3893. if (t !== messageCount) return;
  3894. if (busy) return;
  3895. busy = true;
  3896. if (await confirm("Livestream is detected. Press OK to disable YouTube Audio Mode.")) {
  3897. await setEnableVal(!isEnable);
  3898. await GM.setValue('lastCheck_bWsm5', Date.now());
  3899. document.documentElement.setAttribute('forceRefresh032', '');
  3900. location.reload();
  3901. }
  3902. busy = false;
  3903. });
  3904. }
  3905. }
  3906.  
  3907. });
  3908.  
  3909.  
  3910. const pLoad = new Promise(resolve => {
  3911. if (document.readyState !== 'loading') {
  3912. resolve();
  3913. } else {
  3914. window.addEventListener("DOMContentLoaded", resolve, false);
  3915. }
  3916. });
  3917.  
  3918.  
  3919. function contextmenuInfoItemAppearedFn(target) {
  3920.  
  3921. const btn = target.closest('.ytp-menuitem[role="menuitem"]');
  3922. if (!btn) return;
  3923. if (btn.parentNode.querySelector('.ytp-menuitem[role="menuitem"].audio-only-toggle-btn')) return;
  3924. document.documentElement.classList.add('with-audio-only-toggle-btn');
  3925. const newBtn = btn.cloneNode(true)
  3926. newBtn.querySelector('.ytp-menuitem-label').textContent = `Turn ${isEnable ? 'OFF' : 'ON'} YouTube Audio Mode`;
  3927. newBtn.classList.add('audio-only-toggle-btn');
  3928. btn.parentNode.insertBefore(newBtn, btn.nextSibling);
  3929. newBtn.addEventListener('click', async (evt) => {
  3930. try {
  3931. evt.stopPropagation();
  3932. evt.stopImmediatePropagation();
  3933. } catch (e) { }
  3934. await setEnableVal(!isEnable);
  3935. await GM.setValue('lastCheck_bWsm5', Date.now());
  3936. document.documentElement.setAttribute('forceRefresh032', '');
  3937. location.reload();
  3938. });
  3939. let t;
  3940. let h = 0;
  3941. t = btn.closest('.ytp-panel-menu[style*="height"]');
  3942. if (t) t.style.height = t.scrollHeight + 'px';
  3943. t = btn.closest('.ytp-panel[style*="height"]');
  3944. if (t) t.style.height = (h = t.scrollHeight) + 'px';
  3945. t = btn.closest('.ytp-popup.ytp-contextmenu[style*="height"]');
  3946. if (t && h > 0) t.style.height = h + 'px';
  3947. }
  3948.  
  3949.  
  3950. function mobileMenuItemAppearedFn(target) {
  3951.  
  3952. const btn = target.closest('ytm-menu-item');
  3953. if (!btn) return;
  3954. if (btn.parentNode.querySelector('ytm-menu-item.audio-only-toggle-btn')) return;
  3955. document.documentElement.classList.add('with-audio-only-toggle-btn');
  3956. const newBtn = btn.cloneNode(true);
  3957. newBtn.querySelector('.menu-item-button').textContent = `Turn ${isEnable ? 'OFF' : 'ON'} YouTube Audio Mode`;
  3958. newBtn.classList.add('audio-only-toggle-btn');
  3959. btn.parentNode.insertBefore(newBtn, btn.nextSibling);
  3960. newBtn.addEventListener('click', async (evt) => {
  3961. try {
  3962. evt.stopPropagation();
  3963. evt.stopImmediatePropagation();
  3964. } catch (e) { }
  3965. await setEnableVal(!isEnable);
  3966. await GM.setValue('lastCheck_bWsm5', Date.now());
  3967. document.documentElement.setAttribute('forceRefresh032', '');
  3968. location.reload();
  3969. });
  3970. }
  3971.  
  3972. const lastEntry = (arr) => {
  3973. return arr.length > 0 ? arr[arr.length - 1] : null;
  3974. }
  3975.  
  3976. function mobileMenuItemAppearedV2Fn(target) {
  3977.  
  3978. const btn = target.closest('yt-list-item-view-model');
  3979. if (!(btn instanceof HTMLElement)) return;
  3980. if (btn.parentNode.querySelector('yt-list-item-view-model.audio-only-toggle-btn')) return;
  3981. const parentNode = btn.closest('player-settings-menu');
  3982. if (!parentNode) return;
  3983. let qt = 1E9;
  3984. let targetBtnO = lastEntry([...parentNode.getElementsByTagName(btn.nodeName)].filter(e => e.parentElement === btn.parentElement).map((elm) => {
  3985. const count = elm.getElementsByTagName('*').length;
  3986. if (count < qt) qt = count;
  3987. return {
  3988. elm: elm,
  3989. count: count
  3990. }
  3991. }).filter((o) => o.count === qt));
  3992.  
  3993. const targetBtn = targetBtnO && targetBtnO.elm instanceof HTMLElement ? targetBtnO.elm : btn;
  3994.  
  3995.  
  3996. const newBtn = targetBtn.cloneNode(true);
  3997. if (newBtn instanceof HTMLElement) {
  3998. document.documentElement.classList.add('with-audio-only-toggle-btn');
  3999.  
  4000. let newBtnContentElm = newBtn;
  4001. let layerCN = 8;
  4002. while (newBtnContentElm.childElementCount === 1 && layerCN--) {
  4003. newBtnContentElm = newBtnContentElm.firstElementChild;
  4004. }
  4005. if (!(newBtnContentElm instanceof HTMLElement)) newBtnContentElm = newBtn;
  4006. let t;
  4007. if (t = lastEntry(newBtnContentElm.querySelectorAll('span[role="text"]'))) {
  4008. newBtnContentElm = t;
  4009. newBtnContentElm.classList.add('audio-only-toggle-btn-content2');
  4010. } else if (t = lastEntry(newBtnContentElm.querySelectorAll('[role="text"]'))) {
  4011. newBtnContentElm = t;
  4012. newBtnContentElm.classList.add('audio-only-toggle-btn-content2');
  4013. } else if (t = lastEntry(newBtnContentElm.querySelectorAll('span'))) {
  4014. newBtnContentElm = t;
  4015. newBtnContentElm.classList.add('audio-only-toggle-btn-content2');
  4016. } else if (t = lastEntry(newBtnContentElm.querySelector('.yt-core-attributed-string'))) {
  4017. newBtnContentElm = t;
  4018. newBtnContentElm.classList.add('audio-only-toggle-btn-content2');
  4019. }
  4020. newBtnContentElm.textContent = `Turn ${isEnable ? 'OFF' : 'ON'} YouTube Audio Mode`;
  4021. newBtn.classList.add('audio-only-toggle-btn');
  4022. newBtnContentElm.classList.add('audio-only-toggle-btn-content');
  4023. btn.parentNode.insertBefore(newBtn, btn.nextSibling);
  4024. newBtn.addEventListener('click', async (evt) => {
  4025. try {
  4026. evt.stopPropagation();
  4027. evt.stopImmediatePropagation();
  4028. } catch (e) { }
  4029. await setEnableVal(!isEnable);
  4030. await GM.setValue('lastCheck_bWsm5', Date.now());
  4031. document.documentElement.setAttribute('forceRefresh032', '');
  4032. location.reload();
  4033. });
  4034. const contentWrapper = newBtn.closest('#content-wrapper');
  4035. if (contentWrapper) {
  4036. contentWrapper.style.height = 'unset';
  4037. contentWrapper.style.maxHeight = 'unset';
  4038. }
  4039. }
  4040. }
  4041.  
  4042. pLoad.then(() => {
  4043.  
  4044. document.addEventListener('animationstart', (evt) => {
  4045. const animationName = evt.animationName;
  4046. if (!animationName) return;
  4047.  
  4048. if (animationName === 'contextmenuInfoItemAppeared') contextmenuInfoItemAppearedFn(evt.target);
  4049. if (animationName === 'mobileMenuItemAppeared') mobileMenuItemAppearedFn(evt.target);
  4050. if (animationName === 'mobileMenuItemAppearedV2') mobileMenuItemAppearedV2Fn(evt.target);
  4051.  
  4052. }, true);
  4053.  
  4054. const cssForEnabled = isEnable ? `
  4055.  
  4056. .html5-video-player {
  4057. background-color: black;
  4058. }
  4059.  
  4060. [style*="--audio-only-thumbnail-image"]{
  4061. background-image: var(--audio-only-thumbnail-image);
  4062. object-fit: contain;
  4063. background-position: center;
  4064. background-size: contain;
  4065. background-repeat: no-repeat;
  4066. }
  4067. .html5-video-player.ended-mode [style*="--audio-only-thumbnail-image"]{
  4068. background-image: none;
  4069. }
  4070.  
  4071. .html5-video-player.ytp-ce-shown .html5-video-container {
  4072. opacity: 0.5;
  4073. transition: opacity 0.5s;
  4074. }
  4075.  
  4076. ytd-video-preview #media-container div#player-container,
  4077. ytd-video-preview #media-container div#thumbnail-container{
  4078. transition: initial !important;
  4079. transition-duration:0ms !important;
  4080. transition-delay:0ms !important;
  4081. }
  4082. ytd-video-preview #media-container div#thumbnail-container{
  4083. /* pointer-events:none !important; */
  4084. opacity:0;
  4085. /* z-index:-1; */
  4086. }
  4087. ytd-video-preview #media-container div#player-container,
  4088. ytd-video-preview #media-container div#inline-preview-player{
  4089. background-color:transparent !important;
  4090. background-image:none !important;
  4091. }
  4092.  
  4093. #movie_player > .html5-video-container:not(:empty),
  4094. #masthead-player > .html5-video-container:not(:empty) {
  4095. box-sizing: border-box;
  4096. height: 100%;
  4097. }
  4098.  
  4099. #movie_player [style*="--audio-only-thumbnail-image"] ~ .ytp-cued-thumbnail-overlay > .ytp-cued-thumbnail-overlay-image[style*="background-image"],
  4100. #masthead-player [style*="--audio-only-thumbnail-image"] ~ .ytp-cued-thumbnail-overlay > .ytp-cued-thumbnail-overlay-image[style*="background-image"] {
  4101. opacity: 0;
  4102. }
  4103.  
  4104. #movie_player [style*="--audio-only-thumbnail-image"]::before,
  4105. #masthead-player [style*="--audio-only-thumbnail-image"]::before {
  4106. content: '';
  4107. display: block;
  4108. position: absolute;
  4109. left: 0;
  4110. top: 0;
  4111. bottom: 0;
  4112. right: 0;
  4113. /* background: transparent; */
  4114.  
  4115.  
  4116. /* We use multiple backgrounds: one gradient per side */
  4117. background:
  4118. /* Left border gradient */
  4119. linear-gradient(to right, rgba(0,0,0,0.4), transparent) left center,
  4120. /* Right border gradient */
  4121. linear-gradient(to left, rgba(0,0,0,0.4), transparent) right center,
  4122. /* Top border gradient */
  4123. linear-gradient(to bottom, rgba(0,0,0,0.4), transparent) center top,
  4124. /* Bottom border gradient */
  4125. linear-gradient(to top, rgba(0,0,0,0.4), transparent) center bottom;
  4126.  
  4127. /* Prevents repetition of gradients */
  4128. background-repeat: no-repeat;
  4129.  
  4130. /* Set the size of each gradient "border" */
  4131. background-size:
  4132. 12% 100%, /* left border width and full height */
  4133. 12% 100%, /* right border width and full height */
  4134. 100% 12%, /* top border full width and small height */
  4135. 100% 12%; /* bottom border full width and small height */
  4136.  
  4137. /* Optional: a base background color inside the element */
  4138. /* background-color: #fff; */
  4139. /* background-color: var(--blinker-fmw83-bgc, transparent); */
  4140.  
  4141. opacity: var(--fmw83-opacity, 1);
  4142.  
  4143. pointer-events: none !important;
  4144. z-index:-1;
  4145.  
  4146. }
  4147.  
  4148. /*
  4149. @keyframes blinker-fmw83 {
  4150. 0%, 60%, 100% {
  4151. opacity: 1;
  4152. }
  4153. 30% {
  4154. opacity: 0.96;
  4155. }
  4156. }
  4157. */
  4158.  
  4159.  
  4160. #movie_player.playing-mode [style*="--audio-only-thumbnail-image"],
  4161. #masthead-player.playing-mode [style*="--audio-only-thumbnail-image"] {
  4162. /* animation: blinker-fmw83 1.74s linear infinite; */
  4163. --fmw83-opacity: 0.6;
  4164.  
  4165. }
  4166.  
  4167. #global-loader ytw-scrim {
  4168. display: none;
  4169. }
  4170.  
  4171. `: "";
  4172.  
  4173. const style = document.createElement('style');
  4174. style.id = 'fm9v0';
  4175. style.textContent = `
  4176.  
  4177. ${cssForEnabled}
  4178.  
  4179. @keyframes mobileMenuItemAppeared {
  4180. 0% {
  4181. background-position-x: 3px;
  4182. }
  4183. 100% {
  4184. background-position-x: 4px;
  4185. }
  4186. }
  4187.  
  4188. @keyframes mobileMenuItemAppearedV2 {
  4189. 0% {
  4190. background-position-x: 3px;
  4191. }
  4192. 100% {
  4193. background-position-x: 4px;
  4194. }
  4195. }
  4196. ytm-select.player-speed-settings ~ ytm-menu-item:last-of-type {
  4197. animation: mobileMenuItemAppeared 1ms linear 0s 1 normal forwards;
  4198. }
  4199.  
  4200. player-settings-menu > yt-list-item-view-model:last-of-type {
  4201. animation: mobileMenuItemAppearedV2 1ms linear 0s 1 normal forwards;
  4202. }
  4203.  
  4204.  
  4205. player-settings-menu .audio-only-toggle-btn-content {
  4206. padding: 14px 24px;
  4207. box-sizing: border-box;
  4208. font-size: 130%;
  4209. }
  4210.  
  4211. player-settings-menu .audio-only-toggle-btn-content2 {
  4212. padding: 0;
  4213. box-sizing: border-box;
  4214. font-size: inherit;
  4215. }
  4216.  
  4217.  
  4218. @keyframes contextmenuInfoItemAppeared {
  4219. 0% {
  4220. background-position-x: 3px;
  4221. }
  4222. 100% {
  4223. background-position-x: 4px;
  4224. }
  4225. }
  4226. .ytp-contextmenu .ytp-menuitem[role="menuitem"] path[d^="M22 34h4V22h-4v12zm2-30C12.95"]{
  4227. animation: contextmenuInfoItemAppeared 1ms linear 0s 1 normal forwards;
  4228. }
  4229. #confirmDialog794 {
  4230. z-index:999999 !important;
  4231. display: none;
  4232. /* Hidden by default */
  4233. position: fixed;
  4234. /* Stay in place */
  4235. z-index: 1;
  4236. /* Sit on top */
  4237. left: 0;
  4238. top: 0;
  4239. width: 100%;
  4240. /* Full width */
  4241. height: 100%;
  4242. /* Full height */
  4243. overflow: auto;
  4244. /* Enable scroll if needed */
  4245. background-color: rgba(0,0,0,0.4);
  4246. /* Black w/ opacity */
  4247. }
  4248. #confirmDialog794 .confirm-box {
  4249. position:relative;
  4250. color: black;
  4251. z-index:999999 !important;
  4252. background-color: #fefefe;
  4253. margin: 15% auto;
  4254. /* 15% from the top and centered */
  4255. padding: 20px;
  4256. border: 1px solid #888;
  4257. width: 30%;
  4258. /* Could be more or less, depending on screen size */
  4259. box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
  4260. }
  4261. #confirmDialog794 .confirm-buttons {
  4262. text-align: right;
  4263. }
  4264. #confirmDialog794 button {
  4265. margin-left: 10px;
  4266. }
  4267.  
  4268. `
  4269. document.head.appendChild(style);
  4270.  
  4271. });
  4272.  
  4273.  
  4274. const pNavigateFinished = new Promise(resolve => {
  4275. document.addEventListener('yt-navigate-finish', resolve, true);
  4276. });
  4277.  
  4278. pNavigateFinished.then(() => {
  4279. const inputs = document.querySelectorAll('#masthead input[type="text"][name]');
  4280.  
  4281. let lastInputTextValue = null;
  4282. let busy = false;
  4283. let disableMonitoring = false;
  4284. const setGV = async (val) => {
  4285.  
  4286. const videoId = getVideoIdByURL() || getVideoIdByElement();
  4287. if (videoId) {
  4288. const cgv = await GM.getValue(`isEnable_aWsjF_${videoId}`, null);
  4289. if (cgv !== val || isEnable !== val) {
  4290. disableMonitoring = true;
  4291. await GM.setValue(`isEnable_aWsjF_${videoId}`, val);
  4292. await GM.setValue('lastCheck_bWsm5', Date.now());
  4293. document.documentElement.setAttribute('forceRefresh032', '');
  4294. location.reload();
  4295. }
  4296.  
  4297. }
  4298. }
  4299. const checkTextChangeF = async (evt) => {
  4300. busy = false;
  4301. const inputElem = (evt || 0).target;
  4302. if (inputElem instanceof HTMLInputElement && !disableMonitoring) {
  4303. const cv = inputElem.value;
  4304. if (cv === lastInputTextValue) return;
  4305. lastInputTextValue = cv;
  4306. if (cv === 'vvv') {
  4307.  
  4308. await setGV(false);
  4309.  
  4310. } else if (cv === 'aaa') {
  4311.  
  4312. await setGV(true);
  4313.  
  4314. }
  4315. }
  4316. }
  4317. const checkTextChange = (evt) => {
  4318. if (busy) return;
  4319. busy = true;
  4320. Promise.resolve(evt).then(checkTextChangeF)
  4321. };
  4322. for (const input of inputs) {
  4323. input.addEventListener('input', checkTextChange, false);
  4324. input.addEventListener('keydown', checkTextChange, false);
  4325. input.addEventListener('keyup', checkTextChange, false);
  4326. input.addEventListener('keypress', checkTextChange, false);
  4327. input.addEventListener('change', checkTextChange, false);
  4328. }
  4329. });
  4330.  
  4331. const autoCleanUpKey = async () => {
  4332.  
  4333. const lastCheck = await GM.getValue('lastCheck_bWsm5', null) || 0;
  4334. if (Date.now() - lastCheck < 16000) return; // 16s
  4335. GM.setValue('lastCheck_bWsm5', Date.now());
  4336. pLoad.then(async () => {
  4337. const rArr = [];
  4338. const arr = await GM.listValues();
  4339. const cv = await GM.getValue("isEnable_aWsjF", null);
  4340. const fn = async (entry) => {
  4341. try {
  4342. if (typeof entry === 'string' && entry.length > 15 && entry.startsWith('isEnable_aWsjF_')) {
  4343. const res = await GM.getValue(entry, null);
  4344. if (typeof res === 'boolean' && res === cv) {
  4345. await GM.deleteValue(entry);
  4346. rArr.push(entry);
  4347. }
  4348. }
  4349. } catch (e) {
  4350. console.warn(e);
  4351. }
  4352. }
  4353. arr.length > 1 && (await Promise.all(arr.map(fn)));
  4354. rArr.length > 0 && console.log('[YouTube Audio Only] autoCleanUpKey', rArr);
  4355. });
  4356. };
  4357.  
  4358. autoCleanUpKey();
  4359.  
  4360.  
  4361.  
  4362.  
  4363.  
  4364. })();
  4365.