forked from igrigorik/videospeed
-
Notifications
You must be signed in to change notification settings - Fork 47
/
inject.js
904 lines (824 loc) · 27 KB
/
inject.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
var regStrip = /^[\r\t\f\v ]+|[\r\t\f\v ]+$/gm;
var tc = {
settings: {
lastSpeed: 1.0, // default 1x
enabled: true, // default enabled
speeds: {}, // empty object to hold speed for each source
displayKeyCode: 86, // default: V
rememberSpeed: false, // default: false
forceLastSavedSpeed: false, //default: false
audioBoolean: false, // default: false
startHidden: false, // default: false
controllerOpacity: 0.3, // default: 0.3
keyBindings: [],
blacklist: `\
www.instagram.com
twitter.com
vine.co
imgur.com
teams.microsoft.com
`.replace(regStrip, ""),
defaultLogLevel: 4,
logLevel: 3
},
// Holds a reference to all of the AUDIO/VIDEO DOM elements we've attached to
mediaElements: []
};
/* Log levels (depends on caller specifying the correct level)
1 - none
2 - error
3 - warning
4 - info
5 - debug
6 - debug high verbosity + stack trace on each message
*/
function log(message, level) {
verbosity = tc.settings.logLevel;
if (typeof level === "undefined") {
level = tc.settings.defaultLogLevel;
}
if (verbosity >= level) {
if (level === 2) {
console.log("ERROR:" + message);
} else if (level === 3) {
console.log("WARNING:" + message);
} else if (level === 4) {
console.log("INFO:" + message);
} else if (level === 5) {
console.log("DEBUG:" + message);
} else if (level === 6) {
console.log("DEBUG (VERBOSE):" + message);
console.trace();
}
}
}
chrome.storage.sync.get(tc.settings, function (storage) {
tc.settings.keyBindings = storage.keyBindings; // Array
if (storage.keyBindings.length == 0) {
// if first initialization of 0.5.3
// UPDATE
tc.settings.keyBindings.push({
action: "slower",
key: Number(storage.slowerKeyCode) || 83,
value: Number(storage.speedStep) || 0.1,
force: false,
predefined: true
}); // default S
tc.settings.keyBindings.push({
action: "faster",
key: Number(storage.fasterKeyCode) || 68,
value: Number(storage.speedStep) || 0.1,
force: false,
predefined: true
}); // default: D
tc.settings.keyBindings.push({
action: "rewind",
key: Number(storage.rewindKeyCode) || 90,
value: Number(storage.rewindTime) || 10,
force: false,
predefined: true
}); // default: Z
tc.settings.keyBindings.push({
action: "advance",
key: Number(storage.advanceKeyCode) || 88,
value: Number(storage.advanceTime) || 10,
force: false,
predefined: true
}); // default: X
tc.settings.keyBindings.push({
action: "reset",
key: Number(storage.resetKeyCode) || 82,
value: 1.0,
force: false,
predefined: true
}); // default: R
tc.settings.keyBindings.push({
action: "fast",
key: Number(storage.fastKeyCode) || 71,
value: Number(storage.fastSpeed) || 1.8,
force: false,
predefined: true
}); // default: G
tc.settings.version = "0.5.3";
chrome.storage.sync.set({
keyBindings: tc.settings.keyBindings,
version: tc.settings.version,
displayKeyCode: tc.settings.displayKeyCode,
rememberSpeed: tc.settings.rememberSpeed,
forceLastSavedSpeed: tc.settings.forceLastSavedSpeed,
audioBoolean: tc.settings.audioBoolean,
startHidden: tc.settings.startHidden,
enabled: tc.settings.enabled,
controllerOpacity: tc.settings.controllerOpacity,
blacklist: tc.settings.blacklist.replace(regStrip, "")
});
}
tc.settings.lastSpeed = Number(storage.lastSpeed);
tc.settings.displayKeyCode = Number(storage.displayKeyCode);
tc.settings.rememberSpeed = Boolean(storage.rememberSpeed);
tc.settings.forceLastSavedSpeed = Boolean(storage.forceLastSavedSpeed);
tc.settings.audioBoolean = Boolean(storage.audioBoolean);
tc.settings.enabled = Boolean(storage.enabled);
tc.settings.startHidden = Boolean(storage.startHidden);
tc.settings.controllerOpacity = Number(storage.controllerOpacity);
tc.settings.blacklist = String(storage.blacklist);
// ensure that there is a "display" binding (for upgrades from versions that had it as a separate binding)
if (
tc.settings.keyBindings.filter((x) => x.action == "display").length == 0
) {
tc.settings.keyBindings.push({
action: "display",
key: Number(storage.displayKeyCode) || 86,
value: 0,
force: false,
predefined: true
}); // default V
}
initializeWhenReady(document);
});
function getKeyBindings(action, what = "value") {
try {
return tc.settings.keyBindings.find((item) => item.action === action)[what];
} catch (e) {
return false;
}
}
function setKeyBindings(action, value) {
tc.settings.keyBindings.find((item) => item.action === action)[
"value"
] = value;
}
function defineVideoController() {
// Data structures
// ---------------
// videoController (JS object) instances:
// video = AUDIO/VIDEO DOM element
// parent = A/V DOM element's parentElement OR
// (A/V elements discovered from the Mutation Observer)
// A/V element's parentNode OR the node whose children changed.
// div = Controller's DOM element (which happens to be a DIV)
// speedIndicator = DOM element in the Controller of the speed indicator
// added to AUDIO / VIDEO DOM elements
// vsc = reference to the videoController
tc.videoController = function (target, parent) {
if (target.vsc) {
return target.vsc;
}
tc.mediaElements.push(target);
this.video = target;
this.parent = target.parentElement || parent;
storedSpeed = tc.settings.speeds[target.currentSrc];
if (!tc.settings.rememberSpeed) {
if (!storedSpeed) {
log(
"Overwriting stored speed to 1.0 due to rememberSpeed being disabled",
5
);
storedSpeed = 1.0;
}
setKeyBindings("reset", getKeyBindings("fast")); // resetSpeed = fastSpeed
} else {
log("Recalling stored speed due to rememberSpeed being enabled", 5);
storedSpeed = tc.settings.lastSpeed;
}
log("Explicitly setting playbackRate to: " + storedSpeed, 5);
target.playbackRate = storedSpeed;
this.div = this.initializeControls();
var mediaEventAction = function (event) {
storedSpeed = tc.settings.speeds[event.target.currentSrc];
if (!tc.settings.rememberSpeed) {
if (!storedSpeed) {
log("Overwriting stored speed to 1.0 (rememberSpeed not enabled)", 4);
storedSpeed = 1.0;
}
// resetSpeed isn't really a reset, it's a toggle
log("Setting reset keybinding to fast", 5);
setKeyBindings("reset", getKeyBindings("fast")); // resetSpeed = fastSpeed
} else {
log(
"Storing lastSpeed into tc.settings.speeds (rememberSpeed enabled)",
5
);
storedSpeed = tc.settings.lastSpeed;
}
// TODO: Check if explicitly setting the playback rate to 1.0 is
// necessary when rememberSpeed is disabled (this may accidentally
// override a website's intentional initial speed setting interfering
// with the site's default behavior)
log("Explicitly setting playbackRate to: " + storedSpeed, 4);
setSpeed(event.target, storedSpeed);
};
target.addEventListener(
"play",
(this.handlePlay = mediaEventAction.bind(this))
);
target.addEventListener(
"seeked",
(this.handleSeek = mediaEventAction.bind(this))
);
var observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
if (
mutation.type === "attributes" &&
(mutation.attributeName === "src" ||
mutation.attributeName === "currentSrc")
) {
log("mutation of A/V element", 5);
var controller = this.div;
if (!mutation.target.src && !mutation.target.currentSrc) {
controller.classList.add("vsc-nosource");
} else {
controller.classList.remove("vsc-nosource");
}
}
});
});
observer.observe(target, {
attributeFilter: ["src", "currentSrc"]
});
};
tc.videoController.prototype.remove = function () {
this.div.remove();
this.video.removeEventListener("play", this.handlePlay);
this.video.removeEventListener("seek", this.handleSeek);
delete this.video.vsc;
let idx = tc.mediaElements.indexOf(this.video);
if (idx != -1) {
tc.mediaElements.splice(idx, 1);
}
};
tc.videoController.prototype.initializeControls = function () {
log("initializeControls Begin", 5);
const document = this.video.ownerDocument;
const speed = this.video.playbackRate.toFixed(2);
var top = Math.max(this.video.offsetTop, 0) + "px",
left = Math.max(this.video.offsetLeft, 0) + "px";
log("Speed variable set to: " + speed, 5);
var wrapper = document.createElement("div");
wrapper.classList.add("vsc-controller");
if (!this.video.src && !this.video.currentSrc) {
wrapper.classList.add("vsc-nosource");
}
if (tc.settings.startHidden) {
wrapper.classList.add("vsc-hidden");
}
var shadow = wrapper.attachShadow({ mode: "open" });
var shadowTemplate = `
<style>
@import "${chrome.runtime.getURL("shadow.css")}";
</style>
<div id="controller" style="top:${top}; left:${left}; opacity:${
tc.settings.controllerOpacity
}">
<span data-action="drag" class="draggable">${speed}</span>
<span id="controls">
<button data-action="rewind" class="rw">«</button>
<button data-action="slower">−</button>
<button data-action="faster">+</button>
<button data-action="advance" class="rw">»</button>
<button data-action="display" class="hideButton">×</button>
</span>
</div>
`;
shadow.innerHTML = shadowTemplate;
shadow.querySelector(".draggable").addEventListener(
"mousedown",
(e) => {
runAction(e.target.dataset["action"], false, e);
e.stopPropagation();
},
true
);
shadow.querySelectorAll("button").forEach(function (button) {
button.addEventListener(
"click",
(e) => {
runAction(
e.target.dataset["action"],
getKeyBindings(e.target.dataset["action"]),
e
);
e.stopPropagation();
},
true
);
});
shadow
.querySelector("#controller")
.addEventListener("click", (e) => e.stopPropagation(), false);
shadow
.querySelector("#controller")
.addEventListener("mousedown", (e) => e.stopPropagation(), false);
this.speedIndicator = shadow.querySelector("span");
var fragment = document.createDocumentFragment();
fragment.appendChild(wrapper);
switch (true) {
case location.hostname == "www.amazon.com":
case location.hostname == "www.reddit.com":
case /hbogo\./.test(location.hostname):
// insert before parent to bypass overlay
this.parent.parentElement.insertBefore(fragment, this.parent);
break;
case location.hostname == "www.facebook.com":
// this is a monstrosity but new FB design does not have *any*
// semantic handles for us to traverse the tree, and deep nesting
// that we need to bubble up from to get controller to stack correctly
let p = this.parent.parentElement.parentElement.parentElement
.parentElement.parentElement.parentElement.parentElement;
p.insertBefore(fragment, p.firstChild);
break;
case location.hostname == "tv.apple.com":
// insert after parent for correct stacking context
this.parent.getRootNode().querySelector(".scrim").prepend(fragment);
default:
// Note: when triggered via a MutationRecord, it's possible that the
// target is not the immediate parent. This appends the controller as
// the first element of the target, which may not be the parent.
this.parent.insertBefore(fragment, this.parent.firstChild);
}
return wrapper;
};
}
function escapeStringRegExp(str) {
matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
return str.replace(matchOperatorsRe, "\\$&");
}
function isBlacklisted() {
blacklisted = false;
tc.settings.blacklist.split("\n").forEach((match) => {
match = match.replace(regStrip, "");
if (match.length == 0) {
return;
}
if (match.startsWith("/")) {
try {
var regexp = new RegExp(match);
} catch (err) {
return;
}
} else {
var regexp = new RegExp(escapeStringRegExp(match));
}
if (regexp.test(location.href)) {
blacklisted = true;
return;
}
});
return blacklisted;
}
var coolDown = false;
function refreshCoolDown() {
log("Begin refreshCoolDown", 5);
if (coolDown) {
clearTimeout(coolDown);
}
coolDown = setTimeout(function () {
coolDown = false;
}, 1000);
log("End refreshCoolDown", 5);
}
function setupListener() {
/**
* This function is run whenever a video speed rate change occurs.
* It is used to update the speed that shows up in the display as well as save
* that latest speed into the local storage.
*
* @param {*} video The video element to update the speed indicators for.
*/
function updateSpeedFromEvent(video) {
// It's possible to get a rate change on a VIDEO/AUDIO that doesn't have
// a video controller attached to it. If we do, ignore it.
if (!video.vsc)
return;
var speedIndicator = video.vsc.speedIndicator;
var src = video.currentSrc;
var speed = Number(video.playbackRate.toFixed(2));
log("Playback rate changed to " + speed, 4);
log("Updating controller with new speed", 5);
speedIndicator.textContent = speed.toFixed(2);
tc.settings.speeds[src] = speed;
log("Storing lastSpeed in settings for the rememberSpeed feature", 5);
tc.settings.lastSpeed = speed;
log("Syncing chrome settings for lastSpeed", 5);
chrome.storage.sync.set({ lastSpeed: speed }, function () {
log("Speed setting saved: " + speed, 5);
});
// show the controller for 1000ms if it's hidden.
runAction("blink", null, null);
}
document.addEventListener(
"ratechange",
function (event) {
if (coolDown) {
log("Speed event propagation blocked", 4);
event.stopImmediatePropagation();
}
var video = event.target;
/**
* If the last speed is forced, only update the speed based on events created by
* video speed instead of all video speed change events.
*/
if (tc.settings.forceLastSavedSpeed) {
if (event.detail && event.detail.origin === "videoSpeed") {
video.playbackRate = event.detail.speed;
updateSpeedFromEvent(video);
} else {
video.playbackRate = tc.settings.lastSpeed;
}
event.stopImmediatePropagation();
} else {
updateSpeedFromEvent(video);
}
},
true
);
}
function initializeWhenReady(document) {
log("Begin initializeWhenReady", 5);
if (isBlacklisted()) {
return;
}
window.addEventListener('load', () => {
initializeNow(window.document);
});
if (document) {
if (document.readyState === "complete") {
initializeNow(document);
} else {
document.onreadystatechange = () => {
if (document.readyState === "complete") {
initializeNow(document);
}
};
}
}
log("End initializeWhenReady", 5);
}
function inIframe() {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
function getShadow(parent) {
let result = [];
function getChild(parent) {
if (parent.firstElementChild) {
var child = parent.firstElementChild;
do {
result.push(child);
getChild(child);
if (child.shadowRoot) {
result.push(getShadow(child.shadowRoot));
}
child = child.nextElementSibling;
} while (child);
}
}
getChild(parent);
return result.flat(Infinity);
}
function initializeNow(document) {
log("Begin initializeNow", 5);
if (!tc.settings.enabled) return;
// enforce init-once due to redundant callers
if (!document.body || document.body.classList.contains("vsc-initialized")) {
return;
}
try {
setupListener();
} catch {
// no operation
}
document.body.classList.add("vsc-initialized");
log("initializeNow: vsc-initialized added to document body", 5);
if (document === window.document) {
defineVideoController();
} else {
var link = document.createElement("link");
link.href = chrome.runtime.getURL("inject.css");
link.type = "text/css";
link.rel = "stylesheet";
document.head.appendChild(link);
}
var docs = Array(document);
try {
if (inIframe()) docs.push(window.top.document);
} catch (e) {}
docs.forEach(function (doc) {
doc.addEventListener(
"keydown",
function (event) {
var keyCode = event.keyCode;
log("Processing keydown event: " + keyCode, 6);
// Ignore if following modifier is active.
if (
!event.getModifierState ||
event.getModifierState("Alt") ||
event.getModifierState("Control") ||
event.getModifierState("Fn") ||
event.getModifierState("Meta") ||
event.getModifierState("Hyper") ||
event.getModifierState("OS")
) {
log("Keydown event ignored due to active modifier: " + keyCode, 5);
return;
}
// Ignore keydown event if typing in an input box
if (
event.target.nodeName === "INPUT" ||
event.target.nodeName === "TEXTAREA" ||
event.target.isContentEditable
) {
return false;
}
// Ignore keydown event if typing in a page without vsc
if (!tc.mediaElements.length) {
return false;
}
var item = tc.settings.keyBindings.find((item) => item.key === keyCode);
if (item) {
runAction(item.action, item.value);
if (item.force === "true") {
// disable websites key bindings
event.preventDefault();
event.stopPropagation();
}
}
return false;
},
true
);
});
function checkForVideo(node, parent, added) {
// Only proceed with supposed removal if node is missing from DOM
if (!added && document.body.contains(node)) {
return;
}
if (
node.nodeName === "VIDEO" ||
(node.nodeName === "AUDIO" && tc.settings.audioBoolean)
) {
if (added) {
node.vsc = new tc.videoController(node, parent);
} else {
if (node.vsc) {
node.vsc.remove();
}
}
} else if (node.children != undefined) {
for (var i = 0; i < node.children.length; i++) {
const child = node.children[i];
checkForVideo(child, child.parentNode || parent, added);
}
}
}
var observer = new MutationObserver(function (mutations) {
// Process the DOM nodes lazily
requestIdleCallback(
(_) => {
mutations.forEach(function (mutation) {
switch (mutation.type) {
case "childList":
mutation.addedNodes.forEach(function (node) {
if (typeof node === "function") return;
checkForVideo(node, node.parentNode || mutation.target, true);
});
mutation.removedNodes.forEach(function (node) {
if (typeof node === "function") return;
checkForVideo(node, node.parentNode || mutation.target, false);
});
break;
case "attributes":
if (
mutation.target.attributes["aria-hidden"] &&
mutation.target.attributes["aria-hidden"].value == "false"
) {
var flattenedNodes = getShadow(document.body);
var node = flattenedNodes.filter(
(x) => x.tagName == "VIDEO"
)[0];
if (node) {
if (node.vsc)
node.vsc.remove();
checkForVideo(node, node.parentNode || mutation.target, true);
}
}
break;
}
});
},
{ timeout: 1000 }
);
});
observer.observe(document, {
attributeFilter: ["aria-hidden"],
childList: true,
subtree: true
});
if (tc.settings.audioBoolean) {
var mediaTags = document.querySelectorAll("video,audio");
} else {
var mediaTags = document.querySelectorAll("video");
}
mediaTags.forEach(function (video) {
video.vsc = new tc.videoController(video);
});
var frameTags = document.getElementsByTagName("iframe");
Array.prototype.forEach.call(frameTags, function (frame) {
// Ignore frames we don't have permission to access (different origin).
try {
var childDocument = frame.contentDocument;
} catch (e) {
return;
}
initializeWhenReady(childDocument);
});
log("End initializeNow", 5);
}
function setSpeed(video, speed) {
log("setSpeed started: " + speed, 5);
var speedvalue = speed.toFixed(2);
if (tc.settings.forceLastSavedSpeed) {
video.dispatchEvent(
new CustomEvent("ratechange", {
detail: { origin: "videoSpeed", speed: speedvalue }
})
);
} else {
video.playbackRate = Number(speedvalue);
}
var speedIndicator = video.vsc.speedIndicator;
speedIndicator.textContent = speedvalue;
tc.settings.lastSpeed = speed;
refreshCoolDown();
log("setSpeed finished: " + speed, 5);
}
function runAction(action, value, e) {
log("runAction Begin", 5);
var mediaTags = tc.mediaElements;
// Get the controller that was used if called from a button press event e
if (e) {
var targetController = e.target.getRootNode().host;
}
mediaTags.forEach(function (v) {
var controller = v.vsc.div;
// Don't change video speed if the video has a different controller
if (e && !(targetController == controller)) {
return;
}
showController(controller);
if (!v.classList.contains("vsc-cancelled")) {
if (action === "rewind") {
log("Rewind", 5);
v.currentTime -= value;
} else if (action === "advance") {
log("Fast forward", 5);
v.currentTime += value;
} else if (action === "faster") {
log("Increase speed", 5);
// Maximum playback speed in Chrome is set to 16:
// https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/html/media/html_media_element.cc?gsn=kMinRate&l=166
var s = Math.min(
(v.playbackRate < 0.1 ? 0.0 : v.playbackRate) + value,
16
);
setSpeed(v, s);
} else if (action === "slower") {
log("Decrease speed", 5);
// Video min rate is 0.0625:
// https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/html/media/html_media_element.cc?gsn=kMinRate&l=165
var s = Math.max(v.playbackRate - value, 0.07);
setSpeed(v, s);
} else if (action === "reset") {
log("Reset speed", 5);
resetSpeed(v, 1.0);
} else if (action === "display") {
log("Showing controller", 5);
controller.classList.add("vsc-manual");
controller.classList.toggle("vsc-hidden");
} else if (action === "blink") {
log("Showing controller momentarily", 5);
// if vsc is hidden, show it briefly to give the use visual feedback that the action is excuted.
if (
controller.classList.contains("vsc-hidden") ||
controller.blinkTimeOut !== undefined
) {
clearTimeout(controller.blinkTimeOut);
controller.classList.remove("vsc-hidden");
controller.blinkTimeOut = setTimeout(
() => {
controller.classList.add("vsc-hidden");
controller.blinkTimeOut = undefined;
},
value ? value : 1000
);
}
} else if (action === "drag") {
handleDrag(v, e);
} else if (action === "fast") {
resetSpeed(v, value);
} else if (action === "pause") {
pause(v);
} else if (action === "muted") {
muted(v);
} else if (action === "mark") {
setMark(v);
} else if (action === "jump") {
jumpToMark(v);
}
}
});
log("runAction End", 5);
}
function pause(v) {
if (v.paused) {
log("Resuming video", 5);
v.play();
} else {
log("Pausing video", 5);
v.pause();
}
}
function resetSpeed(v, target) {
if (v.playbackRate === target) {
if (v.playbackRate === getKeyBindings("reset")) {
if (target !== 1.0) {
log("Resetting playback speed to 1.0", 4);
setSpeed(v, 1.0);
} else {
log('Toggling playback speed to "fast" speed', 4);
setSpeed(v, getKeyBindings("fast"));
}
} else {
log('Toggling playback speed to "reset" speed', 4);
setSpeed(v, getKeyBindings("reset"));
}
} else {
log('Toggling playback speed to "reset" speed', 4);
setKeyBindings("reset", v.playbackRate);
setSpeed(v, target);
}
}
function muted(v) {
v.muted = v.muted !== true;
}
function setMark(v) {
log("Adding marker", 5);
v.vsc.mark = v.currentTime;
}
function jumpToMark(v) {
log("Recalling marker", 5);
if (v.vsc.mark && typeof v.vsc.mark === "number") {
v.currentTime = v.vsc.mark;
}
}
function handleDrag(video, e) {
const controller = video.vsc.div;
const shadowController = controller.shadowRoot.querySelector("#controller");
// Find nearest parent of same size as video parent.
var parentElement = controller.parentElement;
while (
parentElement.parentNode &&
parentElement.parentNode.offsetHeight === parentElement.offsetHeight &&
parentElement.parentNode.offsetWidth === parentElement.offsetWidth
) {
parentElement = parentElement.parentNode;
}
video.classList.add("vcs-dragging");
shadowController.classList.add("dragging");
const initialMouseXY = [e.clientX, e.clientY];
const initialControllerXY = [
parseInt(shadowController.style.left),
parseInt(shadowController.style.top)
];
const startDragging = (e) => {
let style = shadowController.style;
let dx = e.clientX - initialMouseXY[0];
let dy = e.clientY - initialMouseXY[1];
style.left = initialControllerXY[0] + dx + "px";
style.top = initialControllerXY[1] + dy + "px";
};
const stopDragging = () => {
parentElement.removeEventListener("mousemove", startDragging);
parentElement.removeEventListener("mouseup", stopDragging);
parentElement.removeEventListener("mouseleave", stopDragging);
shadowController.classList.remove("dragging");
video.classList.remove("vcs-dragging");
};
parentElement.addEventListener("mouseup", stopDragging);
parentElement.addEventListener("mouseleave", stopDragging);
parentElement.addEventListener("mousemove", startDragging);
}
var timer = null;
function showController(controller) {
log("Showing controller", 4);
controller.classList.add("vcs-show");
if (timer) clearTimeout(timer);
timer = setTimeout(function () {
controller.classList.remove("vcs-show");
timer = false;
log("Hiding controller", 5);
}, 2000);
}