HTML5 Video Player Enhance

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

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

  1. // ==UserScript==
  2. // @name HTML5 Video Player Enhance
  3. // @version 2.9.1a6
  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. // @match http://*/*
  7. // @match https://*/*
  8. // @run-at document-start
  9. // @require https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js
  10. // @require https://cdnjs.cloudflare.com/ajax/libs/mathjs/9.3.2/math.js
  11. // @namespace https://greasyfork.org/users/371179
  12. // @grant GM_getValue
  13. // @grant GM_setValue
  14. // ==/UserScript==
  15.  
  16.  
  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 $$() {
  25. 'use strict';
  26.  
  27. if (!document || !document.documentElement) return window.requestAnimationFrame($$);
  28.  
  29. let _debug_h5p_logging_ = false;
  30.  
  31. try {
  32. _debug_h5p_logging_ = +window.localStorage.getItem('_h5_player_sLogging_') > 0
  33. } catch (e) {}
  34.  
  35.  
  36.  
  37. const SHIFT = 1;
  38. const CTRL = 2;
  39. const ALT = 4;
  40. const TERMINATE = 0x842;
  41. const _sVersion_ = 1817;
  42. const str_postMsgData = '__postMsgData__'
  43. const DOM_ACTIVE_FOUND = 1;
  44. const DOM_ACTIVE_SRC_LOADED = 2;
  45. const DOM_ACTIVE_ONCE_PLAYED = 4;
  46. const DOM_ACTIVE_MOUSE_CLICK = 8;
  47. const DOM_ACTIVE_MOUSE_IN = 16;
  48. const DOM_ACTIVE_DELAYED_PAUSED = 32;
  49. const DOM_ACTIVE_INVALID_PARENT = 2048;
  50.  
  51.  
  52. let _endlessloop = null;
  53. const isIframe = (window.top !== window.self && window.top && window.self);
  54. const shadowRoots = [];
  55.  
  56. const getRoot = (elm) => elm.getRootNode instanceof Function ? elm.getRootNode() : (elm.ownerDocument || null);
  57.  
  58. const isShadowRoot = (elm) => (elm && ('host' in elm)) ? elm.nodeType == 11 && !!elm.host && elm.host.nodeType == 1 : null; //instanceof ShadowRoot
  59.  
  60. const timeupdateStore = []
  61. document.__h5p_boost_timeupdate_count = 0;
  62.  
  63. const playerConfs = {}
  64.  
  65. const $ws = {
  66. requestAnimationFrame,
  67. cancelAnimationFrame,
  68. MutationObserver
  69. }
  70. //throw Error if your browser is too outdated. (eg ES6 script, no such window object)
  71.  
  72. Element.prototype.__matches__ = (Element.prototype.matches || Element.prototype.matchesSelector ||
  73. Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector ||
  74. Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector ||
  75. Element.prototype.matches()); // throw Error if not supported
  76.  
  77.  
  78. Element.prototype.__requestPointerLock__ = (Element.prototype.requestPointerLock ||
  79. Element.prototype.mozRequestPointerLock || Element.prototype.webkitRequestPointerLock || function() {});
  80.  
  81. // Ask the browser to release the pointer
  82. Document.prototype.__exitPointerLock__ = (Document.prototype.exitPointerLock ||
  83. Document.prototype.mozExitPointerLock || Document.prototype.webkitExitPointerLock || function() {});
  84.  
  85.  
  86. function isSupportAdvancedEventListener() {
  87. if ('_b1750' in $$) return $$._b1750
  88. let prop = 0;
  89. document.createAttribute('z').addEventListener('', null, {
  90. get passive() {
  91. prop++;
  92. },
  93. get once() {
  94. prop++;
  95. }
  96. });
  97. return ($$._b1750 = prop == 2);
  98. }
  99.  
  100. // built-in hash - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
  101. async function digestMessage(message) {
  102. return window.sha256(message)
  103. }
  104.  
  105. const dround = (x) => ~~(x + .5);
  106.  
  107. const jsonStringify_replacer = function(key, val) {
  108. if (val && (val instanceof Element || val instanceof Document)) return val.toString();
  109. return val; // return as is
  110. };
  111.  
  112. const jsonParse = function() {
  113. try {
  114. return JSON.parse.apply(this, arguments)
  115. } catch (e) {}
  116. return null;
  117. }
  118. const jsonStringify = function(obj) {
  119. try {
  120. return JSON.stringify.call(this, obj, jsonStringify_replacer)
  121. } catch (e) {}
  122. return null;
  123. }
  124.  
  125. function _postMsg() {
  126. //async is needed. or error handling for postMessage
  127. const [win, tag, ...data] = arguments;
  128. if (typeof tag == 'string') {
  129. let postMsgObj = {
  130. tag,
  131. passing: true,
  132. winOrder: _postMsg.a
  133. }
  134. try {
  135. let k = 'msg-' + (+new Date)
  136. win.document[str_postMsgData] = win.document[str_postMsgData] || {}
  137. win.document[str_postMsgData][k] = data; //direct
  138. postMsgObj.str = k;
  139. postMsgObj.stype = 1;
  140. } catch (e) {}
  141. if (!postMsgObj.stype) {
  142. postMsgObj.str = jsonStringify({
  143. d: data
  144. })
  145. if (postMsgObj.str && postMsgObj.str.length) postMsgObj.stype = 2;
  146. }
  147. if (!postMsgObj.stype) {
  148. postMsgObj.str = "" + data;
  149. postMsgObj.stype = 0;
  150. }
  151. win.postMessage(postMsgObj, '*');
  152. }
  153.  
  154. }
  155.  
  156. function postMsg() {
  157. let win = window;
  158. let a = 0;
  159. while (win = win.parent) {
  160. _postMsg.a = ++a;
  161. _postMsg(win, ...arguments)
  162. if (win == top) break;
  163. }
  164. }
  165.  
  166.  
  167. function crossBrowserTransition(type) {
  168. if (crossBrowserTransition['_result_' + type]) return crossBrowserTransition['_result_' + type]
  169. let el = document.createElement("fakeelement");
  170.  
  171. const capital = (x) => x[0].toUpperCase() + x.substr(1);
  172. const capitalType = capital(type);
  173.  
  174. const transitions = {
  175. [type]: `${type}end`,
  176. [`O${capitalType}`]: `o${capitalType}End`,
  177. [`Moz${capitalType}`]: `${type}end`,
  178. [`Webkit${capitalType}`]: `webkit${capitalType}End`,
  179. [`MS${capitalType}`]: `MS${capitalType}End`
  180. }
  181.  
  182. for (let styleProp in transitions) {
  183. if (el.style[styleProp] !== undefined) {
  184. return (crossBrowserTransition['_result_' + type] = transitions[styleProp]);
  185. }
  186. }
  187. }
  188.  
  189. function isInOperation(elm) {
  190. let elmInFocus = elm || document.activeElement;
  191. if (!elmInFocus) return false;
  192. let res1 = elmInFocus.__matches__(
  193. 'a[href],link[href],button,input:not([type="hidden"]),select,textarea,iframe,frame,menuitem,[draggable],[contenteditable]'
  194. );
  195. return res1;
  196. }
  197.  
  198. const fn_toString = (f, n = 50) => {
  199. let s = (f + "");
  200. if (s.length > 2 * n + 5) {
  201. s = s.substr(0, n) + ' ... ' + s.substr(-n);
  202. }
  203. return s
  204. };
  205.  
  206. function consoleLog() {
  207. if (!_debug_h5p_logging_) return;
  208. if (isIframe) postMsg('consoleLog', ...arguments);
  209. else console.log.apply(console, arguments);
  210. }
  211.  
  212. function consoleLogF() {
  213. if (isIframe) postMsg('consoleLog', ...arguments);
  214. else console.log.apply(console, arguments);
  215. }
  216.  
  217. class ResizeODM {
  218. static __init__() {
  219. this.__resizerCount__ = 0;
  220. this.__resizeListeners__ = {};
  221. }
  222. constructor() {
  223. let rm = this;
  224. ResizeODM.__resizerCount__++;
  225. let rpid = "rpid-" + ResizeODM.__resizerCount__;
  226. ResizeODM.__resizeListeners__[rpid] = [];
  227.  
  228. rm._resizer_listeners = ResizeODM.__resizeListeners__[rpid];
  229.  
  230. let odm = document.createElement('object');
  231. odm.setAttribute('_resizer_odm_', rpid);
  232. odm.setAttribute('style', 'display: block; position: absolute; top: -300vh; left: -300vw; height: 100%; width: 100%; overflow: hidden; pointer-events: none; z-index: -1;');
  233. odm.onload = ResizeODM.objectLoad;
  234. odm.type = 'text/html';
  235. odm.data = 'about:blank';
  236. rm.odm = odm;
  237. rm.rpid = rpid;
  238. rm.odm.__rm__ = rm;
  239. }
  240.  
  241. static find(rsElm) {
  242. if (!rsElm) return null;
  243. let odm = [...rsElm.querySelectorAll('object[_resizer_odm_]')].filter(elm => elm.parentNode == rsElm)[0];
  244. if (!odm) return null;
  245.  
  246. return odm.__rm__ || null;
  247.  
  248. }
  249.  
  250. static resizeListener(e) {
  251. let odv = e.target || e.srcElement;
  252. let rm = odv._resizer_rm;
  253. if (rm.__resizeRAF__) $ws.cancelAnimationFrame(rm.__resizeRAF__);
  254. rm.__resizeRAF__ = $ws.requestAnimationFrame(function() {
  255. rm.__resizeRAF__ = 0;
  256. for (const fn of rm._resizer_listeners) fn.call(rm, e);
  257. });
  258. }
  259.  
  260. static objectLoad(e) {
  261. let odm = this;
  262. let rm = odm.__rm__;
  263. let odv = odm.contentDocument.defaultView
  264. odv._resizer_rm = rm;
  265. rm.odv = odv;
  266. odv.onresize = ResizeODM.resizeListener;
  267. }
  268.  
  269. resizeElement() {
  270. return this.odm.parentNode;
  271. }
  272.  
  273. // ResizeODM.relativeParent(rsElm);
  274.  
  275. relativeParent(rsElm, existingnode = null) {
  276. let odm = this.odm;
  277. rsElm = rsElm || odm.parentNode;
  278. let rpid = this.rpid;
  279. //if (getComputedStyle(rsElm).position == 'static') rsElm.style.position = 'relative';
  280. rsElm.insertBefore(odm, existingnode);
  281. }
  282.  
  283. listen(fn) {
  284. this._resizer_listeners.push(fn);
  285. }
  286.  
  287. unlisten(fn) {
  288. this._resizer_listeners.splice(this._resizer_listeners.indexOf(fn), 1);
  289. }
  290.  
  291. remove() {
  292. this._resizer_listeners.length = 0;
  293. this.odv.onresize = null;
  294. this.odm.onload = null;
  295. }
  296.  
  297. }
  298.  
  299. class AFLooperArray extends Array {
  300. constructor() {
  301. super();
  302. this.activeLoopsCount = 0;
  303. this.cid = 0;
  304. this.loopingFrame = this.loopingFrame.bind(this);
  305. }
  306.  
  307. loopingFrame() {
  308. if (!this.cid) return; //cancelled
  309. for (const opt of this) {
  310. if (opt.isFunctionLooping) opt.fn(opt);
  311. }
  312. this.cid = $ws.requestAnimationFrame(this.loopingFrame);
  313. }
  314.  
  315. get isArrayLooping() {
  316. return this.cid > 0;
  317. }
  318.  
  319. loopStart() {
  320. this.cid = $ws.requestAnimationFrame(this.loopingFrame);
  321. }
  322. loopStop() {
  323. if (this.cid) $ws.cancelAnimationFrame(this.cid);
  324. this.cid = 0;
  325. }
  326. appendLoop(fn) {
  327. if (typeof fn != 'function' || !this) return;
  328. const opt = new AFLooperFunc(fn, this);
  329. super.push(opt);
  330. return opt;
  331. }
  332. }
  333.  
  334. class AFLooperFunc {
  335. constructor(fn, bind) {
  336. this._looping = false;
  337. this.fn = fn;
  338. this.bind = bind;
  339. }
  340. get isFunctionLooping() {
  341. return this._looping;
  342. }
  343. loopingStart() {
  344. if (this._looping === false) {
  345. this._looping = true;
  346. if (++this.bind.activeLoopsCount == 1) this.bind.loopStart();
  347. }
  348. }
  349. loopingStop() {
  350. if (this._looping === true) {
  351. this._looping = false;
  352. if (--this.bind.activeLoopsCount == 0) this.bind.loopStop();
  353. }
  354. }
  355. }
  356.  
  357. function decimalEqual(a, b) {
  358. return Math.round(a * 100000000) == Math.round(b * 100000000)
  359. }
  360.  
  361. function nonZeroNum(a) {
  362. return a > 0 || a < 0;
  363. }
  364.  
  365. class PlayerConf {
  366.  
  367. get scaleFactor() {
  368. return this.mFactor * this.vFactor;
  369. }
  370.  
  371. cssTransform() {
  372.  
  373. const playerConf = this;
  374. const player = playerConf.domElement;
  375. if (!player) return;
  376. const videoScale = playerConf.scaleFactor;
  377. let {x,y}=playerConf.translate;
  378.  
  379. let [_x,_y]=((playerConf.rotate % 180) == 90)?[y,x]:[x,y];
  380.  
  381. if((playerConf.rotate % 360) == 270)_x = -_x;
  382. if((playerConf.rotate % 360) == 90)_y = -_y;
  383.  
  384. var s = [
  385. playerConf.rotate > 0 ? 'rotate(' + playerConf.rotate + 'deg)' : '',
  386. !decimalEqual(videoScale, 1.0) ? 'scale(' + videoScale + ')' : '',
  387. (nonZeroNum(_x) || nonZeroNum(_y)) ? `translate(${_x}px, ${_y}px)` : '',
  388. ];
  389.  
  390. player.style.transform = s.join(' ').trim()
  391.  
  392. }
  393.  
  394. constructor() {
  395.  
  396. this.translate = {
  397. x: 0,
  398. y: 0
  399. };
  400. this.rotate = 0;
  401. this.mFactor = 1.0;
  402. this.vFactor = 1.0;
  403. this.fps = 30;
  404. this.filter_key = {};
  405. this.filter_view_units = {
  406. 'hue-rotate': 'deg',
  407. 'blur': 'px'
  408. };
  409. this.filterReset();
  410.  
  411. }
  412.  
  413. setFilter(prop, f) {
  414.  
  415. let oldValue = this.filter_key[prop];
  416. if (typeof oldValue != 'number') return;
  417. let newValue = f(oldValue)
  418. if (oldValue != newValue) {
  419.  
  420. newValue = +newValue.toFixed(6); //javascript bug
  421.  
  422. }
  423.  
  424. this.filter_key[prop] = newValue
  425. this.filterSetup();
  426.  
  427. return newValue;
  428.  
  429.  
  430.  
  431. }
  432.  
  433. filterSetup(options) {
  434.  
  435. let ums = GM_getValue("unsharpen_mask")
  436. if (!ums) ums = ""
  437.  
  438. let view = ''
  439. let playerElm = $hs.player();
  440. if (!playerElm) return;
  441. for (let view_key in this.filter_key) {
  442. let filter_value = +((+this.filter_key[view_key] || 0).toFixed(3))
  443. let view_unit = this.filter_view_units[view_key] || ''
  444. view += `${view_key}(${filter_value}${view_unit}) `
  445. this.filter_key[view_key] = Number(+this.filter_key[view_key] || 0)
  446. }
  447. if (ums) view += `url("#_h5p_${ums}")`;
  448. if (options && options.grey) view += ' url("#grey1")';
  449. playerElm.style.filter = view; //performance in firefox is bad
  450. }
  451.  
  452. filterReset() {
  453. this.filter_key['brightness'] = 1.0
  454. this.filter_key['contrast'] = 1.0
  455. this.filter_key['saturate'] = 1.0
  456. this.filter_key['hue-rotate'] = 0.0
  457. this.filter_key['blur'] = 0.0
  458. this.filterSetup()
  459. }
  460.  
  461. }
  462.  
  463. class VideoListener {
  464.  
  465. constructor(shadowRoot) {
  466.  
  467. this.usable = false;
  468. this.observer = null;
  469. this.cid_delayed = 0;
  470.  
  471. this.rootElement = shadowRoot || window.document;
  472. if (this.rootElement && !this.rootElement.__videoListenerEnabled__) {
  473. this.rootElement.__videoListenerEnabled__ = true;
  474. this.usable = true;
  475. }
  476. }
  477.  
  478. listen(fn) {
  479. if (!this.usable) return;
  480. this.checkRoot = async (_, shadowRoot) => {
  481. shadowRoot = shadowRoot || this.rootElement;
  482. const videos = shadowRoot.querySelectorAll('VIDEO'); //shadowRoot don't have getElementsByTagName
  483. for (const video of videos) {
  484. if (!video._onceMutationReady) {
  485. video._onceMutationReady = true;
  486. fn(video); // single function
  487. }
  488. }
  489. };
  490. this.init_observer();
  491. this.checkOnce();
  492. this.checkRoot();
  493. }
  494. init_observer() {
  495. if (this.observer) return;
  496. this.mutationObserverCallback = this.mutationObserverCallback.bind(this);
  497. this.observer = new $ws.MutationObserver(this.mutationObserverCallback);
  498. this.observer.observe(this.rootElement, {
  499. childList: true,
  500. subtree: true
  501. })
  502. }
  503. mutationObserverCallback(mutationsList, observer) {
  504. for (const mutation of mutationsList) {
  505. for (const addedNode of mutation.addedNodes) {
  506. if (addedNode.nodeName == 'VIDEO' || addedNode.childElementCount > 0) {
  507. if (this.cid_delayed) $ws.cancelAnimationFrame(this.cid_delayed);
  508. this.cid_delayed = $ws.requestAnimationFrame(this.checkRoot);
  509. return;
  510. }
  511. }
  512. }
  513. }
  514.  
  515. async checkOnce() {
  516. let treeWalker = document.createTreeWalker(
  517. document.documentElement,
  518. NodeFilter.SHOW_ELEMENT, {
  519. acceptNode: (node) => (node.shadowRoot ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP)
  520. }
  521. );
  522. let nodeList = [];
  523. while (treeWalker.nextNode()) nodeList.push(treeWalker.currentNode);
  524. for (const node of nodeList) this.checkRoot(null, node.shadowRoot);
  525. }
  526.  
  527.  
  528. }
  529.  
  530. const Store = {
  531. prefix: '_h5_player',
  532. save: function(k, v) {
  533. if (!Store.available()) return false;
  534. if (typeof v != 'string') return false;
  535. Store.LS.setItem(Store.prefix + k, v)
  536. let sk = fn_toString(k + "", 30);
  537. let sv = fn_toString(v + "", 30);
  538. consoleLog(`localStorage Saved "${sk}" = "${sv}"`)
  539. return true;
  540.  
  541. },
  542. read: function(k) {
  543. if (!Store.available()) return false;
  544. let v = Store.LS.getItem(Store.prefix + k)
  545. let sk = fn_toString(k + "", 30);
  546. let sv = fn_toString(v + "", 30);
  547. consoleLog(`localStorage Read "${sk}" = "${sv}"`);
  548. return v;
  549.  
  550. },
  551. remove: function(k) {
  552.  
  553. if (!Store.available()) return false;
  554. Store.LS.removeItem(Store.prefix + k)
  555. let sk = fn_toString(k + "", 30);
  556. consoleLog(`localStorage Removed "${sk}"`)
  557. return true;
  558. },
  559. clearInvalid: function(sVersion) {
  560. if (!Store.available()) return false;
  561.  
  562. //let sVersion=1814;
  563. if (+Store.read('_sVersion_') < sVersion) {
  564. Store._keys()
  565. .filter(s => s.indexOf(Store.prefix) === 0)
  566. .forEach(key => window.localStorage.removeItem(key))
  567. Store.save('_sVersion_', sVersion + '')
  568. return 2;
  569. }
  570. return 1;
  571.  
  572. },
  573. available: function() {
  574. if (Store.LS) return true;
  575. if (!window) return false;
  576. const localStorage = window.localStorage;
  577. if (!localStorage) return false;
  578. if (typeof localStorage != 'object') return false;
  579. if (!('getItem' in localStorage)) return false;
  580. if (!('setItem' in localStorage)) return false;
  581. Store.LS = localStorage;
  582. return true;
  583.  
  584. },
  585. _keys: function() {
  586. return Object.keys(localStorage);
  587. },
  588. _setItem: function(key, value) {
  589. return localStorage.setItem(key, value)
  590. },
  591. _getItem: function(key) {
  592. return localStorage.getItem(key)
  593. },
  594. _removeItem: function(key) {
  595. return localStorage.removeItem(key)
  596. }
  597.  
  598. }
  599.  
  600. const domTool = {
  601. nopx: (x) => +x.replace('px', ''),
  602. cssWH: function(m, r) {
  603. if (!r) r = getComputedStyle(m, null);
  604. let c = (x) => +x.replace('px', '');
  605. return {
  606. w: m.offsetWidth || c(r.width),
  607. h: m.offsetHeight || c(r.height)
  608. }
  609. },
  610. _isActionBox_1: function(vEl, pEl) {
  611.  
  612. let vElCSS = domTool.cssWH(vEl);
  613. let vElCSSw = vElCSS.w;
  614. let vElCSSh = vElCSS.h;
  615.  
  616. let vElx = vEl;
  617. let res = [];
  618. let mLevel = 0;
  619. if (vEl && pEl && vEl != pEl && pEl.contains(vEl)) {
  620. while (vElx && vElx != pEl) {
  621. vElx = vElx.parentNode;
  622. let vElx_css = null;
  623. if (isShadowRoot(vElx)) {} else {
  624. vElx_css = getComputedStyle(vElx, null);
  625. let vElx_wp = domTool.nopx(vElx_css.paddingLeft) + domTool.nopx(vElx_css.paddingRight)
  626. vElCSSw += vElx_wp
  627. let vElx_hp = domTool.nopx(vElx_css.paddingTop) + domTool.nopx(vElx_css.paddingBottom)
  628. vElCSSh += vElx_hp
  629. }
  630. res.push({
  631. level: ++mLevel,
  632. padW: vElCSSw,
  633. padH: vElCSSh,
  634. elm: vElx,
  635. css: vElx_css
  636. })
  637.  
  638. }
  639. }
  640.  
  641. // in the array, each item is the parent of video player
  642. res.vEl_cssWH = vElCSS
  643.  
  644. return res;
  645.  
  646. },
  647. _isActionBox: function(vEl, walkRes, pEl_idx) {
  648.  
  649. function absDiff(w1, w2, h1, h2) {
  650. let w = (w1 - w2),
  651. h = h1 - h2;
  652. return [(w > 0 ? w : -w), (h > 0 ? h : -h)]
  653. }
  654.  
  655. function midPoint(rect) {
  656. return {
  657. x: (rect.left + rect.right) / 2,
  658. y: (rect.top + rect.bottom) / 2
  659. }
  660. }
  661.  
  662. let parentCount = walkRes.length;
  663. if (pEl_idx >= 0 && pEl_idx < parentCount) {} else {
  664. return;
  665. }
  666. let pElr = walkRes[pEl_idx]
  667. if (!pElr.css) {
  668. //shadowRoot
  669. return true;
  670. }
  671.  
  672. let pEl = pElr.elm;
  673.  
  674. //prevent activeElement==body
  675. let pElCSS = domTool.cssWH(pEl, pElr.css);
  676.  
  677. //check prediction of parent dimension
  678. let d1v = absDiff(pElCSS.w, pElr.padW, pElCSS.h, pElr.padH)
  679.  
  680. let d1x = d1v[0] < 10
  681. let d1y = d1v[1] < 10;
  682.  
  683. if (d1x && d1y) return true; //both edge along the container - fit size
  684. if (!d1x && !d1y) return false; //no edge along the container - body contain the video element, fixed width&height
  685.  
  686. //case: youtube video fullscreen
  687.  
  688. //check centre point
  689.  
  690. let pEl_rect = pEl.getBoundingClientRect()
  691. let vEl_rect = vEl.getBoundingClientRect()
  692.  
  693. let pEl_center = midPoint(pEl_rect)
  694. let vEl_center = midPoint(vEl_rect)
  695.  
  696. let d2v = absDiff(pEl_center.x, vEl_center.x, pEl_center.y, vEl_center.y);
  697.  
  698. let d2x = d2v[0] < 10;
  699. let d2y = d2v[1] < 10;
  700.  
  701. return (d2x && d2y);
  702.  
  703. },
  704. getRect: function(element) {
  705. let rect = element.getBoundingClientRect();
  706. let scroll = domTool.getScroll();
  707. return {
  708. pageX: rect.left + scroll.left,
  709. pageY: rect.top + scroll.top,
  710. screenX: rect.left,
  711. screenY: rect.top
  712. };
  713. },
  714. getScroll: function() {
  715. return {
  716. left: document.documentElement.scrollLeft || document.body.scrollLeft,
  717. top: document.documentElement.scrollTop || document.body.scrollTop
  718. };
  719. },
  720. getClient: function() {
  721. return {
  722. width: document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth,
  723. height: document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight
  724. };
  725. },
  726. addStyle: //GM_addStyle,
  727. function(css, head) {
  728. if (!head) {
  729. let _doc = document.documentElement;
  730. head = _doc.querySelector('head') || _doc.querySelector('html') || _doc;
  731. }
  732. let doc = head.ownerDocument;
  733. let style = doc.createElement('style');
  734. style.type = 'text/css';
  735. let node = doc.createTextNode(css);
  736. style.appendChild(node);
  737. head.appendChild(style);
  738. //console.log(document.head,style,'add style')
  739. return style;
  740. },
  741. eachParentNode: function(dom, fn) {
  742. let parent = dom.parentNode
  743. while (parent) {
  744. let isEnd = fn(parent, dom)
  745. parent = parent.parentNode
  746. if (isEnd) {
  747. break
  748. }
  749. }
  750. },
  751.  
  752. hideDom: function hideDom(selector) {
  753. let dom = document.querySelector(selector)
  754. if (dom) {
  755. $ws.requestAnimationFrame(function() {
  756. dom.style.opacity = 0;
  757. dom.style.transform = 'translate(-9999px)';
  758. dom = null;
  759. })
  760. }
  761. }
  762. };
  763.  
  764. const handle = {
  765.  
  766. afTipsDOM: async function(opts) {
  767.  
  768. let tipsDoms = $hs._cached_tipsDoms;
  769.  
  770. if (!tipsDoms || !tipsDoms.length) return;
  771. for (const tipsDom of tipsDoms) {
  772.  
  773. let wPlayer = tipsDom._playerBlockElm;
  774. if (wPlayer == null) {
  775. $hs.cacheTipsDoms();
  776. return;
  777. }
  778. let layoutBox = wPlayer.parentNode;
  779. if (layoutBox == null) { //i.e. removed
  780. playerConfs[tipsDom._playerVPID].domActive |= DOM_ACTIVE_INVALID_PARENT;
  781. $hs.cacheTipsDoms();
  782. return;
  783. }
  784. let p = [layoutBox.offsetWidth, layoutBox.offsetHeight, wPlayer.offsetWidth, wPlayer.offsetHeight];
  785.  
  786. if (tipsDom._cached_dimensions) {
  787. let changed = false;
  788. for (let i in p) {
  789. if (tipsDom._cached_dimensions[i] != p[i]) {
  790. changed = true;
  791. break;
  792. }
  793. }
  794. if (!changed) return;
  795. tipsDom._env_changed = (tipsDom._env_changed || 0) + 1;
  796. consoleLog('tipsDom Env changed', tipsDom.id)
  797. }
  798.  
  799. tipsDom._cached_dimensions = p;
  800.  
  801. if (!tipsDom.id) return;
  802. let player = layoutBox.querySelector(`[_h5player_tips="${tipsDom.id}"]`)
  803. if (!player) return;
  804.  
  805. $hs.fixNonBoxingVideoTipsPosition(tipsDom, player)
  806.  
  807. }
  808.  
  809. },
  810.  
  811. afBoostTimeUpdate: async function(opts) {
  812.  
  813.  
  814. let tupConf = timeupdateStore.currentPlayingConf
  815. if (!tupConf) return;
  816. let video = tupConf.videoElement;
  817. let time = video.currentTime;
  818. let fakeTimeUpdateEvent = tupConf.fakeTimeUpdateEvent[0];
  819. if (time !== tupConf.lastTime && fakeTimeUpdateEvent) {
  820. tupConf.lastTime = time;
  821. for (const fn of tupConf.eventHandlersRunner) {
  822. try {
  823. fn.apply(video, fakeTimeUpdateEvent)
  824. } catch (e) {}
  825. }
  826. //document.__h5p_boost_timeupdate_vtid=timeupdateStore.currentPlayingConf
  827. document.__h5p_boost_timeupdate_count = (document.__h5p_boost_timeupdate_count + 1) % 100000000;
  828. }
  829. },
  830. afPlaybackRecording: async function(opts) {
  831.  
  832. let qTime = +new Date;
  833. if (qTime >= opts.pTime) {
  834. opts.pTime = qTime + opts.timeDelta; //prediction of next Interval
  835. opts.savePlaybackProgress()
  836. }
  837.  
  838. },
  839. savePlaybackProgress: function() {
  840.  
  841. //this refer to endless's opts
  842. let player = this.player;
  843.  
  844. let _uid = this.player_uid; //_h5p_uid_encrypted
  845. if (!_uid) return;
  846.  
  847. let shallSave = true;
  848. let currentTimeToSave = ~~player.currentTime;
  849.  
  850. if (this._lastSave == currentTimeToSave) shallSave = false;
  851.  
  852. if (shallSave) {
  853.  
  854. this._lastSave = currentTimeToSave
  855.  
  856. //console.log('aasas',this.player_uid, shallSave, '_play_progress_'+_uid, currentTimeToSave)
  857.  
  858. Store.save('_play_progress_' + _uid, jsonStringify({
  859. 't': currentTimeToSave
  860. }))
  861.  
  862. }
  863.  
  864. },
  865. pr_updateUID: function() {
  866.  
  867. //this refer to endless's opts
  868.  
  869. let player = this.player;
  870.  
  871. let _uid = player.getAttribute('_h5p_uid_encrypted') || ''
  872. if (!_uid) return false;
  873. this.player_uid = _uid;
  874.  
  875. return true;
  876.  
  877. },
  878.  
  879. };
  880.  
  881. class Momentary extends Map {
  882. act(uniqueId, fn_start, fn_end, delay) {
  883. if (!uniqueId) return;
  884. uniqueId = uniqueId + "";
  885. const last_cid = this.get(uniqueId);
  886. if (last_cid > 0) clearTimeout(last_cid);
  887. fn_start();
  888. const new_cid = setTimeout(fn_end, delay)
  889. this.set(uniqueId, new_cid)
  890. }
  891. }
  892.  
  893. const momentary = new Momentary();
  894.  
  895. const $hs = {
  896.  
  897. /* 提示文本的字號 */
  898. fontSize: 16,
  899. enable: true,
  900. playerInstance: null,
  901. playbackRate: 1,
  902. /* 快進快退步長 */
  903. skipStep: 5,
  904. trigger_actionBoxes: [],
  905.  
  906. /* 獲取當前播放器的實例 */
  907. player: function() {
  908. let res = $hs.playerInstance || null;
  909. if (res && res.parentNode == null) {
  910. $hs.playerInstance = null;
  911. res = null;
  912. }
  913.  
  914. if (res == null) {
  915. for (let k in playerConfs) {
  916. let playerConf = playerConfs[k];
  917. if (playerConf && playerConf.domElement && playerConf.domElement.parentNode) return playerConf.domElement;
  918. }
  919. }
  920. return res;
  921. },
  922.  
  923. pictureInPicture: function(videoElm) {
  924. if (document.pictureInPictureElement) {
  925. document.exitPictureInPicture();
  926. } else if ('requestPictureInPicture' in videoElm) {
  927. videoElm.requestPictureInPicture()
  928. } else {
  929. $hs.tips('PIP is not supported.');
  930. }
  931. },
  932.  
  933. getPlayerConf: function(video) {
  934.  
  935. if (!video) return null;
  936. let vpid = video.getAttribute('_h5ppid') || null;
  937. if (!vpid) return null;
  938. return playerConfs[vpid] || null;
  939.  
  940. },
  941.  
  942. handlerVideoPlaying: function(evt) {
  943. const videoElm = evt.target || this || null;
  944. const playerConf = $hs.getPlayerConf(videoElm)
  945.  
  946. $hs._actionBoxSet(videoElm);
  947. if (playerConf) {
  948. if (playerConf.timeout_pause > 0) playerConf.timeout_pause = clearTimeout(playerConf.timeout_pause);
  949. playerConf.lastPauseAt = 0
  950. playerConf.domActive |= DOM_ACTIVE_ONCE_PLAYED;
  951. playerConf.domActive &= ~DOM_ACTIVE_DELAYED_PAUSED;
  952. }
  953.  
  954. $hs.swtichPlayerInstance();
  955.  
  956. $hs.switchCurrentPlayingConf();
  957.  
  958.  
  959. $hs.onVideoTriggering();
  960.  
  961. if (!$hs.enable) return $hs.tips(false);
  962.  
  963. if (videoElm._isThisPausedBefore_) consoleLog('resumed')
  964. let _pausedbefore_ = videoElm._isThisPausedBefore_
  965.  
  966. if (videoElm.playpause_cid) {
  967. clearTimeout(videoElm.playpause_cid);
  968. videoElm.playpause_cid = 0;
  969. }
  970. let _last_paused = videoElm._last_paused
  971. videoElm._last_paused = videoElm.paused
  972. if (_last_paused === !videoElm.paused) {
  973. videoElm.playpause_cid = setTimeout(() => {
  974. if (videoElm.paused === !_last_paused && !videoElm.paused && _pausedbefore_) {
  975. $hs.tips('Playback resumed', undefined, 2500)
  976. }
  977. }, 90)
  978. }
  979.  
  980. /* 播放的時候進行相關同步操作 */
  981.  
  982. if (!videoElm._record_continuous) {
  983.  
  984. /* 同步之前設定的播放速度 */
  985. $hs.setPlaybackRate()
  986.  
  987. if (!_endlessloop) _endlessloop = new AFLooperArray();
  988.  
  989. videoElm._record_continuous = _endlessloop.appendLoop(handle.afPlaybackRecording);
  990. videoElm._record_continuous._lastSave = -999;
  991.  
  992. videoElm._record_continuous.timeDelta = 2000;
  993. videoElm._record_continuous.player = videoElm
  994. videoElm._record_continuous.savePlaybackProgress = handle.savePlaybackProgress;
  995. videoElm._record_continuous.updateUID = handle.pr_updateUID;
  996.  
  997. videoElm._record_continuous.playingWithRecording = function() {
  998. let player = this.player;
  999. if (!player.paused && this.updateUID() && !this.isFunctionLooping) {
  1000. this.pTime = 0;
  1001. this.loopingStart();
  1002. }
  1003. }
  1004.  
  1005. }
  1006.  
  1007. videoElm._record_continuous.playingWithRecording(videoElm); //try to start recording
  1008.  
  1009. videoElm._isThisPausedBefore_ = false;
  1010.  
  1011. },
  1012. handlerVideoPause: function(evt) {
  1013.  
  1014. const videoElm = evt.target || this || null;
  1015.  
  1016. const playerConf = $hs.getPlayerConf(videoElm)
  1017. if (playerConf) {
  1018. playerConf.lastPauseAt = +new Date;
  1019. playerConf.timeout_pause = setTimeout(() => {
  1020. if (playerConf.lastPauseAt > 0) playerConf.domActive |= DOM_ACTIVE_DELAYED_PAUSED;
  1021. }, 600)
  1022. }
  1023.  
  1024. if (!$hs.enable) return $hs.tips(false);
  1025. consoleLog('pause')
  1026. videoElm._isThisPausedBefore_ = true;
  1027.  
  1028. let _last_paused = videoElm._last_paused
  1029. videoElm._last_paused = videoElm.paused
  1030. if (videoElm.playpause_cid) {
  1031. clearTimeout(videoElm.playpause_cid);
  1032. videoElm.playpause_cid = 0;
  1033. }
  1034. if (_last_paused === !videoElm.paused) {
  1035. videoElm.playpause_cid = setTimeout(() => {
  1036. if (videoElm.paused === !_last_paused && videoElm.paused) {
  1037. $hs._tips(videoElm, 'Playback paused', undefined, 2500)
  1038. }
  1039. }, 90)
  1040. }
  1041.  
  1042.  
  1043. if (videoElm._record_continuous && videoElm._record_continuous.isFunctionLooping) {
  1044. videoElm._record_continuous.savePlaybackProgress(); //savePlaybackProgress once before stopping //handle.savePlaybackProgress;
  1045. videoElm._record_continuous.loopingStop();
  1046. }
  1047.  
  1048.  
  1049. },
  1050. handlerVideoVolumeChange: function(evt) {
  1051.  
  1052. const videoElm = evt.target || this || null;
  1053.  
  1054. if (videoElm.volume >= 0) {} else {
  1055. return;
  1056. }
  1057. let cVol = videoElm.volume;
  1058. let cMuted = videoElm.muted;
  1059.  
  1060. if (cVol === videoElm._volume_p && cMuted === videoElm._muted_p) {
  1061. // nothing changed
  1062. } else if (cVol === videoElm._volume_p && cMuted !== videoElm._muted_p) {
  1063. // muted changed
  1064. } else { // cVol != pVol
  1065.  
  1066. // only volume changed
  1067.  
  1068. let shallShowTips = videoElm._volume >= 0; //prevent initialization
  1069.  
  1070. if (!cVol) {
  1071. videoElm.muted = true;
  1072. } else if (cMuted) {
  1073. videoElm.muted = false;
  1074. videoElm._volume = cVol;
  1075. } else if (!cMuted) {
  1076. videoElm._volume = cVol;
  1077. }
  1078. consoleLog('volume changed')
  1079.  
  1080. if (shallShowTips)
  1081. $hs._tips(videoElm, 'Volume: ' + dround(videoElm.volume * 100) + '%', undefined, 3000)
  1082.  
  1083. }
  1084.  
  1085. videoElm._volume_p = cVol
  1086. videoElm._muted_p = cMuted
  1087.  
  1088. },
  1089. handlerVideoLoadedMetaData: function(evt) {
  1090. const videoElm = evt.target || this || null;
  1091. consoleLog('video size', this.videoWidth + ' x ' + this.videoHeight);
  1092.  
  1093. let vpid = videoElm.getAttribute('_h5ppid') || null;
  1094. if (!vpid || !videoElm.currentSrc) return;
  1095.  
  1096. if ($hs.varSrcList[vpid] != videoElm.currentSrc) {
  1097. $hs.varSrcList[vpid] = videoElm.currentSrc;
  1098. $hs.videoSrcFound(videoElm);
  1099. $hs._actionBoxSet(videoElm);
  1100. }
  1101. if (!videoElm._onceVideoLoaded) {
  1102. videoElm._onceVideoLoaded = true;
  1103. videoElm.addEventListener('playing', $hs.handlerVideoPlaying)
  1104. videoElm.addEventListener('pause', $hs.handlerVideoPause);
  1105. videoElm.addEventListener("volumechange", $hs.handlerVideoVolumeChange);
  1106. playerConfs[vpid].domActive |= DOM_ACTIVE_SRC_LOADED;
  1107. }
  1108.  
  1109. },
  1110. handlerElementMouseEnter: function(evt) {
  1111. if ($hs.intVideoInitCount > 0) {} else {
  1112. return;
  1113. }
  1114.  
  1115. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1116. if (!actionBox) return;
  1117. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1118. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1119. if (!videoElm) return;
  1120.  
  1121. $hs._actionBoxSet(videoElm);
  1122.  
  1123. const playerConf = $hs.getPlayerConf(videoElm)
  1124. if (playerConf) {
  1125. momentary.act("actionBoxMouseEnter",
  1126. () => {
  1127. playerConf.domActive |= DOM_ACTIVE_MOUSE_IN;
  1128. },
  1129. () => {
  1130. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_IN;
  1131. },
  1132. 300)
  1133. }
  1134.  
  1135. },
  1136. handlerElementMouseDown: function(evt) {
  1137.  
  1138. if ($hs.intVideoInitCount > 0) {} else {
  1139. return;
  1140. }
  1141.  
  1142. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1143. if (!actionBox) return;
  1144. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1145. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1146. if (!videoElm) return;
  1147.  
  1148. $hs._actionBoxSet(videoElm);
  1149.  
  1150. const playerConf = $hs.getPlayerConf(videoElm)
  1151. if (playerConf) {
  1152. momentary.act("actionBoxClicking",
  1153. () => {
  1154. playerConf.domActive |= DOM_ACTIVE_MOUSE_CLICK;
  1155. },
  1156. () => {
  1157. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_CLICK;
  1158. },
  1159. 300)
  1160. }
  1161. $hs.swtichPlayerInstance();
  1162.  
  1163. },
  1164. handlerElementWheelTuneVolume: function(evt) { //shift + wheel
  1165.  
  1166. if ($hs.intVideoInitCount > 0) {} else {
  1167. return;
  1168. }
  1169.  
  1170. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1171. if (!actionBox) return;
  1172. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1173. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1174. if (!videoElm) return;
  1175.  
  1176. if (!evt.shiftKey) return;
  1177. if (evt.deltaY) {
  1178. let player = $hs.player();
  1179. if (!player || player != videoElm) return;
  1180.  
  1181. if (evt.deltaY > 0) {
  1182.  
  1183. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1184.  
  1185. player.muted = false;
  1186. player.volume = player._volume;
  1187. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1188. player.muted = false;
  1189. }
  1190. $hs.tuneVolume(-0.05)
  1191.  
  1192. evt.stopPropagation()
  1193. evt.preventDefault()
  1194. return false
  1195.  
  1196. } else if (evt.deltaY < 0) {
  1197.  
  1198. if ((player.muted && player.volume === 0) && player._volume > 0) {
  1199. player.muted = false;
  1200. player.volume = player._volume;
  1201. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  1202. player.muted = false;
  1203. }
  1204. $hs.tuneVolume(+0.05)
  1205.  
  1206. evt.stopPropagation()
  1207. evt.preventDefault()
  1208. return false
  1209.  
  1210. }
  1211. }
  1212. },
  1213. debug01: function(evt, videoActive) {
  1214.  
  1215. if (!$hs.eventHooks) {
  1216. document.__h5p_eventhooks = ($hs.eventHooks = {
  1217. _debug_: []
  1218. });
  1219. }
  1220. $hs.eventHooks._debug_.push([videoActive, evt.type]);
  1221. // console.log('h5p eventhooks = document.__h5p_eventhooks')
  1222. },
  1223.  
  1224. swtichPlayerInstance: function() {
  1225.  
  1226. let newPlayerInstance = null;
  1227. const ONLY_PLAYING_NONE = 0x4A00;
  1228. const ONLY_PLAYING_MORE_THAN_ONE = 0x5A00;
  1229. let onlyPlayingInstance = ONLY_PLAYING_NONE;
  1230. for (let k in playerConfs) {
  1231. let playerConf = playerConfs[k] || {};
  1232. let {
  1233. domElement,
  1234. domActive
  1235. } = playerConf;
  1236. if (domElement) {
  1237. if (domActive & DOM_ACTIVE_INVALID_PARENT) continue;
  1238. if (!domElement.parentNode) {
  1239. playerConf.domActive |= DOM_ACTIVE_INVALID_PARENT;
  1240. continue;
  1241. }
  1242. if (domActive & DOM_ACTIVE_MOUSE_CLICK) {
  1243. newPlayerInstance = domElement
  1244. break;
  1245. }
  1246. if (domActive & DOM_ACTIVE_ONCE_PLAYED && (domActive & DOM_ACTIVE_DELAYED_PAUSED) == 0) {
  1247. if (onlyPlayingInstance == ONLY_PLAYING_NONE) onlyPlayingInstance = domElement;
  1248. else onlyPlayingInstance = ONLY_PLAYING_MORE_THAN_ONE;
  1249. }
  1250. }
  1251. }
  1252. if (newPlayerInstance == null && onlyPlayingInstance.nodeType == 1) {
  1253. newPlayerInstance = onlyPlayingInstance;
  1254. }
  1255.  
  1256. $hs.playerInstance = newPlayerInstance
  1257.  
  1258.  
  1259. },
  1260. switchCurrentPlayingConf: function() {
  1261. let player = $hs.player();
  1262. let res = null;
  1263. if (player) {
  1264. for (const tupConf of timeupdateStore) {
  1265. if (tupConf && tupConf.videoElement === player) {
  1266. res = tupConf
  1267. break;
  1268. }
  1269. }
  1270. }
  1271. timeupdateStore.currentPlayingConf = res
  1272.  
  1273. },
  1274. handlerElementDblClick: function(evt) {
  1275.  
  1276. if ($hs.intVideoInitCount > 0) {} else {
  1277. return;
  1278. }
  1279.  
  1280. if (document.readyState != "complete") return;
  1281.  
  1282. const actionBox = $hs.trigger_actionBoxes.filter(actionBox => (evt.target === actionBox || actionBox.contains(evt.target)))[0]
  1283. if (!actionBox) return;
  1284. const vpid = actionBox.getAttribute('_h5p_actionbox_');
  1285. const videoElm = getRoot(actionBox).querySelector(`VIDEO[_h5ppid="${vpid}"]`);
  1286. if (!videoElm) return;
  1287.  
  1288. $hs._actionBoxSet(videoElm);
  1289.  
  1290. const playerConf = $hs.getPlayerConf(videoElm)
  1291. if (playerConf) {
  1292. momentary.act("actionBoxClicking",
  1293. () => {
  1294. playerConf.domActive |= DOM_ACTIVE_MOUSE_CLICK;
  1295. },
  1296. () => {
  1297. playerConf.domActive &= ~DOM_ACTIVE_MOUSE_CLICK;
  1298. },
  1299. 600)
  1300. }
  1301. $hs.swtichPlayerInstance()
  1302.  
  1303. $hs.onVideoTriggering()
  1304.  
  1305. $hs.callFullScreenBtn();
  1306.  
  1307. evt.stopPropagation()
  1308. evt.preventDefault()
  1309. return false
  1310.  
  1311. },
  1312. handlerDocFocusOut: function(e) {
  1313. let doc = this;
  1314. $hs.focusFxLock = true;
  1315. $ws.requestAnimationFrame(function() {
  1316. $hs.focusFxLock = false;
  1317. if (!$hs.enable) $hs.tips(false);
  1318. else
  1319. if (!doc.hasFocus() && $hs.player() && !$hs.isLostFocus) {
  1320. $hs.isLostFocus = true;
  1321. consoleLog('doc.focusout')
  1322. //$hs.tips('focus is lost', -1);
  1323. }
  1324. });
  1325. },
  1326. handlerDocFocusIn: function(e) {
  1327. let doc = this;
  1328. if ($hs.focusFxLock) return;
  1329. $ws.requestAnimationFrame(function() {
  1330.  
  1331. if ($hs.focusFxLock) return;
  1332. if (!$hs.enable) $hs.tips(false);
  1333. else
  1334. if (doc.hasFocus() && $hs.player() && $hs.isLostFocus) {
  1335. $hs.isLostFocus = false;
  1336. consoleLog('doc.focusin')
  1337. $hs.tips(false);
  1338.  
  1339. }
  1340. });
  1341. },
  1342.  
  1343. handlerWinMessage: async function(e) {
  1344. let tag, ed;
  1345. if (typeof e.data == 'object' && typeof e.data.tag == 'string') {
  1346. tag = e.data.tag;
  1347. ed = e.data
  1348. } else {
  1349. return;
  1350. }
  1351. let msg = null,
  1352. success = 0;
  1353. switch (tag) {
  1354. case 'consoleLog':
  1355. let msg_str = ed.str;
  1356. let msg_stype = ed.stype;
  1357. if (msg_stype === 1) {
  1358. msg = (document[str_postMsgData] || {})[msg_str] || [];
  1359. success = 1;
  1360. } else if (msg_stype === 2) {
  1361. msg = jsonParse(msg_str);
  1362. if (msg && msg.d) {
  1363. success = 2;
  1364. msg = msg.d;
  1365. }
  1366. } else {
  1367. msg = msg_str
  1368. }
  1369. let p = (ed.passing && ed.winOrder) ? [' | from win-' + ed.winOrder] : [];
  1370. if (success) {
  1371. console.log(...msg, ...p)
  1372. //document[ed.data]=null; // also delete the information
  1373. } else {
  1374. console.log('msg--', msg, ...p, ed);
  1375. }
  1376. break;
  1377.  
  1378. }
  1379. },
  1380.  
  1381. isInActiveMode: function(activeElm, player) {
  1382.  
  1383. if (activeElm == player) {
  1384. return true;
  1385. }
  1386.  
  1387. if ($hs.trigger_actionBoxes[0]) {
  1388. let actionBox = $hs.trigger_actionBoxes[0];
  1389. if (activeElm == actionBox || actionBox.contains(activeElm)) {
  1390. return true;
  1391. }
  1392.  
  1393. }
  1394.  
  1395. let _checkingPass = false;
  1396.  
  1397. if (!player) return;
  1398. let layoutBox = $hs.getPlayerBlockElement(player).parentNode;
  1399. if (layoutBox && layoutBox.parentNode && layoutBox.contains(activeElm)) {
  1400. let rpid = player.getAttribute('_h5ppid') || "NULL";
  1401. let actionBox = layoutBox.parentNode.querySelector(`[_h5p_actionbox_="${rpid}"]`); //the box can be layoutBox
  1402. if (actionBox && actionBox.contains(activeElm)) _checkingPass = true;
  1403. }
  1404.  
  1405. return _checkingPass
  1406. },
  1407.  
  1408.  
  1409. toolCheckFullScreen: function(doc) {
  1410. if (typeof doc.fullScreen == 'boolean') return doc.fullScreen;
  1411. if (typeof doc.webkitIsFullScreen == 'boolean') return doc.webkitIsFullScreen;
  1412. if (typeof doc.mozFullScreen == 'boolean') return doc.mozFullScreen;
  1413. return null;
  1414. },
  1415.  
  1416. toolFormatCT: function(u) {
  1417.  
  1418. let w = Math.round(u, 0)
  1419. let a = w % 60
  1420. w = (w - a) / 60
  1421. let b = w % 60
  1422. w = (w - b) / 60
  1423. let str = ("0" + b).substr(-2) + ":" + ("0" + a).substr(-2);
  1424. if (w) str = w + ":" + str
  1425.  
  1426. return str
  1427.  
  1428. },
  1429.  
  1430. makeFocus: function(player, evt) {
  1431. setTimeout(function() {
  1432. let rpid = player.getAttribute('_h5ppid');
  1433. let actionBox = getRoot(player).querySelector(`[_h5p_actionbox_="${rpid}"]`);
  1434.  
  1435. //console.log('p',rpid, player,actionBox,document.activeElement)
  1436. if (actionBox && actionBox != document.activeElement && !actionBox.contains(document.activeElement)) {
  1437. consoleLog('make focus on', actionBox)
  1438. actionBox.focus();
  1439.  
  1440. }
  1441.  
  1442. }, 300)
  1443. },
  1444.  
  1445. getActionBlockElement: function(player, layoutBox) {
  1446.  
  1447. if (!player || !layoutBox) return null;
  1448.  
  1449.  
  1450. let walkRes = domTool._isActionBox_1(player, layoutBox);
  1451. let parentCount = walkRes.length;
  1452. let actionBox = null;
  1453. if (parentCount - 1 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 1)) {
  1454. actionBox = walkRes[parentCount - 1].elm;
  1455. } else if (parentCount - 2 >= 0 && domTool._isActionBox(player, walkRes, parentCount - 2)) {
  1456. actionBox = walkRes[parentCount - 2].elm;
  1457. } else {
  1458. actionBox = player;
  1459. }
  1460.  
  1461.  
  1462. let search = $hs.videoFullscreenBtns(actionBox, 4);
  1463. if (search && search.elements.length > 0) actionBox = search.container;
  1464.  
  1465. return actionBox;
  1466.  
  1467.  
  1468. },
  1469.  
  1470. _actionBoxSet: function(player) {
  1471.  
  1472. if (!player) return null;
  1473. let vpid = player.getAttribute('_h5ppid');
  1474. if (!vpid) return null;
  1475.  
  1476. let layoutBox = $hs.getPlayerBlockElement(player).parentNode;
  1477. let actionBox = $hs.getActionBlockElement(player, layoutBox);
  1478.  
  1479.  
  1480. //console.log('actionbox search:', actionBox)
  1481.  
  1482. if (actionBox && actionBox.getAttribute('_h5p_actionbox_') != vpid) {
  1483. consoleLog('D-1', actionBox);
  1484. for (const previousActionboxes of getRoot(player).querySelectorAll(`[_h5p_actionbox_="${vpid}"]`)) {
  1485. //change of parentNode
  1486. previousActionboxes.removeAttribute('_h5p_actionbox_');
  1487. }
  1488. actionBox.setAttribute('_h5p_actionbox_', vpid);
  1489. $hs.trigger_actionBoxes = [actionBox];
  1490.  
  1491. if (!actionBox.hasAttribute('tabindex')) actionBox.setAttribute('tabindex', '-1');
  1492.  
  1493.  
  1494.  
  1495. }
  1496. return actionBox;
  1497. },
  1498.  
  1499. videoSrcFound: function(player) {
  1500.  
  1501. // src loaded
  1502.  
  1503. if (!player) return;
  1504. let vpid = player.getAttribute('_h5ppid') || null;
  1505. if (!vpid || !player.currentSrc) return;
  1506.  
  1507. player._isThisPausedBefore_ = false;
  1508.  
  1509. player.removeAttribute('_h5p_uid_encrypted');
  1510.  
  1511. if (player._record_continuous) player._record_continuous._lastSave = -999; //first time must save
  1512.  
  1513. let uid_A = location.pathname.replace(/[^\d+]/g, '') + '.' + location.search.replace(/[^\d+]/g, '');
  1514. let _uid = location.hostname.replace('www.', '').toLowerCase() + '!' + location.pathname.toLowerCase() + 'A' + uid_A + 'W' + player.videoWidth + 'H' + player.videoHeight + 'L' + (player.duration << 0);
  1515.  
  1516. digestMessage(_uid).then(function(_uid_encrypted) {
  1517.  
  1518. let d = +new Date;
  1519.  
  1520. let recordedTime = null;
  1521.  
  1522. ;
  1523. (function() {
  1524. //read the last record only;
  1525.  
  1526. let k1 = '_h5_player_play_progress_';
  1527. let k1n = '_play_progress_';
  1528. let k2 = _uid_encrypted;
  1529. let k3 = k1 + k2;
  1530. let k3n = k1n + k2;
  1531. let m2 = Store._keys().filter(key => key.substr(0, k3.length) == k3); //all progress records for this video
  1532. let m2v = m2.map(keyName => +(keyName.split('+')[1] || '0'))
  1533. let m2vMax = Math.max(0, ...m2v)
  1534. if (!m2vMax) recordedTime = null;
  1535. else {
  1536. let _json_recordedTime = null;
  1537. _json_recordedTime = Store.read(k3n + '+' + m2vMax);
  1538. if (!_json_recordedTime) _json_recordedTime = {};
  1539. else _json_recordedTime = jsonParse(_json_recordedTime);
  1540. if (typeof _json_recordedTime == 'object') recordedTime = _json_recordedTime;
  1541. else recordedTime = null;
  1542. recordedTime = typeof recordedTime == 'object' ? recordedTime.t : recordedTime;
  1543. if (typeof recordedTime == 'number' && (+recordedTime >= 0 || +recordedTime <= 0)) {
  1544.  
  1545. } else if (typeof recordedTime == 'string' && recordedTime.length > 0 && (+recordedTime >= 0 || +recordedTime <= 0)) {
  1546. recordedTime = +recordedTime
  1547. } else {
  1548. recordedTime = null
  1549. }
  1550. }
  1551. if (recordedTime !== null) {
  1552. player._h5player_lastrecord_ = recordedTime;
  1553. } else {
  1554. player._h5player_lastrecord_ = null;
  1555. }
  1556. if (player._h5player_lastrecord_ > 5) {
  1557. consoleLog('last record playing', player._h5player_lastrecord_);
  1558. setTimeout(function() {
  1559. $hs._tips(player, `Press Shift-R to restore Last Playback: ${$hs.toolFormatCT(player._h5player_lastrecord_)}`, 5000, 4000)
  1560. }, 1000)
  1561. }
  1562.  
  1563. })();
  1564. // delay the recording by 5.4s => prevent ads or mis operation
  1565. setTimeout(function() {
  1566.  
  1567. let k1 = '_h5_player_play_progress_';
  1568. let k1n = '_play_progress_';
  1569. let k2 = _uid_encrypted;
  1570. let k3 = k1 + k2;
  1571. let k3n = k1n + k2;
  1572.  
  1573. //re-read all the localStorage keys
  1574. let m1 = Store._keys().filter(key => key.substr(0, k1.length) == k1); //all progress records in this site
  1575. let p = m1.length + 1;
  1576.  
  1577. for (const key of m1) { //all progress records for this video
  1578. if (key.substr(0, k3.length) == k3) {
  1579. Store._removeItem(key); //remove previous record for the current video
  1580. p--;
  1581. }
  1582. }
  1583.  
  1584. if (recordedTime !== null) {
  1585. Store.save(k3n + '+' + d, jsonStringify({
  1586. 't': recordedTime
  1587. })) //prevent loss of last record
  1588. }
  1589.  
  1590. const _record_max_ = 48;
  1591. const _record_keep_ = 26;
  1592.  
  1593. if (p > _record_max_) {
  1594. //exisiting 48 records for one site;
  1595. //keep only 26 records
  1596.  
  1597. const comparator = (a, b) => (a.t < b.t ? -1 : a.t > b.t ? 1 : 0);
  1598.  
  1599. m1
  1600. .map(keyName => ({
  1601. keyName,
  1602. t: +(keyName.split('+')[1] || '0')
  1603. }))
  1604. .sort(comparator)
  1605. .slice(0, -_record_keep_)
  1606. .forEach((item) => localStorage.removeItem(item.keyName));
  1607.  
  1608. consoleLog(`stored progress: reduced to ${_record_keep_}`)
  1609. }
  1610.  
  1611. player.setAttribute('_h5p_uid_encrypted', _uid_encrypted + '+' + d);
  1612.  
  1613. //try to start recording
  1614. if (player._record_continuous) player._record_continuous.playingWithRecording();
  1615.  
  1616. }, 5400);
  1617.  
  1618. })
  1619.  
  1620. },
  1621. bindDocEvents: function(rootNode) {
  1622. if (!rootNode._onceBindedDocEvents) {
  1623.  
  1624. rootNode._onceBindedDocEvents = true;
  1625. rootNode.addEventListener('keydown', $hs.handlerRootKeyDownEvent, true)
  1626. document._debug_rootNode_ = rootNode;
  1627.  
  1628. rootNode.addEventListener('mouseenter', $hs.handlerElementMouseEnter, true)
  1629. rootNode.addEventListener('mousedown', $hs.handlerElementMouseDown, true)
  1630. rootNode.addEventListener('dblclick', $hs.handlerElementDblClick, true)
  1631. rootNode.addEventListener('wheel', $hs.handlerElementWheelTuneVolume, {
  1632. passive: false
  1633. });
  1634. // wheel - bubble events to keep it simple (i.e. it must be passive:false & capture:false)
  1635.  
  1636. }
  1637. },
  1638. fireGlobalInit: function() {
  1639. if ($hs.intVideoInitCount != 1) return;
  1640. if (!$hs.varSrcList) $hs.varSrcList = {};
  1641. $hs.isLostFocus = null;
  1642. try {
  1643. //iframe may not be able to control top window
  1644. //error; just ignore with async
  1645. let topDoc = window.top && window.top.document ? window.top.document : null;
  1646. if (topDoc) {
  1647. topDoc.addEventListener('focusout', $hs.handlerDocFocusOut, true)
  1648. topDoc.addEventListener('focusin', $hs.handlerDocFocusIn, true)
  1649. }
  1650.  
  1651. } catch (e) {}
  1652. Store.clearInvalid(_sVersion_)
  1653. },
  1654. onVideoTriggering: function() {
  1655.  
  1656.  
  1657. // initialize a single video player - h5Player.playerInstance
  1658.  
  1659. /**
  1660. * 初始化播放器實例
  1661. */
  1662. let player = $hs.playerInstance
  1663. if (!player) return
  1664.  
  1665. let vpid = player.getAttribute('_h5ppid');
  1666.  
  1667. if (!vpid) return;
  1668.  
  1669. let firstTime = !!$hs.initTips()
  1670. if (firstTime) {
  1671. // first time to trigger this player
  1672. if (!player.hasAttribute('playsinline')) player.setAttribute('playsinline', 'playsinline');
  1673. if (!player.hasAttribute('x-webkit-airplay')) player.setAttribute('x-webkit-airplay', 'deny');
  1674. if (!player.hasAttribute('preload')) player.setAttribute('preload', 'auto');
  1675. //player.style['image-rendering'] = 'crisp-edges';
  1676. $hs.playbackRate = $hs.getPlaybackRate()
  1677. }
  1678.  
  1679. },
  1680. getPlaybackRate: function() {
  1681. let playbackRate = Store.read('_playback_rate_') || $hs.playbackRate
  1682. return Number(Number(playbackRate).toFixed(1))
  1683. },
  1684. getPlayerBlockElement: function(player) {
  1685. //without checkActiveBox, just a DOM for you to append tipsDom
  1686.  
  1687. let layoutBox = null,
  1688. wPlayer = null
  1689.  
  1690. if (!player || !player.offsetHeight || !player.offsetWidth || !player.parentNode) {
  1691. return null;
  1692. }
  1693.  
  1694. function search_nodes() {
  1695.  
  1696. wPlayer = player; // NOT NULL
  1697. layoutBox = wPlayer.parentNode; // NOT NULL
  1698.  
  1699. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight == 0) {
  1700. wPlayer = layoutBox; // NOT NULL
  1701. layoutBox = layoutBox.parentNode; // NOT NULL
  1702. }
  1703. //container must be with offsetHeight
  1704.  
  1705. while (layoutBox.parentNode && layoutBox.nodeType == 1 && layoutBox.offsetHeight < player.offsetHeight) {
  1706. wPlayer = layoutBox; // NOT NULL
  1707. layoutBox = layoutBox.parentNode; // NOT NULL
  1708. }
  1709. //container must have height >= player height
  1710.  
  1711. }
  1712.  
  1713. search_nodes();
  1714.  
  1715. if (layoutBox.nodeType == 11) {
  1716.  
  1717.  
  1718. //shadowRoot without html and body
  1719. let shadowChild, shadowElm_container, shadowElm_head, shadowElm_html;
  1720. let rootNode = getRoot(player);
  1721. if (rootNode.querySelectorAll('html,body').length < 2) {
  1722.  
  1723. shadowElm_container = player.ownerDocument.createElement('BODY')
  1724. rootNode.insertBefore(shadowElm_container, rootNode.firstChild)
  1725.  
  1726. while (shadowChild = shadowElm_container.nextSibling) shadowElm_container.appendChild(shadowChild);
  1727.  
  1728. shadowElm_head = rootNode.insertBefore(player.ownerDocument.createElement('HEAD'), shadowElm_container)
  1729.  
  1730. shadowElm_html = rootNode.insertBefore(player.ownerDocument.createElement('HTML'), shadowElm_head)
  1731.  
  1732. shadowElm_container.setAttribute('style', 'padding:0;margin:0;border:0; box-sizing: border-box;')
  1733. shadowElm_html.setAttribute('style', 'padding:0;margin:0;border:0; box-sizing: border-box;')
  1734.  
  1735. shadowElm_html.appendChild(shadowElm_head)
  1736. shadowElm_html.appendChild(shadowElm_container)
  1737.  
  1738. }
  1739.  
  1740. search_nodes();
  1741.  
  1742. }
  1743.  
  1744. //condition:
  1745. //!layoutBox.parentNode || layoutBox.nodeType != 1 || layoutBox.offsetHeight > player.offsetHeight
  1746.  
  1747. // layoutBox is a node contains <video> and offsetHeight>=video.offsetHeight
  1748. // wPlayer is a HTML Element (nodeType==1)
  1749. // you can insert the DOM element into the layoutBox
  1750.  
  1751. if (layoutBox && wPlayer && layoutBox.nodeType === 1 && wPlayer.parentNode == layoutBox) return wPlayer;
  1752. throw 'unknown error';
  1753.  
  1754. },
  1755. getCommonContainer: function(elm1, elm2) {
  1756.  
  1757. let box1 = elm1;
  1758. let box2 = elm2;
  1759.  
  1760. while (box1 && box2) {
  1761. if (box1.contains(box2) || box2.contains(box1)) {
  1762. break;
  1763. }
  1764. box1 = box1.parentNode;
  1765. box2 = box2.parentNode;
  1766. }
  1767.  
  1768. let layoutBox = null;
  1769.  
  1770. box1 = (box1 && box1.contains(elm2)) ? box1 : null;
  1771. box2 = (box2 && box2.contains(elm1)) ? box2 : null;
  1772.  
  1773. if (box1 && box2) layoutBox = box1.contains(box2) ? box2 : box1;
  1774. else layoutBox = box1 || box2 || null;
  1775.  
  1776. return layoutBox
  1777.  
  1778. },
  1779. change_layoutBox: function(tipsDom) {
  1780. let player = $hs.player()
  1781. if (!player) return;
  1782. let wPlayer = $hs.getPlayerBlockElement(player);
  1783. let layoutBox = wPlayer.parentNode;
  1784.  
  1785. if ((layoutBox && layoutBox.nodeType == 1) && (!tipsDom.parentNode || tipsDom.parentNode !== layoutBox)) {
  1786.  
  1787. consoleLog('changed_layoutBox')
  1788. layoutBox.insertBefore(tipsDom, wPlayer);
  1789.  
  1790. }
  1791. },
  1792.  
  1793. queryFullscreenBtnsIndependant: function(parentNode, returnElementsOnly) {
  1794.  
  1795. let btns = [];
  1796. for (const elm of parentNode.querySelectorAll('[class*="full"][class*="screen"]')) {
  1797. let className = (elm.getAttribute('class') || "");
  1798. if (/\b(fullscreen|full-screen)\b/i.test(className.replace(/([A-Z][a-z]+)/g, '-$1-').replace(/[\_\-]+/g, '-'))) {
  1799.  
  1800. let hasClickListeners = null,
  1801. childElementCount = null,
  1802. isVisible = null;
  1803.  
  1804.  
  1805. if ('_listeners' in elm) {
  1806.  
  1807. hasClickListeners = elm._listeners && elm._listeners.click && elm._listeners.click.funcCount > 0
  1808.  
  1809. }
  1810.  
  1811. if ('childElementCount' in elm) {
  1812.  
  1813. childElementCount = elm.childElementCount;
  1814.  
  1815. }
  1816. if ('offsetParent' in elm) {
  1817. isVisible = !!elm.offsetParent; //works with parent/self display none; not work with visiblity hidden / opacity0
  1818.  
  1819. }
  1820.  
  1821. if (hasClickListeners) {
  1822. let btn = {
  1823. elm,
  1824. isVisible,
  1825. hasClickListeners,
  1826. childElementCount,
  1827. isContained: null
  1828. };
  1829.  
  1830.  
  1831. btns.push(returnElementsOnly ? elm : btn)
  1832.  
  1833. }
  1834.  
  1835. }
  1836. }
  1837. return btns;
  1838.  
  1839. },
  1840. exclusiveElements: function(elms) {
  1841.  
  1842. //not containing others
  1843. let res = [];
  1844.  
  1845. for (const roleElm of elms) {
  1846.  
  1847. let isContained = false;
  1848. for (const testElm of elms) {
  1849. if (testElm != roleElm && roleElm.contains(testElm)) {
  1850. isContained = true;
  1851. break;
  1852. }
  1853. }
  1854. if (!isContained) res.push(roleElm)
  1855. }
  1856. return res;
  1857.  
  1858. },
  1859. videoFullscreenBtns: function(startPoint, searchCount) {
  1860.  
  1861.  
  1862. let c = 0,
  1863. p = startPoint,
  1864. q = null;
  1865. while (p && (++c <= searchCount)) {
  1866.  
  1867. if (p.querySelectorAll('video').length !== 1) break;
  1868.  
  1869. let elmFullscreenBtns = $hs.queryFullscreenBtnsIndependant(p, true);
  1870. if (elmFullscreenBtns.length > 0) {
  1871.  
  1872. let exclusiveFullscreenBtns = $hs.exclusiveElements(elmFullscreenBtns)
  1873. if (exclusiveFullscreenBtns.length > 0) {
  1874. return {
  1875. container: p,
  1876. elements: exclusiveFullscreenBtns
  1877. };
  1878.  
  1879. }
  1880. }
  1881.  
  1882.  
  1883. q = p;
  1884. p = p.parentNode;
  1885. }
  1886.  
  1887. return null;
  1888.  
  1889.  
  1890.  
  1891.  
  1892. },
  1893. callFullScreenBtn: function() {
  1894.  
  1895. let player = $hs.player()
  1896. if (!player || !player.ownerDocument || !('exitFullscreen' in player.ownerDocument)) return;
  1897.  
  1898. let btnElement = null;
  1899.  
  1900. let vpid = player.getAttribute('_h5ppid') || null;
  1901.  
  1902. if (!vpid) return;
  1903.  
  1904.  
  1905. const chFull = $hs.toolCheckFullScreen(player.ownerDocument);
  1906.  
  1907.  
  1908.  
  1909.  
  1910. if (chFull === true) {
  1911. player.ownerDocument.exitFullscreen();
  1912. } else if (chFull === false) {
  1913.  
  1914.  
  1915. let actionBox = getRoot(player).querySelector(`[_h5p_actionbox_="${vpid}"]`);
  1916.  
  1917. if (actionBox) {
  1918.  
  1919. let exclusiveFullscreenBtns = $hs.videoFullscreenBtns(actionBox, 1);
  1920. let btnElements = exclusiveFullscreenBtns ? exclusiveFullscreenBtns.elements : null;
  1921. if (btnElements && btnElements.length > 0) {
  1922.  
  1923. //consoleLog('fullscreen btn', btnElements)
  1924.  
  1925. const lens_elemsClassName = btnElements.map(elm => elm.className.length)
  1926. const j_elemsClassName = Math.min(...lens_elemsClassName)
  1927. let btnElement_idx = lens_elemsClassName.lastIndexOf(j_elemsClassName)
  1928. // pick the last btn if there is more than one
  1929. btnElement = btnElements[btnElement_idx];
  1930. window.requestAnimationFrame(() => btnElement.click());
  1931. //consoleLog('original fullscreen')
  1932.  
  1933. }
  1934. }
  1935.  
  1936.  
  1937. }
  1938.  
  1939. if (chFull === null || (chFull === false && !btnElement)) {
  1940.  
  1941. let layoutBox = $hs.getPlayerBlockElement(player).parentNode;
  1942.  
  1943. let gPlayer = null;
  1944. if (!layoutBox || !layoutBox.parentNode) {
  1945. consoleLog('the container for DOM fullscreen cannot be found')
  1946. return;
  1947. }
  1948. gPlayer = layoutBox.parentNode.querySelector(`[_h5p_actionbox_="${vpid}"]`); //the box can be layoutBox
  1949.  
  1950. consoleLog('DOM fullscreen', gPlayer)
  1951. try {
  1952. gPlayer.requestFullscreen() //known bugs : TypeError: fullscreen error
  1953. } catch (e) {
  1954. consoleLogF('fullscreen error', e)
  1955. }
  1956.  
  1957.  
  1958. }
  1959.  
  1960.  
  1961.  
  1962.  
  1963. },
  1964. /* 設置播放速度 */
  1965. setPlaybackRate: function(num, flagTips) {
  1966. let player = $hs.player()
  1967. let curPlaybackRate
  1968. if (num) {
  1969. num = +num
  1970. if (num > 0) { // also checking the type of variable
  1971. curPlaybackRate = num < 0.1 ? 0.1 : +(num.toFixed(1))
  1972. } else {
  1973. console.error('h5player: 播放速度轉換出錯')
  1974. return false
  1975. }
  1976. } else {
  1977. curPlaybackRate = $hs.getPlaybackRate()
  1978. }
  1979. /* 記錄播放速度的信息 */
  1980.  
  1981. let changed = curPlaybackRate !== player.playbackRate;
  1982.  
  1983. if (curPlaybackRate !== player.playbackRate) {
  1984.  
  1985. Store.save('_playback_rate_', curPlaybackRate + '')
  1986. $hs.playbackRate = curPlaybackRate
  1987. player.playbackRate = curPlaybackRate
  1988. /* 本身處於1被播放速度的時候不再提示 */
  1989. //if (!num && curPlaybackRate === 1) return;
  1990.  
  1991. }
  1992.  
  1993. flagTips = (flagTips < 0) ? false : (flagTips > 0) ? true : changed;
  1994. if (flagTips) $hs.tips('Playback speed: ' + player.playbackRate + 'x')
  1995. },
  1996. tuneCurrentTime: function(amount, flagTips) {
  1997. let _amount = +(+amount).toFixed(1);
  1998. let player = $hs.player();
  1999. if (_amount >= 0 || _amount < 0) {} else {
  2000. return;
  2001. }
  2002.  
  2003. let newCurrentTime = player.currentTime + _amount;
  2004. if (newCurrentTime < 0) newCurrentTime = 0;
  2005. if (newCurrentTime > player.duration) newCurrentTime = player.duration;
  2006.  
  2007. let changed = newCurrentTime != player.currentTime && newCurrentTime >= 0 && newCurrentTime <= player.duration;
  2008.  
  2009. if (changed) {
  2010. //player.currentTime = newCurrentTime;
  2011. player.pause();
  2012. let t_ch = (Math.random() / 5 + .75);
  2013. player.currentTime = newCurrentTime * t_ch + player.currentTime * (1.0 - t_ch);
  2014. setTimeout(() => {
  2015. player.play();
  2016. player.currentTime = newCurrentTime;
  2017. }, 33);
  2018. flagTips = (flagTips < 0) ? false : (flagTips > 0) ? true : changed;
  2019. $hs.tips(false);
  2020. if (flagTips) {
  2021. if (_amount > 0) $hs.tips(_amount + ' Sec. Forward', undefined, 3000);
  2022. else $hs.tips(-_amount + ' Sec. Backward', undefined, 3000)
  2023. }
  2024. }
  2025.  
  2026. },
  2027. tuneVolume: function(amount) {
  2028. let _amount = +(+amount).toFixed(2);
  2029.  
  2030. let player = $hs.player()
  2031.  
  2032. let newVol = player.volume + _amount;
  2033. if (newVol < 0) newVol = 0;
  2034. if (newVol > 1) newVol = 1;
  2035. let chVol = player.volume !== newVol && newVol >= 0 && newVol <= 1;
  2036.  
  2037. if (chVol) {
  2038.  
  2039. if (_amount > 0 && player.volume < 1) {
  2040. player.volume = newVol // positive
  2041. } else if (_amount < 0 && player.volume > 0) {
  2042. player.volume = newVol // negative
  2043. }
  2044. $hs.tips(false);
  2045. $hs.tips('Volume: ' + dround(player.volume * 100) + '%', undefined)
  2046. }
  2047. },
  2048. switchPlayStatus: function() {
  2049. let player = $hs.player()
  2050. if (player.paused) {
  2051. player.play()
  2052. if (player._isThisPausedBefore_) {
  2053. $hs.tips(false);
  2054. $hs.tips('Playback resumed', undefined, 2500)
  2055. }
  2056. } else {
  2057. player.pause()
  2058. $hs.tips(false);
  2059. $hs.tips('Playback paused', undefined, 2500)
  2060. }
  2061. },
  2062. tipsClassName: 'html_player_enhance_tips',
  2063. _tips: function(player, str, duration, order) {
  2064.  
  2065.  
  2066. if (!player.getAttribute('_h5player_tips')) $hs.initTips();
  2067.  
  2068. let tipsSelector = '#' + (player.getAttribute('_h5player_tips') || $hs.tipsClassName) //if this attribute still doesnt exist, set it to the base cls name
  2069. let tipsDom = getRoot(player).querySelector(tipsSelector)
  2070. if (!tipsDom) {
  2071. consoleLog('init h5player tips dom error...')
  2072. return false
  2073. }
  2074. $hs.change_layoutBox(tipsDom);
  2075.  
  2076. if (str === false) {
  2077. tipsDom.innerText = '';
  2078. tipsDom.setAttribute('_potTips_', '0')
  2079. } else {
  2080. order = order || 1000
  2081. tipsDom.tipsOrder = tipsDom.tipsOrder || 0;
  2082.  
  2083. let shallDisplay = true
  2084. if (order < tipsDom.tipsOrder && getComputedStyle(tipsDom).opacity > 0) shallDisplay = false
  2085.  
  2086. if (shallDisplay) {
  2087.  
  2088. tipsDom._playerElement = player;
  2089. tipsDom._playerVPID = player.getAttribute('_h5ppid');
  2090. tipsDom._playerBlockElm = $hs.getPlayerBlockElement(player)
  2091. tipsDom._env_changed = 0;
  2092.  
  2093. if (!_endlessloop) _endlessloop = new AFLooperArray();
  2094. tipsDom._cached_dimensions = null;
  2095. if (!$hs.__updateTips) {
  2096. $hs.__updateTips = _endlessloop.appendLoop(handle.afTipsDOM)
  2097. $hs.__updateTips.loopingStart();
  2098. }
  2099.  
  2100. if (duration === undefined) duration = 2000
  2101. tipsDom.innerText = str
  2102.  
  2103. tipsDom.setAttribute('_potTips_', '2')
  2104.  
  2105. $hs.fixNonBoxingVideoTipsPosition(tipsDom, player);
  2106.  
  2107. if (duration > 0) {
  2108. $ws.requestAnimationFrame(() => tipsDom.setAttribute('_potTips_', '1'))
  2109. } else {
  2110. order = -1;
  2111. }
  2112.  
  2113. tipsDom.tipsOrder = order
  2114.  
  2115. }
  2116.  
  2117. }
  2118.  
  2119. $hs.cacheTipsDoms();
  2120. },
  2121. tips: function(str, duration, order) {
  2122. let player = $hs.player()
  2123. if (!player) {
  2124. consoleLog('h5Player Tips:', str)
  2125. return true
  2126. }
  2127.  
  2128. return $hs._tips(player, str, duration, order)
  2129.  
  2130. },
  2131. listOfTipsDom: [],
  2132. cacheTipsDoms: function() {
  2133. $hs._cached_tipsDoms = $hs.getPotTips(['1', '2']); //48673
  2134. },
  2135. getPotTips: function(arr) {
  2136. const res = [];
  2137. for (const tipsDom of $hs.listOfTipsDom) {
  2138. if (tipsDom && tipsDom.nodeType > 0 && tipsDom.parentNode && tipsDom.ownerDocument) {
  2139. if (tipsDom._playerBlockElm && tipsDom._playerBlockElm.parentNode) {
  2140. const potTipsAttr = tipsDom.getAttribute('_potTips_')
  2141. if (arr.indexOf(potTipsAttr) >= 0) res.push(tipsDom)
  2142. }
  2143. }
  2144. }
  2145. return res;
  2146. },
  2147. initTips: function() {
  2148. /* 設置提示DOM的樣式 */
  2149. let player = $hs.player()
  2150. let shadowRoot = getRoot(player);
  2151. let doc = player.ownerDocument;
  2152. //console.log((document.documentElement.qq=player),shadowRoot,'xax')
  2153. let parentNode = player.parentNode
  2154. let tcn = player.getAttribute('_h5player_tips') || ($hs.tipsClassName + '_' + (+new Date));
  2155. player.setAttribute('_h5player_tips', tcn)
  2156. if (shadowRoot.querySelector('#' + tcn)) return false;
  2157.  
  2158. if (!shadowRoot._onceAddedCSS) {
  2159. shadowRoot._onceAddedCSS = true;
  2160.  
  2161. let cssStyle = `
  2162. [_potTips_="1"]{
  2163. animation: 2s linear 0s normal forwards 1 delayHide;
  2164. }
  2165. [_potTips_="0"]{
  2166. opacity:0; transform:translate(-9999px);
  2167. }
  2168. [_potTips_="2"]{
  2169. opacity:.95; transform: translate(0,0);
  2170. }
  2171.  
  2172. @keyframes delayHide{
  2173. 0%, 99% { opacity:0.95; transform: translate(0,0); }
  2174. 100% { opacity:0; transform:translate(-9999px); }
  2175. }
  2176. ` + `
  2177. [_potTips_]{
  2178. font-weight: bold !important;
  2179. position: absolute !important;
  2180. z-index: 999 !important;
  2181. font-size: ${$hs.fontSize || 16}px !important;
  2182. padding: 0px !important;
  2183. border:none !important;
  2184. background: rgba(0,0,0,0) !important;
  2185. color:#738CE6 !important;
  2186. text-shadow: -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000;
  2187. top: 50%;
  2188. left: 50%;
  2189. max-width:500px;max-height:50px;
  2190. border-radius:3px;
  2191. font-family: 'microsoft yahei', Verdana, Geneva, sans-serif;
  2192. -webkit-user-select: none;
  2193. -moz-user-select: none;
  2194. -ms-user-select: none;
  2195. user-select: none;
  2196. -webkit-touch-callout: none;
  2197. -webkit-user-select: none;
  2198. -khtml-user-drag: none;
  2199. -khtml-user-select: none;
  2200. -moz-user-select: none;
  2201. -moz-user-select: -moz-none;
  2202. -ms-user-select: none;
  2203. pointer-events: none;
  2204. user-select: none;
  2205. }
  2206. `.replace(/\r\n/g, '');
  2207.  
  2208. let cssContainer = (shadowRoot.querySelector('head') || shadowRoot.querySelector('html') || document.documentElement);
  2209.  
  2210. domTool.addStyle(cssStyle, cssContainer);
  2211.  
  2212. }
  2213.  
  2214. let tipsDom = doc.createElement('div')
  2215.  
  2216. tipsDom.addEventListener(crossBrowserTransition('animation'), function(e) {
  2217. if (this.getAttribute('_potTips_') == '1') {
  2218. this.setAttribute('_potTips_', '0')
  2219. $hs.cacheTipsDoms();
  2220. }
  2221. })
  2222.  
  2223. tipsDom.id = tcn;
  2224. tipsDom.setAttribute('_potTips_', '0');
  2225. $hs.listOfTipsDom.push(tipsDom);
  2226. $hs.change_layoutBox(tipsDom);
  2227.  
  2228. return true;
  2229. },
  2230.  
  2231. responsiveSizing: function(container, elm) {
  2232.  
  2233. let gcssP = getComputedStyle(container);
  2234.  
  2235. let gcssE = getComputedStyle(elm);
  2236.  
  2237. //console.log(gcssE.left,gcssP.width)
  2238. let elmBound = {
  2239. left: parseFloat(gcssE.left) / parseFloat(gcssP.width),
  2240. width: parseFloat(gcssE.width) / parseFloat(gcssP.width),
  2241. top: parseFloat(gcssE.top) / parseFloat(gcssP.height),
  2242. height: parseFloat(gcssE.height) / parseFloat(gcssP.height)
  2243. };
  2244.  
  2245. let elm00 = [elmBound.left, elmBound.top];
  2246. let elm01 = [elmBound.left + elmBound.width, elmBound.top];
  2247. let elm10 = [elmBound.left, elmBound.top + elmBound.height];
  2248. let elm11 = [elmBound.left + elmBound.width, elmBound.top + elmBound.height];
  2249.  
  2250. return {
  2251. elm00,
  2252. elm01,
  2253. elm10,
  2254. elm11,
  2255. plw: elmBound.width,
  2256. plh: elmBound.height
  2257. };
  2258.  
  2259. },
  2260.  
  2261. fixNonBoxingVideoTipsPosition: function(tipsDom, player) {
  2262.  
  2263. if (!tipsDom || !player) return;
  2264.  
  2265. let ct = $hs.getCommonContainer(tipsDom, player)
  2266.  
  2267. if (!ct) return;
  2268.  
  2269. //relative
  2270.  
  2271. let elm00 = $hs.responsiveSizing(ct, player).elm00;
  2272.  
  2273. if (isNaN(elm00[0]) || isNaN(elm00[1])) {
  2274.  
  2275. [tipsDom.style.left, tipsDom.style.top] = [player.style.left, player.style.top];
  2276. //eg auto
  2277. } else {
  2278.  
  2279. let rlm00 = elm00.map(t => (t * 100).toFixed(2) + '%');
  2280. [tipsDom.style.left, tipsDom.style.top] = rlm00;
  2281.  
  2282. }
  2283.  
  2284. // absolute
  2285.  
  2286. let _offset = {
  2287. left: 10,
  2288. top: 15
  2289. };
  2290.  
  2291. let customOffset = {
  2292. left: _offset.left,
  2293. top: _offset.top
  2294. };
  2295. let p = tipsDom.getBoundingClientRect();
  2296. let q = player.getBoundingClientRect();
  2297. let currentPos = [p.left, p.top];
  2298.  
  2299. let targetPos = [q.left + player.offsetWidth * 0 + customOffset.left, q.top + player.offsetHeight * 0 + customOffset.top];
  2300.  
  2301. let mL = +tipsDom.style.marginLeft.replace('px', '') || 0;
  2302. if (isNaN(mL)) mL = 0;
  2303. let mT = +tipsDom.style.marginTop.replace('px', '') || 0;
  2304. if (isNaN(mT)) mT = 0;
  2305.  
  2306. let z1 = -(currentPos[0] - targetPos[0]);
  2307. let z2 = -(currentPos[1] - targetPos[1]);
  2308.  
  2309. if (z1 || z2) {
  2310.  
  2311. let y1 = z1 + mL;
  2312. let y2 = z2 + mT;
  2313.  
  2314. tipsDom.style.marginLeft = y1 + 'px';
  2315. tipsDom.style.marginTop = y2 + 'px';
  2316.  
  2317. }
  2318. },
  2319.  
  2320. playerTrigger: function(player, event) {
  2321. if (!player || !event) return
  2322. const pCode = event.code;
  2323. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  2324.  
  2325.  
  2326. let vpid = player.getAttribute('_h5ppid') || null;
  2327. if (!vpid) return;
  2328. let playerConf = playerConfs[vpid]
  2329. if (!playerConf) return;
  2330.  
  2331. //shift + key
  2332. if (keyAsm == SHIFT) {
  2333. // 網頁FULLSCREEN
  2334. if (pCode === 'Enter') {
  2335. $hs.callFullScreenBtn()
  2336. return TERMINATE
  2337. } else if (pCode == 'KeyF') {
  2338. //change unsharpen filter
  2339.  
  2340. let resList = ["unsharpen3_05", "unsharpen3_10", "unsharpen5_05", "unsharpen5_10", "unsharpen9_05", "unsharpen9_10"]
  2341. let res = (prompt("Enter the unsharpen mask\n(" + resList.map(x => '"' + x + '"').join(', ') + ")", "unsharpen9_05") || "").toLowerCase();
  2342. if (resList.indexOf(res) < 0) res = ""
  2343. GM_setValue("unsharpen_mask", res)
  2344. for (const el of document.querySelectorAll('video[_h5p_uid_encrypted]')) {
  2345. if (el.style.filter == "" || el.style.filter) {
  2346. let filterStr1 = el.style.filter.replace(/\s*url\(\"#_h5p_unsharpen[\d\_]+\"\)/, '');
  2347. let filterStr2 = (res.length > 0 ? ' url("#_h5p_' + res + '")' : '')
  2348. el.style.filter = filterStr1 + filterStr2;
  2349. }
  2350. }
  2351. return TERMINATE
  2352.  
  2353. }
  2354. // 進入或退出畫中畫模式
  2355. else if (pCode == 'KeyP') {
  2356. $hs.pictureInPicture(player)
  2357.  
  2358. return TERMINATE
  2359. } else if (pCode == 'KeyR') {
  2360. if (player._h5player_lastrecord_ !== null && (player._h5player_lastrecord_ >= 0 || player._h5player_lastrecord_ <= 0)) {
  2361. $hs.setPlayProgress(player, player._h5player_lastrecord_)
  2362.  
  2363. return TERMINATE
  2364. }
  2365.  
  2366. } else if (pCode == 'KeyO') {
  2367. let _debug_h5p_logging_ch = false;
  2368. try {
  2369. Store._setItem('_h5_player_sLogging_', 1 - Store._getItem('_h5_player_sLogging_'))
  2370. _debug_h5p_logging_ = +Store._getItem('_h5_player_sLogging_') > 0;
  2371. _debug_h5p_logging_ch = true;
  2372. } catch (e) {
  2373.  
  2374. }
  2375. consoleLogF('_debug_h5p_logging_', !!_debug_h5p_logging_, 'changed', _debug_h5p_logging_ch)
  2376.  
  2377. if (_debug_h5p_logging_ch) {
  2378.  
  2379. return TERMINATE
  2380. }
  2381. } else if (pCode == 'KeyT') {
  2382. if (/^blob/i.test(player.currentSrc)) {
  2383. alert(`The current video is ${player.currentSrc}\nSorry, it cannot be opened in PotPlayer.`);
  2384. } else {
  2385. let confirm_res = confirm(`The current video is ${player.currentSrc}\nDo you want to open it in PotPlayer?`);
  2386. if (confirm_res) window.open('potplayer://' + player.currentSrc, '_blank');
  2387. }
  2388. return TERMINATE
  2389. }
  2390.  
  2391.  
  2392.  
  2393. let videoScale = playerConf.vFactor;
  2394.  
  2395. function tipsForVideoScaling() {
  2396.  
  2397. playerConf.vFactor = +videoScale.toFixed(1);
  2398.  
  2399. playerConf.cssTransform();
  2400. let tipsMsg = `視頻縮放率:${ +(videoScale * 100).toFixed(2) }%`
  2401. if (playerConf.translate.x) {
  2402. tipsMsg += `,水平位移:${playerConf.translate.x}px`
  2403. }
  2404. if (playerConf.translate.y) {
  2405. tipsMsg += `,垂直位移:${playerConf.translate.y}px`
  2406. }
  2407. $hs.tips(false);
  2408. $hs.tips(tipsMsg)
  2409.  
  2410.  
  2411. }
  2412.  
  2413. // 視頻畫面縮放相關事件
  2414.  
  2415. switch (pCode) {
  2416. // shift+X:視頻縮小 -0.1
  2417. case 'KeyX':
  2418. videoScale -= 0.1
  2419. if (videoScale < 0.1) videoScale = 0.1;
  2420. tipsForVideoScaling();
  2421. return TERMINATE
  2422. break
  2423. // shift+C:視頻放大 +0.1
  2424. case 'KeyC':
  2425. videoScale += 0.1
  2426. if (videoScale > 16) videoScale = 16;
  2427. tipsForVideoScaling();
  2428. return TERMINATE
  2429. break
  2430. // shift+Z:視頻恢復正常大小
  2431. case 'KeyZ':
  2432. videoScale = 1.0
  2433. playerConf.translate.x=0;
  2434. playerConf.translate.y=0;
  2435. tipsForVideoScaling();
  2436. return TERMINATE
  2437. break
  2438. case 'ArrowRight':
  2439. playerConf.translate.x += 10
  2440. tipsForVideoScaling();
  2441. return TERMINATE
  2442. break
  2443. case 'ArrowLeft':
  2444. playerConf.translate.x -= 10
  2445. tipsForVideoScaling();
  2446. return TERMINATE
  2447. break
  2448. case 'ArrowUp':
  2449. playerConf.translate.y -= 10
  2450. tipsForVideoScaling();
  2451. return TERMINATE
  2452. break
  2453. case 'ArrowDown':
  2454. playerConf.translate.y += 10
  2455. tipsForVideoScaling();
  2456. return TERMINATE
  2457. break
  2458.  
  2459. }
  2460.  
  2461. }
  2462. // 防止其它無關組合鍵衝突
  2463. if (!keyAsm) {
  2464. let kControl = null
  2465. let newPBR, oldPBR, nv;
  2466. switch (pCode) {
  2467. // 方向鍵右→:快進3秒
  2468. case 'ArrowRight':
  2469. $hs.tuneCurrentTime($hs.skipStep);
  2470. return TERMINATE;
  2471. break;
  2472. // 方向鍵左←:後退3秒
  2473. case 'ArrowLeft':
  2474. $hs.tuneCurrentTime(-$hs.skipStep);
  2475. return TERMINATE;
  2476. break;
  2477. // 方向鍵上↑:音量升高 1%
  2478. case 'ArrowUp':
  2479. if ((player.muted && player.volume === 0) && player._volume > 0) {
  2480.  
  2481. player.muted = false;
  2482. player.volume = player._volume;
  2483. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  2484. player.muted = false;
  2485. }
  2486. $hs.tuneVolume(0.01);
  2487. return TERMINATE;
  2488. break;
  2489. // 方向鍵下↓:音量降低 1%
  2490. case 'ArrowDown':
  2491.  
  2492. if ((player.muted && player.volume === 0) && player._volume > 0) {
  2493.  
  2494. player.muted = false;
  2495. player.volume = player._volume;
  2496. } else if (player.muted && (player.volume > 0 || !player._volume)) {
  2497. player.muted = false;
  2498. }
  2499. $hs.tuneVolume(-0.01);
  2500. return TERMINATE;
  2501. break;
  2502. // 空格鍵:暫停/播放
  2503. case 'Space':
  2504. $hs.switchPlayStatus();
  2505. return TERMINATE;
  2506. break;
  2507. // 按鍵X:減速播放 -0.1
  2508. case 'KeyX':
  2509. if (player.playbackRate > 0) {
  2510. $hs.tips(false);
  2511. $hs.setPlaybackRate(player.playbackRate - 0.1);
  2512. return TERMINATE
  2513. }
  2514. break;
  2515. // 按鍵C:加速播放 +0.1
  2516. case 'KeyC':
  2517. if (player.playbackRate < 16) {
  2518. $hs.tips(false);
  2519. $hs.setPlaybackRate(player.playbackRate + 0.1);
  2520. return TERMINATE
  2521. }
  2522.  
  2523. break;
  2524. // 按鍵Z:正常速度播放
  2525. case 'KeyZ':
  2526. $hs.tips(false);
  2527. oldPBR = player.playbackRate;
  2528. if (oldPBR != 1.0) {
  2529. player._playbackRate_z = oldPBR;
  2530. newPBR = 1.0;
  2531. } else if (player._playbackRate_z != 1.0) {
  2532. newPBR = player._playbackRate_z || 1.0;
  2533. player._playbackRate_z = 1.0;
  2534. } else {
  2535. newPBR = 1.0
  2536. player._playbackRate_z = 1.0;
  2537. }
  2538. $hs.setPlaybackRate(newPBR, 1)
  2539. return TERMINATE
  2540. break;
  2541. // 按鍵F:下一幀
  2542. case 'KeyF':
  2543. if (window.location.hostname === 'www.netflix.com') return /* netflix 的F鍵是FULLSCREEN的意思 */
  2544. $hs.tips(false);
  2545. if (!player.paused) player.pause()
  2546. player.currentTime += +(1 / playerConf.fps)
  2547. $hs.tips('Jump to: Next frame')
  2548. return TERMINATE
  2549. break;
  2550. // 按鍵D:上一幀
  2551. case 'KeyD':
  2552. $hs.tips(false);
  2553. if (!player.paused) player.pause()
  2554. player.currentTime -= +(1 / playerConf.fps)
  2555. $hs.tips('Jump to: Previous frame')
  2556. return TERMINATE
  2557. break;
  2558. // 按鍵E:亮度增加%
  2559. case 'KeyE':
  2560. $hs.tips(false);
  2561. nv = playerConf.setFilter('brightness', (v) => v + 0.1);
  2562. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  2563. return TERMINATE
  2564. break;
  2565. // 按鍵W:亮度減少%
  2566. case 'KeyW':
  2567. $hs.tips(false);
  2568. nv = playerConf.setFilter('brightness', (v) => v > 0.1 ? v - 0.1 : 0);
  2569. $hs.tips('Brightness: ' + dround(nv * 100) + '%')
  2570. return TERMINATE
  2571. break;
  2572. // 按鍵T:對比度增加%
  2573. case 'KeyT':
  2574. $hs.tips(false);
  2575. nv = playerConf.setFilter('contrast', (v) => v + 0.1);
  2576. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  2577. return TERMINATE
  2578. break;
  2579. // 按鍵R:對比度減少%
  2580. case 'KeyR':
  2581. $hs.tips(false);
  2582. nv = playerConf.setFilter('contrast', (v) => v > 0.1 ? v - 0.1 : 0);
  2583. $hs.tips('Contrast: ' + dround(nv * 100) + '%')
  2584. return TERMINATE
  2585. break;
  2586. // 按鍵U:飽和度增加%
  2587. case 'KeyU':
  2588. $hs.tips(false);
  2589. nv = playerConf.setFilter('saturate', (v) => v + 0.1);
  2590. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  2591. return TERMINATE
  2592. break;
  2593. // 按鍵Y:飽和度減少%
  2594. case 'KeyY':
  2595. $hs.tips(false);
  2596. nv = playerConf.setFilter('saturate', (v) => v > 0.1 ? v - 0.1 : 0);
  2597. $hs.tips('Saturate: ' + dround(nv * 100) + '%')
  2598. return TERMINATE
  2599. break;
  2600. // 按鍵O:色相增加 1 度
  2601. case 'KeyO':
  2602. $hs.tips(false);
  2603. nv = playerConf.setFilter('hue-rotate', (v) => v + 1);
  2604. $hs.tips('Hue: ' + nv + ' deg')
  2605. return TERMINATE
  2606. break;
  2607. // 按鍵I:色相減少 1 度
  2608. case 'KeyI':
  2609. $hs.tips(false);
  2610. nv = playerConf.setFilter('hue-rotate', (v) => v - 1);
  2611. $hs.tips('Hue: ' + nv + ' deg')
  2612. return TERMINATE
  2613. break;
  2614. // 按鍵K:模糊增加 0.1 px
  2615. case 'KeyK':
  2616. $hs.tips(false);
  2617. nv = playerConf.setFilter('blur', (v) => v + 0.1);
  2618. $hs.tips('Blur: ' + nv + ' px')
  2619. return TERMINATE
  2620. break;
  2621. // 按鍵J:模糊減少 0.1 px
  2622. case 'KeyJ':
  2623. $hs.tips(false);
  2624. nv = playerConf.setFilter('blur', (v) => v > 0.1 ? v - 0.1 : 0);
  2625. $hs.tips('Blur: ' + nv + ' px')
  2626. return TERMINATE
  2627. break;
  2628. // 按鍵Q:圖像復位
  2629. case 'KeyQ':
  2630. $hs.tips(false);
  2631. playerConf.filterReset();
  2632. $hs.tips('Video Filter Reset')
  2633. return TERMINATE
  2634. break;
  2635. // 按鍵S:畫面旋轉 90 度
  2636. case 'KeyS':
  2637. $hs.tips(false);
  2638. playerConf.rotate += 90
  2639. if (playerConf.rotate % 360 === 0) playerConf.rotate = 0;
  2640. if(!playerConf.videoHeight||!playerConf.videoWidth){
  2641. playerConf.videoWidth = playerConf.domElement.videoWidth;
  2642. playerConf.videoHeight = playerConf.domElement.videoHeight;
  2643. }
  2644. if (playerConf.videoWidth>0 && playerConf.videoHeight>0) {
  2645.  
  2646.  
  2647. if ((playerConf.rotate % 180) == 90) {
  2648. playerConf.mFactor = playerConf.videoHeight / playerConf.videoWidth;
  2649. } else {
  2650. playerConf.mFactor = 1.0;
  2651. }
  2652.  
  2653.  
  2654. playerConf.cssTransform();
  2655.  
  2656. $hs.tips('Rotation:' + playerConf.rotate + ' deg')
  2657.  
  2658. }
  2659.  
  2660. return TERMINATE
  2661. break;
  2662. // 按鍵迴車,進入FULLSCREEN
  2663. case 'Enter':
  2664. //t.callFullScreenBtn();
  2665. break;
  2666. case 'KeyN':
  2667. $hs.pictureInPicture(player);
  2668. return TERMINATE
  2669. break;
  2670. case 'KeyM':
  2671. //console.log('m!', player.volume,player._volume)
  2672.  
  2673. if (player.volume >= 0) {
  2674.  
  2675. if (!player.volume || player.muted) {
  2676.  
  2677. let newVol = player.volume || player._volume || 0.5;
  2678. if (player.volume !== newVol) {
  2679. player.volume = newVol;
  2680. }
  2681. player.muted = false;
  2682. $hs.tips(false);
  2683. $hs.tips('Mute: Off', undefined);
  2684.  
  2685. } else {
  2686.  
  2687. player._volume = player.volume;
  2688. player._volume_p = player.volume;
  2689. //player.volume = 0;
  2690. player.muted = true;
  2691. $hs.tips(false);
  2692. $hs.tips('Mute: On', undefined);
  2693.  
  2694. }
  2695.  
  2696. }
  2697.  
  2698. return TERMINATE
  2699. break;
  2700. default:
  2701. // 按1-4設置播放速度 49-52;97-100
  2702. let numKey = +(event.key)
  2703.  
  2704. if (numKey >= 1 && numKey <= 4) {
  2705. $hs.tips(false);
  2706. $hs.setPlaybackRate(numKey, 1)
  2707. return TERMINATE
  2708. }
  2709. }
  2710.  
  2711. }
  2712. },
  2713.  
  2714. handlerPlayerMouseMove: function(e) {
  2715. let player = $hs.player();
  2716. let rootNode = getRoot(player);
  2717.  
  2718. if (rootNode.pointerLockElement != player) {
  2719. player.removeEventListener('mousemove', $hs.handlerPlayerMouseMove)
  2720. return;
  2721. }
  2722.  
  2723. let movementX = e.movementX || e.mozMovementX || e.webkitMovementX || 0,
  2724. movementY = e.movementY || e.mozMovementY || e.webkitMovementY || 0;
  2725.  
  2726. player.__xyOffset.x += movementX
  2727. player.__xyOffset.y += movementY
  2728. let ld = Math.sqrt(screen.width * screen.width + screen.height * screen.height) * .1
  2729. let md = Math.sqrt(player.__xyOffset.x * player.__xyOffset.x + player.__xyOffset.y * player.__xyOffset.y);
  2730. if (md > ld) $hs.playerActionLeave();
  2731.  
  2732. },
  2733.  
  2734. playerActionEnter: function() {
  2735. let player = $hs.player();
  2736.  
  2737. if (player) {
  2738. player.__requestPointerLock__();
  2739. player.__xyOffset = {
  2740. x: 0,
  2741. y: 0
  2742. };
  2743. player.addEventListener('mousemove', $hs.handlerPlayerMouseMove)
  2744. }
  2745. },
  2746.  
  2747. playerActionLeave: function() {
  2748. let player = $hs.player();
  2749. if (player) player.removeEventListener('mousemove', $hs.handlerPlayerMouseMove)
  2750. document.__exitPointerLock__();
  2751. },
  2752.  
  2753. /* 按鍵響應方法 */
  2754. handlerRootKeyDownEvent: function(event) {
  2755. if ($hs.intVideoInitCount > 0) {} else {
  2756. return;
  2757. }
  2758. // DOM Standard - either .key or .code
  2759. // Here we adopt .code (physical layout)
  2760.  
  2761. let pCode = event.code;
  2762. if (typeof pCode != 'string') return;
  2763.  
  2764. let player = $hs.player()
  2765.  
  2766. if (!player) return; // no video tag
  2767.  
  2768. let rootNode = getRoot(player);
  2769.  
  2770. let keyAsm = (event.shiftKey ? SHIFT : 0) | ((event.ctrlKey || event.metaKey) ? CTRL : 0) | (event.altKey ? ALT : 0);
  2771.  
  2772. if (!keyAsm && pCode == 'Escape' && (document.fullscreenElement || rootNode.pointerLockElement)) {
  2773. setTimeout(() => {
  2774. if (document.fullscreenElement) {
  2775. document.exitFullscreen();
  2776. } else if (document.pointerLockElement) {
  2777. $hs.playerActionLeave();
  2778. }
  2779. }, 700);
  2780. return;
  2781. }
  2782.  
  2783. if (isInOperation(event.target)) return;
  2784.  
  2785. //console.log('K01')
  2786.  
  2787. /* 切換插件的可用狀態 */
  2788. // Shift-`
  2789. if (keyAsm == SHIFT && pCode == 'Backquote') {
  2790. $hs.enable = !$hs.enable;
  2791. $hs.tips(false);
  2792. if ($hs.enable) {
  2793. $hs.tips('啟用h5Player插件')
  2794. } else {
  2795. $hs.tips('禁用h5Player插件')
  2796. }
  2797. // 阻止事件冒泡
  2798. event.stopPropagation()
  2799. event.preventDefault()
  2800. return false
  2801. }
  2802. if (!$hs.enable) {
  2803. consoleLog('h5Player 已禁用~')
  2804. return false
  2805. }
  2806.  
  2807. /* 非全局模式下,不聚焦則不執行快捷鍵的操作 */
  2808.  
  2809. if (!keyAsm && pCode == 'Enter' && !isInOperation()) { //not NumberpadEnter
  2810. if (!rootNode.pointerLockElement && !document.fullscreenElement) {
  2811. if (rootNode.pointerLockElement != player) {
  2812. $hs.playerActionEnter();
  2813.  
  2814. // 阻止事件冒泡
  2815. event.stopPropagation()
  2816. event.preventDefault()
  2817. return false
  2818. }
  2819. } else if (rootNode.pointerLockElement && !document.fullscreenElement) {
  2820. $hs.playerActionLeave();
  2821.  
  2822. // 阻止事件冒泡
  2823. event.stopPropagation()
  2824. event.preventDefault()
  2825. return false
  2826. } else if (document.fullscreenElement) {
  2827. document.exitFullscreen();
  2828.  
  2829. // 阻止事件冒泡
  2830. event.stopPropagation()
  2831. event.preventDefault()
  2832. return false
  2833. }
  2834. }
  2835.  
  2836. let hv = (elm) => (elm && (elm == player || elm.contains(player)) ? elm : null);
  2837.  
  2838. let _checkingPass;
  2839.  
  2840. let plm = null;
  2841. if (rootNode.activeElement && !rootNode.pointerLockElement && !document.fullscreenElement) {
  2842. // the active element may or may not contains the player
  2843. // but the player box (player->parent->parent->...) shall contains the active element (and the player)
  2844. // so if the active element is inside the layoutbox, okay!
  2845. // ps. layoutbox may be much larger than the activeelement, then it is not overlapping case.
  2846.  
  2847. plm = rootNode.activeElement
  2848.  
  2849. //console.log('activeElement', plm)
  2850. _checkingPass = $hs.isInActiveMode(rootNode.activeElement, player);
  2851. } else {
  2852. plm = hv(rootNode.pointerLockElement) || hv(document.fullscreenElement)
  2853. _checkingPass = !!plm
  2854. }
  2855.  
  2856.  
  2857. if (_checkingPass) {
  2858.  
  2859. if (isInOperation()) return;
  2860.  
  2861.  
  2862. let res = $hs.playerTrigger(player, event)
  2863. if (res == TERMINATE) {
  2864. event.stopPropagation()
  2865. event.preventDefault()
  2866. return false
  2867. }
  2868.  
  2869. }
  2870. },
  2871. /* 設置播放進度 */
  2872. setPlayProgress: function(player, curTime) {
  2873. if (!player) return
  2874. if (!curTime || Number.isNaN(curTime)) return
  2875. player.currentTime = curTime
  2876. if (curTime > 3) {
  2877. $hs.tips(false);
  2878. $hs.tips(`Playback Jumps to ${$hs.toolFormatCT(curTime)}`)
  2879. if (player.paused) player.play();
  2880. }
  2881. }
  2882. }
  2883.  
  2884. function makeFilter(arr, k) {
  2885. let res = ""
  2886. for (const e of arr) {
  2887. for (const d of e) {
  2888. res += " " + (1.0 * d * k).toFixed(9)
  2889. }
  2890. }
  2891. return res.trim()
  2892. }
  2893.  
  2894. function _add_filter(rootElm) {
  2895. let rootView = null;
  2896. if (rootElm && rootElm.nodeType > 0) {
  2897. while (rootElm.parentNode && rootElm.parentNode.nodeType === 1) rootElm = rootElm.parentNode;
  2898. rootView = rootElm.querySelector('body') || rootElm;
  2899. } else {
  2900. return;
  2901. }
  2902.  
  2903. if (rootView && rootView.querySelector && !rootView.querySelector('#_h5player_section_')) {
  2904.  
  2905. let svgFilterElm = document.createElement('section')
  2906. svgFilterElm.style.position = 'fixed';
  2907. svgFilterElm.style.left = '-999px';
  2908. svgFilterElm.style.width = '1px';
  2909. svgFilterElm.style.top = '-999px';
  2910. svgFilterElm.style.height = '1px';
  2911. svgFilterElm.id = '_h5player_section_'
  2912. let svgXML = `
  2913. <svg id='_h5p_image' version="1.1" xmlns="http://www.w3.org/2000/svg">
  2914. <defs>
  2915. <filter id="_h5p_sharpen1">
  2916. <feConvolveMatrix filterRes="100 100" style="color-interpolation-filters:sRGB" order="3" kernelMatrix="` + `
  2917. -0.3 -0.3 -0.3
  2918. -0.3 3.4 -0.3
  2919. -0.3 -0.3 -0.3`.replace(/[\n\r]+/g, ' ').trim() + `" preserveAlpha="true"/>
  2920. </filter>
  2921. <filter id="_h5p_unsharpen1">
  2922. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  2923. makeFilter([
  2924. [1, 4, 6, 4, 1],
  2925. [4, 16, 24, 16, 4],
  2926. [6, 24, -476, 24, 6],
  2927. [4, 16, 24, 16, 4],
  2928. [1, 4, 6, 4, 1]
  2929. ], -1 / 256) + `" preserveAlpha="false"/>
  2930. </filter>
  2931. <filter id="_h5p_unsharpen3_05">
  2932. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  2933. makeFilter(
  2934. [
  2935. [0.025, 0.05, 0.025],
  2936. [0.05, -1.1, 0.05],
  2937. [0.025, 0.05, 0.025]
  2938. ], -1 / .8) + `" preserveAlpha="false"/>
  2939. </filter>
  2940. <filter id="_h5p_unsharpen3_10">
  2941. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="3" kernelMatrix="` +
  2942. makeFilter(
  2943. [
  2944. [0.05, 0.1, 0.05],
  2945. [0.1, -1.4, 0.1],
  2946. [0.05, 0.1, 0.05]
  2947. ], -1 / .8) + `" preserveAlpha="false"/>
  2948. </filter>
  2949. <filter id="_h5p_unsharpen5_05">
  2950. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  2951. makeFilter(
  2952. [
  2953. [0.025, 0.1, 0.15, 0.1, 0.025],
  2954. [0.1, 0.4, 0.6, 0.4, 0.1],
  2955. [0.15, 0.6, -18.3, 0.6, 0.15],
  2956. [0.1, 0.4, 0.6, 0.4, 0.1],
  2957. [0.025, 0.1, 0.15, 0.1, 0.025]
  2958. ], -1 / 12.8) + `" preserveAlpha="false"/>
  2959. </filter>
  2960. <filter id="_h5p_unsharpen5_10">
  2961. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="5" kernelMatrix="` +
  2962. makeFilter(
  2963. [
  2964. [0.05, 0.2, 0.3, 0.2, 0.05],
  2965. [0.2, 0.8, 1.2, 0.8, 0.2],
  2966. [0.3, 1.2, -23.8, 1.2, 0.3],
  2967. [0.2, 0.8, 1.2, 0.8, 0.2],
  2968. [0.05, 0.2, 0.3, 0.2, 0.05]
  2969. ], -1 / 12.8) + `" preserveAlpha="false"/>
  2970. </filter>
  2971. <filter id="_h5p_unsharpen9_05">
  2972. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  2973. makeFilter(
  2974. [
  2975. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025],
  2976. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  2977. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  2978. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  2979. [1.75, 14, 49, 98, -4792.7, 98, 49, 14, 1.75],
  2980. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  2981. [0.7, 5.6, 19.6, 39.2, 49, 39.2, 19.6, 5.6, 0.7],
  2982. [0.2, 1.6, 5.6, 11.2, 14, 11.2, 5.6, 1.6, 0.2],
  2983. [0.025, 0.2, 0.7, 1.4, 1.75, 1.4, 0.7, 0.2, 0.025]
  2984. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  2985. </filter>
  2986. <filter id="_h5p_unsharpen9_10">
  2987. <feConvolveMatrix style="color-interpolation-filters:sRGB;color-interpolation: sRGB;" order="9" kernelMatrix="` +
  2988. makeFilter(
  2989. [
  2990. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05],
  2991. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  2992. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  2993. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  2994. [3.5, 28, 98, 196, -6308.6, 196, 98, 28, 3.5],
  2995. [2.8, 22.4, 78.4, 156.8, 196, 156.8, 78.4, 22.4, 2.8],
  2996. [1.4, 11.2, 39.2, 78.4, 98, 78.4, 39.2, 11.2, 1.4],
  2997. [0.4, 3.2, 11.2, 22.4, 28, 22.4, 11.2, 3.2, 0.4],
  2998. [0.05, 0.4, 1.4, 2.8, 3.5, 2.8, 1.4, 0.4, 0.05]
  2999. ], -1 / 3276.8) + `" preserveAlpha="false"/>
  3000. </filter>
  3001. <filter id="_h5p_grey1">
  3002. <feColorMatrix values="0.3333 0.3333 0.3333 0 0
  3003. 0.3333 0.3333 0.3333 0 0
  3004. 0.3333 0.3333 0.3333 0 0
  3005. 0 0 0 1 0"/>
  3006. <feColorMatrix type="saturate" values="0" />
  3007. </filter>
  3008. </defs>
  3009. </svg>
  3010. `;
  3011.  
  3012. svgFilterElm.innerHTML = svgXML.replace(/[\r\n\s]+/g, ' ').trim();
  3013.  
  3014. rootView.appendChild(svgFilterElm);
  3015. }
  3016.  
  3017. }
  3018.  
  3019. /**
  3020. * 某些網頁用了attachShadow closed mode,需要open才能獲取video標籤,例如百度雲盤
  3021. * 解決參考:
  3022. * https://developers.google.com/web/fundamentals/web-components/shadowdom?hl=zh-cn#closed
  3023. * https://stackoverflow.com/questions/54954383/override-element-prototype-attachshadow-using-chrome-extension
  3024. */
  3025.  
  3026. const initForShadowRoot = async (shadowRoot) => {
  3027. try {
  3028. if (shadowRoot && shadowRoot.nodeType > 0 && 'querySelectorAll' in shadowRoot) {
  3029. $hs.bindDocEvents(shadowRoot);
  3030. new VideoListener(shadowRoot).listen(handlerVideoFound)
  3031. shadowRoots.push(shadowRoot)
  3032. }
  3033. } catch (e) {
  3034. console.log('h5Player: initForShadowRoot failed')
  3035. }
  3036. }
  3037.  
  3038. function hackAttachShadow() { // attachShadow - DOM Standard
  3039.  
  3040. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3041. if (_prototype_ && typeof _prototype_.attachShadow == 'function') {
  3042.  
  3043. let _attachShadow = _prototype_.attachShadow
  3044.  
  3045. hackAttachShadow = null
  3046. _prototype_.attachShadow = function() {
  3047. let arg = [...arguments];
  3048. if (arg[0] && arg[0].mode) arg[0].mode = 'open';
  3049. let shadowRoot = _attachShadow.apply(this, arg);
  3050. initForShadowRoot(shadowRoot);
  3051. return shadowRoot
  3052. };
  3053.  
  3054. _prototype_.attachShadow.toString = () => _attachShadow.toString();
  3055.  
  3056. }
  3057.  
  3058. }
  3059.  
  3060. function hackCreateShadowRoot() { // createShadowRoot - Deprecated
  3061.  
  3062. let _prototype_ = window && window.HTMLElement ? window.HTMLElement.prototype : null;
  3063. if (_prototype_ && typeof _prototype_.createShadowRoot == 'function') {
  3064.  
  3065. let _createShadowRoot = _prototype_.createShadowRoot;
  3066.  
  3067. hackCreateShadowRoot = null
  3068. _prototype_.createShadowRoot = function() {
  3069. const shadowRoot = _createShadowRoot.apply(this, arguments);
  3070. initForShadowRoot(shadowRoot);
  3071. return shadowRoot;
  3072. };
  3073. _prototype_.createShadowRoot.toString = () => _createShadowRoot.toString();
  3074.  
  3075. }
  3076. }
  3077.  
  3078. /* 事件偵聽hack */
  3079. function hackEventListener() {
  3080. if (!window.EventTarget) return;
  3081. const eventTargetPrototype = window.EventTarget.prototype;
  3082. let _addEventListener = eventTargetPrototype.addEventListener;
  3083. let _removeEventListener = eventTargetPrototype.removeEventListener;
  3084. if (typeof _addEventListener == 'function' && typeof _removeEventListener == 'function') {} else return;
  3085. hackEventListener = null;
  3086.  
  3087. class Listeners {
  3088.  
  3089. constructor(dom, type) {
  3090. this._dom = dom;
  3091. this._type = type;
  3092. this.listenersCount = 0;
  3093. this.hashList = {};
  3094. }
  3095. get baseFunc() {
  3096. if (this._dom && this._type) {
  3097. return this._dom['on' + this._type];
  3098. }
  3099. }
  3100. get funcCount() {
  3101. if (this._dom && this._type) {
  3102. return (typeof this.baseFunc == 'function') * 1 + (this.listenersCount || 0)
  3103. }
  3104. }
  3105.  
  3106.  
  3107. }
  3108.  
  3109.  
  3110.  
  3111. let hackedEvtCount = 0;
  3112.  
  3113.  
  3114. function timeupdateHack() {
  3115.  
  3116.  
  3117. let evtTarget = this;
  3118.  
  3119. if (typeof arguments[1] != 'function' || typeof arguments[0] != 'string') throw '';
  3120. const type = arguments[0];
  3121. const fn = arguments[1];
  3122. if (type != 'timeupdate') throw '';
  3123.  
  3124. //console.log('timeupdate detection')
  3125.  
  3126.  
  3127.  
  3128.  
  3129. let tupId = evtTarget.getAttribute('_h5p_tup_');
  3130.  
  3131. if (tupId === null) { // 0 1 2 ...
  3132.  
  3133. const fakeTimeUpdateEvent = [];
  3134.  
  3135. evtTarget.setAttribute('_h5p_tup_', tupId = timeupdateStore.length); // 0, 1, 2...
  3136. timeupdateStore.push({
  3137. videoElement: evtTarget,
  3138. eventHandlersCapture: [],
  3139. eventHandlersBubbles: [],
  3140. eventHandlersRunner: [],
  3141. fakeTimeUpdateEvent,
  3142. lastTime: -1
  3143. });
  3144.  
  3145. const gn = (event) => {
  3146. console.log('h5Player - boost timeupdate is enabled')
  3147. fakeTimeUpdateEvent.push(event);
  3148. };
  3149. _addEventListener.call(evtTarget, type, gn, {
  3150. capture: true,
  3151. passive: true,
  3152. once: true
  3153. })
  3154.  
  3155.  
  3156. } else {
  3157. tupId = +tupId;
  3158.  
  3159. }
  3160.  
  3161.  
  3162. const tupConf = timeupdateStore[tupId];
  3163. let useCapture = false;
  3164. const thirdArg = arguments[2];
  3165. switch (typeof thirdArg) {
  3166. case 'boolean':
  3167. if (thirdArg === true) useCapture = true;
  3168. break;
  3169. case 'object':
  3170. if (thirdArg && thirdArg.capture === true) useCapture = true;
  3171. break;
  3172. }
  3173. if (useCapture) tupConf.eventHandlersCapture.push(fn);
  3174. else tupConf.eventHandlersBubbles.push(fn);
  3175. tupConf.eventHandlersRunner = tupConf.eventHandlersCapture.concat(tupConf.eventHandlersBubbles);
  3176.  
  3177.  
  3178. if (!$hs._onceTimeUpdateHack) {
  3179. $hs._onceTimeUpdateHack = true;
  3180. if (!_endlessloop) _endlessloop = new AFLooperArray();
  3181. let opts = _endlessloop.appendLoop(handle.afBoostTimeUpdate)
  3182. opts.loopingStart();
  3183. }
  3184.  
  3185.  
  3186. return _addEventListener.apply(this, arguments)
  3187.  
  3188. }
  3189.  
  3190. let watchList = ['timeupdate', 'click'];
  3191.  
  3192. eventTargetPrototype.addEventListener = function() {
  3193.  
  3194. let arg = arguments
  3195. let type = arg[0]
  3196. let listener = arg[1]
  3197.  
  3198. if (!this || !(this instanceof EventTarget) || typeof type != 'string' || typeof listener != 'function') {
  3199. return _addEventListener.apply(this, arguments)
  3200. //unknown bug?
  3201. }
  3202.  
  3203. if (watchList.indexOf(type) < 0) return _addEventListener.apply(this, arguments);
  3204.  
  3205.  
  3206. let res;
  3207. if (type == 'timeupdate' && this.nodeType == 1 && this.nodeName == "VIDEO" && isSupportAdvancedEventListener()) {
  3208. res = timeupdateHack.apply(this, arg)
  3209. } else {
  3210. res = _addEventListener.apply(this, arg)
  3211. }
  3212.  
  3213.  
  3214. let boolCapture = (arg[2] && typeof arg[2] == 'object') ? (arg[2].capture === true) : (arg[2] === true)
  3215.  
  3216. this._listeners = this._listeners || {}
  3217. this._listeners[type] = this._listeners[type] || new Listeners(this, type)
  3218. let uid = 100000 + (++hackedEvtCount);
  3219. let listenerObj = {
  3220. listener,
  3221. options: arg[2],
  3222. uid: uid,
  3223. useCapture: boolCapture
  3224. }
  3225. this._listeners[type].hashList[uid + ''] = listenerObj;
  3226. this._listeners[type].listenersCount++;
  3227. return res;
  3228. }
  3229. // hack removeEventListener
  3230. eventTargetPrototype.removeEventListener = function() {
  3231.  
  3232. let arg = arguments
  3233. let type = arg[0]
  3234. let listener = arg[1]
  3235.  
  3236. if (!this || !(this instanceof EventTarget) || typeof type != 'string' || typeof listener != 'function') {
  3237. return _removeEventListener.apply(this, arguments)
  3238. //unknown bug?
  3239. }
  3240.  
  3241. if (watchList.indexOf(type) < 0) return _removeEventListener.apply(this, arguments);
  3242.  
  3243. let boolCapture = (arg[2] && typeof arg[2] == 'object') ? (arg[2].capture === true) : (arg[2] === true)
  3244.  
  3245. let defaultRemoval = true;
  3246. if (this._listeners && this._listeners[type] && this._listeners[type].hashList) {
  3247. let hashList = this._listeners[type].hashList
  3248. for (let k in hashList) {
  3249. if (hashList[k].listener === listener && hashList[k].useCapture == boolCapture) {
  3250. delete hashList[k];
  3251. this._listeners[type].listenersCount--;
  3252. break;
  3253. }
  3254. }
  3255. }
  3256. if (defaultRemoval) return _removeEventListener.apply(this, arg);
  3257. }
  3258. eventTargetPrototype.addEventListener.toString = () => _addEventListener.toString();
  3259. eventTargetPrototype.removeEventListener.toString = () => _removeEventListener.toString();
  3260.  
  3261.  
  3262. }
  3263.  
  3264. function handlerVideoFound(video) {
  3265.  
  3266. if (!video) return;
  3267. if (video.getAttribute('_h5ppid')) return;
  3268. let alabel = video.getAttribute('aria-label')
  3269. if (alabel && typeof alabel == "string" && alabel.toUpperCase() == "GIF") return;
  3270.  
  3271.  
  3272. consoleLog('handlerVideoFound', video)
  3273.  
  3274. $hs.intVideoInitCount = ($hs.intVideoInitCount || 0) + 1;
  3275. let vpid = 'h5p-' + $hs.intVideoInitCount
  3276. consoleLog(' - HTML5 Video is detected -', `Number of Videos: ${$hs.intVideoInitCount}`)
  3277. if ($hs.intVideoInitCount === 1) $hs.fireGlobalInit();
  3278. video.setAttribute('_h5ppid', vpid)
  3279.  
  3280.  
  3281. playerConfs[vpid] = new PlayerConf();
  3282. playerConfs[vpid].domElement = video;
  3283. playerConfs[vpid].domActive = DOM_ACTIVE_FOUND;
  3284.  
  3285. let rootNode = getRoot(video);
  3286.  
  3287. if (rootNode.host) $hs.getPlayerBlockElement(video); // shadowing
  3288. let rootElm = rootNode.querySelector('head') || rootNode.querySelector('html') || document.documentElement //48763
  3289. _add_filter(rootElm) // either main document or shadow node
  3290.  
  3291. video.addEventListener('loadedmetadata', $hs.handlerVideoLoadedMetaData, true);
  3292.  
  3293. }
  3294.  
  3295.  
  3296. ResizeODM.__init__();
  3297.  
  3298. hackAttachShadow()
  3299. hackCreateShadowRoot()
  3300. hackEventListener()
  3301.  
  3302.  
  3303. window.addEventListener('message', $hs.handlerWinMessage, false);
  3304. $hs.bindDocEvents(document);
  3305. new VideoListener(document.documentElement).listen(handlerVideoFound)
  3306.  
  3307. let windowsLD = (function() {
  3308. let ls_res = [];
  3309. try {
  3310. ls_res = [!!window.localStorage, !!window.top.localStorage];
  3311. } catch (e) {}
  3312. try {
  3313. let winp = window;
  3314. let winc = 0;
  3315. while (winp !== window.top && winp && ++winc) winp = winp.parentNode;
  3316. ls_res.push(winc);
  3317. } catch (e) {}
  3318. return ls_res;
  3319. })();
  3320.  
  3321. consoleLogF('- h5Player Plugin Loaded -', ...windowsLD)
  3322.  
  3323. function isInCrossOriginFrame() {
  3324. let result = true;
  3325. try {
  3326. if (window.top.localStorage || window.top.location.href) result = false;
  3327. } catch (e) {}
  3328. return result
  3329. }
  3330.  
  3331. if (isInCrossOriginFrame()) consoleLog('cross origin frame detected');
  3332.  
  3333.  
  3334. })();