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