HTML5 Video Player Enhance

To enhance the functionality of HTML5 Video Player (h5player) supporting all websites using shortcut keys similar to PotPlayer.

当前为 2021-06-27 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name HTML5 Video Player Enhance
  3. // @version 2.9.5.0
  4. // @description To enhance the functionality of HTML5 Video Player (h5player) supporting all websites using shortcut keys similar to PotPlayer.
  5. // @author CY Fung
  6. // @icon https://image.flaticon.com/icons/png/128/3291/3291444.png
  7. // @match http://*/*
  8. // @match https://*/*
  9. // @run-at document-start
  10. // @require https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js
  11. // @namespace https://greasyfork.org/users/371179
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // @grant GM_addStyle
  15. // @grant unsafeWindow
  16. // ==/UserScript==
  17. /**
  18. * Remarks
  19. * This script support modern browser only with ES6+.
  20. * fullscreen and pointerLock buggy in shadowRoot
  21. * Space Pause not success
  22. * shift F key issue
  23. **/
  24. !(function($winUnsafe, $winSafe) {
  25. 'use strict';
  26.  
  27.  
  28. !(() => 0)({
  29. requestAnimationFrame,
  30. cancelAnimationFrame,
  31. MutationObserver,
  32. setInterval,
  33. clearInterval,
  34. EventTarget,
  35. Promise,
  36. ResizeObserver
  37. });
  38. //throw Error if your browser is too outdated. (eg ES6 script, no such window object)
  39.  
  40. const window = $winUnsafe || $winSafe
  41. const document = window.document
  42. const $$uWin = $winUnsafe || $winSafe;
  43.  
  44. const $rAf = $$uWin.requestAnimationFrame;
  45. const $cAf = $$uWin.cancelAnimationFrame;
  46.  
  47. const $$setTimeout = $$uWin.setTimeout
  48. const $$clearTimeout = $$uWin.clearTimeout
  49. const $$requestAnimationFrame = $$uWin.requestAnimationFrame;
  50. const $$cancelAnimationFrame = $$uWin.cancelAnimationFrame;
  51.  
  52. const $$addEventListener = Node.prototype.addEventListener;
  53. const $$removeEventListener = Node.prototype.removeEventListener;
  54.  
  55. const $bz = {
  56. boosted: false
  57. }
  58.  
  59. const utPositioner='KVZX';
  60.  
  61.  
  62. !(function $$() {
  63. 'use strict';
  64.  
  65. if (!document || !document.documentElement) return window.requestAnimationFrame($$);
  66.  
  67. const prettyElm = function(elm) {
  68. if (!elm || !elm.nodeName) return null;
  69. const eId = elm.id || null;
  70. const eClsName = elm.className || null;
  71. return [elm.nodeName.toLowerCase(), typeof eId == 'string' ? "#" + eId : '', typeof eClsName == 'string' ? '.' + eClsName.replace(/\s+/g, '.') : ''].join('').trim();
  72. }
  73.  
  74. const delayCall = function(p, f, d) {
  75. if (delayCall[p] > 0) delayCall[p] = window.clearTimeout(delayCall[p])
  76. if (f) delayCall[p] = window.setTimeout(f, d)
  77. }
  78.  
  79. HTMLVideoElement.prototype.__isPlaying = function() {
  80. const video = this;
  81. return video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  82. }
  83.  
  84.  
  85. const wmListeners = new WeakMap();
  86.  
  87. class Listeners {
  88. constructor() {}
  89. get count() {
  90. return (this._count || 0)
  91. }
  92. makeId() {
  93. return ++this._lastId
  94. }
  95. add(lh) {
  96. this[++this._lastId] = lh;
  97. }
  98. remove(lh_removal) {
  99. for (let k in this) {
  100. let lh = this[k]
  101. if (lh && lh.constructor == ListenerHandle && lh_removal.isEqual(lh)) {
  102. delete this[k];
  103. this._count--;
  104. }
  105. }
  106. }
  107. }
  108.  
  109.  
  110. class ListenerHandle {
  111. constructor(func, options) {
  112. this.func = func
  113. this.options = options
  114. }
  115. isEqual(anotherLH) {
  116. if (this.func != anotherLH.func) return false;
  117. if (this.options === anotherLH.options) return true;
  118. if (this.options && anotherLH.options && typeof this.options == 'object' && typeof anotherLH.options == 'object') {} else {
  119. return false;
  120. }
  121. return this.uOpt() == anotherLH.uOpt()
  122. }
  123. uOpt() {
  124. let opt1 = "";
  125. for (var k in this.options) {
  126. opt1 += ", " + k + " : " + (typeof this[k] == 'boolean' ? this[k] : "N/A");
  127. }
  128. return opt1;
  129. }
  130. }
  131.  
  132.  
  133. Object.defineProperties(Listeners.prototype, {
  134. _lastId: {
  135. value: 0,
  136. writable: true,
  137. enumerable: false,
  138. configurable: true
  139. },
  140. _count: {
  141. value: 0,
  142. writable: true,
  143. enumerable: false,
  144. configurable: true
  145. }
  146. });
  147.  
  148.  
  149.  
  150.  
  151. let _debug_h5p_logging_ = false;
  152.  
  153. try {
  154. _debug_h5p_logging_ = +window.localStorage.getItem('_h5_player_sLogging_') > 0
  155. } catch (e) {}
  156.  
  157.  
  158.  
  159. const SHIFT = 1;
  160. const CTRL = 2;
  161. const ALT = 4;
  162. const TERMINATE = 0x842;
  163. const _sVersion_ = 1817;
  164. const str_postMsgData = '__postMsgData__'
  165. const DOM_ACTIVE_FOUND = 1;
  166. const DOM_ACTIVE_SRC_LOADED = 2;
  167. const DOM_ACTIVE_ONCE_PLAYED = 4;
  168. const DOM_ACTIVE_MOUSE_CLICK = 8;
  169. const DOM_ACTIVE_MOUSE_IN = 16;
  170. const DOM_ACTIVE_DELAYED_PAUSED = 32;
  171. const DOM_ACTIVE_INVALID_PARENT = 2048;
  172.  
  173. var console = {};
  174.  
  175. console.log = function() {
  176. window.console.log(...['[h5p]', ...arguments])
  177. }
  178. console.error = function() {
  179. window.console.error(...['[h5p]', ...arguments])
  180. }
  181.  
  182. function makeNoRoot(shadowRoot) {
  183. const doc = shadowRoot.ownerDocument || document;
  184. const htmlInShadowRoot = doc.createElement('noroot'); // pseudo element
  185. const childNodes = [...shadowRoot.childNodes]
  186. shadowRoot.insertBefore(htmlInShadowRoot, shadowRoot.firstChild)
  187. for (const childNode of childNodes) htmlInShadowRoot.appendChild(childNode);
  188. return shadowRoot.querySelector('noroot');
  189. }
  190.  
  191. let _endlessloop = null;
  192. const isIframe = (window.top !== window.self && window.top && window.self);
  193. const shadowRoots = [];
  194.  
  195. const _getRoot = Element.prototype.getRootNode || HTMLElement.prototype.getRootNode || function() {
  196. let elm = this;
  197. while (elm) {
  198. if ('host' in elm) return elm;
  199. elm = elm.parentNode;
  200. }
  201. return elm;
  202. }
  203.  
  204. const getRoot = (elm) => _getRoot.call(elm);
  205.  
  206. const isShadowRoot = (elm) => (elm && ('host' in elm)) ? elm.nodeType == 11 && !!elm.host && elm.host.nodeType == 1 : null; //instanceof ShadowRoot
  207.  
  208.  
  209. const domAppender = (d) => d.querySelector('head') || d.querySelector('html') || d.querySelector('noroot') || null;
  210.  
  211. const playerConfs = {}
  212.  
  213. const hanlderResizeVideo = (entries) => {
  214. const detected_changes = {};
  215. for (let entry of entries) {
  216. const player = entry.target.nodeName == "VIDEO" ? entry.target : entry.target.querySelector("VIDEO[_h5ppid]");
  217. if (!player) continue;
  218. const vpid = player.getAttribute('_h5ppid');
  219. if (!vpid) continue;
  220. if (vpid in detected_changes) continue;
  221. detected_changes[vpid] = true;
  222. const wPlayer = $hs.getPlayerBlockElement(player, true)
  223. if (!wPlayer) continue;
  224. const layoutBox = wPlayer.parentNode
  225. if (!layoutBox) continue;
  226. let tipsDom = layoutBox.querySelector('[data-h5p-pot-tips]');
  227.  
  228. if (tipsDom) {
  229. if (tipsDom._tips_display_none) tipsDom.setAttribute('data-h5p-pot-tips', '')
  230. $hs.fixNonBoxingVideoTipsPosition2(tipsDom, player);
  231. } else {
  232. tipsDom = getRoot(player).querySelector(`#${player.getAttribute('_h5player_tips')}`)
  233. if (tipsDom) {
  234. if (tipsDom._tips_display_none) tipsDom.setAttribute('data-h5p-pot-tips', '')
  235. $hs.change_layoutBox(tipsDom, player);
  236. $hs.tipsDomObserve(tipsDom, player);
  237. }
  238. }
  239.  
  240. }
  241. };
  242.  
  243. const $mb = {
  244.  
  245.  
  246.  
  247. nightly_isSupportQueueMicrotask: function() {
  248.  
  249. if ('_isSupportQueueMicrotask' in $mb) return $mb._isSupportQueueMicrotask;
  250.  
  251. $mb._isSupportQueueMicrotask = false;
  252. $mb.queueMicrotask = window.queueMicrotask;
  253. if (typeof $mb.queueMicrotask == 'function') {
  254. $mb._isSupportQueueMicrotask = true;
  255. }
  256.  
  257. return $mb._isSupportQueueMicrotask;
  258.  
  259. },
  260.  
  261. stable_isSupportAdvancedEventListener: function() {
  262.  
  263. if ('_isSupportAdvancedEventListener' in $mb) return $mb._isSupportAdvancedEventListener
  264. let prop = 0;
  265. $$addEventListener.call(document.createAttribute('z'), 'z', () => 0, {
  266. get passive() {
  267. prop++;
  268. },
  269. get once() {
  270. prop++;
  271. }
  272. });
  273. return ($mb._isSupportAdvancedEventListener = (prop == 2));
  274. },
  275.  
  276. stable_isSupportPassiveEventListener: function() {
  277.  
  278. if ('_isSupportPassiveEventListener' in $mb) return $mb._isSupportPassiveEventListener
  279. let prop = 0;
  280. $$addEventListener.call(document.createAttribute('z'), 'z', () => 0, {
  281. get passive() {
  282. prop++;
  283. }
  284. });
  285. return ($mb._isSupportPassiveEventListener = (prop == 1));
  286. },
  287.  
  288. eh_capture_passive: () => ($mb._eh_capture_passive = $mb._eh_capture_passive || ($mb.stable_isSupportPassiveEventListener() ? {
  289. capture: true,
  290. passive: true
  291. } : true)),
  292.  
  293. eh_bubble_passive: () => ($mb._eh_capture_passive = $mb._eh_capture_passive || ($mb.stable_isSupportPassiveEventListener() ? {
  294. capture: false,
  295. passive: true
  296. } : false))
  297.  
  298. }
  299.  
  300.  
  301.  
  302. Element.prototype.__matches__ = (Element.prototype.matches || Element.prototype.matchesSelector ||
  303. Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector ||
  304. Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector ||
  305. Element.prototype.matches()); // throw Error if not supported
  306.  
  307. // built-in hash - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  308. async function digestMessage(message) {
  309. return $winSafe.sha256(message)
  310. }
  311.  
  312. const dround = (x) => ~~(x + .5);
  313.  
  314. const jsonStringify_replacer = function(key, val) {
  315. if (val && (val instanceof Element || val instanceof Document)) return val.toString();
  316. return val; // return as is
  317. };
  318.  
  319. const jsonParse = function() {
  320. try {
  321. return JSON.parse.apply(this, arguments)
  322. } catch (e) {}
  323. return null;
  324. }
  325. const jsonStringify = function(obj) {
  326. try {
  327. return JSON.stringify.call(this, obj, jsonStringify_replacer)
  328. } catch (e) {}
  329. return null;
  330. }
  331.  
  332. function _postMsg() {
  333. //async is needed. or error handling for postMessage
  334. const [win, tag, ...data] = arguments;
  335. if (typeof tag == 'string') {
  336. let postMsgObj = {
  337. tag,
  338. passing: true,
  339. winOrder: _postMsg.a
  340. }
  341. try {
  342. let k = 'msg-' + (+new Date)
  343. win.document[str_postMsgData] = win.document[str_postMsgData] || {}
  344. win.document[str_postMsgData][k] = data; //direct
  345. postMsgObj.str = k;
  346. postMsgObj.stype = 1;
  347. } catch (e) {}
  348. if (!postMsgObj.stype) {
  349. postMsgObj.str = jsonStringify({
  350. d: data
  351. })
  352. if (postMsgObj.str && postMsgObj.str.length) postMsgObj.stype = 2;
  353. }
  354. if (!postMsgObj.stype) {
  355. postMsgObj.str = "" + data;
  356. postMsgObj.stype = 0;
  357. }
  358. win.postMessage(postMsgObj, '*');
  359. }
  360.  
  361. }
  362.  
  363. function postMsg() {
  364. let win = window;
  365. let a = 0;
  366. while ((win = win.parent) && ('postMessage' in win)) {
  367. _postMsg.a = ++a;
  368. _postMsg(win, ...arguments)
  369. if (win == top) break;
  370. }
  371. }
  372.  
  373.  
  374. function crossBrowserTransition(type) {
  375. if (crossBrowserTransition['_result_' + type]) return crossBrowserTransition['_result_' + type]
  376. let el = document.createElement("fakeelement");
  377.  
  378. const capital = (x) => x[0].toUpperCase() + x.substr(1);
  379. const capitalType = capital(type);
  380.  
  381. const transitions = {
  382. [type]: `${type}end`,
  383. [`O${capitalType}`]: `o${capitalType}End`,
  384. [`Moz${capitalType}`]: `${type}end`,
  385. [`Webkit${capitalType}`]: `webkit${capitalType}End`,
  386. [`MS${capitalType}`]: `MS${capitalType}End`
  387. }
  388.  
  389. for (let styleProp in transitions) {
  390. if (el.style[styleProp] !== undefined) {
  391. return (crossBrowserTransition['_result_' + type] = transitions[styleProp]);
  392. }
  393. }
  394. }
  395.  
  396. function isInOperation(elm) {
  397. let elmInFocus = elm || document.activeElement;
  398. if (!elmInFocus) return false;
  399. let res1 = elmInFocus.__matches__(
  400. 'a[href],link[href],button,input:not([type="hidden"]),select,textarea,iframe,frame,menuitem,[draggable],[contenteditable]'
  401. );
  402. return res1;
  403. }
  404.  
  405. const fn_toString = (f, n = 50) => {
  406. let s = (f + "");
  407. if (s.length > 2 * n + 5) {
  408. s = s.substr(0, n) + ' ... ' + s.substr(-n);
  409. }
  410. return s
  411. };
  412.  
  413. function consoleLog() {
  414. if (!_debug_h5p_logging_) return;
  415. if (isIframe) postMsg('consoleLog', ...arguments);
  416. else console.log.apply(console, arguments);
  417. }
  418.  
  419. function consoleLogF() {
  420. if (isIframe) postMsg('consoleLog', ...arguments);
  421. else console.log.apply(console, arguments);
  422. }
  423.  
  424. class AFLooperArray extends Array {
  425. constructor() {
  426. super();
  427. this.activeLoopsCount = 0;
  428. this.cid = 0;
  429. this.loopingFrame = this.loopingFrame.bind(this);
  430. }
  431.  
  432. loopingFrame() {
  433. if (!this.cid) return; //cancelled
  434. for (const opt of this) {
  435. if (opt.isFunctionLooping) opt.fn();
  436. }
  437. }
  438.  
  439. get isArrayLooping() {
  440. return this.cid > 0;
  441. }
  442.  
  443. loopStart() {
  444. this.cid = window.setInterval(this.loopingFrame, 300);
  445. }
  446. loopStop() {
  447. if (this.cid) window.clearInterval(this.cid);
  448. this.cid = 0;
  449. }
  450. appendLoop(fn) {
  451. if (typeof fn != 'function' || !this) return;
  452. const opt = new AFLooperFunc(fn, this);
  453. super.push(opt);
  454. return opt;
  455. }
  456. }
  457.  
  458. class AFLooperFunc {
  459. constructor(fn, bind) {
  460. this._looping = false;
  461. this.bind = bind;
  462. this.fn = fn;
  463. }
  464. get isFunctionLooping() {
  465. return this._looping;
  466. }
  467. loopingStart() {
  468. if (this._looping === false) {
  469. this._looping = true;
  470. if (++this.bind.activeLoopsCount == 1) this.bind.loopStart();
  471. }
  472. }
  473. loopingStop() {
  474. if (this._looping === true) {
  475. this._looping = false;
  476. if (--this.bind.activeLoopsCount == 0) this.bind.loopStop();
  477. }
  478. }
  479. }
  480.  
  481. function decimalEqual(a, b) {
  482. return Math.round(a * 100000000) == Math.round(b * 100000000)
  483. }
  484.  
  485. function nonZeroNum(a) {
  486. return a > 0 || a < 0;
  487. }
  488.  
  489. class PlayerConf {
  490.  
  491. get scaleFactor() {
  492. return this.mFactor * this.vFactor;
  493. }
  494.  
  495. cssTransform() {
  496.  
  497. const playerConf = this;
  498. const player = playerConf.domElement;
  499. if (!player) return;
  500. const videoScale = playerConf.scaleFactor;
  501.  
  502. let {
  503. x,
  504. y
  505. } = playerConf.translate;
  506.  
  507. let [_x, _y] = ((playerConf.rotate % 180) == 90) ? [y, x] : [x, y];
  508.  
  509.  
  510. if ((playerConf.rotate % 360) == 270) _x = -_x;
  511. if ((playerConf.rotate % 360) == 90) _y = -_y;
  512.  
  513. var s = [
  514. playerConf.rotate > 0 ? 'rotate(' + playerConf.rotate + 'deg)' : '',
  515. !decimalEqual(videoScale, 1.0) ? 'scale(' + videoScale + ')' : '',
  516. (nonZeroNum(_x) || nonZeroNum(_y)) ? `translate(${_x}px, ${_y}px)` : '',
  517. ];
  518.  
  519. player.style.transform = s.join(' ').trim()
  520.  
  521. }
  522.  
  523. constructor() {
  524.  
  525. this.translate = {
  526. x: 0,
  527. y: 0
  528. };
  529. this.rotate = 0;
  530. this.mFactor = 1.0;
  531. this.vFactor = 1.0;
  532. this.fps = 30;
  533. this.filter_key = {};
  534. this.filter_view_units = {
  535. 'hue-rotate': 'deg',
  536. 'blur': 'px'
  537. };
  538. this.filterReset();
  539.  
  540. }
  541.  
  542. setFilter(prop, f) {
  543.  
  544. let oldValue = this.filter_key[prop];
  545. if (typeof oldValue != 'number') return;
  546. let newValue = f(oldValue)
  547. if (oldValue != newValue) {
  548.  
  549. newValue = +newValue.toFixed(6); //javascript bug
  550.  
  551. }
  552.  
  553. this.filter_key[prop] = newValue
  554. this.filterSetup();
  555.  
  556. return newValue;
  557.  
  558.  
  559.  
  560. }
  561.  
  562. filterSetup(options) {
  563.  
  564. let ums = GM_getValue("unsharpen_mask")
  565. if (!ums) ums = ""
  566.  
  567. let view = []
  568. let playerElm = $hs.player();
  569. if (!playerElm) return;
  570. for (let view_key in this.filter_key) {
  571. let filter_value = +((+this.filter_key[view_key] || 0).toFixed(3))
  572. let addTo = true;
  573. switch (view_key) {
  574. case 'brightness':
  575. /* fall through */
  576. case 'contrast':
  577. /* fall through */
  578. case 'saturate':
  579. if (decimalEqual(filter_value, 1.0)) addTo = false;
  580. break;
  581. case 'hue-rotate':
  582. /* fall through */
  583. case 'blur':
  584. if (decimalEqual(filter_value, 0.0)) addTo = false;
  585. break;
  586. }
  587. let view_unit = this.filter_view_units[view_key] || ''
  588. if (addTo) view.push(`${view_key}(${filter_value}${view_unit})`)
  589. this.filter_key[view_key] = Number(+this.filter_key[view_key] || 0)
  590. }
  591. if (ums) view.push(`url("#_h5p_${ums}")`);
  592. if (options && options.grey) view.push('url("#grey1")');
  593. playerElm.style.filter = view.join(' ').trim(); //performance in firefox is bad
  594. }
  595.  
  596. filterReset() {
  597. this.filter_key['brightness'] = 1.0
  598. this.filter_key['contrast'] = 1.0
  599. this.filter_key['saturate'] = 1.0
  600. this.filter_key['hue-rotate'] = 0.0
  601. this.filter_key['blur'] = 0.0
  602. this.filterSetup()
  603. }
  604.  
  605. }
  606.  
  607. const Store = {
  608. prefix: '_h5_player',
  609. save: function(k, v) {
  610. if (!Store.available()) return false;
  611. if (typeof v != 'string') return false;
  612. Store.LS.setItem(Store.prefix + k, v)
  613. let sk = fn_toString(k + "", 30);
  614. let sv = fn_toString(v + "", 30);
  615. consoleLog(`localStorage Saved "${sk}" = "${sv}"`)
  616. return true;
  617.  
  618. },
  619. read: function(k) {
  620. if (!Store.available()) return false;
  621. let v = Store.LS.getItem(Store.prefix + k)
  622. let sk = fn_toString(k + "", 30);
  623. let sv = fn_toString(v + "", 30);
  624. consoleLog(`localStorage Read "${sk}" = "${sv}"`);
  625. return v;
  626.  
  627. },
  628. remove: function(k) {
  629.  
  630. if (!Store.available()) return false;
  631. Store.LS.removeItem(Store.prefix + k)
  632. let sk = fn_toString(k + "", 30);
  633. consoleLog(`localStorage Removed "${sk}"`)
  634. return true;
  635. },
  636. clearInvalid: function(sVersion) {
  637. if (!Store.available()) return false;
  638.  
  639. //let sVersion=1814;
  640. if (+Store.read('_sVersion_') < sVersion) {
  641. Store._keys()
  642. .filter(s => s.indexOf(Store.prefix) === 0)
  643. .forEach(key => window.localStorage.removeItem(key))
  644. Store.save('_sVersion_', sVersion + '')
  645. return 2;
  646. }
  647. return 1;
  648.  
  649. },
  650. available: function() {
  651. if (Store.LS) return true;
  652. if (!window) return false;
  653. const localStorage = window.localStorage;
  654. if (!localStorage) return false;
  655. if (typeof localStorage != 'object') return false;
  656. if (!('getItem' in localStorage)) return false;
  657. if (!('setItem' in localStorage)) return false;
  658. Store.LS = localStorage;
  659. return true;
  660.  
  661. },
  662. _keys: function() {
  663. return Object.keys(localStorage);
  664. },
  665. _setItem: function(key, value) {
  666. return localStorage.setItem(key, value)
  667. },
  668. _getItem: function(key) {
  669. return localStorage.getItem(key)
  670. },
  671. _removeItem: function(key) {
  672. return localStorage.removeItem(key)
  673. }
  674.  
  675. }
  676.  
  677. const domTool = {
  678. nopx: (x) => +x.replace('px', ''),
  679. cssWH: function(m, r) {
  680. if (!r) r = getComputedStyle(m, null);
  681. let c = (x) => +x.replace('px', '');
  682. return {
  683. w: m.offsetWidth || c(r.width),
  684. h: m.offsetHeight || c(r.height)
  685. }
  686. },
  687. _isActionBox_1: function(vEl, pEl) {
  688.  
  689. const vElCSS = domTool.cssWH(vEl);
  690. let vElCSSw = vElCSS.w;
  691. let vElCSSh = vElCSS.h;
  692.  
  693. let vElx = vEl;
  694. const res = [];
  695. //let mLevel = 0;
  696. if (vEl && pEl && vEl != pEl && pEl.contains(vEl)) {
  697. while (vElx && vElx != pEl) {
  698. vElx = vElx.parentNode;
  699. let vElx_css = null;
  700. if (isShadowRoot(vElx)) {} else {
  701. vElx_css = getComputedStyle(vElx, null);
  702. let vElx_wp = domTool.nopx(vElx_css.paddingLeft) + domTool.nopx(vElx_css.paddingRight)
  703. vElCSSw += vElx_wp
  704. let vElx_hp = domTool.nopx(vElx_css.paddingTop) + domTool.nopx(vElx_css.paddingBottom)
  705. vElCSSh += vElx_hp
  706. }
  707. res.push({
  708. //level: ++mLevel,
  709. padW: vElCSSw,
  710. padH: vElCSSh,
  711. elm: vElx,
  712. css: vElx_css
  713. })
  714.  
  715. }
  716. }
  717.  
  718. // in the array, each item is the parent of video player
  719. //res.vEl_cssWH = vElCSS
  720.  
  721. return res;
  722.  
  723. },
  724. _isActionBox: function(vEl, walkRes, pEl_idx) {
  725.  
  726. function absDiff(w1, w2, h1, h2) {
  727. const w = (w1 - w2),
  728. h = h1 - h2;
  729. return [(w > 0 ? w : -w), (h > 0 ? h : -h)]
  730. }
  731.  
  732. function midPoint(rect) {
  733. return {
  734. x: (rect.left + rect.right) / 2,
  735. y: (rect.top + rect.bottom) / 2
  736. }
  737. }
  738.  
  739. const parentCount = walkRes.length;
  740. if (pEl_idx >= 0 && pEl_idx < parentCount) {} else {
  741. return;
  742. }
  743. const pElr = walkRes[pEl_idx]
  744. if (!pElr.css) {
  745. //shadowRoot
  746. return true;
  747. }
  748.  
  749. const pEl = pElr.elm;
  750.  
  751. //prevent activeElement==body
  752. const pElCSS = domTool.cssWH(pEl, pElr.css);
  753.  
  754. //check prediction of parent dimension
  755. const d1v = absDiff(pElCSS.w, pElr.padW, pElCSS.h, pElr.padH)
  756.  
  757. const d1x = d1v[0] < 10
  758. const d1y = d1v[1] < 10;
  759.  
  760. if (d1x && d1y) return true; //both edge along the container - fit size
  761. if (!d1x && !d1y) return false; //no edge along the container - body contain the video element, fixed width&height
  762.  
  763. //case: youtube video fullscreen
  764.  
  765. //check centre point
  766.  
  767. const pEl_rect = pEl.getBoundingClientRect()
  768. const vEl_rect = vEl.getBoundingClientRect()
  769.  
  770. const pEl_center = midPoint(pEl_rect)
  771. const vEl_center = midPoint(vEl_rect)
  772.  
  773. const d2v = absDiff(pEl_center.x, vEl_center.x, pEl_center.y, vEl_center.y);
  774.  
  775. const d2x = d2v[0] < 10;
  776. const d2y = d2v[1] < 10;
  777.  
  778. return (d2x && d2y);
  779.  
  780. },
  781. getRect: function(element) {
  782. let rect = element.getBoundingClientRect();
  783. let scroll = domTool.getScroll();
  784. return {
  785. pageX: rect.left + scroll.left,
  786. pageY: rect.top + scroll.top,
  787. screenX: rect.left,
  788. screenY: rect.top
  789. };
  790. },
  791. getScroll: function() {
  792. return {
  793. left: document.documentElement.scrollLeft || document.body.scrollLeft,
  794. top: document.documentElement.scrollTop || document.body.scrollTop
  795. };
  796. },
  797. getClient: function() {
  798. return {
  799. width: document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth,
  800. height: document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight
  801. };
  802. },
  803. addStyle: //GM_addStyle,
  804. function(css, head) {
  805. if (!head) {
  806. let _doc = document.documentElement;
  807. head = domAppender(_doc);
  808. }
  809. let doc = head.ownerDocument;
  810. let style = doc.createElement('style');
  811. style.type = 'text/css';
  812. style.textContent = css;
  813. head.appendChild(style);
  814. //console.log(document.head,style,'add style')
  815. return style;
  816. },
  817. eachParentNode: function(dom, fn) {
  818. let parent = dom.parentNode
  819. while (parent) {
  820. let isEnd = fn(parent, dom)
  821. parent = parent.parentNode
  822. if (isEnd) {
  823. break
  824. }
  825. }
  826. },
  827.  
  828. hideDom: function hideDom(selector) {
  829. let dom = document.querySelector(selector)
  830. if (dom) {
  831. window.requestAnimationFrame(function() {
  832. dom.style.opacity = 0;
  833. dom.style.transform = 'translate(-9999px)';
  834. dom = null;
  835. })
  836. }
  837. }
  838. };
  839.  
  840. const handle = {
  841.  
  842.  
  843. afPlaybackRecording: async function() {
  844. const opts = this;
  845.  
  846. let qTime = +new Date;
  847. if (qTime >= opts.pTime) {
  848. opts.pTime = qTime + opts.timeDelta; //prediction of next Interval
  849. opts.savePlaybackProgress()
  850. }
  851.  
  852. },
  853. savePlaybackProgress: function() {
  854.  
  855. //this refer to endless's opts
  856. let player = this.player;
  857.  
  858. let _uid = this.player_uid; //_h5p_uid_encrypted
  859. if (!_uid) return;
  860.  
  861. let shallSave = true;
  862. let currentTimeToSave = ~~player.currentTime;
  863.  
  864. if (this._lastSave == currentTimeToSave) shallSave = false;
  865.  
  866. if (shallSave) {
  867.  
  868. this._lastSave = currentTimeToSave
  869.  
  870. Promise.resolve().then(() => {
  871.  
  872. //console.log('aasas',this.player_uid, shallSave, '_play_progress_'+_uid, currentTimeToSave)
  873.  
  874. Store.save('_play_progress_' + _uid, jsonStringify({
  875. 't': currentTimeToSave
  876. }))
  877. })
  878.  
  879. }
  880. //console.log('playback logged')
  881.  
  882. },
  883. playingWithRecording: function() {
  884. let player = this.player;
  885. if (!player.paused && !this.isFunctionLooping) {
  886. let player = this.player;
  887. let _uid = player.getAttribute('_h5p_uid_encrypted') || ''
  888. if (_uid) {
  889. this.player_uid = _uid;
  890. this.pTime = 0;
  891. this.loopingStart();
  892. }
  893. }
  894. }
  895.  
  896. };
  897.  
  898. /*
  899. class Momentary extends Map {
  900. act(uniqueId, fn_start, fn_end, delay) {
  901. if (!uniqueId) return;
  902. uniqueId = uniqueId + "";
  903. const last_cid = this.get(uniqueId);
  904. if (last_cid > 0) window.clearTimeout(last_cid);
  905. fn_start();
  906. const new_cid = window.setTimeout(fn_end, delay)
  907. this.set(uniqueId, new_cid)
  908. }
  909. }
  910.  
  911. const momentary = new Momentary();*/
  912.  
  913. const $hs = {
  914.  
  915. /* 提示文本的字號 */
  916. fontSize: 16,
  917. enable: true,
  918. playerInstance: null,
  919. playbackRate: 1,
  920. /* 快進快退步長 */
  921. skipStep: 5,
  922.  
  923. /* 獲取當前播放器的實例 */
  924. player: function() {
  925. let res = $hs.playerInstance || null;
  926. if (res && res.parentNode == null) {
  927. $hs.playerInstance = null;
  928. res = null;
  929. }
  930.  
  931. if (res == null) {
  932. for (let k in playerConfs) {
  933. let playerConf = playerConfs[k];
  934. if (playerConf && playerConf.domElement && playerConf.domElement.parentNode) return playerConf.domElement;
  935. }
  936. }
  937. return res;
  938. },
  939.  
  940. pictureInPicture: function(videoElm) {
  941. if (document.pictureInPictureElement) {
  942. document.exitPictureInPicture();
  943. } else if ('requestPictureInPicture' in videoElm) {
  944. videoElm.requestPictureInPicture()
  945. } else {
  946. $hs.tips('PIP is not supported.');
  947. }
  948. },
  949.  
  950. getPlayerConf: function(video) {
  951.  
  952. if (!video) return null;
  953. let vpid = video.getAttribute('_h5ppid') || null;
  954. if (!vpid) return null;
  955. return playerConfs[vpid] || null;
  956.  
  957. },
  958. debug01: function(evt, videoActive) {
  959.  
  960. if (!$hs.eventHooks) {
  961. document.__h5p_eventhooks = ($hs.eventHooks = {
  962. _debug_: []
  963. });
  964. }
  965. $hs.eventHooks._debug_.push([videoActive, evt.type]);
  966. // console.log('h5p eventhooks = document.__h5p_eventhooks')
  967. },
  968.  
  969. swtichPlayerInstance: function() {
  970.  
  971. let newPlayerInstance = null;
  972. const ONLY_PLAYING_NONE = 0x4A00;
  973. const ONLY_PLAYING_MORE_THAN_ONE = 0x5A00;
  974. let onlyPlayingInstance = ONLY_PLAYING_NONE;
  975. for (let k in playerConfs) {
  976. let playerConf = playerConfs[k] || {};
  977. let {
  978. domElement,
  979. domActive
  980. } = playerConf;
  981. if (domElement) {
  982. if (domActive & DOM_ACTIVE_INVALID_PARENT) continue;
  983. if (!domElement.parentNode) {
  984. playerConf.domActive |= DOM_ACTIVE_INVALID_PARENT;
  985. continue;
  986. }
  987. if (domActive & DOM_ACTIVE_MOUSE_CLICK) {
  988. newPlayerInstance = domElement
  989. break;
  990. }
  991. if (domActive & DOM_ACTIVE_ONCE_PLAYED && (domActive & DOM_ACTIVE_DELAYED_PAUSED) == 0) {
  992. if (onlyPlayingInstance == ONLY_PLAYING_NONE) onlyPlayingInstance = domElement;
  993. else onlyPlayingInstance = ONLY_PLAYING_MORE_THAN_ONE;
  994. }
  995. }
  996. }
  997. if (newPlayerInstance == null && onlyPlayingInstance.nodeType == 1) {
  998. newPlayerInstance = onlyPlayingInstance;
  999. }
  1000.  
  1001. $hs.playerInstance = newPlayerInstance
  1002.  
  1003.  
  1004. },
  1005.  
  1006. mouseMoveCount: 0,
  1007.  
  1008. handlerVideoPlaying: function(evt) {
  1009. const videoElm = evt.target || this || null;
  1010.  
  1011. if (!videoElm || videoElm.nodeName != "VIDEO") return;
  1012.  
  1013. const vpid = videoElm.getAttribute('_h5ppid')
  1014.  
  1015. if (!vpid) return;
  1016.  
  1017.  
  1018.  
  1019. Promise.resolve().then(() => {
  1020.  
  1021. if ($hs.cid_playHook > 0) window.clearTimeout($hs.cid_playHook);
  1022. $hs.cid_playHook = window.setTimeout(function() {
  1023. let onlyPlayed = null;
  1024. for (var k in playerConfs) {
  1025. if (k == vpid) {
  1026. if (playerConfs[k].domElement.paused === false) onlyPlayed = true;
  1027. } else if (playerConfs[k].domElement.paused === false) {
  1028. onlyPlayed = false;
  1029. break;
  1030. }
  1031. }
  1032. if (onlyPlayed === true) {
  1033. $hs.focusHookVDoc = getRoot(videoElm)
  1034. $hs.focusHookVId = vpid
  1035. }
  1036. $bv.boostVideoPerformanceActivate();
  1037.  
  1038. $hs.hcDelayMouseHideAndStartMointoring(videoElm);
  1039.  
  1040. }, 100)
  1041.  
  1042. }).then(() => {
  1043.  
  1044. const playerConf = $hs.getPlayerConf(videoElm)
  1045.  
  1046. if (playerConf) {
  1047. if (playerConf.timeout_pause > 0) playerConf.timeout_pause = window.clearTimeout(playerConf.timeout_pause);
  1048. playerConf.lastPauseAt = 0
  1049. playerConf.domActive |= DOM_ACTIVE_ONCE_PLAYED;
  1050. playerConf.domActive &= ~DOM_ACTIVE_DELAYED_PAUSED;
  1051. }
  1052.  
  1053. }).then(() => {
  1054.  
  1055. $hs._actionBoxObtain(videoElm);
  1056.  
  1057. }).then(() => {
  1058.  
  1059. $hs.swtichPlayerInstance();
  1060. $hs.onVideoTriggering();
  1061.  
  1062.  
  1063.  
  1064. }).then(() => {
  1065.  
  1066. if (!$hs.enable) return $hs.tips(false);
  1067.  
  1068. if (videoElm._isThisPausedBefore_) consoleLog('resumed')
  1069. let _pausedbefore_ = videoElm._isThisPausedBefore_
  1070.  
  1071. if (videoElm.playpause_cid) {
  1072. window.clearTimeout(videoElm.playpause_cid);
  1073. videoElm.playpause_cid = 0;
  1074. }
  1075. let _last_paused = videoElm._last_paused
  1076. videoElm._last_paused = videoElm.paused
  1077. if (_last_paused === !videoElm.paused) {
  1078. videoElm.playpause_cid = window.setTimeout(() => {
  1079. if (videoElm.paused === !_last_paused && !videoElm.paused && _pausedbefore_) {
  1080. $hs.tips('Playback resumed', undefined, 2500)
  1081. }
  1082. }, 90)
  1083. }
  1084.  
  1085. /* 播放的時候進行相關同步操作 */
  1086.  
  1087. if (!videoElm._record_continuous) {
  1088.  
  1089. /* 同步之前設定的播放速度 */
  1090. $hs.setPlaybackRate()
  1091.  
  1092. if (!_endlessloop) _endlessloop = new AFLooperArray();
  1093.  
  1094. videoElm._record_continuous = _endlessloop.appendLoop(handle.afPlaybackRecording);
  1095. videoElm._record_continuous._lastSave = -999;
  1096.  
  1097. videoElm._record_continuous.timeDelta = 2000;
  1098. videoElm._record_continuous.player = videoElm
  1099. videoElm._record_continuous.savePlaybackProgress = handle.savePlaybackProgress;
  1100. videoElm._record_continuous.playingWithRecording = handle.playingWithRecording;
  1101. }
  1102.  
  1103. videoElm._record_continuous.playingWithRecording(videoElm); //try to start recording
  1104.  
  1105. videoElm._isThisPausedBefore_ = false;
  1106.  
  1107. })
  1108.  
  1109. },
  1110. handlerVideoPause: function(evt) {
  1111.  
  1112. const videoElm = evt.target || this || null;
  1113.  
  1114. if (!videoElm || videoElm.nodeName != "VIDEO") return;
  1115.  
  1116. const vpid = videoElm.getAttribute('_h5ppid')
  1117.  
  1118. if (!vpid) return;
  1119.  
  1120.  
  1121. Promise.resolve().then(() => {
  1122.  
  1123. if ($hs.cid_playHook > 0) window.clearTimeout($hs.cid_playHook);
  1124. $hs.cid_playHook = window.setTimeout(function() {
  1125. let allPaused = true;
  1126. for (var k in playerConfs) {
  1127. if (playerConfs[k].domElement.paused === false) {
  1128. allPaused = false;
  1129. break;
  1130. }
  1131. }
  1132. if (allPaused) {
  1133. $hs.focusHookVDoc = getRoot(videoElm)
  1134. $hs.focusHookVId = vpid
  1135. }
  1136. $bv.boostVideoPerformanceDeactivate();
  1137. }, 100)
  1138.  
  1139. }).then(() => {
  1140.  
  1141. const playerConf = $hs.getPlayerConf(videoElm)
  1142. if (playerConf) {
  1143. playerConf.lastPauseAt = +new Date;
  1144. playerConf.timeout_pause = window.setTimeout(() => {
  1145. if (playerConf.lastPauseAt > 0) playerConf.domActive |= DOM_ACTIVE_DELAYED_PAUSED;
  1146. }, 600)
  1147. }
  1148.  
  1149. }).then(() => {
  1150.  
  1151. if (!$hs.enable) return $hs.tips(false);
  1152. consoleLog('pause')
  1153. videoElm._isThisPausedBefore_ = true;
  1154.  
  1155. let _last_paused = videoElm._last_paused
  1156. videoElm._last_paused = videoElm.paused
  1157. if (videoElm.playpause_cid) {
  1158. window.clearTimeout(videoElm.playpause_cid);
  1159. videoElm.playpause_cid = 0;
  1160. }
  1161. if (_last_paused === !videoElm.paused) {
  1162. videoElm.playpause_cid = window.setTimeout(() => {
  1163. if (videoElm.paused === !_last_paused && videoElm.paused) {
  1164. $hs._tips(videoElm, 'Playback paused', undefined, 2500)
  1165. }
  1166. }, 90)
  1167. }
  1168.  
  1169.  
  1170. if (videoElm._record_continuous && videoElm._record_continuous.isFunctionLooping) {
  1171. window.setTimeout(function() {
  1172. if (videoElm.paused === true && !videoElm._record_continuous.isFunctionLooping) videoElm._record_continuous.savePlaybackProgress(); //savePlaybackProgress once before stopping //handle.savePlaybackProgress;
  1173. }, 380)
  1174. videoElm._record_continuous.loopingStop();
  1175. }
  1176.  
  1177.  
  1178. })
  1179.  
  1180.  
  1181. },
  1182. handlerVideoVolumeChange: function(evt) {
  1183.  
  1184. let videoElm = evt.target || this || null;
  1185.  
  1186. if (videoElm.nodeName != "VIDEO") return;
  1187. if (videoElm.volume >= 0) {} else {
  1188. return;
  1189. }
  1190.  
  1191. if ($hs._volume_change_counter > 0) return;
  1192. $hs._volume_change_counter = ($hs._volume_change_counter || 0) + 1
  1193.  
  1194. window.requestAnimationFrame(function() {
  1195.  
  1196. let makeTips = false;
  1197. Promise.resolve(videoElm).then((videoElm) => {
  1198.  
  1199.  
  1200. let cVol = videoElm.volume;
  1201. let cMuted = videoElm.muted;
  1202.  
  1203. if (cVol === videoElm._volume_p && cMuted === videoElm._muted_p) {
  1204. // nothing changed
  1205. } else if (cVol === videoElm._volume_p && cMuted !== videoElm._muted_p) {
  1206. // muted changed
  1207. } else { // cVol != pVol
  1208.  
  1209. // only volume changed
  1210.  
  1211. let shallShowTips = videoElm._volume >= 0; //prevent initialization
  1212.  
  1213. if (!cVol) {
  1214. videoElm.muted = true;
  1215. } else if (cMuted) {
  1216. videoElm.muted = false;
  1217. videoElm._volume = cVol;
  1218. } else if (!cMuted) {
  1219. videoElm._volume = cVol;
  1220. }
  1221. consoleLog('volume changed');
  1222.  
  1223. if (shallShowTips) makeTips = true;
  1224.  
  1225. }
  1226.  
  1227. videoElm._volume_p = cVol;
  1228. videoElm._muted_p = cMuted;
  1229.  
  1230. return videoElm;
  1231.  
  1232. }).then((videoElm) => {
  1233.  
  1234. if (makeTips) $hs._tips(videoElm, 'Volume: ' + dround(videoElm.volume * 100) + '%', undefined, 3000);
  1235.  
  1236. $hs._volume_change_counter = 0;
  1237.  
  1238. })
  1239. videoElm = null
  1240.  
  1241. })
  1242.  
  1243.  
  1244.  
  1245. },
  1246. handlerVideoLoadedMetaData: function(evt) {
  1247. const videoElm = evt.target || this || null;
  1248.  
  1249. if (!videoElm || videoElm.nodeName != "VIDEO") return;
  1250.  
  1251. Promise.resolve(videoElm).then((videoElm) => {
  1252.  
  1253. consoleLog('video size', videoElm.videoWidth + ' x ' + videoElm.videoHeight);
  1254.  
  1255. let vpid = videoElm.getAttribute('_h5ppid') || null;
  1256. if (!vpid || !videoElm.currentSrc) return;
  1257.  
  1258. let videoElm_withSrcChanged = null
  1259.  
  1260. if ($hs.varSrcList[vpid] != videoElm.currentSrc) {
  1261. $hs.varSrcList[vpid] = videoElm.currentSrc;
  1262. $hs.videoSrcFound(videoElm);
  1263. videoElm_withSrcChanged = videoElm;
  1264. }
  1265. if (!videoElm._onceVideoLoaded) {
  1266. videoElm._onceVideoLoaded = true;
  1267. playerConfs[vpid].domActive |= DOM_ACTIVE_SRC_LOADED;
  1268. }
  1269.  
  1270. return videoElm_withSrcChanged
  1271. }).then((videoElm_withSrcChanged) => {
  1272.  
  1273. if (videoElm_withSrcChanged) $hs._actionBoxObtain(videoElm_withSrcChanged);
  1274.  
  1275.  
  1276.  
  1277. })
  1278.  
  1279. },
  1280. handlerSizing:(entries)=>{
  1281.  
  1282. for(const {target} of entries){
  1283.  
  1284. let cw=target.clientWidth
  1285. let ch=target.clientHeight
  1286. target.__clientWidth = cw
  1287. target.__clientHeight = ch
  1288. target.mouseMoveMax = Math.sqrt(cw * cw + ch * ch) * 0.06;
  1289.  
  1290.  
  1291. }
  1292.  
  1293. },
  1294. mouseActioner: {
  1295. calls: [],
  1296. time: 0,
  1297. cid: 0,
  1298. lastFound: null,
  1299. lastHoverElm: null
  1300. },
  1301. mouseEnteredElement: null,
  1302. mouseAct: function() {
  1303.  
  1304. $hs.mouseActioner.cid = 0;
  1305.  
  1306. if (+new Date - $hs.mouseActioner.time < 30) {
  1307. $hs.mouseActioner.cid = window.setTimeout($hs.mouseAct, 82)
  1308. return;
  1309. }
  1310.  
  1311. if ($hs.mouseDownAt && $hs.mouseActioner.lastFound && $hs.mouseDownAt.insideVideo === $hs.mouseActioner.lastFound) {
  1312.  
  1313. return;
  1314.  
  1315. }
  1316.  
  1317. const getVideo = (target) => {
  1318.  
  1319.  
  1320. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(target);
  1321. if (!actionBoxRelation) return;
  1322. const actionBox = actionBoxRelation.actionBox
  1323. if (!actionBox) return;
  1324. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1325. const videoElm = actionBoxRelation.player;
  1326. if (!videoElm) return;
  1327.  
  1328. return videoElm
  1329. }
  1330.  
  1331. Promise.resolve().then(() => {
  1332. for (const {
  1333. type,
  1334. target
  1335. } of $hs.mouseActioner.calls) {
  1336. if (type == 'mouseenter') {
  1337. const videoElm = getVideo(target);
  1338. if (videoElm) {
  1339. return videoElm
  1340. }
  1341. }
  1342. }
  1343. return null;
  1344. }).then(videoFound => {
  1345.  
  1346. Promise.resolve().then(() => {
  1347.  
  1348. var plastHoverElm = $hs.mouseActioner.lastHoverElm;
  1349. $hs.mouseActioner.lastHoverElm = $hs.mouseActioner.calls[0] ? $hs.mouseActioner.calls[0].target : null
  1350.  
  1351. //console.log(!!$hs.mointoringVideo , !!videoFound)
  1352. //console.log(554,'mointoringVideo:'+!!$hs.mointoringVideo,'videoFound:'+ !!videoFound)
  1353.  
  1354. if ($hs.mointoringVideo && !videoFound) {
  1355. $hs.hcShowMouseAndRemoveMointoring($hs.mointoringVideo)
  1356. } else if ($hs.mointoringVideo && videoFound) {
  1357. if (plastHoverElm != $hs.mouseActioner.lastHoverElm) $hs.hcMouseShowWithMonitoring(videoFound);
  1358. } else if (!$hs.mointoringVideo && videoFound) {
  1359. $hs.hcDelayMouseHideAndStartMointoring(videoFound)
  1360. }
  1361.  
  1362. $hs.mouseMoveCount = 0;
  1363. $hs.mouseActioner.calls.length = 0;
  1364. $hs.mouseActioner.lastFound = videoFound;
  1365.  
  1366. })
  1367.  
  1368.  
  1369.  
  1370. if (videoFound !== $hs.mouseActioner.lastFound) {
  1371. if ($hs.mouseActioner.lastFound) {
  1372. $hs.handlerElementMouseLeaveVideo($hs.mouseActioner.lastFound)
  1373. }
  1374. if (videoFound) {
  1375. $hs.handlerElementMouseEnterVideo(videoFound)
  1376. }
  1377. }
  1378.  
  1379.  
  1380. })
  1381.  
  1382. },
  1383. handlerElementMouseEnterVideo: function(video) {
  1384.  
  1385. //console.log('mouseenter video')
  1386.  
  1387. const playerConf = $hs.getPlayerConf(video)
  1388. if (playerConf) {
  1389. playerConf.domActive |= DOM_ACTIVE_MOUSE_IN;
  1390. }
  1391.  
  1392. $hs._actionBoxObtain(video);
  1393.  
  1394. $hs.enteredActionBoxRelation = $hs.actionBoxRelations[video.getAttribute('_h5ppid') || 'null'] || null
  1395.  
  1396. },
  1397. handlerElementMouseLeaveVideo: function(video) {
  1398.  
  1399. //console.log('mouseleave video')
  1400.  
  1401. const playerConf = $hs.getPlayerConf(video)
  1402. if (playerConf) {
  1403. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_IN;
  1404. }
  1405.  
  1406.  
  1407. $hs.enteredActionBoxRelation = null
  1408.  
  1409.  
  1410. },
  1411. handlerElementMouseEnter: function(evt) {
  1412. if ($hs.intVideoInitCount > 0) {} else {
  1413. return;
  1414. }
  1415. if (!evt || !evt.target || !(evt.target.nodeType > 0)) return;
  1416. $hs.mouseEnteredElement = evt.target
  1417.  
  1418. if ($hs.mouseDownAt && $hs.mouseDownAt.insideVideo) return;
  1419.  
  1420. if ($hs.enteredActionBoxRelation && $hs.enteredActionBoxRelation.pContainer && $hs.enteredActionBoxRelation.pContainer.contains(evt.target)) return;
  1421.  
  1422. //console.log('mouseenter call')
  1423.  
  1424. $hs.mouseActioner.calls.length = 1;
  1425. $hs.mouseActioner.calls[0] = {
  1426. type: evt.type,
  1427. target: evt.target
  1428. }
  1429.  
  1430.  
  1431. //$hs.mouseActioner.calls.push({type:evt.type,target:evt.target});
  1432. $hs.mouseActioner.time = +new Date;
  1433.  
  1434. if (!$hs.mouseActioner.cid) {
  1435. $hs.mouseActioner.cid = window.setTimeout($hs.mouseAct, 82)
  1436. }
  1437.  
  1438. //console.log(evt.target)
  1439.  
  1440. },
  1441. handlerElementMouseLeave: function(evt) {
  1442. if ($hs.intVideoInitCount > 0) {} else {
  1443. return;
  1444. }
  1445. if (!evt || !evt.target || !(evt.target.nodeType > 0)) return;
  1446.  
  1447. if ($hs.mouseDownAt && $hs.mouseDownAt.insideVideo) return;
  1448.  
  1449. if ($hs.enteredActionBoxRelation && $hs.enteredActionBoxRelation.pContainer && !$hs.enteredActionBoxRelation.pContainer.contains(evt.target)) {
  1450.  
  1451. //console.log('mouseleave call')
  1452.  
  1453. //$hs.mouseActioner.calls.push({type:evt.type,target:evt.target});
  1454. $hs.mouseActioner.time = +new Date;
  1455.  
  1456. if (!$hs.mouseActioner.cid) {
  1457. $hs.mouseActioner.cid = window.setTimeout($hs.mouseAct, 82)
  1458. }
  1459. }
  1460.  
  1461. },
  1462. handlerElementMouseDown: function(evt) {
  1463. if ($hs.mouseDownAt) return;
  1464. $hs.mouseDownAt = {
  1465. elm: evt.target,
  1466. insideVideo: false,
  1467. pContainer: null
  1468. };
  1469.  
  1470.  
  1471. if ($hs.intVideoInitCount > 0) {} else {
  1472. return;
  1473. }
  1474.  
  1475. // $hs._mouseIsDown=true;
  1476.  
  1477. if (!evt || !evt.target || !(evt.target.nodeType > 0)) return;
  1478.  
  1479. if ($hs.mouseActioner.lastFound && $hs.mointoringVideo) $hs.hcMouseShowWithMonitoring($hs.mouseActioner.lastFound)
  1480.  
  1481. Promise.resolve(evt.target).then((evtTarget) => {
  1482.  
  1483.  
  1484. if (document.readyState != "complete") return;
  1485.  
  1486.  
  1487. function notAtVideo() {
  1488. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  1489. if ($hs.focusHookVId) $hs.focusHookVId = ''
  1490. }
  1491.  
  1492.  
  1493. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(evtTarget);
  1494. if (!actionBoxRelation) return notAtVideo();
  1495. const actionBox = actionBoxRelation.actionBox
  1496. if (!actionBox) return notAtVideo();
  1497. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1498. const videoElm = actionBoxRelation.player;
  1499. if (!videoElm) return notAtVideo();
  1500.  
  1501. if (!$hs.mouseDownAt) return;
  1502. $hs.mouseDownAt.insideVideo = videoElm;
  1503.  
  1504. $hs.mouseDownAt.pContainer = actionBoxRelation.pContainer;
  1505.  
  1506. if (vpid) {
  1507. $hs.focusHookVDoc = getRoot(videoElm)
  1508. $hs.focusHookVId = vpid
  1509. }
  1510.  
  1511.  
  1512. const playerConf = $hs.getPlayerConf(videoElm)
  1513. if (playerConf) {
  1514. delayCall("$$actionBoxClicking", function() {
  1515. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_CLICK;
  1516. }, 300)
  1517. playerConf.domActive |= DOM_ACTIVE_MOUSE_CLICK;
  1518. }
  1519.  
  1520.  
  1521. return videoElm
  1522.  
  1523. }).then((videoElm) => {
  1524.  
  1525. if (!videoElm) return;
  1526.  
  1527. $hs._actionBoxObtain(videoElm);
  1528.  
  1529. return videoElm
  1530.  
  1531. }).then((videoElm) => {
  1532.  
  1533. if (!videoElm) return;
  1534.  
  1535. $hs.swtichPlayerInstance();
  1536.  
  1537. })
  1538.  
  1539. },
  1540. handlerElementMouseUp: function(evt) {
  1541.  
  1542. if ($hs.pendingTips) {
  1543.  
  1544. let pendingTips = $hs.pendingTips;
  1545. $hs.pendingTips = null;
  1546.  
  1547. for (let vpid in pendingTips) {
  1548. const tipsDom = pendingTips[vpid]
  1549. Promise.resolve(tipsDom).then(() => {
  1550. if (tipsDom.getAttribute('_h5p_animate') == '0') tipsDom.setAttribute('_h5p_animate', '1');
  1551.  
  1552. })
  1553. }
  1554. pendingTips = null;
  1555.  
  1556. }
  1557. if ($hs.mouseDownAt) {
  1558.  
  1559. $hs.mouseDownAt = null;
  1560. }
  1561. },
  1562. handlerElementWheelTuneVolume: function(evt) { //shift + wheel
  1563.  
  1564. if ($hs.intVideoInitCount > 0) {} else {
  1565. return;
  1566. }
  1567.  
  1568. if (!evt.shiftKey || !evt.target || !(evt.target.nodeType > 0)) return;
  1569.  
  1570. const fDeltaY = (evt.deltaY > 0) ? 1 : (evt.deltaY < 0) ? -1 : 0;
  1571. if (fDeltaY) {
  1572.  
  1573.  
  1574.  
  1575. const randomID = +new Date
  1576. $hs.handlerElementWheelTuneVolume._randomID = randomID;
  1577.  
  1578.  
  1579. Promise.resolve(evt.target).then((evtTarget) => {
  1580.  
  1581.  
  1582. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(evtTarget);
  1583. if (!actionBoxRelation) return;
  1584. const actionBox = actionBoxRelation.actionBox
  1585. if (!actionBox) return;
  1586. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1587. const videoElm = actionBoxRelation.player;
  1588. if (!videoElm) return;
  1589.  
  1590. let player = $hs.player();
  1591. if (!player || player != videoElm) return;
  1592.  
  1593. return videoElm
  1594.  
  1595. }).then((videoElm) => {
  1596. if (!videoElm) return;
  1597.  
  1598. if ($hs.handlerElementWheelTuneVolume._randomID != randomID) return;
  1599. // $hs._actionBoxObtain(videoElm);
  1600. return videoElm;
  1601. }).then((player) => {
  1602. if (!player) return;
  1603. if ($hs.handlerElementWheelTuneVolume._randomID != randomID) return;
  1604. if (fDeltaY > 0) {
  1605. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1606. player.muted = false;
  1607. player.volume = player._volume;
  1608. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1609. player.muted = false;
  1610. }
  1611. $hs.tuneVolume(-0.05)
  1612. } else if (fDeltaY < 0) {
  1613. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1614. player.muted = false;
  1615. player.volume = player._volume;
  1616. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1617. player.muted = false;
  1618. }
  1619. $hs.tuneVolume(+0.05)
  1620. }
  1621. })
  1622. evt.stopPropagation()
  1623. evt.preventDefault()
  1624. return false
  1625. }
  1626. },
  1627.  
  1628. handlerWinMessage: async function(e) {
  1629. let tag, ed;
  1630. if (typeof e.data == 'object' && typeof e.data.tag == 'string') {
  1631. tag = e.data.tag;
  1632. ed = e.data
  1633. } else {
  1634. return;
  1635. }
  1636. let msg = null,
  1637. success = 0;
  1638. let msg_str, msg_stype, p
  1639. switch (tag) {
  1640. case 'consoleLog':
  1641. msg_str = ed.str;
  1642. msg_stype = ed.stype;
  1643. if (msg_stype === 1) {
  1644. msg = (document[str_postMsgData] || {})[msg_str] || [];
  1645. success = 1;
  1646. } else if (msg_stype === 2) {
  1647. msg = jsonParse(msg_str);
  1648. if (msg && msg.d) {
  1649. success = 2;
  1650. msg = msg.d;
  1651. }
  1652. } else {
  1653. msg = msg_str
  1654. }
  1655. p = (ed.passing && ed.winOrder) ? [' | from win-' + ed.winOrder] : [];
  1656. if (success) {
  1657. console.log(...msg, ...p)
  1658. //document[ed.data]=null; // also delete the information
  1659. } else {
  1660. console.log('msg--', msg, ...p, ed);
  1661. }
  1662. break;
  1663.  
  1664. }
  1665. },
  1666.  
  1667. toolCheckFullScreen: function(doc) {
  1668. if (typeof doc.fullScreen == 'boolean') return doc.fullScreen;
  1669. if (typeof doc.webkitIsFullScreen == 'boolean') return doc.webkitIsFullScreen;
  1670. if (typeof doc.mozFullScreen == 'boolean') return doc.mozFullScreen;
  1671. return null;
  1672. },
  1673.  
  1674. toolFormatCT: function(u) {
  1675.  
  1676. let w = Math.round(u, 0)
  1677. let a = w % 60
  1678. w = (w - a) / 60
  1679. let b = w % 60
  1680. w = (w - b) / 60
  1681. let str = ("0" + b).substr(-2) + ":" + ("0" + a).substr(-2);
  1682. if (w) str = w + ":" + str
  1683.  
  1684. return str
  1685.  
  1686. },
  1687.  
  1688. loopOutwards: function(startPoint, maxStep) {
  1689.  
  1690.  
  1691. let c = 0,
  1692. p = startPoint,
  1693. q = null;
  1694. while (p && (++c <= maxStep)) {
  1695. if (p.querySelectorAll('video').length !== 1) {
  1696. return q;
  1697. break;
  1698. }
  1699. q = p;
  1700. p = p.parentNode;
  1701. }
  1702.  
  1703. return p || q || null;
  1704.  
  1705. },
  1706.  
  1707. getActionBlockElement: function(player, layoutBox) {
  1708.  
  1709. //player, $hs.getPlayerBlockElement(player).parentNode;
  1710. //player, player.parentNode .... player.parentNode.parentNode.parentNode
  1711.  
  1712. //layoutBox: a container element containing video and with innerHeight>=player.innerHeight [skipped wrapping]
  1713. //layoutBox parentSize > layoutBox Size
  1714.  
  1715. //actionBox: a container with video and controls
  1716. //can be outside layoutbox (bilibili)
  1717. //assume maximum 3 layers
  1718.  
  1719.  
  1720. let outerLayout = $hs.loopOutwards(layoutBox, 3); //i.e. layoutBox.parent.parent.parent
  1721.  
  1722.  
  1723. const allFullScreenBtns = $hs.queryFullscreenBtnsIndependant(outerLayout)
  1724. //console.log('xx', outerLayout.querySelectorAll('[class*="-fullscreen"]').length, allFullScreenBtns.length)
  1725. let actionBox = null;
  1726.  
  1727. // console.log('fa0a', allFullScreenBtns.length, layoutBox)
  1728. if (allFullScreenBtns.length > 0) {
  1729. // console.log('faa', allFullScreenBtns.length)
  1730.  
  1731. for (const possibleFullScreenBtn of allFullScreenBtns) possibleFullScreenBtn.setAttribute('__h5p_fsb__', '');
  1732. let pElm = player.parentNode;
  1733. let fullscreenBtns = null;
  1734. while (pElm && pElm.parentNode) {
  1735. fullscreenBtns = pElm.querySelectorAll('[__h5p_fsb__]');
  1736. if (fullscreenBtns.length > 0) {
  1737. break;
  1738. }
  1739. pElm = pElm.parentNode;
  1740. }
  1741. for (const possibleFullScreenBtn of allFullScreenBtns) possibleFullScreenBtn.removeAttribute('__h5p_fsb__');
  1742. if (fullscreenBtns && fullscreenBtns.length > 0) {
  1743. actionBox = pElm;
  1744. fullscreenBtns = $hs.exclusiveElements(fullscreenBtns);
  1745. return {
  1746. actionBox,
  1747. fullscreenBtns
  1748. };
  1749. }
  1750. }
  1751.  
  1752. let walkRes = domTool._isActionBox_1(player, layoutBox);
  1753. //walkRes.elm = player... player.parentNode.parentNode (i.e. wPlayer)
  1754. let parentCount = walkRes.length;
  1755.  
  1756. if (parentCount - 1 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 1)) {
  1757. actionBox = walkRes[parentCount - 1].elm;
  1758. } else if (parentCount - 2 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 2)) {
  1759. actionBox = walkRes[parentCount - 2].elm;
  1760. } else {
  1761. actionBox = player;
  1762. }
  1763.  
  1764. return {
  1765. actionBox,
  1766. fullscreenBtns: []
  1767. };
  1768.  
  1769.  
  1770.  
  1771.  
  1772. },
  1773.  
  1774. actionBoxRelations: {},
  1775.  
  1776. actionBoxMutationCallback: function(mutations, observer) {
  1777. for (const mutation of mutations) {
  1778.  
  1779.  
  1780. const vpid = mutation.target.getAttribute('_h5p_mf_');
  1781. if (!vpid) continue;
  1782.  
  1783. const actionBoxRelation = $hs.actionBoxRelations[vpid];
  1784. if (!actionBoxRelation) continue;
  1785.  
  1786.  
  1787. const removedNodes = mutation.removedNodes;
  1788. if (removedNodes && removedNodes.length > 0) {
  1789. for (const node of removedNodes) {
  1790. if (node.nodeType == 1) {
  1791. actionBoxRelation.mutationRemovalsCount++
  1792. node.removeAttribute('_h5p_mf_');
  1793. }
  1794. }
  1795.  
  1796. }
  1797.  
  1798. const addedNodes = mutation.addedNodes;
  1799. if (addedNodes && addedNodes.length > 0) {
  1800. for (const node of addedNodes) {
  1801. if (node.nodeType == 1) {
  1802. actionBoxRelation.mutationAdditionsCount++
  1803. }
  1804. }
  1805.  
  1806. }
  1807.  
  1808.  
  1809.  
  1810.  
  1811. }
  1812. },
  1813.  
  1814.  
  1815. getActionBoxRelationFromDOM: function(elm) {
  1816.  
  1817. //assume action boxes are mutually exclusive
  1818.  
  1819. for (let vpid in $hs.actionBoxRelations) {
  1820. const actionBoxRelation = $hs.actionBoxRelations[vpid];
  1821. const actionBox = actionBoxRelation.actionBox
  1822. //console.log('ab', actionBox)
  1823. if (actionBox && actionBox.parentNode) {
  1824. if (elm == actionBox || actionBox.contains(elm)) {
  1825. return actionBoxRelation;
  1826. }
  1827. }
  1828. }
  1829.  
  1830.  
  1831. return null;
  1832.  
  1833. },
  1834.  
  1835.  
  1836.  
  1837. _actionBoxObtain: function(player) {
  1838.  
  1839. if (!player) return null;
  1840. let vpid = player.getAttribute('_h5ppid');
  1841. if (!vpid) return null;
  1842. if (!player.parentNode) return null;
  1843.  
  1844. let actionBoxRelation = $hs.actionBoxRelations[vpid],
  1845. layoutBox = null,
  1846. actionBox = null,
  1847. boxSearchResult = null,
  1848. fullscreenBtns = null,
  1849. wPlayer = null;
  1850.  
  1851. function a() {
  1852. wPlayer = $hs.getPlayerBlockElement(player);
  1853. layoutBox = wPlayer.parentNode;
  1854. boxSearchResult = $hs.getActionBlockElement(player, layoutBox);
  1855. actionBox = boxSearchResult.actionBox
  1856. fullscreenBtns = boxSearchResult.fullscreenBtns
  1857. }
  1858.  
  1859. function setDOM_mflag(startElm, endElm, vpid) {
  1860. if (!startElm || !endElm) return;
  1861. if (startElm == endElm) startElm.setAttribute('_h5p_mf_', vpid)
  1862. else if (endElm.contains(startElm)) {
  1863.  
  1864. let p = startElm
  1865. while (p) {
  1866. p.setAttribute('_h5p_mf_', vpid)
  1867. if (p == endElm) break;
  1868. p = p.parentNode
  1869. }
  1870.  
  1871. }
  1872. }
  1873.  
  1874. function b(domNodes) {
  1875.  
  1876. actionBox.setAttribute('_h5p_actionbox_', vpid);
  1877. if (!$hs.actionBoxMutationObserver) $hs.actionBoxMutationObserver = new MutationObserver($hs.actionBoxMutationCallback);
  1878.  
  1879. // console.log('Major Mutation on Player Container')
  1880. const actionRelation = {
  1881. player: player,
  1882. wPlayer: wPlayer,
  1883. layoutBox: layoutBox,
  1884. actionBox: actionBox,
  1885. mutationRemovalsCount: 0,
  1886. mutationAdditionsCount: 0,
  1887. fullscreenBtns: fullscreenBtns,
  1888. pContainer: domNodes[domNodes.length - 1], // the block Element as the entire player (including control btns) having size>=video
  1889. ppContainer: domNodes[domNodes.length - 1].parentNode, // reference to the webpage
  1890. }
  1891.  
  1892.  
  1893. const pContainer = actionRelation.pContainer;
  1894. setDOM_mflag(player, pContainer, vpid)
  1895. for (const btn of fullscreenBtns) setDOM_mflag(btn, pContainer, vpid)
  1896. setDOM_mflag = null;
  1897.  
  1898. $hs.actionBoxRelations[vpid] = actionRelation
  1899.  
  1900.  
  1901. //console.log('mutt0',pContainer)
  1902. $hs.actionBoxMutationObserver.observe(pContainer, {
  1903. childList: true,
  1904. subtree: true
  1905. });
  1906. }
  1907.  
  1908. if (actionBoxRelation) {
  1909. //console.log('ddx', actionBoxRelation.mutationCount)
  1910. if (actionBoxRelation.pContainer && actionBoxRelation.pContainer.parentNode && actionBoxRelation.pContainer.parentNode === actionBoxRelation.ppContainer) {
  1911.  
  1912. if (actionBoxRelation.fullscreenBtns && actionBoxRelation.fullscreenBtns.length > 0) {
  1913.  
  1914. if (actionBoxRelation.mutationRemovalsCount === 0 && actionBoxRelation.mutationAdditionsCount === 0) return actionBoxRelation.actionBox
  1915.  
  1916. // if (actionBoxRelation.mutationCount === 0 && actionBoxRelation.fullscreenBtns.every(btn=>actionBoxRelation.actionBox.contains(btn))) return actionBoxRelation.actionBox
  1917. //console.log('Minor Mutation on Player Container', actionBoxRelation ? actionBoxRelation.mutationRemovalsCount : null, actionBoxRelation ? actionBoxRelation.mutationAdditionsCount : null)
  1918. a();
  1919. //console.log(3535,fullscreenBtns.length)
  1920. if (actionBox == actionBoxRelation.actionBox && layoutBox == actionBoxRelation.layoutBox && wPlayer == actionBoxRelation.wPlayer) {
  1921. //pContainer remains the same as actionBox and layoutBox remain unchanged
  1922. actionBoxRelation.ppContainer = actionBoxRelation.pContainer.parentNode; //just update the reference
  1923. if (actionBoxRelation.ppContainer) { //in case removed from DOM
  1924. actionBoxRelation.mutationRemovalsCount = 0;
  1925. actionBoxRelation.mutationAdditionsCount = 0;
  1926. actionBoxRelation.fullscreenBtns = fullscreenBtns;
  1927. return actionBox;
  1928. }
  1929. }
  1930.  
  1931. }
  1932.  
  1933. }
  1934.  
  1935. const elms = (getRoot(actionBoxRelation.pContainer) || document).querySelectorAll(`[_h5p_mf_="${vpid}"]`)
  1936. for (const elm of elms) elm.removeAttribute('_h5p_mf_')
  1937. actionBoxRelation.pContainer.removeAttribute('_h5p_mf_')
  1938. for (var k in actionBoxRelation) delete actionBoxRelation[k]
  1939. actionBoxRelation = null;
  1940. delete $hs.actionBoxRelations[vpid]
  1941. }
  1942.  
  1943. if (boxSearchResult == null) a();
  1944. a = null;
  1945. if (actionBox) {
  1946. const domNodes = [];
  1947. let pElm = player;
  1948. let containing = 0;
  1949. while (pElm) {
  1950. domNodes.push(pElm);
  1951. if (pElm === actionBox) containing |= 1;
  1952. if (pElm === layoutBox) containing |= 2;
  1953. if (containing === 3) {
  1954. b(domNodes);
  1955. b = null;
  1956. return actionBox
  1957. }
  1958. pElm = pElm.parentNode;
  1959. }
  1960. }
  1961.  
  1962. return null;
  1963.  
  1964.  
  1965. // if (!actionBox.hasAttribute('tabindex')) actionBox.setAttribute('tabindex', '-1');
  1966.  
  1967.  
  1968.  
  1969.  
  1970. },
  1971.  
  1972. videoSrcFound: function(player) {
  1973.  
  1974. // src loaded
  1975.  
  1976. if (!player) return;
  1977. let vpid = player.getAttribute('_h5ppid') || null;
  1978. if (!vpid || !player.currentSrc) return;
  1979.  
  1980. player._isThisPausedBefore_ = false;
  1981.  
  1982. player.removeAttribute('_h5p_uid_encrypted');
  1983.  
  1984. if (player._record_continuous) player._record_continuous._lastSave = -999; //first time must save
  1985.  
  1986. let uid_A = location.pathname.replace(/[^\d+]/g, '') + '.' + location.search.replace(/[^\d+]/g, '');
  1987. let _uid = location.hostname.replace('www.', '').toLowerCase() + '!' + location.pathname.toLowerCase() + 'A' + uid_A + 'W' + player.videoWidth + 'H' + player.videoHeight + 'L' + (player.duration << 0);
  1988.  
  1989. digestMessage(_uid).then(function(_uid_encrypted) {
  1990.  
  1991. let d = +new Date;
  1992.  
  1993. let recordedTime = null;
  1994.  
  1995. ;
  1996. (function() {
  1997. //read the last record only;
  1998.  
  1999. let k3 = `_h5_player_play_progress_${_uid_encrypted}`;
  2000. let k3n = `_play_progress_${_uid_encrypted}`;
  2001. let m2 = Store._keys().filter(key => key.substr(0, k3.length) == k3); //all progress records for this video
  2002. let m2v = m2.map(keyName => +(keyName.split('+')[1] || '0'))
  2003. let m2vMax = Math.max(0, ...m2v)
  2004. if (!m2vMax) recordedTime = null;
  2005. else {
  2006. let _json_recordedTime = null;
  2007. _json_recordedTime = Store.read(k3n + '+' + m2vMax);
  2008. if (!_json_recordedTime) _json_recordedTime = {};
  2009. else _json_recordedTime = jsonParse(_json_recordedTime);
  2010. if (typeof _json_recordedTime == 'object') recordedTime = _json_recordedTime;
  2011. else recordedTime = null;
  2012. recordedTime = typeof recordedTime == 'object' ? recordedTime.t : recordedTime;
  2013. if (typeof recordedTime == 'number' && (+recordedTime >= 0 || +recordedTime <= 0)) {
  2014.  
  2015. } else if (typeof recordedTime == 'string' && recordedTime.length > 0 && (+recordedTime >= 0 || +recordedTime <= 0)) {
  2016. recordedTime = +recordedTime
  2017. } else {
  2018. recordedTime = null
  2019. }
  2020. }
  2021. if (recordedTime !== null) {
  2022. player._h5player_lastrecord_ = recordedTime;
  2023. } else {
  2024. player._h5player_lastrecord_ = null;
  2025. }
  2026. if (player._h5player_lastrecord_ > 5) {
  2027. consoleLog('last record playing', player._h5player_lastrecord_);
  2028. window.setTimeout(function() {
  2029. $hs._tips(player, `Press Shift-R to restore Last Playback: ${$hs.toolFormatCT(player._h5player_lastrecord_)}`, 5000, 4000)
  2030. }, 1000)
  2031. }
  2032.  
  2033. })();
  2034. // delay the recording by 5.4s => prevent ads or mis operation
  2035. window.setTimeout(function() {
  2036.  
  2037.  
  2038.  
  2039. let k1 = '_h5_player_play_progress_';
  2040. let k3 = `_h5_player_play_progress_${_uid_encrypted}`;
  2041. let k3n = `_play_progress_${_uid_encrypted}`;
  2042.  
  2043. //re-read all the localStorage keys
  2044. let m1 = Store._keys().filter(key => key.substr(0, k1.length) == k1); //all progress records in this site
  2045. let p = m1.length + 1;
  2046.  
  2047. for (const key of m1) { //all progress records for this video
  2048. if (key.substr(0, k3.length) == k3) {
  2049. Store._removeItem(key); //remove previous record for the current video
  2050. p--;
  2051. }
  2052. }
  2053.  
  2054. let asyncPromise = Promise.resolve();
  2055.  
  2056. if (recordedTime !== null) {
  2057. asyncPromise = asyncPromise.then(() => {
  2058. Store.save(k3n + '+' + d, jsonStringify({
  2059. 't': recordedTime
  2060. })) //prevent loss of last record
  2061. })
  2062. }
  2063.  
  2064. const _record_max_ = 48;
  2065. const _record_keep_ = 26;
  2066.  
  2067. if (p > _record_max_) {
  2068. //exisiting 48 records for one site;
  2069. //keep only 26 records
  2070.  
  2071. asyncPromise = asyncPromise.then(() => {
  2072. const comparator = (a, b) => (a.t < b.t ? -1 : a.t > b.t ? 1 : 0);
  2073.  
  2074. m1
  2075. .map(keyName => ({
  2076. keyName,
  2077. t: +(keyName.split('+')[1] || '0')
  2078. }))
  2079. .sort(comparator)
  2080. .slice(0, -_record_keep_)
  2081. .forEach((item) => localStorage.removeItem(item.keyName));
  2082.  
  2083. consoleLog(`stored progress: reduced to ${_record_keep_}`)
  2084. })
  2085. }
  2086.  
  2087. asyncPromise = asyncPromise.then(() => {
  2088. player.setAttribute('_h5p_uid_encrypted', _uid_encrypted + '+' + d);
  2089.  
  2090. //try to start recording
  2091. if (player._record_continuous) player._record_continuous.playingWithRecording();
  2092. })
  2093.  
  2094. }, 5400);
  2095.  
  2096. })
  2097.  
  2098. },
  2099. bindDocEvents: function(rootNode) {
  2100. if (!rootNode._onceBindedDocEvents) {
  2101.  
  2102. rootNode._onceBindedDocEvents = true;
  2103. rootNode.addEventListener('keydown', $hs.handlerRootKeyDownEvent, true)
  2104. //document._debug_rootNode_ = rootNode;
  2105.  
  2106. rootNode.addEventListener('mouseenter', $hs.handlerElementMouseEnter, true)
  2107. rootNode.addEventListener('mouseleave', $hs.handlerElementMouseLeave, true)
  2108. rootNode.addEventListener('mousedown', $hs.handlerElementMouseDown, true)
  2109. rootNode.addEventListener('mouseup', $hs.handlerElementMouseUp, true)
  2110. rootNode.addEventListener('wheel', $hs.handlerElementWheelTuneVolume, {
  2111. passive: false
  2112. });
  2113.  
  2114. // wheel - bubble events to keep it simple (i.e. it must be passive:false & capture:false)
  2115.  
  2116.  
  2117. rootNode.addEventListener('focus', $hs.handlerElementFocus, $mb.eh_capture_passive())
  2118. rootNode.addEventListener('fullscreenchange', $hs.handlerFullscreenChanged, true)
  2119.  
  2120. //rootNode.addEventListener('mousemove', $hs.handlerOverrideMouseMove, {capture:true, passive:false})
  2121.  
  2122. }
  2123. },
  2124. fireGlobalInit: function() {
  2125. if ($hs.intVideoInitCount != 1) return;
  2126. if (!$hs.varSrcList) $hs.varSrcList = {};
  2127.  
  2128. Store.clearInvalid(_sVersion_)
  2129.  
  2130.  
  2131. Promise.resolve().then(() => {
  2132.  
  2133. GM_addStyle(`
  2134. .ytp-chrome-bottom+span#volumeUI:last-child:empty{
  2135. display:none;
  2136. }
  2137. html[_h5p_hide_cursor]{
  2138. cursor:none !important;
  2139. }
  2140. `)
  2141. })
  2142.  
  2143. },
  2144. onVideoTriggering: function() {
  2145.  
  2146.  
  2147. // initialize a single video player - h5Player.playerInstance
  2148.  
  2149. /**
  2150. * 初始化播放器實例
  2151. */
  2152. let player = $hs.playerInstance
  2153. if (!player) return
  2154.  
  2155. let vpid = player.getAttribute('_h5ppid');
  2156.  
  2157. if (!vpid) return;
  2158.  
  2159. let firstTime = !!$hs.initTips()
  2160. if (firstTime) {
  2161. // first time to trigger this player
  2162. if (!player.hasAttribute('playsinline')) player.setAttribute('playsinline', 'playsinline');
  2163. if (!player.hasAttribute('x-webkit-airplay')) player.setAttribute('x-webkit-airplay', 'deny');
  2164. if (!player.hasAttribute('preload')) player.setAttribute('preload', 'auto');
  2165. //player.style['image-rendering'] = 'crisp-edges';
  2166. $hs.playbackRate = $hs.getPlaybackRate()
  2167. }
  2168.  
  2169. },
  2170. getPlaybackRate: function() {
  2171. let playbackRate = Store.read('_playback_rate_') || $hs.playbackRate
  2172. return Number(Number(playbackRate).toFixed(1))
  2173. },
  2174.  
  2175. _getPlayerBlockElement:function(player,useCache){
  2176.  
  2177.  
  2178. let layoutBox = null,
  2179. wPlayer = null
  2180.  
  2181. if (!player || !player.parentNode) {
  2182. return null;
  2183. }
  2184.  
  2185.  
  2186. if (useCache === true) {
  2187. let vpid = player.getAttribute('_h5ppid');
  2188. let actionBoxRelation = $hs.actionBoxRelations[vpid]
  2189. if (actionBoxRelation && actionBoxRelation.mutationRemovalsCount === 0) {
  2190. return actionBoxRelation.wPlayer
  2191. }
  2192. }
  2193.  
  2194.  
  2195. //without checkActiveBox, just a DOM for you to append tipsDom
  2196.  
  2197. function oWH(elm) {
  2198. return [elm.offsetWidth, elm.offsetHeight].join(',');
  2199. }
  2200.  
  2201. function search_nodes() {
  2202.  
  2203. wPlayer = player; // NOT NULL
  2204. layoutBox = wPlayer.parentNode; // NOT NULL
  2205.  
  2206. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight == 0) {
  2207. wPlayer = layoutBox; // NOT NULL
  2208. layoutBox = layoutBox.parentNode; // NOT NULL
  2209. }
  2210. //container must be with offsetHeight
  2211.  
  2212. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight < player.offsetHeight) {
  2213. wPlayer = layoutBox; // NOT NULL
  2214. layoutBox = layoutBox.parentNode; // NOT NULL
  2215. }
  2216. //container must have height >= player height
  2217.  
  2218. const layoutOWH = oWH(layoutBox)
  2219. //const playerOWH=oWH(player)
  2220.  
  2221. //skip all inner wraps
  2222. while (layoutBox.parentNode && layoutBox.nodeType == 1 && oWH(layoutBox.parentNode) == layoutOWH) {
  2223. wPlayer = layoutBox; // NOT NULL
  2224. layoutBox = layoutBox.parentNode; // NOT NULL
  2225. }
  2226.  
  2227. // oWH of layoutBox.parentNode != oWH of layoutBox and layoutBox.offsetHeight >= player.offsetHeight
  2228.  
  2229. }
  2230.  
  2231. search_nodes();
  2232.  
  2233. if (layoutBox.nodeType == 11) {
  2234. makeNoRoot(layoutBox);
  2235. search_nodes();
  2236. }
  2237.  
  2238.  
  2239.  
  2240. //condition:
  2241. //!layoutBox.parentNode || layoutBox.nodeType != 1 || layoutBox.offsetHeight > player.offsetHeight
  2242.  
  2243. // layoutBox is a node contains <video> and offsetHeight>=video.offsetHeight
  2244. // wPlayer is a HTML Element (nodeType==1)
  2245. // you can insert the DOM element into the layoutBox
  2246.  
  2247. if (layoutBox && wPlayer && layoutBox.nodeType === 1 && wPlayer.parentNode == layoutBox && layoutBox.parentNode) return wPlayer;
  2248. throw 'unknown error';
  2249. },
  2250.  
  2251. parentingN:function(elm, parent, n){
  2252.  
  2253. if(!elm || !parent) return false;
  2254. let pElm=elm;
  2255. for(let i =0;i<n && pElm;i++) pElm=pElm.parentNode;
  2256. return (pElm===parent);
  2257.  
  2258.  
  2259.  
  2260. },
  2261.  
  2262. parentingInclusive:function(elm, parent){
  2263.  
  2264.  
  2265. let pElm=elm, arr=[];
  2266. while(pElm){
  2267. arr.push(pElm);
  2268. if(pElm===parent)break;
  2269. pElm=pElm.parentNode;
  2270. }
  2271. if(pElm===parent) return arr;
  2272. return null;
  2273.  
  2274. },
  2275. getPlayerBlockElement: function(player, useCache) {
  2276.  
  2277. if(!player.__layout_resize_observer__){
  2278.  
  2279. let wPlayer = $hs._getPlayerBlockElement(player, false)
  2280. let layoutBox = wPlayer.parentNode
  2281.  
  2282. player.__layout_resize_observer__=new ResizeObserver((entries, observer)=>{
  2283. player._cache_wPlayer=null;
  2284. for(const {target} of entries){
  2285. if('__to_player_n__' in target && target.__to_player_n__>=0){
  2286. if(!$hs.parentingN(player, target, target.__to_player_n__)) observer.unobserve(target)
  2287. }else{
  2288. observer.unobserve(target)
  2289. }
  2290. }
  2291. })
  2292.  
  2293. let kh= $hs.parentingInclusive(player, layoutBox);
  2294. if(kh){
  2295.  
  2296. for(const elm of kh) player.__layout_resize_observer__.observe(elm)
  2297. player.__layout_resize_n__=kh.length
  2298.  
  2299. }else{
  2300. player.__layout_resize_n__=0
  2301. }
  2302.  
  2303.  
  2304. return (player._cache_wPlayer=wPlayer);
  2305. }
  2306.  
  2307.  
  2308. if(player._cache_wPlayer && player.__layout_resize_n__>0) {
  2309. let kt=$hs.parentingN(player, player._cache_wPlayer.parentNode, player.__layout_resize_n__-1);
  2310. if(kt) return (player._cache_wPlayer);
  2311. }
  2312.  
  2313. let wPlayer=$hs._getPlayerBlockElement(player, useCache);
  2314. let layoutBox = wPlayer.parentNode
  2315.  
  2316. let kh= $hs.parentingInclusive(player, layoutBox);
  2317.  
  2318. if(kh){
  2319.  
  2320. let wi=0;
  2321. for(const elm of kh) {
  2322. elm.__to_player_n__=wi;
  2323. player.__layout_resize_observer__.observe(elm)
  2324. wi++;
  2325. }
  2326. player.__layout_resize_n__=kh.length
  2327. }else{
  2328. player.__layout_resize_n__=0
  2329. }
  2330.  
  2331. return (player._cache_wPlayer=wPlayer);
  2332.  
  2333. },
  2334. change_layoutBox: function(tipsDom, player) {
  2335. if (!player) return;
  2336. let wPlayer = $hs.getPlayerBlockElement(player, true);
  2337. let layoutBox = wPlayer.parentNode;
  2338. let beforeParent = tipsDom.parentNode;
  2339.  
  2340. if ((layoutBox && layoutBox.nodeType == 1) && (!beforeParent || beforeParent !== layoutBox)) {
  2341.  
  2342. consoleLog('changed_layoutBox')
  2343. if (beforeParent && beforeParent !== layoutBox){
  2344. if($hs.observer_resizeVideos) $hs.observer_resizeVideos.unobserve(beforeParent)
  2345. if(tipsDom.nextSibling && tipsDom.nextSibling.nodeName==utPositioner) beforeParent.removeChild(tipsDom.nextSibling);
  2346. }
  2347. layoutBox.insertBefore(tipsDom, wPlayer);
  2348.  
  2349. }
  2350.  
  2351. tipsDom._playerVPID = player.getAttribute('_h5ppid');
  2352. },
  2353.  
  2354. _hasEventListener: function(elm, p) {
  2355. if (typeof elm['on' + p] == 'function') return true;
  2356. let listeners = $hs._getEventListeners(elm)
  2357. if (listeners) {
  2358. const cache = listeners[p]
  2359. return cache && cache.count > 0
  2360. }
  2361. return false;
  2362. },
  2363.  
  2364. _getEventListeners: function(elmNode) {
  2365.  
  2366.  
  2367. let listeners = wmListeners.get(elmNode);
  2368.  
  2369. if (listeners && typeof listeners == 'object') return listeners;
  2370.  
  2371. return null;
  2372.  
  2373. },
  2374.  
  2375. queryFullscreenBtnsIndependant: function(parentNode) {
  2376.  
  2377. let btns = [];
  2378.  
  2379. function elmCallback(elm) {
  2380.  
  2381. let hasClickListeners = null,
  2382. childElementCount = null,
  2383. isVisible = null,
  2384. btnElm = elm;
  2385. var pElm = elm;
  2386. while (pElm && pElm.nodeType === 1 && pElm != parentNode && pElm.querySelector('video') === null) {
  2387.  
  2388. let funcTest = $hs._hasEventListener(pElm, 'click');
  2389. funcTest = funcTest || $hs._hasEventListener(pElm, 'mousedown');
  2390. funcTest = funcTest || $hs._hasEventListener(pElm, 'mouseup');
  2391.  
  2392. if (funcTest) {
  2393. hasClickListeners = true
  2394. btnElm = pElm;
  2395. break;
  2396. }
  2397.  
  2398. pElm = pElm.parentNode;
  2399. }
  2400. if (btns.indexOf(btnElm) >= 0) return; //btn>a.fullscreen-1>b.fullscreen-2>c.fullscreen-3
  2401.  
  2402.  
  2403. if ('childElementCount' in elm) {
  2404.  
  2405. childElementCount = elm.childElementCount;
  2406.  
  2407. }
  2408. if ('offsetParent' in elm) {
  2409. isVisible = !!elm.offsetParent; //works with parent/self display none; not work with visiblity hidden / opacity0
  2410.  
  2411. }
  2412.  
  2413. if (hasClickListeners) {
  2414. let btn = {
  2415. elm,
  2416. btnElm,
  2417. isVisible,
  2418. hasClickListeners,
  2419. childElementCount,
  2420. isContained: null
  2421. };
  2422.  
  2423. //console.log('btnElm', btnElm)
  2424.  
  2425. btns.push(btnElm)
  2426.  
  2427. }
  2428. }
  2429.  
  2430.  
  2431. for (const elm of parentNode.querySelectorAll('[class*="full"][class*="screen"]')) {
  2432. let className = (elm.getAttribute('class') || "");
  2433. if (/\b(fullscreen|full-screen)\b/i.test(className.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2434. elmCallback(elm)
  2435. }
  2436. }
  2437.  
  2438.  
  2439. for (const elm of parentNode.querySelectorAll('[id*="full"][id*="screen"]')) {
  2440. let idName = (elm.getAttribute('id') || "");
  2441. if (/\b(fullscreen|full-screen)\b/i.test(idName.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2442. elmCallback(elm)
  2443. }
  2444. }
  2445.  
  2446. for (const elm of parentNode.querySelectorAll('[name*="full"][name*="screen"]')) {
  2447. let nName = (elm.getAttribute('name') || "");
  2448. if (/\b(fullscreen|full-screen)\b/i.test(nName.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  2449. elmCallback(elm)
  2450. }
  2451. }
  2452.  
  2453. parentNode = null;
  2454.  
  2455. return btns;
  2456.  
  2457. },
  2458. exclusiveElements: function(elms) {
  2459.  
  2460. //not containing others
  2461. let res = [];
  2462.  
  2463. for (const roleElm of elms) {
  2464.  
  2465. let isContained = false;
  2466. for (const testElm of elms) {
  2467. if (testElm != roleElm && roleElm.contains(testElm)) {
  2468. isContained = true;
  2469. break;
  2470. }
  2471. }
  2472. if (!isContained) res.push(roleElm)
  2473. }
  2474. return res;
  2475.  
  2476. },
  2477.  
  2478. getWithFullscreenBtn: function(actionBoxRelation) {
  2479.  
  2480.  
  2481.  
  2482. //console.log('callFullScreenBtn', 300)
  2483.  
  2484. if (actionBoxRelation && actionBoxRelation.actionBox) {
  2485. let actionBox = actionBoxRelation.actionBox;
  2486. let btnElements = actionBoxRelation.fullscreenBtns;
  2487.  
  2488. // console.log('callFullScreenBtn', 400)
  2489. if (btnElements && btnElements.length > 0) {
  2490.  
  2491. // console.log('callFullScreenBtn', 500, btnElements, actionBox.contains(btnElements[0]))
  2492.  
  2493. let btnElement_idx = btnElements._only_idx;
  2494.  
  2495. if (btnElement_idx >= 0) {
  2496.  
  2497. } else if (btnElements.length === 1) {
  2498. btnElement_idx = 0;
  2499. } else if (btnElements.length > 1) {
  2500. //web-fullscreen-on/off ; fullscreen-on/off ....
  2501.  
  2502. const strList = btnElements.map(elm => [elm.className || 'null', elm.id || 'null', elm.name || 'null'].join('-').replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))
  2503.  
  2504. const filterOutScores = new Array(strList.length).fill(0);
  2505. const filterInScores = new Array(strList.length).fill(0);
  2506. const filterScores = new Array(strList.length).fill(0);
  2507. for (const [j, str] of strList.entries()) {
  2508. if (/\b(fullscreen|full-screen)\b/i.test(str)) filterInScores[j] += 1
  2509. if (/\b(web-fullscreen|web-full-screen)\b/i.test(str)) filterOutScores[j] += 1
  2510. if (/\b(fullscreen-on|full-screen-on)\b/i.test(str)) filterInScores[j] += 1
  2511. if (/\b(fullscreen-off|full-screen-off)\b/i.test(str)) filterOutScores[j] += 1
  2512. if (/\b(on-fullscreen|on-full-screen)\b/i.test(str)) filterInScores[j] += 1
  2513. if (/\b(off-fullscreen|off-full-screen)\b/i.test(str)) filterOutScores[j] += 1
  2514. }
  2515.  
  2516. let maxScore = -1e7;
  2517. for (const [j, str] of strList.entries()) {
  2518. filterScores[j] = filterInScores[j] * 3 - filterOutScores[j] * 2
  2519. if (filterScores[j] > maxScore) maxScore = filterScores[j];
  2520. }
  2521. btnElement_idx = filterScores.indexOf(maxScore)
  2522. if (btnElement_idx < 0) btnElement_idx = 0; //unknown
  2523. }
  2524.  
  2525. btnElements._only_idx = btnElement_idx
  2526.  
  2527.  
  2528. //consoleLog('original fullscreen')
  2529. return btnElements[btnElement_idx];
  2530.  
  2531. }
  2532.  
  2533.  
  2534. }
  2535. return null
  2536. },
  2537.  
  2538. callFullScreenBtn: function() {
  2539. console.log('callFullScreenBtn')
  2540.  
  2541.  
  2542.  
  2543. let player = $hs.player()
  2544. if (!player || !player.ownerDocument || !('exitFullscreen' in player.ownerDocument)) return;
  2545.  
  2546. let btnElement = null;
  2547.  
  2548. let vpid = player.getAttribute('_h5ppid') || null;
  2549.  
  2550. if (!vpid) return;
  2551.  
  2552.  
  2553. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  2554.  
  2555.  
  2556.  
  2557. if (chFull === true) {
  2558. player.ownerDocument.exitFullscreen();
  2559. return;
  2560. }
  2561.  
  2562. let actionBoxRelation = $hs.actionBoxRelations[vpid];
  2563.  
  2564.  
  2565. let asyncRes = Promise.resolve(actionBoxRelation)
  2566. if (chFull === false) asyncRes = asyncRes.then($hs.getWithFullscreenBtn);
  2567. else asyncRes = asyncRes.then(() => null)
  2568.  
  2569. asyncRes.then((btnElement) => {
  2570.  
  2571. if (btnElement) {
  2572.  
  2573. window.requestAnimationFrame(() => btnElement.click());
  2574. player = null;
  2575. actionBoxRelation = null;
  2576. return;
  2577. }
  2578.  
  2579. let fsElm = getRoot(player).querySelector(`[_h5p_fsElm_="${vpid}"]`); //it is set in fullscreenchange
  2580.  
  2581. let gPlayer = fsElm
  2582.  
  2583. if (gPlayer) {
  2584.  
  2585. } else if (actionBoxRelation && actionBoxRelation.actionBox) {
  2586. gPlayer = actionBoxRelation.actionBox;
  2587. } else if (actionBoxRelation && actionBoxRelation.layoutBox) {
  2588. gPlayer = actionBoxRelation.layoutBox;
  2589. } else {
  2590. gPlayer = player;
  2591. }
  2592.  
  2593.  
  2594. player = null;
  2595. actionBoxRelation = null;
  2596.  
  2597. if (gPlayer != fsElm && !fsElm) {
  2598. delayCall('$$videoReset_fsElm', function() {
  2599. gPlayer.removeAttribute('_h5p_fsElm_')
  2600. }, 500)
  2601. }
  2602.  
  2603. console.log('DOM fullscreen', gPlayer)
  2604. try {
  2605. const res = gPlayer.requestFullscreen()
  2606. if (res && res.constructor.name == "Promise") res.catch((e) => 0)
  2607. } catch (e) {
  2608. console.log('DOM fullscreen Error', e)
  2609. }
  2610.  
  2611.  
  2612.  
  2613.  
  2614. })
  2615.  
  2616.  
  2617.  
  2618.  
  2619. },
  2620. /* 設置播放速度 */
  2621. setPlaybackRate: function(num, flagTips) {
  2622. let player = $hs.player()
  2623. let curPlaybackRate
  2624. if (num) {
  2625. num = +num
  2626. if (num > 0) { // also checking the type of variable
  2627. curPlaybackRate = num < 0.1 ? 0.1 : +(num.toFixed(1))
  2628. } else {
  2629. console.error('h5player: 播放速度轉換出錯')
  2630. return false
  2631. }
  2632. } else {
  2633. curPlaybackRate = $hs.getPlaybackRate()
  2634. }
  2635. /* 記錄播放速度的信息 */
  2636.  
  2637. let changed = curPlaybackRate !== player.playbackRate;
  2638.  
  2639. if (curPlaybackRate !== player.playbackRate) {
  2640.  
  2641. Store.save('_playback_rate_', curPlaybackRate + '')
  2642. $hs.playbackRate = curPlaybackRate
  2643. player.playbackRate = curPlaybackRate
  2644. /* 本身處於1被播放速度的時候不再提示 */
  2645. //if (!num && curPlaybackRate === 1) return;
  2646.  
  2647. }
  2648.  
  2649. flagTips = (flagTips < 0) ? false : (flagTips > 0) ? true : changed;
  2650. if (flagTips) $hs.tips('Playback speed: ' + player.playbackRate + 'x')
  2651. },
  2652. tuneCurrentTimeTips: function(_amount, changed) {
  2653.  
  2654. $hs.tips(false);
  2655. if (changed) {
  2656. if (_amount > 0) $hs.tips(_amount + ' Sec. Forward', undefined, 3000);
  2657. else $hs.tips(-_amount + ' Sec. Backward', undefined, 3000)
  2658. }
  2659. },
  2660. tuneCurrentTime: function(amount) {
  2661. let _amount = +(+amount).toFixed(1);
  2662. let player = $hs.player();
  2663. if (_amount >= 0 || _amount < 0) {} else {
  2664. return;
  2665. }
  2666.  
  2667. let newCurrentTime = player.currentTime + _amount;
  2668. if (newCurrentTime < 0) newCurrentTime = 0;
  2669. if (newCurrentTime > player.duration) newCurrentTime = player.duration;
  2670.  
  2671. let changed = newCurrentTime != player.currentTime && newCurrentTime >= 0 && newCurrentTime <= player.duration;
  2672.  
  2673. if (changed) {
  2674. //player.currentTime = newCurrentTime;
  2675. //player.pause();
  2676.  
  2677.  
  2678. const video = player;
  2679. var isPlaying = video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
  2680.  
  2681. if (isPlaying) {
  2682. player.pause();
  2683. $hs.ccad = $hs.ccad || function() {
  2684. if (player.paused) player.play();
  2685. };
  2686. player.addEventListener('seeked', $hs.ccad, {
  2687. passive: true,
  2688. capture: true,
  2689. once: true
  2690. });
  2691.  
  2692. }
  2693.  
  2694.  
  2695.  
  2696.  
  2697. player.currentTime = +newCurrentTime.toFixed(0)
  2698.  
  2699. $hs.tuneCurrentTimeTips(_amount, changed)
  2700.  
  2701.  
  2702. }
  2703.  
  2704. },
  2705. tuneVolume: function(amount) {
  2706.  
  2707. let player = $hs.player()
  2708.  
  2709. let intAmount = Math.round(amount * 100)
  2710.  
  2711. let intOldVol = Math.round(player.volume * 100)
  2712. let intNewVol = intOldVol + intAmount
  2713.  
  2714.  
  2715. //0.53 -> 0.55
  2716.  
  2717. //0.53 / 0.05 =10.6 => 11 => 11*0.05 = 0.55
  2718.  
  2719. intNewVol = Math.round(intNewVol / intAmount) * intAmount
  2720. if (intAmount > 0 && intNewVol - intOldVol > intAmount) intNewVol -= intAmount;
  2721. else if (intAmount < 0 && intNewVol - intOldVol < intAmount) intNewVol -= intAmount;
  2722.  
  2723.  
  2724. let _amount = intAmount / 100;
  2725. let oldVol = intOldVol / 100;
  2726. let newVol = intNewVol / 100;
  2727.  
  2728.  
  2729. if (newVol < 0) newVol = 0;
  2730. if (newVol > 1) newVol = 1;
  2731. let chVol = oldVol !== newVol && newVol >= 0 && newVol <= 1;
  2732.  
  2733. if (chVol) {
  2734.  
  2735. if (_amount > 0 && oldVol < 1) {
  2736. player.volume = newVol // positive
  2737. } else if (_amount < 0 && oldVol > 0) {
  2738. player.volume = newVol // negative
  2739. }
  2740. $hs.tips(false);
  2741. $hs.tips('Volume: ' + dround(player.volume * 100) + '%', undefined)
  2742. }
  2743. },
  2744. switchPlayStatus: function() {
  2745. let player = $hs.player()
  2746. if (player.paused) {
  2747. player.play()
  2748. if (player._isThisPausedBefore_) {
  2749. $hs.tips(false);
  2750. $hs.tips('Playback resumed', undefined, 2500)
  2751. }
  2752. } else {
  2753. player.pause()
  2754. $hs.tips(false);
  2755. $hs.tips('Playback paused', undefined, 2500)
  2756. }
  2757. },
  2758. tipsClassName: 'html_player_enhance_tips',
  2759. tipsDomObserve: (tipsDom, player) => {
  2760.  
  2761. //observe not fire twice for the same element.
  2762. if (!$hs.observer_resizeVideos) $hs.observer_resizeVideos = new ResizeObserver(hanlderResizeVideo)
  2763. $hs.observer_resizeVideos.observe(tipsDom.parentNode)
  2764. $hs.observer_resizeVideos.observe(player)
  2765.  
  2766. $hs.fixNonBoxingVideoTipsPosition2(tipsDom, player);
  2767.  
  2768.  
  2769. },
  2770. _tips: function(player, str, duration, order) {
  2771.  
  2772.  
  2773. if (!player) return;
  2774. let fSetDOM = false;
  2775.  
  2776. Promise.resolve().then(() => {
  2777.  
  2778.  
  2779. if (!player.getAttribute('_h5player_tips')) $hs.initTips();
  2780.  
  2781. }).then(() => {
  2782.  
  2783. let tipsSelector = '#' + (player.getAttribute('_h5player_tips') || $hs.tipsClassName) //if this attribute still doesnt exist, set it to the base cls name
  2784. let tipsDom = getRoot(player).querySelector(tipsSelector)
  2785. if (!tipsDom) {
  2786. consoleLog('init h5player tips dom error...')
  2787. return false
  2788. }
  2789.  
  2790. return tipsDom
  2791.  
  2792. }).then((tipsDom) => {
  2793. if (tipsDom === false) return false;
  2794.  
  2795. if (str === false) {
  2796. if ((tipsDom.getAttribute('data-h5p-pot-tips') || '').length) {
  2797. tipsDom.setAttribute('data-h5p-pot-tips', '');
  2798. tipsDom._tips_display_none = true;
  2799. }
  2800. } else {
  2801. order = order || 1000
  2802. tipsDom.tipsOrder = tipsDom.tipsOrder || 0;
  2803.  
  2804. let shallDisplay = true
  2805. if (order < tipsDom.tipsOrder && tipsDom._tips_display_none == false) shallDisplay = false
  2806.  
  2807. if (shallDisplay) {
  2808.  
  2809. if (tipsDom._tips_display_none || tipsDom._playerVPID != player.getAttribute('_h5ppid')) {
  2810.  
  2811. $hs.change_layoutBox(tipsDom, player);
  2812. fSetDOM = true;
  2813.  
  2814. }
  2815.  
  2816. $hs.pendingTips = $hs.pendingTips || {};
  2817. $hs.pendingTips[tipsDom._playerVPID] = tipsDom
  2818.  
  2819. if (duration === undefined) duration = 2000
  2820.  
  2821.  
  2822. tipsDom.setAttribute('data-h5p-pot-tips', str);
  2823. tipsDom._tips_display_none = false;
  2824.  
  2825.  
  2826.  
  2827.  
  2828. const withFadeOut = duration > 0 && (player.paused || !($hs.mouseDownAt && $hs.mouseDownAt.insideVideo === player));
  2829.  
  2830.  
  2831. !(function(tipsDom, withFadeOut) {
  2832. const vpid = tipsDom._playerVPID
  2833. window.requestAnimationFrame(function() {
  2834. tipsDom.setAttribute('_h5p_animate', '0');
  2835. if (!withFadeOut) return;
  2836. window.requestAnimationFrame(function() {
  2837. const tipsDom = $hs.pendingTips ? $hs.pendingTips[vpid] : null;
  2838. if (!tipsDom) return;
  2839. tipsDom.setAttribute('_h5p_animate', '1');
  2840. delete $hs.pendingTips[vpid]
  2841.  
  2842. })
  2843. })
  2844. })(tipsDom, withFadeOut);
  2845.  
  2846.  
  2847.  
  2848. if (!(duration > 0)) {
  2849. order = -1;
  2850. }
  2851.  
  2852. tipsDom.tipsOrder = order
  2853.  
  2854.  
  2855.  
  2856. }
  2857.  
  2858. }
  2859.  
  2860. return tipsDom;
  2861.  
  2862. }).then((tipsDom) => {
  2863. if (tipsDom === false) return false;
  2864.  
  2865. if (fSetDOM) {
  2866. $hs.tipsDomObserve(tipsDom, player);
  2867.  
  2868. }
  2869.  
  2870. })
  2871.  
  2872. },
  2873. tips: function(str, duration, order) {
  2874. let player = $hs.player()
  2875. if (!player) {
  2876. consoleLog('h5Player Tips:', str)
  2877. } else {
  2878. $hs._tips(player, str, duration, order)
  2879.  
  2880. }
  2881.  
  2882. },
  2883. initTips: function() {
  2884. /* 設置提示DOM的樣式 */
  2885. let player = $hs.player()
  2886. let shadowRoot = getRoot(player);
  2887. let doc = player.ownerDocument;
  2888. //console.log((document.documentElement.qq=player),shadowRoot,'xax')
  2889. let parentNode = player.parentNode
  2890. let tcn = player.getAttribute('_h5player_tips') || ($hs.tipsClassName + '_' + (+new Date));
  2891. player.setAttribute('_h5player_tips', tcn)
  2892. if (shadowRoot.querySelector('#' + tcn)) return false;
  2893.  
  2894. if (!shadowRoot._onceAddedCSS) {
  2895. shadowRoot._onceAddedCSS = true;
  2896.  
  2897. let cssStyle = `
  2898. ${utPositioner}{
  2899. position:absolute !important;
  2900. top:auto !important;
  2901. left:auto !important;
  2902. right:auto !important;
  2903. bottom:auto !important;
  2904. width:0 !important;
  2905. height:0 !important;
  2906. margin:0 !important;
  2907. padding:0 !important;
  2908. border:0 !important;
  2909. outline:0 !important;
  2910. transform:none !important;
  2911. }
  2912. [data-h5p-pot-tips][_h5p_animate="1"]{
  2913. animation: 2s linear 0s normal forwards 1 delayHide;
  2914. }
  2915. [data-h5p-pot-tips][_h5p_animate="0"]{
  2916. opacity:.95; transform: translate(0px, 0px);
  2917. }
  2918.  
  2919. @keyframes delayHide{
  2920. 0%, 99% { opacity:0.95; transform: translate(0px, 0px); }
  2921. 100% { opacity:0; transform:translate(-9999px, -9999px); }
  2922. }
  2923. [data-h5p-pot-tips]{
  2924. font-weight: bold !important;
  2925. position:absolute !important;
  2926. top:auto !important;
  2927. left:auto !important;
  2928. right:auto !important;
  2929. bottom:auto !important;
  2930.  
  2931. display:inline-block;
  2932. z-index: 999 !important;
  2933. font-size: ${$hs.fontSize || 16}px !important;
  2934. padding: 0px !important;
  2935. border:none !important;
  2936. background: rgba(0,0,0,0) !important;
  2937. color:#738CE6 !important;
  2938. text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
  2939. max-width:500px;max-height:50px;
  2940. border-radius:3px;
  2941. font-family: 'microsoft yahei', Verdana, Geneva, sans-serif;
  2942. pointer-events: none;
  2943. }
  2944. [data-h5p-pot-tips]::before{
  2945. content:attr(data-h5p-pot-tips);
  2946. display:inline-block;
  2947. position:relative;
  2948.  
  2949. }
  2950. body div[data-h5p-pot-tips]{
  2951. -webkit-user-select: none !important;
  2952. -moz-user-select: none !important;
  2953. -ms-user-select: none !important;
  2954. user-select: none !important;
  2955. -webkit-touch-callout: none !important;
  2956. -webkit-user-select: none !important;
  2957. -khtml-user-drag: none !important;
  2958. -khtml-user-select: none !important;
  2959. -moz-user-select: none !important;
  2960. -moz-user-select: -moz-none !important;
  2961. -ms-user-select: none !important;
  2962. user-select: none !important;
  2963. }
  2964. .ytp-chrome-bottom+span#volumeUI:last-child:empty{
  2965. display:none;
  2966. }
  2967. `.replace(/\r\n/g, '');
  2968.  
  2969.  
  2970. let cssContainer = domAppender(shadowRoot);
  2971.  
  2972.  
  2973. if (!cssContainer) {
  2974. cssContainer = makeNoRoot(shadowRoot)
  2975. }
  2976.  
  2977. domTool.addStyle(cssStyle, cssContainer);
  2978.  
  2979. }
  2980.  
  2981. let tipsDom = doc.createElement('div')
  2982.  
  2983. $hs.handler_tipsDom_animation = $hs.handler_tipsDom_animation || function(e) {
  2984. this._tips_display_none = true;
  2985. }
  2986.  
  2987. tipsDom.addEventListener(crossBrowserTransition('animation'), $hs.handler_tipsDom_animation, $mb.eh_bubble_passive())
  2988.  
  2989. tipsDom.id = tcn;
  2990. tipsDom.setAttribute('data-h5p-pot-tips', '');
  2991. tipsDom.setAttribute('_h5p_animate', '0');
  2992. tipsDom._tips_display_none = true;
  2993. $hs.change_layoutBox(tipsDom, player);
  2994.  
  2995. return true;
  2996. },
  2997.  
  2998.  
  2999. fixNonBoxingVideoTipsPosition2:function(tipsDom, player) {
  3000.  
  3001.  
  3002. function k(){
  3003. $hs.cid_fixVideo=0;
  3004. f();
  3005. }
  3006.  
  3007. function f(){
  3008. let r;
  3009. r=$hs.fixNonBoxingVideoTipsPosition(tipsDom, player);
  3010. if(r && !$hs.cid_fixVideo) {
  3011. // $hs.cid_fixVideo= window.requestAnimationFrame(k)
  3012. }
  3013. }
  3014.  
  3015. f();
  3016.  
  3017. },
  3018. fixNonBoxingVideoTipsPosition: function(tipsDom, player) {
  3019.  
  3020. if (!tipsDom || !player) return false;
  3021.  
  3022. let ct = tipsDom.parentNode
  3023.  
  3024. if (!ct) return false;
  3025.  
  3026. //return;
  3027. // absolute
  3028.  
  3029. let targetOffset = {
  3030. left: 10,
  3031. top: 15
  3032. };
  3033. if(!tipsDom.nextSibling||tipsDom.nextSibling.nodeName!=utPositioner){
  3034. tipsDom.parentNode.insertBefore(document.createElement(utPositioner),tipsDom.nextSibling);
  3035. }
  3036. let p = tipsDom.nextSibling.getBoundingClientRect();
  3037. let q = player.getBoundingClientRect();
  3038. let basePos = [+(p.left).toFixed(2), +(p.top).toFixed(2)];
  3039.  
  3040. let targetPos = [+(q.left + targetOffset.left).toFixed(2), +(q.top + targetOffset.top).toFixed(2)];
  3041.  
  3042.  
  3043. let tt=basePos.join(',')+','+targetPos.join(',')
  3044.  
  3045. if(tipsDom.__cache_dim__!=tt){
  3046. tipsDom.__cache_dim__=tt;
  3047.  
  3048.  
  3049. let y1 = targetPos[0]- basePos[0]
  3050. if(y1>=0){}else{y1=0;}
  3051.  
  3052. let y2 = targetPos[1]- basePos[1]
  3053. if(y2>=0){}else{y2=0;}
  3054.  
  3055.  
  3056. tipsDom.style.marginLeft = (y1) + 'px';
  3057. tipsDom.style.marginTop = (y2) + 'px';
  3058. return true;
  3059.  
  3060. }
  3061.  
  3062. tipsDom=null;
  3063. player=null;
  3064.  
  3065. },
  3066.  
  3067. playerTrigger: function(player, event) {
  3068.  
  3069.  
  3070.  
  3071. if (!player || !event) return
  3072. const pCode = event.code;
  3073. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  3074.  
  3075.  
  3076.  
  3077.  
  3078. let vpid = player.getAttribute('_h5ppid') || null;
  3079. if (!vpid) return;
  3080. let playerConf = playerConfs[vpid]
  3081. if (!playerConf) return;
  3082.  
  3083. //shift + key
  3084. if (keyAsm == SHIFT) {
  3085. // 網頁FULLSCREEN
  3086. if (pCode === 'Enter') {
  3087. //$hs.callFullScreenBtn()
  3088. //return TERMINATE
  3089. } else if (pCode == 'KeyF') {
  3090. //change unsharpen filter
  3091.  
  3092. let resList = ["unsharpen3_05", "unsharpen3_10", "unsharpen5_05", "unsharpen5_10", "unsharpen9_05", "unsharpen9_10"]
  3093. let res = (prompt("Enter the unsharpen mask\n(" + resList.map(x => '"' + x + '"').join(', ') + ")", "unsharpen9_05") || "").toLowerCase();
  3094. if (resList.indexOf(res) < 0) res = ""
  3095. GM_setValue("unsharpen_mask", res)
  3096. for (const el of document.querySelectorAll('video[_h5p_uid_encrypted]')) {
  3097. if (el.style.filter == "" || el.style.filter) {
  3098. let filterStr1 = el.style.filter.replace(/\s*url\(\"#_h5p_unsharpen[\d\_]+\"\)/, '');
  3099. let filterStr2 = (res.length > 0 ? ' url("#_h5p_' + res + '")' : '')
  3100. el.style.filter = filterStr1 + filterStr2;
  3101. }
  3102. }
  3103. return TERMINATE
  3104.  
  3105. }
  3106. // 進入或退出畫中畫模式
  3107. else if (pCode == 'KeyP') {
  3108. $hs.pictureInPicture(player)
  3109.  
  3110. return TERMINATE
  3111. } else if (pCode == 'KeyR') {
  3112. if (player._h5player_lastrecord_ !== null && (player._h5player_lastrecord_ >= 0 || player._h5player_lastrecord_ <= 0)) {
  3113. $hs.setPlayProgress(player, player._h5player_lastrecord_)
  3114.  
  3115. return TERMINATE
  3116. }
  3117.  
  3118. } else if (pCode == 'KeyO') {
  3119. let _debug_h5p_logging_ch = false;
  3120. try {
  3121. Store._setItem('_h5_player_sLogging_', 1 - Store._getItem('_h5_player_sLogging_'))
  3122. _debug_h5p_logging_ = +Store._getItem('_h5_player_sLogging_') > 0;
  3123. _debug_h5p_logging_ch = true;
  3124. } catch (e) {
  3125.  
  3126. }
  3127. consoleLogF('_debug_h5p_logging_', !!_debug_h5p_logging_, 'changed', _debug_h5p_logging_ch)
  3128.  
  3129. if (_debug_h5p_logging_ch) {
  3130.  
  3131. return TERMINATE
  3132. }
  3133. } else if (pCode == 'KeyT') {
  3134. if (/^blob/i.test(player.currentSrc)) {
  3135. alert(`The current video is ${player.currentSrc}\nSorry, it cannot be opened in PotPlayer.`);
  3136. } else {
  3137. let confirm_res = confirm(`The current video is ${player.currentSrc}\nDo you want to open it in PotPlayer?`);
  3138. if (confirm_res) window.open('potplayer://' + player.currentSrc, '_blank');
  3139. }
  3140. return TERMINATE
  3141. }
  3142.  
  3143.  
  3144.  
  3145. let videoScale = playerConf.vFactor;
  3146.  
  3147. function tipsForVideoScaling() {
  3148.  
  3149. playerConf.vFactor = +videoScale.toFixed(1);
  3150.  
  3151. playerConf.cssTransform();
  3152. let tipsMsg = `視頻縮放率:${ +(videoScale * 100).toFixed(2) }%`
  3153. if (playerConf.translate.x) {
  3154. tipsMsg += `,水平位移:${playerConf.translate.x}px`
  3155. }
  3156. if (playerConf.translate.y) {
  3157. tipsMsg += `,垂直位移:${playerConf.translate.y}px`
  3158. }
  3159. $hs.tips(false);
  3160. $hs.tips(tipsMsg)
  3161.  
  3162.  
  3163. }
  3164.  
  3165. // 視頻畫面縮放相關事件
  3166.  
  3167. switch (pCode) {
  3168. // shift+X:視頻縮小 -0.1
  3169. case 'KeyX':
  3170. videoScale -= 0.1
  3171. if (videoScale < 0.1) videoScale = 0.1;
  3172. tipsForVideoScaling();
  3173. return TERMINATE
  3174. break
  3175. // shift+C:視頻放大 +0.1
  3176. case 'KeyC':
  3177. videoScale += 0.1
  3178. if (videoScale > 16) videoScale = 16;
  3179. tipsForVideoScaling();
  3180. return TERMINATE
  3181. break
  3182. // shift+Z:視頻恢復正常大小
  3183. case 'KeyZ':
  3184. videoScale = 1.0
  3185. playerConf.translate.x = 0;
  3186. playerConf.translate.y = 0;
  3187. tipsForVideoScaling();
  3188. return TERMINATE
  3189. break
  3190. case 'ArrowRight':
  3191. playerConf.translate.x += 10
  3192. tipsForVideoScaling();
  3193. return TERMINATE
  3194. break
  3195. case 'ArrowLeft':
  3196. playerConf.translate.x -= 10
  3197. tipsForVideoScaling();
  3198. return TERMINATE
  3199. break
  3200. case 'ArrowUp':
  3201. playerConf.translate.y -= 10
  3202. tipsForVideoScaling();
  3203. return TERMINATE
  3204. break
  3205. case 'ArrowDown':
  3206. playerConf.translate.y += 10
  3207. tipsForVideoScaling();
  3208. return TERMINATE
  3209. break
  3210.  
  3211. }
  3212.  
  3213. }
  3214. // 防止其它無關組合鍵衝突
  3215. if (!keyAsm) {
  3216. let kControl = null
  3217. let newPBR, oldPBR, nv, numKey;
  3218. switch (pCode) {
  3219. // 方向鍵右→:快進3秒
  3220. case 'ArrowRight':
  3221. if (1) {
  3222. let aCurrentTime = player.currentTime;
  3223. window.requestAnimationFrame(() => {
  3224. let diff = player.currentTime - aCurrentTime
  3225. diff = Math.round(diff * 5) / 5;
  3226. if (Math.abs(diff) < 0.8) {
  3227. $hs.tuneCurrentTime(+$hs.skipStep);
  3228. } else {
  3229. $hs.tuneCurrentTimeTips(diff, true)
  3230. }
  3231. })
  3232. //if(document.domain.indexOf('youtube.com')>=0){}else{
  3233. //$hs.tuneCurrentTime($hs.skipStep);
  3234. //return TERMINATE;
  3235. //}
  3236. }
  3237. break;
  3238. // 方向鍵左←:後退3秒
  3239. case 'ArrowLeft':
  3240.  
  3241. if (1) {
  3242. let aCurrentTime = player.currentTime;
  3243. window.requestAnimationFrame(() => {
  3244. let diff = player.currentTime - aCurrentTime
  3245. diff = Math.round(diff * 5) / 5;
  3246. if (Math.abs(diff) < 0.8) {
  3247. $hs.tuneCurrentTime(-$hs.skipStep);
  3248. } else {
  3249. $hs.tuneCurrentTimeTips(diff, true)
  3250. }
  3251. })
  3252. //if(document.domain.indexOf('youtube.com')>=0){}else{
  3253. //
  3254. //return TERMINATE;
  3255. //}
  3256. }
  3257. break;
  3258. // 方向鍵上↑:音量升高 1%
  3259. case 'ArrowUp':
  3260. if ((player.muted && player.volume === 0) && player._volume > 0) {
  3261.  
  3262. player.muted = false;
  3263. player.volume = player._volume;
  3264. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  3265. player.muted = false;
  3266. }
  3267. $hs.tuneVolume(0.01);
  3268. return TERMINATE;
  3269. break;
  3270. // 方向鍵下↓:音量降低 1%
  3271. case 'ArrowDown':
  3272.  
  3273. if ((player.muted && player.volume === 0) && player._volume > 0) {
  3274.  
  3275. player.muted = false;
  3276. player.volume = player._volume;
  3277. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  3278. player.muted = false;
  3279. }
  3280. $hs.tuneVolume(-0.01);
  3281. return TERMINATE;
  3282. break;
  3283. // 空格鍵:暫停/播放
  3284. case 'Space':
  3285. $hs.switchPlayStatus();
  3286. return TERMINATE;
  3287. break;
  3288. // 按鍵X:減速播放 -0.1
  3289. case 'KeyX':
  3290. if (player.playbackRate > 0) {
  3291. $hs.tips(false);
  3292. $hs.setPlaybackRate(player.playbackRate - 0.1);
  3293. return TERMINATE
  3294. }
  3295. break;
  3296. // 按鍵C:加速播放 +0.1
  3297. case 'KeyC':
  3298. if (player.playbackRate < 16) {
  3299. $hs.tips(false);
  3300. $hs.setPlaybackRate(player.playbackRate + 0.1);
  3301. return TERMINATE
  3302. }
  3303.  
  3304. break;
  3305. // 按鍵Z:正常速度播放
  3306. case 'KeyZ':
  3307. $hs.tips(false);
  3308. oldPBR = player.playbackRate;
  3309. if (oldPBR != 1.0) {
  3310. player._playbackRate_z = oldPBR;
  3311. newPBR = 1.0;
  3312. } else if (player._playbackRate_z != 1.0) {
  3313. newPBR = player._playbackRate_z || 1.0;
  3314. player._playbackRate_z = 1.0;
  3315. } else {
  3316. newPBR = 1.0
  3317. player._playbackRate_z = 1.0;
  3318. }
  3319. $hs.setPlaybackRate(newPBR, 1)
  3320. return TERMINATE
  3321. break;
  3322. // 按鍵F:下一幀
  3323. case 'KeyF':
  3324. if (window.location.hostname === 'www.netflix.com') return /* netflix 的F鍵是FULLSCREEN的意思 */
  3325. $hs.tips(false);
  3326. if (!player.paused) player.pause()
  3327. player.currentTime += +(1 / playerConf.fps)
  3328. $hs.tips('Jump to: Next frame')
  3329. return TERMINATE
  3330. break;
  3331. // 按鍵D:上一幀
  3332. case 'KeyD':
  3333. $hs.tips(false);
  3334. if (!player.paused) player.pause()
  3335. player.currentTime -= +(1 / playerConf.fps)
  3336. $hs.tips('Jump to: Previous frame')
  3337. return TERMINATE
  3338. break;
  3339. // 按鍵E:亮度增加%
  3340. case 'KeyE':
  3341. $hs.tips(false);
  3342. nv = playerConf.setFilter('brightness', (v) => v + 0.1);
  3343. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  3344. return TERMINATE
  3345. break;
  3346. // 按鍵W:亮度減少%
  3347. case 'KeyW':
  3348. $hs.tips(false);
  3349. nv = playerConf.setFilter('brightness', (v) => v > 0.1 ? v - 0.1 : 0);
  3350. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  3351. return TERMINATE
  3352. break;
  3353. // 按鍵T:對比度增加%
  3354. case 'KeyT':
  3355. $hs.tips(false);
  3356. nv = playerConf.setFilter('contrast', (v) => v + 0.1);
  3357. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  3358. return TERMINATE
  3359. break;
  3360. // 按鍵R:對比度減少%
  3361. case 'KeyR':
  3362. $hs.tips(false);
  3363. nv = playerConf.setFilter('contrast', (v) => v > 0.1 ? v - 0.1 : 0);
  3364. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  3365. return TERMINATE
  3366. break;
  3367. // 按鍵U:飽和度增加%
  3368. case 'KeyU':
  3369. $hs.tips(false);
  3370. nv = playerConf.setFilter('saturate', (v) => v + 0.1);
  3371. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  3372. return TERMINATE
  3373. break;
  3374. // 按鍵Y:飽和度減少%
  3375. case 'KeyY':
  3376. $hs.tips(false);
  3377. nv = playerConf.setFilter('saturate', (v) => v > 0.1 ? v - 0.1 : 0);
  3378. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  3379. return TERMINATE
  3380. break;
  3381. // 按鍵O:色相增加 1 度
  3382. case 'KeyO':
  3383. $hs.tips(false);
  3384. nv = playerConf.setFilter('hue-rotate', (v) => v + 1);
  3385. $hs.tips('Hue: ' + nv + ' deg')
  3386. return TERMINATE
  3387. break;
  3388. // 按鍵I:色相減少 1 度
  3389. case 'KeyI':
  3390. $hs.tips(false);
  3391. nv = playerConf.setFilter('hue-rotate', (v) => v - 1);
  3392. $hs.tips('Hue: ' + nv + ' deg')
  3393. return TERMINATE
  3394. break;
  3395. // 按鍵K:模糊增加 0.1 px
  3396. case 'KeyK':
  3397. $hs.tips(false);
  3398. nv = playerConf.setFilter('blur', (v) => v + 0.1);
  3399. $hs.tips('Blur: ' + nv + ' px')
  3400. return TERMINATE
  3401. break;
  3402. // 按鍵J:模糊減少 0.1 px
  3403. case 'KeyJ':
  3404. $hs.tips(false);
  3405. nv = playerConf.setFilter('blur', (v) => v > 0.1 ? v - 0.1 : 0);
  3406. $hs.tips('Blur: ' + nv + ' px')
  3407. return TERMINATE
  3408. break;
  3409. // 按鍵Q:圖像復位
  3410. case 'KeyQ':
  3411. $hs.tips(false);
  3412. playerConf.filterReset();
  3413. $hs.tips('Video Filter Reset')
  3414. return TERMINATE
  3415. break;
  3416. // 按鍵S:畫面旋轉 90 度
  3417. case 'KeyS':
  3418. $hs.tips(false);
  3419. playerConf.rotate += 90
  3420. if (playerConf.rotate % 360 === 0) playerConf.rotate = 0;
  3421. if (!playerConf.videoHeight || !playerConf.videoWidth) {
  3422. playerConf.videoWidth = playerConf.domElement.videoWidth;
  3423. playerConf.videoHeight = playerConf.domElement.videoHeight;
  3424. }
  3425. if (playerConf.videoWidth > 0 && playerConf.videoHeight > 0) {
  3426.  
  3427.  
  3428. if ((playerConf.rotate % 180) == 90) {
  3429. playerConf.mFactor = playerConf.videoHeight / playerConf.videoWidth;
  3430. } else {
  3431. playerConf.mFactor = 1.0;
  3432. }
  3433.  
  3434.  
  3435. playerConf.cssTransform();
  3436.  
  3437. $hs.tips('Rotation:' + playerConf.rotate + ' deg')
  3438.  
  3439. }
  3440.  
  3441. return TERMINATE
  3442. break;
  3443. // 按鍵迴車,進入FULLSCREEN
  3444. case 'Enter':
  3445. //t.callFullScreenBtn();
  3446. break;
  3447. case 'KeyN':
  3448. $hs.pictureInPicture(player);
  3449. return TERMINATE
  3450. break;
  3451. case 'KeyM':
  3452. //console.log('m!', player.volume,player._volume)
  3453.  
  3454. if (player.volume >= 0) {
  3455.  
  3456. if (!player.volume || player.muted) {
  3457.  
  3458. let newVol = player.volume || player._volume || 0.5;
  3459. if (player.volume !== newVol) {
  3460. player.volume = newVol;
  3461. }
  3462. player.muted = false;
  3463. $hs.tips(false);
  3464. $hs.tips('Mute: Off', undefined);
  3465.  
  3466. } else {
  3467.  
  3468. player._volume = player.volume;
  3469. player._volume_p = player.volume;
  3470. //player.volume = 0;
  3471. player.muted = true;
  3472. $hs.tips(false);
  3473. $hs.tips('Mute: On', undefined);
  3474.  
  3475. }
  3476.  
  3477. }
  3478.  
  3479. return TERMINATE
  3480. break;
  3481. default:
  3482. // 按1-4設置播放速度 49-52;97-100
  3483. numKey = +(event.key)
  3484.  
  3485. if (numKey >= 1 && numKey <= 4) {
  3486. $hs.tips(false);
  3487. $hs.setPlaybackRate(numKey, 1)
  3488. return TERMINATE
  3489. }
  3490. }
  3491.  
  3492. }
  3493. },
  3494.  
  3495. mointoringVideo:false, //false -> xxx -> null -> xxx
  3496.  
  3497. handlerPlayerLockedMouseMove: function(e) {
  3498. //console.log(4545)
  3499.  
  3500. const player = $hs.mointoringVideo;
  3501.  
  3502. if (!player) return;
  3503.  
  3504.  
  3505. $hs.mouseMoveCount += Math.sqrt(e.movementX * e.movementX + e.movementY * e.movementY);
  3506.  
  3507. delayCall('$$VideoClearMove', function() {
  3508. $hs.mouseMoveCount = $hs.mouseMoveCount * 0.4;
  3509. }, 100)
  3510.  
  3511. delayCall('$$VideoClearMove2', function() {
  3512. $hs.mouseMoveCount = $hs.mouseMoveCount * 0.1;
  3513. }, 400)
  3514.  
  3515. if ($hs.mouseMoveCount > player.mouseMoveMax) {
  3516. $hs.hcMouseShowWithMonitoring(player)
  3517. }
  3518.  
  3519. },
  3520.  
  3521. _hcMouseHidePre: function(player) {
  3522. if (player.paused === true) {
  3523. $hs.hcShowMouseAndRemoveMointoring(player);
  3524. return;
  3525. }
  3526. if ($hs.mouseEnteredElement) {
  3527. const elm = $hs.mouseEnteredElement;
  3528. switch (getComputedStyle(elm).getPropertyValue('cursor')) {
  3529. case 'grab':
  3530. case 'pointer':
  3531. return;
  3532. }
  3533. if (elm.hasAttribute('alt')) return;
  3534. if (elm.getAttribute('aria-hidden') == 'true') return;
  3535. }
  3536. Promise.resolve().then(() => {
  3537. if (!$hs.mouseDownAt) player.ownerDocument.querySelector('html').setAttribute('_h5p_hide_cursor', '');
  3538. player = null;
  3539. })
  3540. return true;
  3541. },
  3542.  
  3543. hcStartMointoring:(player)=>{
  3544.  
  3545.  
  3546. $hs.mouseMoveCount = 0;
  3547.  
  3548. Promise.resolve($hs._hcMouseHidePre(player)).then(r => {
  3549. if (r) {
  3550.  
  3551. if($hs.mointoringVideo===false) player.ownerDocument.addEventListener('mousemove', $hs.handlerPlayerLockedMouseMove, $mb.eh_capture_passive())
  3552. $hs.mointoringVideo = player;
  3553.  
  3554. }
  3555.  
  3556. player = null;
  3557.  
  3558. })
  3559.  
  3560. },
  3561.  
  3562. hcMouseHideAndStartMointoring: function(player) {
  3563.  
  3564. //console.log(554, 'hcMouseHideAndStartMointoring')
  3565. delayCall('$$hcMouseMove')
  3566.  
  3567. $hs.hcStartMointoring(player)
  3568.  
  3569.  
  3570. },
  3571.  
  3572. hcDelayMouseHideAndStartMointoring: function(player) {
  3573. //console.log(554, 'hcDelayMouseHideAndStartMointoring')
  3574. delayCall('$$hcMouseMove', ()=> $hs.hcStartMointoring(player), 1240)
  3575. },
  3576.  
  3577. hcMouseShowWithMonitoring: function(player) {
  3578. //console.log(554, 'hcMouseShowWithMonitoring')
  3579. delayCall('$$hcMouseMove', function() {
  3580. $hs.mouseMoveCount = 0;
  3581. $hs._hcMouseHidePre(player)
  3582. }, 1240)
  3583. $hs.mouseMoveCount = 0;
  3584. player.ownerDocument.querySelector('html').removeAttribute('_h5p_hide_cursor')
  3585. },
  3586.  
  3587. hcShowMouseAndRemoveMointoring: function(player) {
  3588. //console.log(554, 'hcShowMouseAndRemoveMointoring')
  3589. delayCall('$$hcMouseMove')
  3590. if($hs.mointoringVideo) $hs.mointoringVideo = null;
  3591. $hs.mouseMoveCount = 0;
  3592. player.ownerDocument.querySelector('html').removeAttribute('_h5p_hide_cursor')
  3593.  
  3594. },
  3595.  
  3596.  
  3597. focusHookVDoc: null,
  3598. focusHookVId: '',
  3599.  
  3600.  
  3601. handlerElementFocus: function(event) {
  3602.  
  3603. function notAtVideo() {
  3604. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  3605. if ($hs.focusHookVId) $hs.focusHookVId = ''
  3606. }
  3607.  
  3608. const hookVideo = $hs.focusHookVDoc && $hs.focusHookVId ? $hs.focusHookVDoc.querySelector(`VIDEO[_h5ppid=${$hs.focusHookVId}]`) : null
  3609.  
  3610. if (hookVideo && (event.target == hookVideo || event.target.contains(hookVideo))) {} else {
  3611. notAtVideo();
  3612. }
  3613.  
  3614. },
  3615.  
  3616. handlerFullscreenChanged: function(event) {
  3617.  
  3618.  
  3619. let videoElm = null,
  3620. videosQuery = null;
  3621. if (event && event.target) {
  3622. if (event.target.nodeName == "VIDEO") videoElm = event.target;
  3623. else if (videosQuery = event.target.querySelectorAll("VIDEO")) {
  3624. if (videosQuery.length === 1) videoElm = videosQuery[0]
  3625. }
  3626. }
  3627.  
  3628. if (videoElm) {
  3629. const player = videoElm;
  3630. const vpid = player.getAttribute('_h5ppid')
  3631. event.target.setAttribute('_h5p_fsElm_', vpid)
  3632.  
  3633. function hookTheActionedVideo() {
  3634. $hs.focusHookVDoc = getRoot(player)
  3635. $hs.focusHookVId = vpid
  3636. }
  3637. hookTheActionedVideo();
  3638. window.setTimeout(function() {
  3639. hookTheActionedVideo()
  3640. }, 300)
  3641. window.setTimeout(() => {
  3642. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  3643. if (chFull) {
  3644. $hs.hcMouseHideAndStartMointoring(player);
  3645. } else {
  3646. $hs.hcShowMouseAndRemoveMointoring(player);
  3647. }
  3648. });
  3649. } else {
  3650. $hs.focusHookVDoc = null
  3651. $hs.focusHookVId = ''
  3652. }
  3653. },
  3654.  
  3655. /*
  3656. handlerOverrideMouseMove:function(evt){
  3657.  
  3658.  
  3659. if(evt&&evt.target){}else{return;}
  3660. const targetElm = evt.target;
  3661.  
  3662. if(targetElm.nodeName=="VIDEO"){
  3663. evt.preventDefault();
  3664. evt.stopPropagation();
  3665. evt.stopImmediatePropagation();
  3666. }
  3667.  
  3668. },*/
  3669.  
  3670. /* 按鍵響應方法 */
  3671. handlerRootKeyDownEvent: function(event) {
  3672.  
  3673. function notAtVideo() {
  3674. if ($hs.focusHookVDoc) $hs.focusHookVDoc = null
  3675. if ($hs.focusHookVId) $hs.focusHookVId = ''
  3676. }
  3677.  
  3678.  
  3679.  
  3680.  
  3681. if ($hs.intVideoInitCount > 0) {} else {
  3682. // return notAtVideo();
  3683. }
  3684.  
  3685.  
  3686.  
  3687. // $hs.lastKeyDown = event.timeStamp
  3688.  
  3689.  
  3690. // DOM Standard - either .key or .code
  3691. // Here we adopt .code (physical layout)
  3692.  
  3693. let pCode = event.code;
  3694. if (typeof pCode != 'string') return;
  3695. let player = $hs.player()
  3696. if (!player) return; // no video tag
  3697.  
  3698. let rootNode = getRoot(player);
  3699. let isRequiredListen = false;
  3700.  
  3701. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  3702.  
  3703.  
  3704. if (document.fullscreenElement) {
  3705. isRequiredListen = true;
  3706.  
  3707.  
  3708. if (!keyAsm && pCode == 'Escape') {
  3709. window.setTimeout(() => {
  3710. if (document.fullscreenElement) {
  3711. document.exitFullscreen();
  3712. }
  3713. }, 700);
  3714. return;
  3715. }
  3716.  
  3717.  
  3718. }
  3719.  
  3720. const actionBoxRelation = $hs.getActionBoxRelationFromDOM(event.target)
  3721. let hookVideo = null;
  3722.  
  3723. if (actionBoxRelation) {
  3724. $hs.focusHookVDoc = getRoot(actionBoxRelation.player);
  3725. $hs.focusHookVId = actionBoxRelation.player.getAttribute('_h5ppid');
  3726. hookVideo = actionBoxRelation.player;
  3727. } else {
  3728. hookVideo = $hs.focusHookVDoc && $hs.focusHookVId ? $hs.focusHookVDoc.querySelector(`VIDEO[_h5ppid=${$hs.focusHookVId}]`) : null
  3729. }
  3730.  
  3731. if (hookVideo) isRequiredListen = true;
  3732.  
  3733. //console.log('root key', isRequiredListen, event.target, hookVideo)
  3734.  
  3735. if (!isRequiredListen) return;
  3736.  
  3737. //console.log('K01')
  3738.  
  3739. /* 切換插件的可用狀態 */
  3740. // Shift-`
  3741. if (keyAsm == SHIFT && pCode == 'Backquote') {
  3742. $hs.enable = !$hs.enable;
  3743. $hs.tips(false);
  3744. if ($hs.enable) {
  3745. $hs.tips('啟用h5Player插件')
  3746. } else {
  3747. $hs.tips('禁用h5Player插件')
  3748. }
  3749. // 阻止事件冒泡
  3750. event.stopPropagation()
  3751. event.preventDefault()
  3752. return false
  3753. }
  3754. if (!$hs.enable) {
  3755. consoleLog('h5Player 已禁用~')
  3756. return false
  3757. }
  3758.  
  3759. /* 非全局模式下,不聚焦則不執行快捷鍵的操作 */
  3760.  
  3761. if (!keyAsm && pCode == 'Enter') { //not NumberpadEnter
  3762.  
  3763. Promise.resolve(player).then((player) => {
  3764. $hs._actionBoxObtain(player);
  3765. }).then(() => {
  3766. $hs.callFullScreenBtn()
  3767. })
  3768. event.stopPropagation()
  3769. event.preventDefault()
  3770. return false
  3771. }
  3772.  
  3773.  
  3774.  
  3775. let res = $hs.playerTrigger(player, event)
  3776. if (res == TERMINATE) {
  3777. event.stopPropagation()
  3778. event.preventDefault()
  3779. return false
  3780. }
  3781.  
  3782. },
  3783. /* 設置播放進度 */
  3784. setPlayProgress: function(player, curTime) {
  3785. if (!player) return
  3786. if (!curTime || Number.isNaN(curTime)) return
  3787. player.currentTime = curTime
  3788. if (curTime > 3) {
  3789. $hs.tips(false);
  3790. $hs.tips(`Playback Jumps to ${$hs.toolFormatCT(curTime)}`)
  3791. if (player.paused) player.play();
  3792. }
  3793. }
  3794. }
  3795.  
  3796. function makeFilter(arr, k) {
  3797. let res = ""
  3798. for (const e of arr) {
  3799. for (const d of e) {
  3800. res += " " + (1.0 * d * k).toFixed(9)
  3801. }
  3802. }
  3803. return res.trim()
  3804. }
  3805.  
  3806. function _add_filter(rootElm) {
  3807. let rootView = null;
  3808. if (rootElm && rootElm.nodeType > 0) {
  3809. while (rootElm.parentNode && rootElm.parentNode.nodeType === 1) rootElm = rootElm.parentNode;
  3810. rootView = rootElm.querySelector('body') || rootElm;
  3811. } else {
  3812. return;
  3813. }
  3814.  
  3815. if (rootView && rootView.querySelector && !rootView.querySelector('#_h5player_section_')) {
  3816.  
  3817. let svgFilterElm = document.createElement('section')
  3818. svgFilterElm.style.position = 'fixed';
  3819. svgFilterElm.style.left = '-999px';
  3820. svgFilterElm.style.width = '1px';
  3821. svgFilterElm.style.top = '-999px';
  3822. svgFilterElm.style.height = '1px';
  3823. svgFilterElm.id = '_h5player_section_'
  3824. let svgXML = `
  3825. <svg id='_h5p_image' version="1.1" xmlns="http://www.w3.org/2000/svg">
  3826. <defs>
  3827. <filter id="_h5p_sharpen1">
  3828. <feConvolveMatrix filterRes="100 100" style="color-interpolation-filters:sRGB" order="3" kernelMatrix="` + `
  3829. -0.3 -0.3 -0.3
  3830. -0.3 3.4 -0.3
  3831. -0.3 -0.3 -0.3`.replace(/[\n\r]+/g, ' ').trim() + `" preserveAlpha="true"/>
  3832. </filter>
  3833. <filter id="_h5p_unsharpen1">
  3834. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3835. makeFilter([
  3836. [1, 4, 6, 4, 1],
  3837. [4, 16, 24, 16, 4],
  3838. [6, 24, -476, 24, 6],
  3839. [4, 16, 24, 16, 4],
  3840. [1, 4, 6, 4, 1]
  3841. ], -1 / 256) + `" preserveAlpha="false"/>
  3842. </filter>
  3843. <filter id="_h5p_unsharpen3_05">
  3844. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  3845. makeFilter(
  3846. [
  3847. [0.025, 0.05, 0.025],
  3848. [0.05, -1.1, 0.05],
  3849. [0.025, 0.05, 0.025]
  3850. ], -1 / .8) + `" preserveAlpha="false"/>
  3851. </filter>
  3852. <filter id="_h5p_unsharpen3_10">
  3853. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  3854. makeFilter(
  3855. [
  3856. [0.05, 0.1, 0.05],
  3857. [0.1, -1.4, 0.1],
  3858. [0.05, 0.1, 0.05]
  3859. ], -1 / .8) + `" preserveAlpha="false"/>
  3860. </filter>
  3861. <filter id="_h5p_unsharpen5_05">
  3862. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3863. makeFilter(
  3864. [
  3865. [0.025, 0.1, 0.15, 0.1, 0.025],
  3866. [0.1, 0.4, 0.6, 0.4, 0.1],
  3867. [0.15, 0.6, -18.3, 0.6, 0.15],
  3868. [0.1, 0.4, 0.6, 0.4, 0.1],
  3869. [0.025, 0.1, 0.15, 0.1, 0.025]
  3870. ], -1 / 12.8) + `" preserveAlpha="false"/>
  3871. </filter>
  3872. <filter id="_h5p_unsharpen5_10">
  3873. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  3874. makeFilter(
  3875. [
  3876. [0.05, 0.2, 0.3, 0.2, 0.05],
  3877. [0.2, 0.8, 1.2, 0.8, 0.2],
  3878. [0.3, 1.2, -23.8, 1.2, 0.3],
  3879. [0.2, 0.8, 1.2, 0.8, 0.2],
  3880. [0.05, 0.2, 0.3, 0.2, 0.05]
  3881. ], -1 / 12.8) + `" preserveAlpha="false"/>
  3882. </filter>
  3883. <filter id="_h5p_unsharpen9_05">
  3884. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  3885. makeFilter(
  3886. [
  3887. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025],
  3888. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  3889. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  3890. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3891. [1.75, 14, 49, 98, -4792.7, 98, 49, 14, 1.75],
  3892. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3893. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  3894. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  3895. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025]
  3896. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3897. </filter>
  3898. <filter id="_h5p_unsharpen9_10">
  3899. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  3900. makeFilter(
  3901. [
  3902. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05],
  3903. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3904. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3905. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3906. [3.5, 28, 98, 196, -6308.6, 196, 98, 28, 3.5],
  3907. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  3908. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  3909. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  3910. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05]
  3911. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3912. </filter>
  3913. <filter id="_h5p_grey1">
  3914. <feColorMatrix values="0.3333 0.3333 0.3333 0 0
  3915. 0.3333 0.3333 0.3333 0 0
  3916. 0.3333 0.3333 0.3333 0 0
  3917. 0 0 0 1 0"/>
  3918. <feColorMatrix type="saturate" values="0" />
  3919. </filter>
  3920. </defs>
  3921. </svg>
  3922. `;
  3923.  
  3924. svgFilterElm.innerHTML = svgXML.replace(/[\r\n\s]+/g, ' ').trim();
  3925.  
  3926. rootView.appendChild(svgFilterElm);
  3927. }
  3928.  
  3929. }
  3930.  
  3931. /**
  3932. * 某些網頁用了attachShadow closed mode,需要open才能獲取video標籤,例如百度雲盤
  3933. * 解決參考:
  3934. * https://developers.google.com/web/fundamentals/web-components/shadowdom?hl=zh-cn#closed
  3935. * https://stackoverflow.com/questions/54954383/override-element-prototype-attachshadow-using-chrome-extension
  3936. */
  3937.  
  3938. const initForShadowRoot = async (shadowRoot) => {
  3939. try {
  3940. if (shadowRoot && shadowRoot.nodeType > 0 && shadowRoot.mode == 'open' && 'querySelectorAll' in shadowRoot) {
  3941. if (!shadowRoot.host.hasAttribute('_h5p_shadowroot_')) {
  3942. shadowRoot.host.setAttribute('_h5p_shadowroot_', '')
  3943.  
  3944. $hs.bindDocEvents(shadowRoot);
  3945. captureVideoEvents(shadowRoot);
  3946.  
  3947. shadowRoots.push(shadowRoot)
  3948. }
  3949. }
  3950. } catch (e) {
  3951. console.log('h5Player: initForShadowRoot failed')
  3952. }
  3953. }
  3954.  
  3955. function hackAttachShadow() { // attachShadow - DOM Standard
  3956.  
  3957. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3958. if (_prototype_ && typeof _prototype_.attachShadow == 'function') {
  3959.  
  3960. let _attachShadow = _prototype_.attachShadow
  3961.  
  3962. hackAttachShadow = null
  3963. _prototype_.attachShadow = function() {
  3964. let arg = [...arguments];
  3965. if (arg[0] && arg[0].mode) arg[0].mode = 'open';
  3966. let shadowRoot = _attachShadow.apply(this, arg);
  3967. initForShadowRoot(shadowRoot);
  3968. return shadowRoot
  3969. };
  3970.  
  3971. _prototype_.attachShadow.toString = () => _attachShadow.toString();
  3972.  
  3973. }
  3974.  
  3975. }
  3976.  
  3977. function hackCreateShadowRoot() { // createShadowRoot - Deprecated
  3978.  
  3979. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3980. if (_prototype_ && typeof _prototype_.createShadowRoot == 'function') {
  3981.  
  3982. let _createShadowRoot = _prototype_.createShadowRoot;
  3983.  
  3984. hackCreateShadowRoot = null
  3985. _prototype_.createShadowRoot = function() {
  3986. const shadowRoot = _createShadowRoot.apply(this, arguments);
  3987. initForShadowRoot(shadowRoot);
  3988. return shadowRoot;
  3989. };
  3990. _prototype_.createShadowRoot.toString = () => _createShadowRoot.toString();
  3991.  
  3992. }
  3993. }
  3994.  
  3995.  
  3996.  
  3997.  
  3998. /* 事件偵聽hack */
  3999. function hackEventListener() {
  4000. if (!window.Node) return;
  4001. const _prototype = window.Node.prototype;
  4002. let _addEventListener = _prototype.addEventListener;
  4003. let _removeEventListener = _prototype.removeEventListener;
  4004. if (typeof _addEventListener == 'function' && typeof _removeEventListener == 'function') {} else return;
  4005. hackEventListener = null;
  4006.  
  4007.  
  4008.  
  4009. let hackedEvtCount = 0;
  4010.  
  4011. const options_passive_capture = {
  4012. passive: true,
  4013. capture: true
  4014. }
  4015. const options_passive_bubble = {
  4016. passive: true,
  4017. capture: false
  4018. }
  4019.  
  4020. let phListeners = Promise.resolve();
  4021.  
  4022. let phActioners = Promise.resolve();
  4023. let phActionersCount = 0;
  4024.  
  4025.  
  4026.  
  4027. _prototype.addEventListener = function addEventListener() {
  4028. //console.log(3321,arguments[0])
  4029. const args = arguments
  4030. const type = args[0]
  4031. const listener = args[1]
  4032.  
  4033. if (!(this instanceof Node) || typeof type != 'string' || typeof listener != 'function') {
  4034. // if (!this || !(this instanceof EventTarget) || typeof type != 'string' || typeof listener != 'function') {
  4035. return _addEventListener.apply(this, args)
  4036. //unknown bug?
  4037. }
  4038.  
  4039. let bClickAction = false;
  4040. switch (type) {
  4041. case 'load':
  4042. case 'beforeunload':
  4043. case 'DOMContentLoaded':
  4044. return _addEventListener.apply(this, args);
  4045. break;
  4046. case 'touchstart':
  4047. case 'touchmove':
  4048. case 'wheel':
  4049. case 'mousewheel':
  4050. case 'timeupdate':
  4051. if ($mb.stable_isSupportPassiveEventListener()) {
  4052. if (!(args[2] && typeof args[2] == 'object')) {
  4053. const fs = (listener + "");
  4054. if (fs.indexOf('{ [native code] }') < 0 && fs.indexOf('.preventDefault()') < 0) {
  4055. //make default passive if not set
  4056. const options = args[2] === true ? options_passive_capture : options_passive_bubble
  4057. args[2] = options
  4058. if (args.length < 3) args.length = 3;
  4059. }
  4060. }
  4061. if (args[2] && args[2].passive === true) {
  4062. const nType = `__nListener|${type}__`;
  4063. const nListener = listener[nType] || function() {
  4064. let _listener = listener;
  4065. let _this = this;
  4066. let _arguments = arguments;
  4067. let calling = () => {
  4068. phActioners = phActioners.then(() => {
  4069. _listener.apply(_this, _arguments);
  4070. phActionersCount--;
  4071. _listener = null;
  4072. _this = null;
  4073. _arguments = null;
  4074. calling = null;
  4075. })
  4076. }
  4077. Promise.resolve().then(() => {
  4078. if (phActionersCount === 0) {
  4079. phActionersCount++
  4080. window.requestAnimationFrame(calling)
  4081. } else {
  4082. phActionersCount++
  4083. calling();
  4084. }
  4085. })
  4086. };
  4087. listener[nType] = nListener;
  4088. args[1] = nListener;
  4089. args[2].passive = true;
  4090. args[2] = args[2];
  4091. }
  4092. }
  4093. break;
  4094. case 'mouseout':
  4095. case 'mouseover':
  4096. case 'focusin':
  4097. case 'focusout':
  4098. case 'mouseenter':
  4099. case 'mouseleave':
  4100. case 'mousemove':
  4101. /*if (this.nodeType === 1 && this.nodeName != "BODY" && this.nodeName != "HTML") {
  4102. const nType = `__nListener|${type}__`
  4103. const nListener = listener[nType] || function() {
  4104. window.requestAnimationFrame(() => listener.apply(this, arguments))
  4105. }
  4106. listener[nType] = nListener;
  4107. args[1] = nListener;
  4108. }*/
  4109. break;
  4110. case 'click':
  4111. case 'mousedown':
  4112. case 'mouseup':
  4113. bClickAction = true;
  4114. break;
  4115. default:
  4116. return _addEventListener.apply(this, args);
  4117. }
  4118.  
  4119.  
  4120. if (bClickAction) {
  4121.  
  4122.  
  4123. let res;
  4124. res = _addEventListener.apply(this, args)
  4125.  
  4126. phListeners = phListeners.then(() => {
  4127.  
  4128. let listeners = wmListeners.get(this);
  4129. if (!listeners) wmListeners.set(this, listeners = {});
  4130.  
  4131. let lh = new ListenerHandle(args[1], args[2])
  4132.  
  4133. listeners[type] = listeners[type] || new Listeners()
  4134.  
  4135. listeners[type].add(lh)
  4136. listeners[type]._count++;
  4137.  
  4138. })
  4139.  
  4140. return res
  4141.  
  4142.  
  4143. } else if (args[2] && args[2].passive) {
  4144.  
  4145. const nType = `__nListener|${type}__`
  4146. const nListener = listener[nType] || function() {
  4147. return Promise.resolve().then(() => listener.apply(this, arguments))
  4148. }
  4149.  
  4150. listener[nType] = nListener;
  4151. args[1] = nListener;
  4152.  
  4153. }
  4154.  
  4155. return _addEventListener.apply(this, args);
  4156.  
  4157.  
  4158. }
  4159. // hack removeEventListener
  4160. _prototype.removeEventListener = function removeEventListener() {
  4161.  
  4162. let args = arguments
  4163. let type = args[0]
  4164. let listener = args[1]
  4165.  
  4166.  
  4167. if (!this || !(this instanceof Node) || typeof type != 'string' || typeof listener != 'function') {
  4168. return _removeEventListener.apply(this, args)
  4169. //unknown bug?
  4170. }
  4171.  
  4172. let bClickAction = false;
  4173. switch (type) {
  4174. case 'load':
  4175. case 'beforeunload':
  4176. case 'DOMContentLoaded':
  4177. return _removeEventListener.apply(this, args);
  4178. break;
  4179. case 'mousewheel':
  4180. case 'touchstart':
  4181. case 'wheel':
  4182. case 'timeupdate':
  4183. if ($mb.stable_isSupportPassiveEventListener()) {
  4184. if (!(args[2] && typeof args[2] == 'object')) {
  4185. const fs = (listener + "");
  4186. if (fs.indexOf('{ [native code] }') < 0 && fs.indexOf('.preventDefault()') < 0) {
  4187. //make default passive if not set
  4188. const options = args[2] === true ? options_passive_capture : options_passive_bubble
  4189. args[2] = options
  4190. if (args.length < 3) args.length = 3;
  4191. }
  4192. }
  4193. }
  4194. break;
  4195. case 'mouseout':
  4196. case 'mouseover':
  4197. case 'focusin':
  4198. case 'focusout':
  4199. case 'mouseenter':
  4200. case 'mouseleave':
  4201. case 'mousemove':
  4202.  
  4203. break;
  4204. case 'click':
  4205. case 'mousedown':
  4206. case 'mouseup':
  4207. bClickAction = true;
  4208. break;
  4209. default:
  4210. return _removeEventListener.apply(this, args);
  4211. }
  4212.  
  4213. if (bClickAction) {
  4214.  
  4215.  
  4216. phListeners = phListeners.then(() => {
  4217. const listeners = wmListeners.get(this);
  4218. if (listeners) {
  4219. const lh_removal = new ListenerHandle(args[1], args[2])
  4220.  
  4221. listeners[type].remove(lh_removal)
  4222. }
  4223. })
  4224. return _removeEventListener.apply(this, args);
  4225.  
  4226.  
  4227. } else {
  4228. const nType = `__nListener|${type}__`
  4229. if (typeof listener[nType] == 'function') args[1] = listener[nType]
  4230. return _removeEventListener.apply(this, args);
  4231. }
  4232.  
  4233.  
  4234.  
  4235.  
  4236. }
  4237. _prototype.addEventListener.toString = () => _addEventListener.toString();
  4238. _prototype.removeEventListener.toString = () => _removeEventListener.toString();
  4239.  
  4240.  
  4241. }
  4242.  
  4243.  
  4244. function initShadowRoots(rootDoc) {
  4245. function onReady() {
  4246. var treeWalker = rootDoc.createTreeWalker(
  4247. rootDoc.documentElement,
  4248. NodeFilter.SHOW_ELEMENT, {
  4249. acceptNode: (node) => (node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
  4250. }
  4251. );
  4252. var nodeList = [];
  4253. while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
  4254. for (const node of nodeList) {
  4255. initForShadowRoot(node.shadowRoot)
  4256. }
  4257. }
  4258. if (rootDoc.readyState !== 'loading') {
  4259. onReady();
  4260. } else {
  4261. rootDoc.addEventListener('DOMContentLoaded', onReady, false);
  4262. }
  4263. }
  4264.  
  4265. function captureVideoEvents(rootDoc) {
  4266.  
  4267. var g = function(evt) {
  4268.  
  4269.  
  4270. var domElement = evt.target || this || null
  4271. if (domElement && domElement.nodeType == 1 && domElement.nodeName == "VIDEO") {
  4272. var video = domElement
  4273. if (!domElement.getAttribute('_h5ppid')) handlerVideoFound(video);
  4274. if (domElement.getAttribute('_h5ppid')) {
  4275. switch (evt.type) {
  4276. case 'loadedmetadata':
  4277. return $hs.handlerVideoLoadedMetaData.call(video, evt);
  4278. // case 'playing':
  4279. // return $hs.handlerVideoPlaying.call(video, evt);
  4280. // case 'pause':
  4281. // return $hs.handlerVideoPause.call(video, evt);
  4282. // case 'volumechange':
  4283. // return $hs.handlerVideoVolumeChange.call(video, evt);
  4284. }
  4285. }
  4286. }
  4287.  
  4288.  
  4289. }
  4290.  
  4291. // using capture phase
  4292. rootDoc.addEventListener('loadedmetadata', g, $mb.eh_capture_passive());
  4293.  
  4294. }
  4295.  
  4296. function handlerVideoFound(video) {
  4297.  
  4298. if (!video) return;
  4299. if (video.getAttribute('_h5ppid')) return;
  4300.  
  4301. const toSkip = (() => {
  4302. //skip GIF video
  4303. let alabel = video.getAttribute('aria-label')
  4304. if (alabel && typeof alabel == "string" && alabel.toUpperCase() == "GIF") return true;
  4305.  
  4306. //skip video with opacity
  4307. const videoOpacity = video.style.opacity + ''
  4308. if (videoOpacity.length > 0 && +videoOpacity < 0.99 && +videoOpacity >= 0) return true;
  4309.  
  4310. //Google Result Video Preview
  4311. let pElm = video;
  4312. while (pElm && pElm.nodeType == 1) {
  4313. if (pElm.nodeName == "A" && pElm.getAttribute('href')) return true;
  4314. pElm = pElm.parentNode
  4315. }
  4316. pElm = null;
  4317. })();
  4318.  
  4319. if (toSkip) return;
  4320.  
  4321. consoleLog('handlerVideoFound', video)
  4322.  
  4323. $hs.intVideoInitCount = ($hs.intVideoInitCount || 0) + 1;
  4324. let vpid = 'h5p-' + $hs.intVideoInitCount
  4325. consoleLog(' - HTML5 Video is detected -', `Number of Videos: ${$hs.intVideoInitCount}`)
  4326. if ($hs.intVideoInitCount === 1) $hs.fireGlobalInit();
  4327. video.setAttribute('_h5ppid', vpid)
  4328.  
  4329.  
  4330. playerConfs[vpid] = new PlayerConf();
  4331. playerConfs[vpid].domElement = video;
  4332. playerConfs[vpid].domActive = DOM_ACTIVE_FOUND;
  4333.  
  4334. let rootNode = getRoot(video);
  4335.  
  4336. if (rootNode.host) $hs.getPlayerBlockElement(video); // shadowing
  4337. let rootElm = domAppender(rootNode) || document.documentElement //48763
  4338. _add_filter(rootElm) // either main document or shadow node
  4339.  
  4340.  
  4341.  
  4342. video.addEventListener('playing', $hs.handlerVideoPlaying, $mb.eh_capture_passive());
  4343. video.addEventListener('pause', $hs.handlerVideoPause, $mb.eh_capture_passive());
  4344. video.addEventListener('volumechange', $hs.handlerVideoVolumeChange, $mb.eh_capture_passive());
  4345.  
  4346.  
  4347.  
  4348. //observe not fire twice for the same element.
  4349. if (!$hs.observer_cacheSizing) $hs.observer_cacheSizing = new ResizeObserver($hs.handlerSizing);
  4350. $hs.observer_cacheSizing.observe(video)
  4351.  
  4352.  
  4353.  
  4354. }
  4355.  
  4356.  
  4357. hackAttachShadow()
  4358. hackCreateShadowRoot()
  4359. hackEventListener()
  4360.  
  4361.  
  4362. window.addEventListener('message', $hs.handlerWinMessage, false);
  4363. $hs.bindDocEvents(document);
  4364. captureVideoEvents(document);
  4365. initShadowRoots(document);
  4366.  
  4367.  
  4368. let windowsLD = (function() {
  4369. let ls_res = [];
  4370. try {
  4371. ls_res = [!!window.localStorage, !!window.top.localStorage];
  4372. } catch (e) {}
  4373. try {
  4374. let winp = window;
  4375. let winc = 0;
  4376. while (winp !== window.top && winp && ++winc) winp = winp.parentNode;
  4377. ls_res.push(winc);
  4378. } catch (e) {}
  4379. return ls_res;
  4380. })();
  4381.  
  4382. consoleLogF('- h5Player Plugin Loaded -', ...windowsLD)
  4383.  
  4384. function isInCrossOriginFrame() {
  4385. let result = true;
  4386. try {
  4387. if (window.top.localStorage || window.top.location.href) result = false;
  4388. } catch (e) {}
  4389. return result
  4390. }
  4391.  
  4392. if (isInCrossOriginFrame()) consoleLog('cross origin frame detected');
  4393.  
  4394.  
  4395. const $bv = {
  4396.  
  4397. boostVideoPerformanceActivate: function() {
  4398. if ($bz.boosted) return;
  4399. $bz.boosted = true;
  4400. },
  4401.  
  4402.  
  4403. boostVideoPerformanceDeactivate: function() {
  4404. if (!$bz.boosted) return;
  4405. $bz.boosted = false;
  4406. }
  4407.  
  4408. }
  4409.  
  4410.  
  4411.  
  4412. })();
  4413.  
  4414. })(window.unsafeWindow, window);