-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhtml5-video-hotkeys.user.js
4317 lines (3356 loc) · 170 KB
/
html5-video-hotkeys.user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==UserScript==
// @name HTML5 Video Player Enhance
// @version 2.9.6.1.2
// @description To enhance the functionality of HTML5 Video Player (h5player) supporting all websites using shortcut keys similar to PotPlayer.
// @author CY Fung (mods by Alistair1231)
// @icon https://image.flaticon.com/icons/png/128/3291/3291444.png
// @match https://*/*
// @match http://*/*
// @exclude https://www.youtube.com/live_chat*
// @run-at document-start
// @require https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js
// @namespace https://github.com/Alistair1231/my-userscripts/
// @grant GM_getValue
// @grant GM_setValue
// @grant unsafeWindow
// ==/UserScript==
/**
* Remarks
* This script support modern browser only with ES6+.
* fullscreen and pointerLock buggy in shadowRoot
* Space Pause not success
* shift F key issue
**/
!(function ($winUnsafe, $winSafe) {
'use strict';
!(() => 0)({
requestAnimationFrame,
cancelAnimationFrame,
MutationObserver,
setInterval,
clearInterval,
EventTarget,
Promise,
ResizeObserver
});
//throw Error if your browser is too outdated. (eg ES6 script, no such window object)
const window = $winUnsafe || $winSafe
const document = window.document
const $$uWin = $winUnsafe || $winSafe;
const $rAf = $$uWin.requestAnimationFrame;
const $cAf = $$uWin.cancelAnimationFrame;
const $$setTimeout = $$uWin.setTimeout
const $$clearTimeout = $$uWin.clearTimeout
const $$requestAnimationFrame = $$uWin.requestAnimationFrame;
const $$cancelAnimationFrame = $$uWin.cancelAnimationFrame;
const $$addEventListener = Node.prototype.addEventListener;
const $$removeEventListener = Node.prototype.removeEventListener;
const $bz = {
boosted: false
}
const utPositioner = 'KVZX';
1 && !(function $$() {
'use strict';
if (!document) return;
if (!document.documentElement) return window.requestAnimationFrame($$);
const prettyElm = function (elm) {
if (!elm || !elm.nodeName) return null;
const eId = elm.id || null;
const eClsName = elm.className || null;
return [elm.nodeName.toLowerCase(), typeof eId == 'string' ? "#" + eId : '', typeof eClsName == 'string' ? '.' + eClsName.replace(/\s+/g, '.') : ''].join('').trim();
}
const delayCall = function (p, f, d) {
if (delayCall[p] > 0) delayCall[p] = window.clearTimeout(delayCall[p])
if (f) delayCall[p] = window.setTimeout(f, d)
}
function isVideoPlaying(video) {
return video.currentTime > 0 && !video.paused && !video.ended && video.readyState > video.HAVE_CURRENT_DATA;
}
const wmListeners = new WeakMap();
class Listeners {
constructor() { }
get count() {
return (this._count || 0)
}
makeId() {
return ++this._lastId
}
add(lh) {
this[++this._lastId] = lh;
this._count++;
}
remove(lh_removal) {
for (let k in this) {
let lh = this[k]
if (lh && lh.constructor == ListenerHandle && lh_removal.isEqual(lh)) {
delete this[k];
this._count--;
}
}
}
}
class ListenerHandle {
constructor(func, options) {
this.func = func
this.options = options
}
isEqual(anotherLH) {
if (this.func != anotherLH.func) return false;
if (this.options === anotherLH.options) return true;
if (this.options && anotherLH.options && typeof this.options == 'object' && typeof anotherLH.options == 'object') {
return this.uOpt() == anotherLH.uOpt()
} else {
return false;
}
}
uOpt() {
let opt1 = "";
for (var k in this.options) {
opt1 += ", " + k + " : " + (typeof this[k] == 'boolean' ? this[k] : "N/A");
}
return opt1;
}
}
Object.defineProperties(Listeners.prototype, {
_lastId: {
value: 0,
writable: true,
enumerable: false,
configurable: true
},
_count: {
value: 0,
writable: true,
enumerable: false,
configurable: true
}
});
let _debug_h5p_logging_ = false;
try {
_debug_h5p_logging_ = +window.localStorage.getItem('_h5_player_sLogging_') > 0
} catch (e) { }
const SHIFT = 1;
const CTRL = 2;
const ALT = 4;
const TERMINATE = 0x842;
const _sVersion_ = 1817;
const str_postMsgData = '__postMsgData__'
const DOM_ACTIVE_FOUND = 1;
const DOM_ACTIVE_SRC_LOADED = 2;
const DOM_ACTIVE_ONCE_PLAYED = 4;
const DOM_ACTIVE_MOUSE_CLICK = 8;
const DOM_ACTIVE_KEY_DOWN = 64;
const DOM_ACTIVE_FULLSCREEN = 128;
const DOM_ACTIVE_MOUSE_IN = 16;
const DOM_ACTIVE_DELAYED_PAUSED = 32;
const DOM_ACTIVE_INVALID_PARENT = 2048;
var console = {};
console.log = function () {
window.console.log(...['[h5p]', ...arguments])
}
console.error = function () {
window.console.error(...['[h5p]', ...arguments])
}
function makeNoRoot(shadowRoot) {
const doc = shadowRoot.ownerDocument || document;
const htmlInShadowRoot = doc.createElement('noroot'); // pseudo element
const childNodes = [...shadowRoot.childNodes]
shadowRoot.insertBefore(htmlInShadowRoot, shadowRoot.firstChild)
for (const childNode of childNodes) htmlInShadowRoot.appendChild(childNode);
return shadowRoot.querySelector('noroot');
}
let _endlessloop = null;
const isIframe = (window.top !== window.self && window.top && window.self);
const rootDocs = [];
const _getRoot = Element.prototype.getRootNode || HTMLElement.prototype.getRootNode || function () {
let elm = this;
while (elm) {
if ('host' in elm) return elm;
elm = elm.parentNode;
}
return elm;
}
const getRoot = (elm) => _getRoot.call(elm);
class VQuery {
constructor() {
this.videos = {};
this.wmMutations = {};
}
setVideo(key, value) { this.videos[key] = value }
player(key) {
const video = this.videos[key];
return video && video.parentNode ? video : null;
}
rootNode(key) {
const video = this.videos[key];
return video ? getRoot(video) : null;
}
}
const $vQuery = new VQuery();
const isShadowRoot = (elm) => (elm && ('host' in elm)) ? elm.nodeType == 11 && !!elm.host && elm.host.nodeType == 1 : null; //instanceof ShadowRoot
const domAppender = (d) => d.querySelector('head') || d.querySelector('html') || d.querySelector('noroot') || null;
const playerConfs = {}
const hanlderResizeVideo = (entries) => {
const detected_changes = {};
for (let entry of entries) {
const player = entry.target.nodeName == "VIDEO" ? entry.target : entry.target.querySelector("VIDEO[_h5ppid]");
if (!player || !player.parentNode) continue;
const vpid = player.getAttribute('_h5ppid');
if (!vpid) continue;
if (vpid in detected_changes) continue;
detected_changes[vpid] = true;
const { wPlayerInner, wPlayer } = $hs.getPlayerBlockElement(player)
if (!wPlayerInner) continue;
const layoutBoxInner = wPlayerInner.parentNode
if (!layoutBoxInner) continue;
let tipsDom = layoutBoxInner.querySelector('[data-h5p-pot-tips]');
if (tipsDom) {
if (tipsDom._tips_display_none) tipsDom.setAttribute('data-h5p-pot-tips', '')
$hs.fixNonBoxingVideoTipsPosition(tipsDom, player);
} else {
tipsDom = $vQuery.rootNode(vpid).querySelector(`#${player.getAttribute('_h5player_tips')}`)
if (tipsDom) {
if (tipsDom._tips_display_none) tipsDom.setAttribute('data-h5p-pot-tips', '')
$hs.change_layoutBox(tipsDom, player);
$hs.tipsDomObserve(tipsDom, player);
}
}
}
};
const $mb = {
nightly_isSupportQueueMicrotask: function () {
if ('_isSupportQueueMicrotask' in $mb) return $mb._isSupportQueueMicrotask;
$mb._isSupportQueueMicrotask = false;
$mb.queueMicrotask = window.queueMicrotask;
if (typeof $mb.queueMicrotask == 'function') {
$mb._isSupportQueueMicrotask = true;
}
return $mb._isSupportQueueMicrotask;
},
stable_isSupportAdvancedEventListener: function () {
if ('_isSupportAdvancedEventListener' in $mb) return $mb._isSupportAdvancedEventListener
let prop = 0;
$$addEventListener.call(document.createAttribute('z'), 'z', () => 0, {
get passive() {
prop++;
},
get once() {
prop++;
}
});
return ($mb._isSupportAdvancedEventListener = (prop == 2));
},
stable_isSupportPassiveEventListener: function () {
if ('_isSupportPassiveEventListener' in $mb) return $mb._isSupportPassiveEventListener
let prop = 0;
$$addEventListener.call(document.createAttribute('z'), 'z', () => 0, {
get passive() {
prop++;
}
});
return ($mb._isSupportPassiveEventListener = (prop == 1));
},
eh_capture_passive: () => ($mb._eh_capture_passive = $mb._eh_capture_passive || ($mb.stable_isSupportPassiveEventListener() ? {
capture: true,
passive: true
} : true)),
eh_bubble_passive: () => ($mb._eh_capture_passive = $mb._eh_capture_passive || ($mb.stable_isSupportPassiveEventListener() ? {
capture: false,
passive: true
} : false))
}
Element.prototype.__matches__ = (Element.prototype.matches || Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector ||
Element.prototype.matches()); // throw Error if not supported
// built-in hash - https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
async function digestMessage(message) {
return $winSafe.sha256(message)
}
const dround = (x) => ~~(x + .5);
const jsonStringify_replacer = function (key, val) {
if (val && (val instanceof Element || val instanceof Document)) return val.toString();
return val; // return as is
};
const jsonParse = function () {
try {
return JSON.parse.apply(this, arguments)
} catch (e) { }
return null;
}
const jsonStringify = function (obj) {
try {
return JSON.stringify.call(this, obj, jsonStringify_replacer)
} catch (e) { }
return null;
}
function _postMsg() {
//async is needed. or error handling for postMessage
const [win, tag, ...data] = arguments;
if (typeof tag == 'string') {
let postMsgObj = {
tag,
passing: true,
winOrder: _postMsg.a
}
try {
let k = 'msg-' + (+new Date)
win.document[str_postMsgData] = win.document[str_postMsgData] || {}
win.document[str_postMsgData][k] = data; //direct
postMsgObj.str = k;
postMsgObj.stype = 1;
} catch (e) { }
if (!postMsgObj.stype) {
postMsgObj.str = jsonStringify({
d: data
})
if (postMsgObj.str && postMsgObj.str.length) postMsgObj.stype = 2;
}
if (!postMsgObj.stype) {
postMsgObj.str = "" + data;
postMsgObj.stype = 0;
}
win.postMessage(postMsgObj, '*');
}
}
function postMsg() {
let win = window;
let a = 0;
while ((win = win.parent) && ('postMessage' in win)) {
_postMsg.a = ++a;
_postMsg(win, ...arguments)
if (win == top) break;
}
}
function crossBrowserTransition(type) {
if (crossBrowserTransition['_result_' + type]) return crossBrowserTransition['_result_' + type]
let el = document.createElement("fakeelement");
const capital = (x) => x[0].toUpperCase() + x.substr(1);
const capitalType = capital(type);
const transitions = {
[type]: `${type}end`,
[`O${capitalType}`]: `o${capitalType}End`,
[`Moz${capitalType}`]: `${type}end`,
[`Webkit${capitalType}`]: `webkit${capitalType}End`,
[`MS${capitalType}`]: `MS${capitalType}End`
}
for (let styleProp in transitions) {
if (el.style[styleProp] !== undefined) {
return (crossBrowserTransition['_result_' + type] = transitions[styleProp]);
}
}
}
const fn_toString = (f, n = 50) => {
let s = (f + "");
if (s.length > 2 * n + 5) {
s = s.substr(0, n) + ' ... ' + s.substr(-n);
}
return s
};
function consoleLog() {
if (!_debug_h5p_logging_) return;
if (isIframe) postMsg('consoleLog', ...arguments);
else console.log.apply(console, arguments);
}
function consoleLogF() {
if (isIframe) postMsg('consoleLog', ...arguments);
else console.log.apply(console, arguments);
}
class AFLooperArray extends Array {
constructor() {
super();
this.activeLoopsCount = 0;
this.cid = 0;
this.loopingFrame = this.loopingFrame.bind(this);
}
loopingFrame() {
if (!this.cid) return; //cancelled
for (const opt of this) {
if (opt.isFunctionLooping) opt.fn();
}
}
get isArrayLooping() {
return this.cid > 0;
}
loopStart() {
this.cid = window.setInterval(this.loopingFrame, 300);
}
loopStop() {
if (this.cid) window.clearInterval(this.cid);
this.cid = 0;
}
appendLoop(fn) {
if (typeof fn != 'function' || !this) return;
const opt = new AFLooperFunc(fn, this);
super.push(opt);
return opt;
}
}
class AFLooperFunc {
constructor(fn, bind) {
this._looping = false;
this.bind = bind;
this.fn = fn;
}
get isFunctionLooping() {
return this._looping;
}
loopingStart() {
if (this._looping === false) {
this._looping = true;
if (++this.bind.activeLoopsCount == 1) this.bind.loopStart();
}
}
loopingStop() {
if (this._looping === true) {
this._looping = false;
if (--this.bind.activeLoopsCount == 0) this.bind.loopStop();
}
}
}
function decimalEqual(a, b) {
return Math.round(a * 100000000) == Math.round(b * 100000000)
}
function nonZeroNum(a) {
return a > 0 || a < 0;
}
class PlayerConf {
get scaleFactor() {
return this.mFactor * this.vFactor;
}
cssTransform() {
const playerConf = this;
const player = playerConf.domElement;
if (!player || !player.parentNode) return;
const videoScale = playerConf.scaleFactor;
let {
x,
y
} = playerConf.translate;
let [_x, _y] = ((playerConf.rotate % 180) == 90) ? [y, x] : [x, y];
if ((playerConf.rotate % 360) == 270) _x = -_x;
if ((playerConf.rotate % 360) == 90) _y = -_y;
var s = [
playerConf.rotate > 0 ? 'rotate(' + playerConf.rotate + 'deg)' : '',
!decimalEqual(videoScale, 1.0) ? 'scale(' + videoScale + ')' : '',
(nonZeroNum(_x) || nonZeroNum(_y)) ? `translate(${_x}px, ${_y}px)` : '',
];
player.style.transform = s.join(' ').trim()
}
constructor() {
this.translate = {
x: 0,
y: 0
};
this.rotate = 0;
this.mFactor = 1.0;
this.vFactor = 1.0;
this.fps = 30;
this.filter_key = {};
this.filter_view_units = {
'hue-rotate': 'deg',
'blur': 'px'
};
this.filterReset();
}
setFilter(prop, f) {
let oldValue = this.filter_key[prop];
if (typeof oldValue != 'number') return;
let newValue = f(oldValue)
if (oldValue != newValue) {
newValue = +newValue.toFixed(6); //javascript bug
}
this.filter_key[prop] = newValue
this.filterSetup();
return newValue;
}
filterSetup(options) {
let ums = GM_getValue("unsharpen_mask")
if (!ums) ums = ""
let view = []
let playerElm = $hs.player();
if (!playerElm || !playerElm.parentNode) return;
for (let view_key in this.filter_key) {
let filter_value = +((+this.filter_key[view_key] || 0).toFixed(3))
let addTo = true;
switch (view_key) {
case 'brightness':
/* fall through */
case 'contrast':
/* fall through */
case 'saturate':
if (decimalEqual(filter_value, 1.0)) addTo = false;
break;
case 'hue-rotate':
/* fall through */
case 'blur':
if (decimalEqual(filter_value, 0.0)) addTo = false;
break;
}
let view_unit = this.filter_view_units[view_key] || ''
if (addTo) view.push(`${view_key}(${filter_value}${view_unit})`)
this.filter_key[view_key] = Number(+this.filter_key[view_key] || 0)
}
if (ums) view.push(`url("#_h5p_${ums}")`);
if (options && options.grey) view.push('url("#grey1")');
playerElm.style.filter = view.join(' ').trim(); //performance in firefox is bad
}
filterReset() {
this.filter_key['brightness'] = 1.0
this.filter_key['contrast'] = 1.0
this.filter_key['saturate'] = 1.0
this.filter_key['hue-rotate'] = 0.0
this.filter_key['blur'] = 0.0
this.filterSetup()
}
}
const Store = {
prefix: '_h5_player',
save: function (k, v) {
if (!Store.available()) return false;
if (typeof v != 'string') return false;
Store.LS.setItem(Store.prefix + k, v)
let sk = fn_toString(k + "", 30);
let sv = fn_toString(v + "", 30);
consoleLog(`localStorage Saved "${sk}" = "${sv}"`)
return true;
},
read: function (k) {
if (!Store.available()) return false;
let v = Store.LS.getItem(Store.prefix + k)
let sk = fn_toString(k + "", 30);
let sv = fn_toString(v + "", 30);
consoleLog(`localStorage Read "${sk}" = "${sv}"`);
return v;
},
remove: function (k) {
if (!Store.available()) return false;
Store.LS.removeItem(Store.prefix + k)
let sk = fn_toString(k + "", 30);
consoleLog(`localStorage Removed "${sk}"`)
return true;
},
clearInvalid: function (sVersion) {
if (!Store.available()) return false;
//let sVersion=1814;
if (+Store.read('_sVersion_') < sVersion) {
Store._keys()
.filter(s => s.indexOf(Store.prefix) === 0)
.forEach(key => window.localStorage.removeItem(key))
Store.save('_sVersion_', sVersion + '')
return 2;
}
return 1;
},
available: function () {
if (Store.LS) return true;
if (!window) return false;
const localStorage = window.localStorage;
if (!localStorage) return false;
if (typeof localStorage != 'object') return false;
if (!('getItem' in localStorage)) return false;
if (!('setItem' in localStorage)) return false;
Store.LS = localStorage;
return true;
},
_keys: function () {
return Object.keys(localStorage);
},
_setItem: function (key, value) {
return localStorage.setItem(key, value)
},
_getItem: function (key) {
return localStorage.getItem(key)
},
_removeItem: function (key) {
return localStorage.removeItem(key)
}
}
const domTool = {
cssWH: function (m, r) {
if (!r) r = getComputedStyle(m, null);
let c = (x) => +x.replace('px', '');
return {
w: m.offsetWidth || c(r.width),
h: m.offsetHeight || c(r.height)
}
},
_isActionBox_1: function (vEl, pEl) {
const vElCSS = domTool.cssWH(vEl);
let vElCSSw = vElCSS.w;
let vElCSSh = vElCSS.h;
let vElx = vEl;
const res = [];
//let mLevel = 0;
if (vEl && pEl && vEl != pEl && pEl.contains(vEl)) {
while (vElx && vElx != pEl) {
vElx = vElx.parentNode;
let vElx_css = null;
if (isShadowRoot(vElx)) { } else {
vElx_css = getComputedStyle(vElx, null);
let vElx_wp = parseFloat(vElx_css.paddingLeft) + parseFloat(vElx_css.paddingRight)
vElCSSw += vElx_wp
let vElx_hp = parseFloat(vElx_css.paddingTop) + parseFloat(vElx_css.paddingBottom)
vElCSSh += vElx_hp
}
res.push({
//level: ++mLevel,
padW: vElCSSw,
padH: vElCSSh,
elm: vElx,
css: vElx_css
})
}
}
// in the array, each item is the parent of video player
//res.vEl_cssWH = vElCSS
return res;
},
_isActionBox: function (vEl, walkRes, pEl_idx) {
function absDiff(w1, w2, h1, h2) {
const w = (w1 - w2),
h = h1 - h2;
return [(w > 0 ? w : -w), (h > 0 ? h : -h)]
}
function midPoint(rect) {
return {
x: (rect.left + rect.right) / 2,
y: (rect.top + rect.bottom) / 2
}
}
const parentCount = walkRes.length;
if (pEl_idx >= 0 && pEl_idx < parentCount) { } else {
return;
}
const pElr = walkRes[pEl_idx]
if (!pElr.css) {
//shadowRoot
return true;
}
const pEl = pElr.elm;
//prevent activeElement==body
const pElCSS = domTool.cssWH(pEl, pElr.css);
//check prediction of parent dimension
const d1v = absDiff(pElCSS.w, pElr.padW, pElCSS.h, pElr.padH)
const d1x = d1v[0] < 10
const d1y = d1v[1] < 10;
if (d1x && d1y) return true; //both edge along the container - fit size
if (!d1x && !d1y) return false; //no edge along the container - body contain the video element, fixed width&height
//case: youtube video fullscreen
//check centre point
const pEl_rect = pEl.getBoundingClientRect()
const vEl_rect = vEl.getBoundingClientRect()
const pEl_center = midPoint(pEl_rect)
const vEl_center = midPoint(vEl_rect)
const d2v = absDiff(pEl_center.x, vEl_center.x, pEl_center.y, vEl_center.y);
const d2x = d2v[0] < 10;
const d2y = d2v[1] < 10;
return (d2x && d2y);
},
addStyle: //GM_addStyle,
function (css, head) {
if (!head) {
let _doc = document.documentElement;
head = domAppender(_doc);
}
let doc = head.ownerDocument;
let style = doc.createElement('style');
style.type = 'text/css';
style.textContent = css;
head.appendChild(style);
//console.log(document.head,style,'add style')
return style;
}
};
const handle = {
afPlaybackRecording: async function () {
const opts = this;
let qTime = +new Date;
if (qTime >= opts.pTime) {
opts.pTime = qTime + opts.timeDelta; //prediction of next Interval
opts.savePlaybackProgress()
}
},
savePlaybackProgress: function () {
//this refer to endless's opts
let player = this.player;
let _uid = this.player_uid; //_h5p_uid_encrypted
if (!_uid) return;
let shallSave = true;
let currentTimeToSave = ~~player.currentTime;
if (this._lastSave == currentTimeToSave) shallSave = false;
if (shallSave) {
this._lastSave = currentTimeToSave
Promise.resolve().then(() => {
//console.log('aasas',this.player_uid, shallSave, '_play_progress_'+_uid, currentTimeToSave)
Store.save('_play_progress_' + _uid, jsonStringify({
't': currentTimeToSave
}))
})
}
//console.log('playback logged')
},
playingWithRecording: function () {
let player = this.player;
if (!player.paused && !this.isFunctionLooping) {
let player = this.player;
let _uid = player.getAttribute('_h5p_uid_encrypted') || ''
if (_uid) {
this.player_uid = _uid;
this.pTime = 0;
this.loopingStart();
}
}
}
};
const $hs = {
/* 提示文本的字號 */
fontSize: 16,
enable: true,
playerInstance: null,
/* 快進快退步長 */
skipStep: 5,
mouseMoveCount: 0,
//video mouse enter and leave
mouseActioner: {
calls: [],
time: 0,
cid: 0,
lastFound: null,
lastHoverElm: null
},
mouseEnteredElement: null,
actionBoxRelations: {},
tipsClassName: 'html_player_enhance_tips',
//cursor control
mointoringVideo: false, //false -> xxx -> null -> xxx
//global focused video
focusHookVId: '',
/* 獲取當前播放器的實例 */
player: function () {
let res = $hs.playerInstance || null;
if (res && res.parentNode == null) {
$hs.playerInstance = null;
res = null;
}
if (res == null) {
for (let k in playerConfs) {
let playerConf = playerConfs[k];
if (playerConf && playerConf.domElement && playerConf.domElement.parentNode) return playerConf.domElement;
}
}
if (res && res.parentNode) return res;
return null;
},
pictureInPicture: function (videoElm) {
if (document.pictureInPictureElement) {
document.exitPictureInPicture();
} else if ('requestPictureInPicture' in videoElm) {
videoElm.requestPictureInPicture()
} else {
$hs.tips('PIP is not supported.');
}
},
getPlayerConf: function (video) {
if (!video) return null;
let vpid = video.getAttribute('_h5ppid') || null;
if (!vpid) return null;
return playerConfs[vpid] || null;
},
debug01: function (evt, videoActive) {
if (!$hs.eventHooks) {
document.__h5p_eventhooks = ($hs.eventHooks = {
_debug_: []
});
}
$hs.eventHooks._debug_.push([videoActive, evt.type]);
// console.log('h5p eventhooks = document.__h5p_eventhooks')
},
swtichPlayerInstance: function () {
let newPlayerInstance = null;
const ONLY_PLAYING_NONE = 0x4A00;
const ONLY_PLAYING_MORE_THAN_ONE = 0x5A00;
let onlyPlayingInstance = ONLY_PLAYING_NONE;
for (let k in playerConfs) {
let playerConf = playerConfs[k] || {};
let {
domElement,
domActive
} = playerConf;
if (domElement) {
if (domActive & DOM_ACTIVE_INVALID_PARENT) continue;
if (!domElement.parentNode) {
playerConf.domActive |= DOM_ACTIVE_INVALID_PARENT;
continue;
}
if ((domActive & DOM_ACTIVE_MOUSE_CLICK) || (domActive & DOM_ACTIVE_KEY_DOWN) || (domActive & DOM_ACTIVE_FULLSCREEN)) {
newPlayerInstance = domElement
break;
}
if (domActive & DOM_ACTIVE_ONCE_PLAYED && (domActive & DOM_ACTIVE_DELAYED_PAUSED) == 0) {
if (onlyPlayingInstance == ONLY_PLAYING_NONE) onlyPlayingInstance = domElement;
else onlyPlayingInstance = ONLY_PLAYING_MORE_THAN_ONE;
}
}
}
if (newPlayerInstance == null && onlyPlayingInstance.nodeType == 1) {
newPlayerInstance = onlyPlayingInstance;
}
$hs.playerInstance = newPlayerInstance
},
handlerVideoPlaying: function (evt) {
const videoElm = evt.target || this || null;
if (!videoElm || videoElm.nodeName != "VIDEO") return;
const vpid = videoElm.getAttribute('_h5ppid')
if (!vpid) return;
$bv.boostVideoPerformanceActivate();
//console.log('video play',videoElm.duration,videoElm.currentTime)
Promise.resolve().then(() => {