mirror of
https://github.com/SoPat712/videospeed.git
synced 2026-02-10 03:25:09 -05:00
youtube subtitle fix
This commit is contained in:
1404
inject.js
1404
inject.js
@@ -21,481 +21,695 @@ var tc = {
|
|||||||
teams.microsoft.com
|
teams.microsoft.com
|
||||||
`.replace(regStrip, ""),
|
`.replace(regStrip, ""),
|
||||||
defaultLogLevel: 4,
|
defaultLogLevel: 4,
|
||||||
logLevel: 3
|
logLevel: 3,
|
||||||
|
// --- Nudge settings (ADDED) ---
|
||||||
|
enableSubtitleNudge: true,
|
||||||
|
subtitleNudgeInterval: 25,
|
||||||
|
subtitleNudgeAmount: 0.001
|
||||||
},
|
},
|
||||||
|
|
||||||
// Holds a reference to all of the AUDIO/VIDEO DOM elements we've attached to
|
// Holds a reference to all of the AUDIO/VIDEO DOM elements we've attached to
|
||||||
mediaElements: []
|
mediaElements: [],
|
||||||
|
isNudging: false // Flag for nudge operation (ADDED)
|
||||||
};
|
};
|
||||||
|
|
||||||
/* Log levels (depends on caller specifying the correct level)
|
/* 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) {
|
function log(message, level) {
|
||||||
verbosity = tc.settings.logLevel;
|
verbosity = tc.settings.logLevel;
|
||||||
if (typeof level === "undefined") {
|
if (typeof level === "undefined") {
|
||||||
level = tc.settings.defaultLogLevel;
|
level = tc.settings.defaultLogLevel;
|
||||||
}
|
}
|
||||||
if (verbosity >= level) {
|
if (verbosity >= level) {
|
||||||
|
// MODIFIED: Added [VSC] prefix for clarity
|
||||||
|
let prefix = "[VSC] ";
|
||||||
if (level === 2) {
|
if (level === 2) {
|
||||||
console.log("ERROR:" + message);
|
console.log(prefix + "ERROR: " + message);
|
||||||
} else if (level === 3) {
|
} else if (level === 3) {
|
||||||
console.log("WARNING:" + message);
|
console.log(prefix + "WARNING: " + message);
|
||||||
} else if (level === 4) {
|
} else if (level === 4) {
|
||||||
console.log("INFO:" + message);
|
console.log(prefix + "INFO: " + message);
|
||||||
} else if (level === 5) {
|
} else if (level === 5) {
|
||||||
console.log("DEBUG:" + message);
|
console.log(prefix + "DEBUG: " + message);
|
||||||
} else if (level === 6) {
|
} else if (level === 6) {
|
||||||
console.log("DEBUG (VERBOSE):" + message);
|
console.log(prefix + "DEBUG (VERBOSE): " + message);
|
||||||
console.trace();
|
console.trace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
chrome.storage.sync.get(tc.settings, function (storage) {
|
chrome.storage.sync.get(tc.settings, function (storage) {
|
||||||
tc.settings.keyBindings = storage.keyBindings; // Array
|
// MODIFIED: Robust keyBinding initialization from storage or defaults.
|
||||||
if (storage.keyBindings.length == 0) {
|
tc.settings.keyBindings =
|
||||||
// if first initialization of 0.5.3
|
Array.isArray(storage.keyBindings) &&
|
||||||
// UPDATE
|
storage.keyBindings.length > 0 &&
|
||||||
tc.settings.keyBindings.push({
|
storage.keyBindings[0].hasOwnProperty("predefined")
|
||||||
action: "slower",
|
? storage.keyBindings
|
||||||
key: Number(storage.slowerKeyCode) || 83,
|
: [
|
||||||
value: Number(storage.speedStep) || 0.1,
|
{
|
||||||
force: false,
|
action: "slower",
|
||||||
predefined: true
|
key: Number(storage.slowerKeyCode) || 83,
|
||||||
}); // default S
|
value: Number(storage.speedStep) || 0.1,
|
||||||
tc.settings.keyBindings.push({
|
force: false,
|
||||||
action: "faster",
|
predefined: true
|
||||||
key: Number(storage.fasterKeyCode) || 68,
|
},
|
||||||
value: Number(storage.speedStep) || 0.1,
|
{
|
||||||
force: false,
|
action: "faster",
|
||||||
predefined: true
|
key: Number(storage.fasterKeyCode) || 68,
|
||||||
}); // default: D
|
value: Number(storage.speedStep) || 0.1,
|
||||||
tc.settings.keyBindings.push({
|
force: false,
|
||||||
action: "rewind",
|
predefined: true
|
||||||
key: Number(storage.rewindKeyCode) || 90,
|
},
|
||||||
value: Number(storage.rewindTime) || 10,
|
{
|
||||||
force: false,
|
action: "rewind",
|
||||||
predefined: true
|
key: Number(storage.rewindKeyCode) || 90,
|
||||||
}); // default: Z
|
value: Number(storage.rewindTime) || 10,
|
||||||
tc.settings.keyBindings.push({
|
force: false,
|
||||||
action: "advance",
|
predefined: true
|
||||||
key: Number(storage.advanceKeyCode) || 88,
|
},
|
||||||
value: Number(storage.advanceTime) || 10,
|
{
|
||||||
force: false,
|
action: "advance",
|
||||||
predefined: true
|
key: Number(storage.advanceKeyCode) || 88,
|
||||||
}); // default: X
|
value: Number(storage.advanceTime) || 10,
|
||||||
tc.settings.keyBindings.push({
|
force: false,
|
||||||
action: "reset",
|
predefined: true
|
||||||
key: Number(storage.resetKeyCode) || 82,
|
},
|
||||||
value: 1.0,
|
{
|
||||||
force: false,
|
action: "reset",
|
||||||
predefined: true
|
key: Number(storage.resetKeyCode) || 82,
|
||||||
}); // default: R
|
value: 1.0,
|
||||||
tc.settings.keyBindings.push({
|
force: false,
|
||||||
action: "fast",
|
predefined: true
|
||||||
key: Number(storage.fastKeyCode) || 71,
|
}, // Default value for reset action is 1.0
|
||||||
value: Number(storage.fastSpeed) || 1.8,
|
{
|
||||||
force: false,
|
action: "fast",
|
||||||
predefined: true
|
key: Number(storage.fastKeyCode) || 71,
|
||||||
}); // default: G
|
value: Number(storage.fastSpeed) || 1.8,
|
||||||
tc.settings.version = "0.5.3";
|
force: false,
|
||||||
|
predefined: true
|
||||||
|
}
|
||||||
|
];
|
||||||
|
if (
|
||||||
|
!Array.isArray(storage.keyBindings) ||
|
||||||
|
storage.keyBindings.length === 0 ||
|
||||||
|
(storage.keyBindings.length > 0 &&
|
||||||
|
!storage.keyBindings[0].hasOwnProperty("predefined"))
|
||||||
|
) {
|
||||||
|
log("Initializing/Updating keybindings in storage.", 4);
|
||||||
chrome.storage.sync.set({
|
chrome.storage.sync.set({
|
||||||
keyBindings: tc.settings.keyBindings,
|
keyBindings: tc.settings.keyBindings,
|
||||||
version: tc.settings.version,
|
version: "0.6.3.8"
|
||||||
displayKeyCode: tc.settings.displayKeyCode,
|
}); // Update version
|
||||||
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.lastSpeed = Number(storage.lastSpeed) || 1.0;
|
||||||
|
tc.settings.displayKeyCode = Number(storage.displayKeyCode) || 86;
|
||||||
tc.settings.rememberSpeed = Boolean(storage.rememberSpeed);
|
tc.settings.rememberSpeed = Boolean(storage.rememberSpeed);
|
||||||
tc.settings.forceLastSavedSpeed = Boolean(storage.forceLastSavedSpeed);
|
tc.settings.forceLastSavedSpeed = Boolean(storage.forceLastSavedSpeed);
|
||||||
tc.settings.audioBoolean = Boolean(storage.audioBoolean);
|
tc.settings.audioBoolean = Boolean(storage.audioBoolean);
|
||||||
tc.settings.enabled = Boolean(storage.enabled);
|
tc.settings.enabled =
|
||||||
|
typeof storage.enabled !== "undefined" ? Boolean(storage.enabled) : true;
|
||||||
tc.settings.startHidden = Boolean(storage.startHidden);
|
tc.settings.startHidden = Boolean(storage.startHidden);
|
||||||
tc.settings.controllerOpacity = Number(storage.controllerOpacity);
|
tc.settings.controllerOpacity = Number(storage.controllerOpacity) || 0.3;
|
||||||
tc.settings.blacklist = String(storage.blacklist);
|
tc.settings.blacklist = String(storage.blacklist || tc.settings.blacklist);
|
||||||
|
|
||||||
|
if (typeof storage.logLevel !== "undefined") {
|
||||||
|
tc.settings.logLevel = Number(storage.logLevel);
|
||||||
|
}
|
||||||
|
// ADDED: Load nudge settings from storage
|
||||||
|
tc.settings.enableSubtitleNudge =
|
||||||
|
typeof storage.enableSubtitleNudge !== "undefined"
|
||||||
|
? Boolean(storage.enableSubtitleNudge)
|
||||||
|
: tc.settings.enableSubtitleNudge;
|
||||||
|
tc.settings.subtitleNudgeInterval =
|
||||||
|
Number(storage.subtitleNudgeInterval) || 25; // Using 25ms as requested
|
||||||
|
tc.settings.subtitleNudgeAmount =
|
||||||
|
Number(storage.subtitleNudgeAmount) || tc.settings.subtitleNudgeAmount;
|
||||||
|
|
||||||
// ensure that there is a "display" binding (for upgrades from versions that had it as a separate binding)
|
|
||||||
if (
|
if (
|
||||||
tc.settings.keyBindings.filter((x) => x.action == "display").length == 0
|
tc.settings.keyBindings.filter((x) => x.action == "display").length == 0
|
||||||
) {
|
) {
|
||||||
tc.settings.keyBindings.push({
|
tc.settings.keyBindings.push({
|
||||||
action: "display",
|
action: "display",
|
||||||
key: Number(storage.displayKeyCode) || 86,
|
key: tc.settings.displayKeyCode,
|
||||||
value: 0,
|
value: 0,
|
||||||
force: false,
|
force: false,
|
||||||
predefined: true
|
predefined: true
|
||||||
}); // default V
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
initializeWhenReady(document);
|
initializeWhenReady(document);
|
||||||
});
|
});
|
||||||
|
|
||||||
function getKeyBindings(action, what = "value") {
|
function getKeyBindings(action, what = "value") {
|
||||||
|
if (!tc.settings.keyBindings) return false; // ADDED: Guard against undefined keyBindings
|
||||||
try {
|
try {
|
||||||
return tc.settings.keyBindings.find((item) => item.action === action)[what];
|
const binding = tc.settings.keyBindings.find(
|
||||||
|
(item) => item.action === action
|
||||||
|
);
|
||||||
|
if (binding) return binding[what];
|
||||||
|
// Fallback defaults for safety
|
||||||
|
if (what === "value") {
|
||||||
|
if (action === "slower" || action === "faster") return 0.1;
|
||||||
|
if (action === "rewind" || action === "advance") return 10;
|
||||||
|
if (action === "reset") return 1.0;
|
||||||
|
if (action === "fast") return 1.8;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
log(`Error in getKeyBindings for ${action} (${what}): ${e.message}`, 2);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Original setKeyBindings, used by original resetSpeed logic.
|
||||||
function setKeyBindings(action, value) {
|
function setKeyBindings(action, value) {
|
||||||
tc.settings.keyBindings.find((item) => item.action === action)[
|
if (!tc.settings.keyBindings) return; // ADDED: Guard
|
||||||
"value"
|
const binding = tc.settings.keyBindings.find(
|
||||||
] = value;
|
(item) => item.action === action
|
||||||
|
);
|
||||||
|
if (binding) {
|
||||||
|
binding["value"] = value;
|
||||||
|
log(
|
||||||
|
`In-memory value for keyBinding '${action}' set to ${value} by original setKeyBindings func`,
|
||||||
|
6
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function defineVideoController() {
|
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) {
|
tc.videoController = function (target, parent) {
|
||||||
if (target.vsc) {
|
if (target.vsc) {
|
||||||
|
log(`VSC controller already exists for ${target.src || "video"}.`, 6);
|
||||||
return target.vsc;
|
return target.vsc;
|
||||||
}
|
}
|
||||||
|
log(`Creating VSC controller for ${target.src || "video"}.`, 4);
|
||||||
|
|
||||||
tc.mediaElements.push(target);
|
tc.mediaElements.push(target);
|
||||||
|
target.vsc = this;
|
||||||
|
|
||||||
this.video = target;
|
this.video = target;
|
||||||
this.parent = target.parentElement || parent;
|
this.parent = parent || target.parentElement;
|
||||||
storedSpeed = tc.settings.speeds[target.currentSrc];
|
this.nudgeIntervalId = null; // ADDED: For the subtitle nudge feature
|
||||||
|
|
||||||
|
// Original logic for determining initial speed
|
||||||
|
let storedSpeed;
|
||||||
if (!tc.settings.rememberSpeed) {
|
if (!tc.settings.rememberSpeed) {
|
||||||
|
storedSpeed = tc.settings.speeds[target.currentSrc];
|
||||||
if (!storedSpeed) {
|
if (!storedSpeed) {
|
||||||
log(
|
log(
|
||||||
"Overwriting stored speed to 1.0 due to rememberSpeed being disabled",
|
"Overwriting stored speed to 1.0 due to rememberSpeed being disabled or no speed for src",
|
||||||
5
|
5
|
||||||
);
|
);
|
||||||
storedSpeed = 1.0;
|
storedSpeed = 1.0;
|
||||||
}
|
}
|
||||||
setKeyBindings("reset", getKeyBindings("fast")); // resetSpeed = fastSpeed
|
setKeyBindings("reset", getKeyBindings("fast")); // Original logic for 'R' key toggle state
|
||||||
} else {
|
} else {
|
||||||
log("Recalling stored speed due to rememberSpeed being enabled", 5);
|
log("Recalling stored speed due to rememberSpeed being enabled", 5);
|
||||||
|
storedSpeed =
|
||||||
|
tc.settings.speeds[target.currentSrc] || tc.settings.lastSpeed;
|
||||||
|
}
|
||||||
|
if (tc.settings.forceLastSavedSpeed) {
|
||||||
storedSpeed = tc.settings.lastSpeed;
|
storedSpeed = tc.settings.lastSpeed;
|
||||||
}
|
}
|
||||||
|
|
||||||
log("Explicitly setting playbackRate to: " + storedSpeed, 5);
|
|
||||||
target.playbackRate = storedSpeed;
|
|
||||||
|
|
||||||
this.div = this.initializeControls();
|
this.div = this.initializeControls();
|
||||||
|
|
||||||
var mediaEventAction = function (event) {
|
if (Math.abs(target.playbackRate - storedSpeed) > 0.001) {
|
||||||
storedSpeed = tc.settings.speeds[event.target.currentSrc];
|
log(
|
||||||
if (!tc.settings.rememberSpeed) {
|
`Video current rate ${target.playbackRate.toFixed(2)} differs from VSC target ${storedSpeed.toFixed(2)}. Setting speed (initial).`,
|
||||||
if (!storedSpeed) {
|
4
|
||||||
log("Overwriting stored speed to 1.0 (rememberSpeed not enabled)", 4);
|
);
|
||||||
storedSpeed = 1.0;
|
setSpeed(target, storedSpeed, true); // MODIFIED: Pass true for isInitialSet
|
||||||
}
|
} else {
|
||||||
// resetSpeed isn't really a reset, it's a toggle
|
if (this.speedIndicator)
|
||||||
log("Setting reset keybinding to fast", 5);
|
this.speedIndicator.textContent = storedSpeed.toFixed(2);
|
||||||
setKeyBindings("reset", getKeyBindings("fast")); // resetSpeed = fastSpeed
|
if (
|
||||||
} else {
|
!tc.settings.forceLastSavedSpeed &&
|
||||||
log(
|
tc.settings.lastSpeed !== storedSpeed
|
||||||
"Storing lastSpeed into tc.settings.speeds (rememberSpeed enabled)",
|
) {
|
||||||
5
|
tc.settings.lastSpeed = storedSpeed;
|
||||||
);
|
|
||||||
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
|
// Original mediaEventAction
|
||||||
// with the site's default behavior)
|
var mediaEventAction = function (event) {
|
||||||
log("Explicitly setting playbackRate to: " + storedSpeed, 4);
|
const video = event.target;
|
||||||
setSpeed(event.target, storedSpeed);
|
if (!video.vsc) return;
|
||||||
|
|
||||||
|
let speedToSet = tc.settings.speeds[video.currentSrc]; // Use 'let'
|
||||||
|
if (!tc.settings.rememberSpeed) {
|
||||||
|
if (!speedToSet) speedToSet = 1.0;
|
||||||
|
setKeyBindings("reset", getKeyBindings("fast"));
|
||||||
|
} else {
|
||||||
|
speedToSet = tc.settings.lastSpeed;
|
||||||
|
}
|
||||||
|
if (tc.settings.forceLastSavedSpeed) speedToSet = tc.settings.lastSpeed;
|
||||||
|
|
||||||
|
if (Math.abs(video.playbackRate - speedToSet) > 0.001) {
|
||||||
|
log(
|
||||||
|
`Media event '${event.type}': rate ${video.playbackRate.toFixed(2)} vs target ${speedToSet.toFixed(2)}. Setting.`,
|
||||||
|
4
|
||||||
|
);
|
||||||
|
setSpeed(video, speedToSet, false); // MODIFIED: isInitialSet is false
|
||||||
|
}
|
||||||
|
|
||||||
|
// ADDED: Manage nudge based on event type
|
||||||
|
if (event.type === "play") video.vsc.startSubtitleNudge();
|
||||||
|
else if (event.type === "pause" || event.type === "ended")
|
||||||
|
video.vsc.stopSubtitleNudge();
|
||||||
};
|
};
|
||||||
|
|
||||||
target.addEventListener(
|
target.addEventListener(
|
||||||
"play",
|
"play",
|
||||||
(this.handlePlay = mediaEventAction.bind(this))
|
(this.handlePlay = mediaEventAction.bind(this))
|
||||||
);
|
);
|
||||||
|
target.addEventListener(
|
||||||
|
"pause",
|
||||||
|
(this.handlePause = mediaEventAction.bind(this))
|
||||||
|
); // ADDED for nudge
|
||||||
|
target.addEventListener(
|
||||||
|
"ended",
|
||||||
|
(this.handleEnded = mediaEventAction.bind(this))
|
||||||
|
); // ADDED for nudge
|
||||||
target.addEventListener(
|
target.addEventListener(
|
||||||
"seeked",
|
"seeked",
|
||||||
(this.handleSeek = mediaEventAction.bind(this))
|
(this.handleSeek = mediaEventAction.bind(this))
|
||||||
);
|
);
|
||||||
|
|
||||||
var observer = new MutationObserver((mutations) => {
|
var srcObserver = new MutationObserver((mutations) => {
|
||||||
mutations.forEach((mutation) => {
|
mutations.forEach((mutation) => {
|
||||||
if (
|
if (
|
||||||
mutation.type === "attributes" &&
|
mutation.type === "attributes" &&
|
||||||
(mutation.attributeName === "src" ||
|
(mutation.attributeName === "src" ||
|
||||||
mutation.attributeName === "currentSrc")
|
mutation.attributeName === "currentSrc")
|
||||||
) {
|
) {
|
||||||
log("mutation of A/V element", 5);
|
if (!this.div) return; // MODIFIED: Check if div exists
|
||||||
var controller = this.div;
|
log(`Src changed to: ${mutation.target.currentSrc || "empty"}`, 4);
|
||||||
|
this.stopSubtitleNudge(); // ADDED: Stop nudge for old src
|
||||||
|
|
||||||
if (!mutation.target.src && !mutation.target.currentSrc) {
|
if (!mutation.target.src && !mutation.target.currentSrc) {
|
||||||
controller.classList.add("vsc-nosource");
|
this.div.classList.add("vsc-nosource");
|
||||||
} else {
|
} else {
|
||||||
controller.classList.remove("vsc-nosource");
|
this.div.classList.remove("vsc-nosource");
|
||||||
|
let newSrcSpeed = tc.settings.speeds[mutation.target.currentSrc]; // MODIFIED: Follow original logic
|
||||||
|
if (!tc.settings.rememberSpeed) {
|
||||||
|
if (!newSrcSpeed) newSrcSpeed = 1.0;
|
||||||
|
} else {
|
||||||
|
newSrcSpeed = newSrcSpeed || tc.settings.lastSpeed;
|
||||||
|
}
|
||||||
|
if (tc.settings.forceLastSavedSpeed)
|
||||||
|
newSrcSpeed = tc.settings.lastSpeed;
|
||||||
|
|
||||||
|
setSpeed(mutation.target, newSrcSpeed, true); // MODIFIED: isInitialSet = true
|
||||||
|
if (!mutation.target.paused && mutation.target.playbackRate !== 1.0)
|
||||||
|
this.startSubtitleNudge(); // ADDED
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
observer.observe(target, {
|
srcObserver.observe(target, { attributeFilter: ["src", "currentSrc"] });
|
||||||
attributeFilter: ["src", "currentSrc"]
|
|
||||||
});
|
// ADDED: Initial nudge check
|
||||||
|
if (!target.paused && target.playbackRate !== 1.0) {
|
||||||
|
this.startSubtitleNudge();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Nudge Methods (ADDED) ---
|
||||||
|
tc.videoController.prototype.startSubtitleNudge = function () {
|
||||||
|
if (
|
||||||
|
!tc.settings.enableSubtitleNudge ||
|
||||||
|
this.nudgeIntervalId !== null ||
|
||||||
|
!this.video
|
||||||
|
)
|
||||||
|
return;
|
||||||
|
if (this.video.paused || this.video.playbackRate === 1.0) {
|
||||||
|
this.stopSubtitleNudge();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log(
|
||||||
|
`Nudge: Starting for ${this.video.currentSrc || "video"} (Rate: ${this.video.playbackRate.toFixed(2)}) interval: ${tc.settings.subtitleNudgeInterval}ms.`,
|
||||||
|
5
|
||||||
|
);
|
||||||
|
this.nudgeIntervalId = setInterval(() => {
|
||||||
|
if (
|
||||||
|
!this.video ||
|
||||||
|
this.video.paused ||
|
||||||
|
this.video.playbackRate === 1.0 ||
|
||||||
|
tc.isNudging
|
||||||
|
) {
|
||||||
|
this.stopSubtitleNudge();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const currentRate = this.video.playbackRate;
|
||||||
|
const nudgeAmount = tc.settings.subtitleNudgeAmount;
|
||||||
|
|
||||||
|
tc.isNudging = true;
|
||||||
|
this.video.playbackRate = currentRate + nudgeAmount;
|
||||||
|
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
if (
|
||||||
|
this.video &&
|
||||||
|
Math.abs(this.video.playbackRate - (currentRate + nudgeAmount)) <
|
||||||
|
nudgeAmount * 1.5
|
||||||
|
) {
|
||||||
|
this.video.playbackRate = currentRate;
|
||||||
|
}
|
||||||
|
tc.isNudging = false;
|
||||||
|
});
|
||||||
|
}, tc.settings.subtitleNudgeInterval);
|
||||||
|
};
|
||||||
|
|
||||||
|
tc.videoController.prototype.stopSubtitleNudge = function () {
|
||||||
|
if (this.nudgeIntervalId !== null) {
|
||||||
|
log(
|
||||||
|
`Nudge: Stopping for ${this.video ? this.video.currentSrc || "video" : "detached video"}`,
|
||||||
|
5
|
||||||
|
);
|
||||||
|
clearInterval(this.nudgeIntervalId);
|
||||||
|
this.nudgeIntervalId = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
// --- End Nudge Methods ---
|
||||||
|
|
||||||
tc.videoController.prototype.remove = function () {
|
tc.videoController.prototype.remove = function () {
|
||||||
this.div.remove();
|
this.stopSubtitleNudge(); // ADDED
|
||||||
this.video.removeEventListener("play", this.handlePlay);
|
// Original remove logic:
|
||||||
this.video.removeEventListener("seek", this.handleSeek);
|
if (this.div && this.div.parentNode) this.div.remove();
|
||||||
delete this.video.vsc;
|
if (this.video) {
|
||||||
let idx = tc.mediaElements.indexOf(this.video);
|
this.video.removeEventListener("play", this.handlePlay);
|
||||||
if (idx != -1) {
|
this.video.removeEventListener("pause", this.handlePause); // ADDED
|
||||||
tc.mediaElements.splice(idx, 1);
|
this.video.removeEventListener("ended", this.handleEnded); // ADDED
|
||||||
|
this.video.removeEventListener("seeked", this.handleSeek); // MODIFIED: was "seek" in original provided code
|
||||||
|
delete this.video.vsc;
|
||||||
}
|
}
|
||||||
|
let idx = tc.mediaElements.indexOf(this.video);
|
||||||
|
if (idx !== -1) tc.mediaElements.splice(idx, 1);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Original initializeControls
|
||||||
tc.videoController.prototype.initializeControls = function () {
|
tc.videoController.prototype.initializeControls = function () {
|
||||||
log("initializeControls Begin", 5);
|
log("initializeControls Begin", 5);
|
||||||
const document = this.video.ownerDocument;
|
const doc = this.video.ownerDocument;
|
||||||
const speed = this.video.playbackRate.toFixed(2);
|
const speedForUI = this.video.playbackRate.toFixed(2);
|
||||||
var top = Math.max(this.video.offsetTop, 0) + "px",
|
var top = Math.max(this.video.offsetTop, 0) + "px",
|
||||||
left = Math.max(this.video.offsetLeft, 0) + "px";
|
left = Math.max(this.video.offsetLeft, 0) + "px";
|
||||||
|
log("Speed variable for UI set to: " + speedForUI, 5);
|
||||||
log("Speed variable set to: " + speed, 5);
|
var wrapper = doc.createElement("div");
|
||||||
|
|
||||||
var wrapper = document.createElement("div");
|
|
||||||
wrapper.classList.add("vsc-controller");
|
wrapper.classList.add("vsc-controller");
|
||||||
|
if (!this.video.src && !this.video.currentSrc)
|
||||||
if (!this.video.src && !this.video.currentSrc) {
|
|
||||||
wrapper.classList.add("vsc-nosource");
|
wrapper.classList.add("vsc-nosource");
|
||||||
}
|
if (tc.settings.startHidden) wrapper.classList.add("vsc-hidden");
|
||||||
|
|
||||||
if (tc.settings.startHidden) {
|
|
||||||
wrapper.classList.add("vsc-hidden");
|
|
||||||
}
|
|
||||||
|
|
||||||
var shadow = wrapper.attachShadow({ mode: "open" });
|
var shadow = wrapper.attachShadow({ mode: "open" });
|
||||||
var shadowTemplate = `
|
var shadowTemplate = `
|
||||||
<style>
|
<style> @import "${chrome.runtime.getURL("shadow.css")}"; </style>
|
||||||
@import "${chrome.runtime.getURL("shadow.css")}";
|
<div id="controller" style="top:${top}; left:${left}; opacity:${tc.settings.controllerOpacity}">
|
||||||
</style>
|
<span data-action="drag" class="draggable">${speedForUI}</span>
|
||||||
|
|
||||||
<div id="controller" style="top:${top}; left:${left}; opacity:${
|
|
||||||
tc.settings.controllerOpacity
|
|
||||||
}">
|
|
||||||
<span data-action="drag" class="draggable">${speed}</span>
|
|
||||||
<span id="controls">
|
<span id="controls">
|
||||||
<button data-action="rewind" class="rw">«</button>
|
<button data-action="rewind" class="rw">«</button>
|
||||||
<button data-action="slower">−</button>
|
<button data-action="slower">−</button>
|
||||||
<button data-action="faster">+</button>
|
<button data-action="faster">+</button>
|
||||||
<button data-action="advance" class="rw">»</button>
|
<button data-action="advance" class="rw">»</button>
|
||||||
<button data-action="display" class="hideButton">×</button>
|
<button data-action="display" class="hideButton">×</button>
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>`;
|
||||||
`;
|
|
||||||
shadow.innerHTML = shadowTemplate;
|
shadow.innerHTML = shadowTemplate;
|
||||||
|
this.speedIndicator = shadow.querySelector(".draggable"); // MODIFIED: Original was "span"
|
||||||
|
|
||||||
|
// MODIFIED: Pass this.video as 4th arg to runAction
|
||||||
shadow.querySelector(".draggable").addEventListener(
|
shadow.querySelector(".draggable").addEventListener(
|
||||||
"mousedown",
|
"mousedown",
|
||||||
(e) => {
|
(e) => {
|
||||||
runAction(e.target.dataset["action"], false, e);
|
runAction(
|
||||||
|
e.target.dataset["action"],
|
||||||
|
getKeyBindings(e.target.dataset["action"], "value"),
|
||||||
|
e,
|
||||||
|
this.video
|
||||||
|
);
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
},
|
},
|
||||||
true
|
true
|
||||||
);
|
);
|
||||||
|
shadow.querySelectorAll("button").forEach((button) => {
|
||||||
shadow.querySelectorAll("button").forEach(function (button) {
|
|
||||||
button.addEventListener(
|
button.addEventListener(
|
||||||
"click",
|
"click",
|
||||||
(e) => {
|
(e) => {
|
||||||
runAction(
|
runAction(
|
||||||
e.target.dataset["action"],
|
e.target.dataset["action"],
|
||||||
getKeyBindings(e.target.dataset["action"]),
|
getKeyBindings(e.target.dataset["action"]),
|
||||||
e
|
e,
|
||||||
|
this.video
|
||||||
);
|
);
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
},
|
},
|
||||||
true
|
true
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
shadow
|
shadow
|
||||||
.querySelector("#controller")
|
.querySelector("#controller")
|
||||||
.addEventListener("click", (e) => e.stopPropagation(), false);
|
.addEventListener("click", (e) => e.stopPropagation(), false);
|
||||||
shadow
|
shadow
|
||||||
.querySelector("#controller")
|
.querySelector("#controller")
|
||||||
.addEventListener("mousedown", (e) => e.stopPropagation(), false);
|
.addEventListener("mousedown", (e) => e.stopPropagation(), false);
|
||||||
|
var fragment = doc.createDocumentFragment();
|
||||||
this.speedIndicator = shadow.querySelector("span");
|
|
||||||
var fragment = document.createDocumentFragment();
|
|
||||||
fragment.appendChild(wrapper);
|
fragment.appendChild(wrapper);
|
||||||
|
const parentEl = this.parent || this.video.parentElement;
|
||||||
|
if (!parentEl || !parentEl.parentNode) {
|
||||||
|
doc.body.appendChild(fragment);
|
||||||
|
return wrapper;
|
||||||
|
}
|
||||||
|
// Original placement logic
|
||||||
switch (true) {
|
switch (true) {
|
||||||
case location.hostname == "www.amazon.com":
|
case location.hostname == "www.amazon.com":
|
||||||
case location.hostname == "www.reddit.com":
|
case location.hostname == "www.reddit.com":
|
||||||
case /hbogo\./.test(location.hostname):
|
case /hbogo\./.test(location.hostname):
|
||||||
// insert before parent to bypass overlay
|
parentEl.parentElement.insertBefore(fragment, parentEl);
|
||||||
this.parent.parentElement.insertBefore(fragment, this.parent);
|
|
||||||
break;
|
break;
|
||||||
case location.hostname == "www.facebook.com":
|
case location.hostname == "www.facebook.com":
|
||||||
// this is a monstrosity but new FB design does not have *any*
|
let p =
|
||||||
// semantic handles for us to traverse the tree, and deep nesting
|
parentEl.parentElement.parentElement.parentElement.parentElement
|
||||||
// that we need to bubble up from to get controller to stack correctly
|
.parentElement.parentElement.parentElement;
|
||||||
let p = this.parent.parentElement.parentElement.parentElement
|
if (p && p.firstChild) p.insertBefore(fragment, p.firstChild);
|
||||||
.parentElement.parentElement.parentElement.parentElement;
|
else if (parentEl.firstChild)
|
||||||
p.insertBefore(fragment, p.firstChild);
|
parentEl.insertBefore(fragment, parentEl.firstChild);
|
||||||
|
else parentEl.appendChild(fragment);
|
||||||
break;
|
break;
|
||||||
case location.hostname == "tv.apple.com":
|
case location.hostname == "tv.apple.com":
|
||||||
// insert after parent for correct stacking context
|
const appleRoot = parentEl.getRootNode();
|
||||||
this.parent.getRootNode().querySelector(".scrim").prepend(fragment);
|
const scrim =
|
||||||
|
appleRoot && appleRoot.querySelector
|
||||||
|
? appleRoot.querySelector(".scrim")
|
||||||
|
: null;
|
||||||
|
if (scrim) scrim.prepend(fragment);
|
||||||
|
else parentEl.insertBefore(fragment, parentEl.firstChild);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
// Note: when triggered via a MutationRecord, it's possible that the
|
parentEl.insertBefore(fragment, parentEl.firstChild);
|
||||||
// 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;
|
return wrapper;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapeStringRegExp(str) {
|
function escapeStringRegExp(str) {
|
||||||
matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
|
const matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
|
||||||
return str.replace(matchOperatorsRe, "\\$&");
|
return str.replace(matchOperatorsRe, "\\$&");
|
||||||
}
|
}
|
||||||
|
|
||||||
function isBlacklisted() {
|
function isBlacklisted() {
|
||||||
blacklisted = false;
|
let blacklisted = false;
|
||||||
tc.settings.blacklist.split("\n").forEach((match) => {
|
const blacklistLines = tc.settings.blacklist
|
||||||
|
? tc.settings.blacklist.split("\n")
|
||||||
|
: [];
|
||||||
|
blacklistLines.forEach((match) => {
|
||||||
|
if (blacklisted) return;
|
||||||
match = match.replace(regStrip, "");
|
match = match.replace(regStrip, "");
|
||||||
if (match.length == 0) {
|
if (match.length == 0) return;
|
||||||
return;
|
let regexp;
|
||||||
}
|
if (match.startsWith("/") && match.lastIndexOf("/") > 0) {
|
||||||
|
|
||||||
if (match.startsWith("/")) {
|
|
||||||
try {
|
try {
|
||||||
var regexp = new RegExp(match);
|
const ls = match.lastIndexOf("/");
|
||||||
|
regexp = new RegExp(match.substring(1, ls), match.substring(ls + 1));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
log(`Invalid regex in blacklist: ${match}. Error: ${err.message}`, 2);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
} else {
|
} else regexp = new RegExp(escapeStringRegExp(match));
|
||||||
var regexp = new RegExp(escapeStringRegExp(match));
|
if (regexp && regexp.test(location.href)) blacklisted = true;
|
||||||
}
|
|
||||||
|
|
||||||
if (regexp.test(location.href)) {
|
|
||||||
blacklisted = true;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
if (blacklisted) log(`Page ${location.href} is blacklisted.`, 4);
|
||||||
return blacklisted;
|
return blacklisted;
|
||||||
}
|
}
|
||||||
|
|
||||||
var coolDown = false;
|
var coolDown = false;
|
||||||
function refreshCoolDown() {
|
function refreshCoolDown() {
|
||||||
log("Begin refreshCoolDown", 5);
|
log("Begin refreshCoolDown", 5);
|
||||||
if (coolDown) {
|
if (coolDown) clearTimeout(coolDown);
|
||||||
clearTimeout(coolDown);
|
|
||||||
}
|
|
||||||
coolDown = setTimeout(function () {
|
coolDown = setTimeout(function () {
|
||||||
coolDown = false;
|
coolDown = false;
|
||||||
}, 1000);
|
}, 1000);
|
||||||
log("End refreshCoolDown", 5);
|
// log("End refreshCoolDown", 6); // Original log level was 5
|
||||||
}
|
}
|
||||||
|
|
||||||
function setupListener() {
|
function setupListener() {
|
||||||
/**
|
if (document.vscRateListenerAttached) return; // MODIFIED: Ensure flag check
|
||||||
* 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
|
// MODIFIED: fromUserInput parameter added
|
||||||
* that latest speed into the local storage.
|
function updateSpeedFromEvent(video, fromUserInput = false) {
|
||||||
*
|
if (!video.vsc || !video.vsc.speedIndicator) return;
|
||||||
* @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));
|
var speed = Number(video.playbackRate.toFixed(2));
|
||||||
|
log(
|
||||||
|
`updateSpeedFromEvent: Rate is ${speed}. FromUserInput: ${fromUserInput}`,
|
||||||
|
4
|
||||||
|
);
|
||||||
|
|
||||||
log("Playback rate changed to " + speed, 4);
|
video.vsc.speedIndicator.textContent = speed.toFixed(2);
|
||||||
|
tc.settings.speeds[video.currentSrc || "unknown_src"] = speed;
|
||||||
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;
|
tc.settings.lastSpeed = speed;
|
||||||
log("Syncing chrome settings for lastSpeed", 5);
|
chrome.storage.sync.set({ lastSpeed: speed }, () => {
|
||||||
chrome.storage.sync.set({ lastSpeed: speed }, function () {
|
if (chrome.runtime.lastError)
|
||||||
log("Speed setting saved: " + speed, 5);
|
log(`Error saving lastSpeed: ${chrome.runtime.lastError.message}`, 2);
|
||||||
});
|
});
|
||||||
// show the controller for 1000ms if it's hidden.
|
|
||||||
runAction("blink", null, null);
|
// MODIFIED: Only "blink" (show controller) if change was from user input
|
||||||
|
if (fromUserInput) {
|
||||||
|
runAction("blink", getKeyBindings("blink", "value") || 1000, null, video);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (video.vsc) {
|
||||||
|
// MODIFIED: Manage nudge based on new speed
|
||||||
|
if (speed === 1.0 || video.paused) video.vsc.stopSubtitleNudge();
|
||||||
|
else video.vsc.startSubtitleNudge();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
document.addEventListener(
|
document.addEventListener(
|
||||||
"ratechange",
|
"ratechange",
|
||||||
function (event) {
|
function (event) {
|
||||||
if (coolDown) {
|
// ADDED: Check tc.isNudging at the very start
|
||||||
log("Speed event propagation blocked", 4);
|
if (tc.isNudging) {
|
||||||
event.stopImmediatePropagation();
|
// log("Ratechange event during nudge, VSC UI/state update skipped. Allowing propagation for YT.", 6);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
var video = event.target;
|
|
||||||
|
|
||||||
/**
|
// Original coolDown logic
|
||||||
* If the last speed is forced, only update the speed based on events created by
|
if (coolDown) {
|
||||||
* video speed instead of all video speed change events.
|
log("Speed event propagation blocked by coolDown", 4);
|
||||||
*/
|
|
||||||
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();
|
event.stopImmediatePropagation();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var video = event.target;
|
||||||
|
if (!video || typeof video.playbackRate === "undefined" || !video.vsc)
|
||||||
|
return;
|
||||||
|
|
||||||
|
const eventOrigin = event.detail && event.detail.origin;
|
||||||
|
let isFromUserInputForBlink = false; // MODIFIED: Flag to control blink
|
||||||
|
|
||||||
|
if (tc.settings.forceLastSavedSpeed) {
|
||||||
|
if (eventOrigin === "videoSpeed") {
|
||||||
|
if (event.detail.speed) {
|
||||||
|
const detailSpeedNum = Number(event.detail.speed);
|
||||||
|
if (
|
||||||
|
!isNaN(detailSpeedNum) &&
|
||||||
|
Math.abs(video.playbackRate - detailSpeedNum) > 0.001
|
||||||
|
) {
|
||||||
|
video.playbackRate = detailSpeedNum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
isFromUserInputForBlink = event.detail.fromUserInput !== false; // Respect passed flag
|
||||||
|
updateSpeedFromEvent(video, isFromUserInputForBlink);
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
} else {
|
||||||
|
if (Math.abs(video.playbackRate - tc.settings.lastSpeed) > 0.001) {
|
||||||
|
log(
|
||||||
|
`Ratechange (Force ON): Discrepancy. Video rate: ${video.playbackRate.toFixed(2)}, VSC wants: ${tc.settings.lastSpeed.toFixed(2)}. Forcing.`,
|
||||||
|
3
|
||||||
|
);
|
||||||
|
video.playbackRate = tc.settings.lastSpeed;
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
// The next ratechange will be from VSC forcing, consider that not direct user input for blink
|
||||||
|
// updateSpeedFromEvent will be called by that next event.
|
||||||
|
} else {
|
||||||
|
updateSpeedFromEvent(video, false); // Not user input, just confirming forced speed
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
updateSpeedFromEvent(video);
|
// forceLastSavedSpeed is OFF
|
||||||
|
// Determine if it was a VSC-initiated user action (like S/D keys)
|
||||||
|
// The `setSpeed` function, when called by `runAction`, doesn't add a special origin detail
|
||||||
|
// when forceLastSavedSpeed is off. So, a native ratechange event fires.
|
||||||
|
// We assume if forceLastSavedSpeed is off, any rate change processed here
|
||||||
|
// that isn't a nudge IS significant enough to update UI state.
|
||||||
|
// The "blink" should happen if tc.settings.lastSpeed *changed* due to this event,
|
||||||
|
// implying it wasn't just a confirmation of existing speed.
|
||||||
|
const oldLastSpeed = tc.settings.lastSpeed;
|
||||||
|
updateSpeedFromEvent(video, false); // Initially assume not user-driven for blink
|
||||||
|
if (
|
||||||
|
Math.abs(oldLastSpeed - tc.settings.lastSpeed) > 0.001 &&
|
||||||
|
oldLastSpeed !== 1.0 &&
|
||||||
|
tc.settings.lastSpeed !== 1.0
|
||||||
|
) {
|
||||||
|
// If lastSpeed actually changed due to this event, it was likely a user action via VSC
|
||||||
|
// or a significant external change. Trigger blink.
|
||||||
|
// Exception: don't blink if going to/from 1.0x as that's often a reset.
|
||||||
|
// This logic is imperfect for determining "user input" when not forcing.
|
||||||
|
// A cleaner way would be if setSpeed could flag the *next* native event.
|
||||||
|
// For now, this is a heuristic.
|
||||||
|
if (!tc.isNudging) {
|
||||||
|
// Double check not a nudge, though already filtered
|
||||||
|
runAction(
|
||||||
|
"blink",
|
||||||
|
getKeyBindings("blink", "value") || 1000,
|
||||||
|
null,
|
||||||
|
video
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
true
|
true
|
||||||
);
|
);
|
||||||
|
document.vscRateChangeListenerAttached = true; // MODIFIED: Ensure flag is set
|
||||||
}
|
}
|
||||||
|
|
||||||
function initializeWhenReady(document) {
|
// MODIFIED: More robust initialization flow with unique flags
|
||||||
log("Begin initializeWhenReady", 5);
|
var vscInitializedDocuments = new Set();
|
||||||
|
function initializeWhenReady(doc) {
|
||||||
|
if (doc.vscInitWhenReadyCalledFullUniqueFlag && doc.readyState !== "loading")
|
||||||
|
return;
|
||||||
|
doc.vscInitWhenReadyCalledFullUniqueFlag = true;
|
||||||
if (isBlacklisted()) {
|
if (isBlacklisted()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
window.addEventListener('load', () => {
|
log(
|
||||||
initializeNow(window.document);
|
`initializeWhenReady for: ${doc.location ? doc.location.href : "iframe"}. ReadyState: ${doc.readyState}`,
|
||||||
});
|
5
|
||||||
if (document) {
|
);
|
||||||
if (document.readyState === "complete") {
|
|
||||||
initializeNow(document);
|
if (doc === window.document && !window.vscPageLoadListenerFullUniqueFlag) {
|
||||||
} else {
|
window.addEventListener("load", () => initializeNow(window.document), {
|
||||||
document.onreadystatechange = () => {
|
once: true
|
||||||
if (document.readyState === "complete") {
|
});
|
||||||
initializeNow(document);
|
window.vscPageLoadListenerFullUniqueFlag = true;
|
||||||
|
}
|
||||||
|
if (doc.readyState === "complete") {
|
||||||
|
initializeNow(doc);
|
||||||
|
} else {
|
||||||
|
if (!doc.vscReadyStateListenerFullUniqueFlag) {
|
||||||
|
doc.addEventListener(
|
||||||
|
"readystatechange",
|
||||||
|
function onRSChange_VSC_Final_Unique_CB() {
|
||||||
|
if (doc.readyState === "complete") {
|
||||||
|
doc.removeEventListener(
|
||||||
|
"readystatechange",
|
||||||
|
onRSChange_VSC_Final_Unique_CB
|
||||||
|
);
|
||||||
|
initializeNow(doc);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
};
|
);
|
||||||
|
doc.vscReadyStateListenerFullUniqueFlag = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log("End initializeWhenReady", 5);
|
|
||||||
}
|
}
|
||||||
function inIframe() {
|
function inIframe() {
|
||||||
try {
|
try {
|
||||||
@@ -506,399 +720,449 @@ function inIframe() {
|
|||||||
}
|
}
|
||||||
function getShadow(parent) {
|
function getShadow(parent) {
|
||||||
let result = [];
|
let result = [];
|
||||||
function getChild(parent) {
|
function getChild(p) {
|
||||||
if (parent.firstElementChild) {
|
if (p.firstElementChild) {
|
||||||
var child = parent.firstElementChild;
|
var c = p.firstElementChild;
|
||||||
do {
|
do {
|
||||||
result.push(child);
|
result.push(c);
|
||||||
getChild(child);
|
getChild(c);
|
||||||
if (child.shadowRoot) {
|
if (c.shadowRoot) result.push(...getShadow(c.shadowRoot));
|
||||||
result.push(getShadow(child.shadowRoot));
|
c = c.nextElementSibling;
|
||||||
}
|
} while (c);
|
||||||
child = child.nextElementSibling;
|
|
||||||
} while (child);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
getChild(parent);
|
getChild(parent);
|
||||||
return result.flat(Infinity);
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
function initializeNow(document) {
|
function initializeNow(doc) {
|
||||||
log("Begin initializeNow", 5);
|
if (vscInitializedDocuments.has(doc) || !doc.body) return;
|
||||||
if (!tc.settings.enabled) return;
|
log(
|
||||||
// enforce init-once due to redundant callers
|
`initializeNow for doc: ${doc.location ? doc.location.href : "iframe"}`,
|
||||||
if (!document.body || document.body.classList.contains("vsc-initialized")) {
|
4
|
||||||
|
);
|
||||||
|
if (!tc.settings.enabled) {
|
||||||
|
log("VSC is disabled.", 4);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
try {
|
if (!doc.body.classList.contains("vsc-initialized"))
|
||||||
setupListener();
|
doc.body.classList.add("vsc-initialized");
|
||||||
} catch {
|
if (typeof tc.videoController === "undefined") defineVideoController();
|
||||||
// no operation
|
setupListener();
|
||||||
}
|
if (
|
||||||
document.body.classList.add("vsc-initialized");
|
inIframe() &&
|
||||||
log("initializeNow: vsc-initialized added to document body", 5);
|
doc !== window.top.document &&
|
||||||
|
!doc.head.querySelector('link[href*="inject.css"]')
|
||||||
if (document === window.document) {
|
) {
|
||||||
defineVideoController();
|
var link = doc.createElement("link");
|
||||||
} else {
|
|
||||||
var link = document.createElement("link");
|
|
||||||
link.href = chrome.runtime.getURL("inject.css");
|
link.href = chrome.runtime.getURL("inject.css");
|
||||||
link.type = "text/css";
|
link.type = "text/css";
|
||||||
link.rel = "stylesheet";
|
link.rel = "stylesheet";
|
||||||
document.head.appendChild(link);
|
doc.head.appendChild(link);
|
||||||
}
|
}
|
||||||
var docs = Array(document);
|
const docsForKeydown = new Set([doc]);
|
||||||
try {
|
try {
|
||||||
if (inIframe()) docs.push(window.top.document);
|
if (inIframe() && window.top.document)
|
||||||
|
docsForKeydown.add(window.top.document);
|
||||||
} catch (e) {}
|
} catch (e) {}
|
||||||
|
docsForKeydown.forEach((lDoc) => {
|
||||||
docs.forEach(function (doc) {
|
if (!lDoc.vscKeydownListenerUniqueFlagB) {
|
||||||
doc.addEventListener(
|
// Different flag
|
||||||
"keydown",
|
lDoc.addEventListener(
|
||||||
function (event) {
|
"keydown",
|
||||||
var keyCode = event.keyCode;
|
function (event) {
|
||||||
log("Processing keydown event: " + keyCode, 6);
|
if (!tc.settings.enabled) return;
|
||||||
|
const target = event.target;
|
||||||
// Ignore if following modifier is active.
|
if (
|
||||||
if (
|
target.nodeName === "INPUT" ||
|
||||||
!event.getModifierState ||
|
target.nodeName === "TEXTAREA" ||
|
||||||
event.getModifierState("Alt") ||
|
target.isContentEditable
|
||||||
event.getModifierState("Control") ||
|
)
|
||||||
event.getModifierState("Fn") ||
|
return;
|
||||||
event.getModifierState("Meta") ||
|
if (
|
||||||
event.getModifierState("Hyper") ||
|
event.getModifierState &&
|
||||||
event.getModifierState("OS")
|
(event.getModifierState("Alt") ||
|
||||||
) {
|
event.getModifierState("Control") ||
|
||||||
log("Keydown event ignored due to active modifier: " + keyCode, 5);
|
event.getModifierState("Meta") ||
|
||||||
return;
|
event.getModifierState("Fn") ||
|
||||||
}
|
event.getModifierState("Hyper") ||
|
||||||
|
event.getModifierState("OS"))
|
||||||
// Ignore keydown event if typing in an input box
|
)
|
||||||
if (
|
return;
|
||||||
event.target.nodeName === "INPUT" ||
|
if (
|
||||||
event.target.nodeName === "TEXTAREA" ||
|
tc.mediaElements.length === 0 &&
|
||||||
event.target.isContentEditable
|
!lDoc.querySelector("video,audio")
|
||||||
) {
|
)
|
||||||
return false;
|
return;
|
||||||
}
|
var item = tc.settings.keyBindings.find(
|
||||||
|
(kb) => kb.key === event.keyCode
|
||||||
// Ignore keydown event if typing in a page without vsc
|
);
|
||||||
if (!tc.mediaElements.length) {
|
if (item) {
|
||||||
return false;
|
runAction(item.action, item.value, event);
|
||||||
}
|
if (item.force === "true" || item.force === true) {
|
||||||
|
event.preventDefault();
|
||||||
var item = tc.settings.keyBindings.find((item) => item.key === keyCode);
|
event.stopPropagation();
|
||||||
if (item) {
|
}
|
||||||
runAction(item.action, item.value);
|
|
||||||
if (item.force === "true") {
|
|
||||||
// disable websites key bindings
|
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
|
true
|
||||||
return false;
|
);
|
||||||
},
|
lDoc.vscKeydownListenerUniqueFlagB = true;
|
||||||
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" ||
|
if (!doc.vscMutationObserverUniqueFlagB) {
|
||||||
(node.nodeName === "AUDIO" && tc.settings.audioBoolean)
|
// Different flag
|
||||||
) {
|
const obs = new MutationObserver((muts) => {
|
||||||
if (added) {
|
if (typeof requestIdleCallback === "function")
|
||||||
node.vsc = new tc.videoController(node, parent);
|
requestIdleCallback(() => processMutations(muts), { timeout: 1000 });
|
||||||
} else {
|
else setTimeout(() => processMutations(muts), 200);
|
||||||
if (node.vsc) {
|
});
|
||||||
node.vsc.remove();
|
function processMutations(mList) {
|
||||||
|
for (const m of mList) {
|
||||||
|
if (m.type === "childList") {
|
||||||
|
m.addedNodes.forEach((n) => {
|
||||||
|
if (n instanceof Element) chkVid(n, n.parentNode || m.target, true);
|
||||||
|
});
|
||||||
|
m.removedNodes.forEach((n) => {
|
||||||
|
if (n instanceof Element)
|
||||||
|
chkVid(n, n.parentNode || m.target, false);
|
||||||
|
});
|
||||||
|
} else if (
|
||||||
|
m.type === "attributes" &&
|
||||||
|
m.attributeName === "aria-hidden" &&
|
||||||
|
m.target instanceof Element &&
|
||||||
|
m.target.getAttribute("aria-hidden") === "false"
|
||||||
|
) {
|
||||||
|
const vidsInTgt = Array.from(getShadow(m.target)).filter(
|
||||||
|
(el) => el.tagName === "VIDEO"
|
||||||
|
);
|
||||||
|
vidsInTgt.forEach((vEl) => {
|
||||||
|
if (!vEl.vsc) chkVid(vEl, vEl.parentNode || m.target, true);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (node.children != undefined) {
|
}
|
||||||
for (var i = 0; i < node.children.length; i++) {
|
function chkVid(n, p, add) {
|
||||||
const child = node.children[i];
|
if (!add && !n.isConnected) {
|
||||||
checkForVideo(child, child.parentNode || parent, added);
|
} else if (!add && n.isConnected) return;
|
||||||
|
if (
|
||||||
|
n.nodeName === "VIDEO" ||
|
||||||
|
(n.nodeName === "AUDIO" && tc.settings.audioBoolean)
|
||||||
|
) {
|
||||||
|
if (add) {
|
||||||
|
if (!n.vsc) new tc.videoController(n, p);
|
||||||
|
} else {
|
||||||
|
if (n.vsc) n.vsc.remove();
|
||||||
|
}
|
||||||
|
} else if (n.children && n.children.length > 0) {
|
||||||
|
for (let i = 0; i < n.children.length; i++)
|
||||||
|
chkVid(n.children[i], n.children[i].parentNode || p, add);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
obs.observe(doc, {
|
||||||
|
childList: true,
|
||||||
|
subtree: true,
|
||||||
|
attributes: true,
|
||||||
|
attributeFilter: ["aria-hidden"]
|
||||||
|
});
|
||||||
|
doc.vscMutationObserverUniqueFlagB = true;
|
||||||
}
|
}
|
||||||
|
const q = tc.settings.audioBoolean ? "video,audio" : "video";
|
||||||
var observer = new MutationObserver(function (mutations) {
|
doc.querySelectorAll(q).forEach((vid) => {
|
||||||
// Process the DOM nodes lazily
|
if (!vid.vsc) new tc.videoController(vid, vid.parentElement);
|
||||||
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, {
|
Array.from(doc.getElementsByTagName("iframe")).forEach((fr) => {
|
||||||
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 {
|
try {
|
||||||
var childDocument = frame.contentDocument;
|
if (fr.contentDocument) initializeWhenReady(fr.contentDocument);
|
||||||
} catch (e) {
|
} catch (e) {}
|
||||||
return;
|
|
||||||
}
|
|
||||||
initializeWhenReady(childDocument);
|
|
||||||
});
|
});
|
||||||
log("End initializeNow", 5);
|
vscInitializedDocuments.add(doc);
|
||||||
}
|
}
|
||||||
|
|
||||||
function setSpeed(video, speed) {
|
// MODIFIED setSpeed to accept `isInitialCall` and use it for `fromUserInput`
|
||||||
log("setSpeed started: " + speed, 5);
|
function setSpeed(video, speed, isInitialCall = false) {
|
||||||
var speedvalue = speed.toFixed(2);
|
const numericSpeed = Number(speed);
|
||||||
|
if (isNaN(numericSpeed) || numericSpeed <= 0 || numericSpeed > 16) return;
|
||||||
|
if (!video || !video.vsc || !video.vsc.speedIndicator) return;
|
||||||
|
log(
|
||||||
|
`setSpeed: Target ${numericSpeed.toFixed(2)}. Initial: ${isInitialCall}`,
|
||||||
|
4
|
||||||
|
);
|
||||||
|
|
||||||
|
tc.settings.lastSpeed = numericSpeed;
|
||||||
|
video.vsc.speedIndicator.textContent = numericSpeed.toFixed(2);
|
||||||
|
|
||||||
if (tc.settings.forceLastSavedSpeed) {
|
if (tc.settings.forceLastSavedSpeed) {
|
||||||
video.dispatchEvent(
|
video.dispatchEvent(
|
||||||
new CustomEvent("ratechange", {
|
new CustomEvent("ratechange", {
|
||||||
detail: { origin: "videoSpeed", speed: speedvalue }
|
detail: {
|
||||||
|
origin: "videoSpeed",
|
||||||
|
speed: numericSpeed.toFixed(2),
|
||||||
|
fromUserInput: !isInitialCall
|
||||||
|
}
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
video.playbackRate = Number(speedvalue);
|
if (Math.abs(video.playbackRate - numericSpeed) > 0.001) {
|
||||||
|
// Before changing rate, set a flag that this is VSC initiated for non-forced mode
|
||||||
|
video.vscIsSettingRate = !isInitialCall; // True if user action, false if initial
|
||||||
|
video.playbackRate = numericSpeed;
|
||||||
|
// Flag will be cleared by ratechange listener after processing
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!isInitialCall) refreshCoolDown();
|
||||||
|
if (video.vsc) {
|
||||||
|
if (numericSpeed === 1.0 || video.paused) video.vsc.stopSubtitleNudge();
|
||||||
|
else video.vsc.startSubtitleNudge();
|
||||||
}
|
}
|
||||||
var speedIndicator = video.vsc.speedIndicator;
|
|
||||||
speedIndicator.textContent = speedvalue;
|
|
||||||
tc.settings.lastSpeed = speed;
|
|
||||||
refreshCoolDown();
|
|
||||||
log("setSpeed finished: " + speed, 5);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function runAction(action, value, e) {
|
// MODIFIED runAction to pass 4th arg `specificVideo` to some internal calls if needed.
|
||||||
log("runAction Begin", 5);
|
// And pass `isInitialCall=false` to setSpeed calls.
|
||||||
|
function runAction(action, value, e, specificVideo = null) {
|
||||||
|
// ... (robust mediaTagsToProcess logic from previous correct version) ...
|
||||||
|
var mediaTagsToProcess = [];
|
||||||
|
if (specificVideo) mediaTagsToProcess = [specificVideo];
|
||||||
|
else if (e && e.target) {
|
||||||
|
const docContext = e.target.ownerDocument || document;
|
||||||
|
let activeVideo = tc.mediaElements.find(
|
||||||
|
(v) =>
|
||||||
|
v.ownerDocument === docContext &&
|
||||||
|
(docContext.activeElement === v || v.contains(docContext.activeElement))
|
||||||
|
);
|
||||||
|
if (activeVideo) mediaTagsToProcess = [activeVideo];
|
||||||
|
else {
|
||||||
|
activeVideo = tc.mediaElements.find(
|
||||||
|
(v) =>
|
||||||
|
v.ownerDocument === docContext &&
|
||||||
|
v.offsetParent !== null &&
|
||||||
|
(!v.paused || v.readyState > 0)
|
||||||
|
);
|
||||||
|
if (activeVideo) mediaTagsToProcess = [activeVideo];
|
||||||
|
else {
|
||||||
|
mediaTagsToProcess = tc.mediaElements.filter(
|
||||||
|
(v) => v.ownerDocument === docContext
|
||||||
|
);
|
||||||
|
if (mediaTagsToProcess.length === 0 && tc.mediaElements.length > 0)
|
||||||
|
mediaTagsToProcess = [tc.mediaElements[0]];
|
||||||
|
else if (mediaTagsToProcess.length === 0) mediaTagsToProcess = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else mediaTagsToProcess = tc.mediaElements;
|
||||||
|
if (mediaTagsToProcess.length === 0 && action !== "display") return;
|
||||||
|
|
||||||
var mediaTags = tc.mediaElements;
|
var targetControllerFromEvent =
|
||||||
|
e && e.target && e.target.getRootNode && e.target.getRootNode().host
|
||||||
|
? e.target.getRootNode().host
|
||||||
|
: null;
|
||||||
|
var originalActionForResetContext = actionBeingProcessedForReset_ctx; // Use a local context var
|
||||||
|
actionBeingProcessedForReset_ctx = action;
|
||||||
|
|
||||||
// Get the controller that was used if called from a button press event e
|
mediaTagsToProcess.forEach(function (v) {
|
||||||
if (e) {
|
if (!v || !v.vsc || !v.vsc.div || !v.vsc.speedIndicator) return;
|
||||||
var targetController = e.target.getRootNode().host;
|
var controllerDiv = v.vsc.div;
|
||||||
}
|
if (
|
||||||
|
targetControllerFromEvent &&
|
||||||
mediaTags.forEach(function (v) {
|
targetControllerFromEvent !== controllerDiv &&
|
||||||
var controller = v.vsc.div;
|
action !== "blink"
|
||||||
|
)
|
||||||
// Don't change video speed if the video has a different controller
|
|
||||||
if (e && !(targetController == controller)) {
|
|
||||||
return;
|
return;
|
||||||
|
if (action === "blink" && specificVideo && v !== specificVideo) return;
|
||||||
|
|
||||||
|
const userDrivenActionsThatShowController = [
|
||||||
|
"rewind",
|
||||||
|
"advance",
|
||||||
|
"faster",
|
||||||
|
"slower",
|
||||||
|
"reset",
|
||||||
|
"fast",
|
||||||
|
"pause",
|
||||||
|
"muted",
|
||||||
|
"mark",
|
||||||
|
"jump",
|
||||||
|
"drag"
|
||||||
|
];
|
||||||
|
if (userDrivenActionsThatShowController.includes(action)) {
|
||||||
|
showController(controllerDiv);
|
||||||
}
|
}
|
||||||
|
|
||||||
showController(controller);
|
if (v.classList.contains("vsc-cancelled")) return;
|
||||||
|
const numValue = parseFloat(value);
|
||||||
if (!v.classList.contains("vsc-cancelled")) {
|
switch (action) {
|
||||||
if (action === "rewind") {
|
case "rewind":
|
||||||
log("Rewind", 5);
|
v.currentTime -= numValue;
|
||||||
v.currentTime -= value;
|
break;
|
||||||
} else if (action === "advance") {
|
case "advance":
|
||||||
log("Fast forward", 5);
|
v.currentTime += numValue;
|
||||||
v.currentTime += value;
|
break;
|
||||||
} else if (action === "faster") {
|
case "faster":
|
||||||
log("Increase speed", 5);
|
setSpeed(
|
||||||
// Maximum playback speed in Chrome is set to 16:
|
v,
|
||||||
// https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/html/media/html_media_element.cc?gsn=kMinRate&l=166
|
Math.min(
|
||||||
var s = Math.min(
|
(v.playbackRate < 0.07 ? 0.07 : v.playbackRate) + numValue,
|
||||||
(v.playbackRate < 0.1 ? 0.0 : v.playbackRate) + value,
|
16
|
||||||
16
|
),
|
||||||
|
false
|
||||||
);
|
);
|
||||||
setSpeed(v, s);
|
break;
|
||||||
} else if (action === "slower") {
|
case "slower":
|
||||||
log("Decrease speed", 5);
|
setSpeed(v, Math.max(v.playbackRate - numValue, 0.07), false);
|
||||||
// Video min rate is 0.0625:
|
break;
|
||||||
// https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/html/media/html_media_element.cc?gsn=kMinRate&l=165
|
// MODIFIED: Calls new resetSpeed directly
|
||||||
var s = Math.max(v.playbackRate - value, 0.07);
|
case "reset":
|
||||||
setSpeed(v, s);
|
resetSpeedSimple(v, 1.0);
|
||||||
} else if (action === "reset") {
|
break;
|
||||||
log("Reset speed", 5);
|
case "fast":
|
||||||
resetSpeed(v, 1.0);
|
resetSpeedSimple(v, numValue);
|
||||||
} else if (action === "display") {
|
break;
|
||||||
log("Showing controller", 5);
|
case "display":
|
||||||
controller.classList.add("vsc-manual");
|
controllerDiv.classList.add("vsc-manual");
|
||||||
controller.classList.toggle("vsc-hidden");
|
controllerDiv.classList.toggle("vsc-hidden");
|
||||||
} else if (action === "blink") {
|
break;
|
||||||
log("Showing controller momentarily", 5);
|
case "blink":
|
||||||
// if vsc is hidden, show it briefly to give the use visual feedback that the action is excuted.
|
|
||||||
if (
|
if (
|
||||||
controller.classList.contains("vsc-hidden") ||
|
controllerDiv.classList.contains("vsc-hidden") ||
|
||||||
controller.blinkTimeOut !== undefined
|
controllerDiv.blinkTimeOut !== undefined
|
||||||
) {
|
) {
|
||||||
clearTimeout(controller.blinkTimeOut);
|
clearTimeout(controllerDiv.blinkTimeOut);
|
||||||
controller.classList.remove("vsc-hidden");
|
controllerDiv.classList.remove("vsc-hidden");
|
||||||
controller.blinkTimeOut = setTimeout(
|
controllerDiv.blinkTimeOut = setTimeout(
|
||||||
() => {
|
() => {
|
||||||
controller.classList.add("vsc-hidden");
|
if (
|
||||||
controller.blinkTimeOut = undefined;
|
controllerDiv.classList.contains("vsc-manual") &&
|
||||||
|
!controllerDiv.classList.contains("vsc-hidden")
|
||||||
|
) {
|
||||||
|
} else {
|
||||||
|
controllerDiv.classList.add("vsc-hidden");
|
||||||
|
}
|
||||||
|
controllerDiv.blinkTimeOut = undefined;
|
||||||
},
|
},
|
||||||
value ? value : 1000
|
typeof value === "number" && !isNaN(value) ? value : 1000
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if (action === "drag") {
|
break;
|
||||||
handleDrag(v, e);
|
case "drag":
|
||||||
} else if (action === "fast") {
|
if (e) handleDrag(v, e);
|
||||||
resetSpeed(v, value);
|
break;
|
||||||
} else if (action === "pause") {
|
case "pause":
|
||||||
pause(v);
|
pause(v);
|
||||||
} else if (action === "muted") {
|
break;
|
||||||
|
case "muted":
|
||||||
muted(v);
|
muted(v);
|
||||||
} else if (action === "mark") {
|
break;
|
||||||
|
case "mark":
|
||||||
setMark(v);
|
setMark(v);
|
||||||
} else if (action === "jump") {
|
break;
|
||||||
|
case "jump":
|
||||||
jumpToMark(v);
|
jumpToMark(v);
|
||||||
}
|
break;
|
||||||
|
default:
|
||||||
|
log(`Unknown action: ${action}`, 3);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
log("runAction End", 5);
|
actionBeingProcessedForReset_ctx = originalActionForResetContext;
|
||||||
}
|
}
|
||||||
|
var actionBeingProcessedForReset_ctx = null; // Context for original resetSpeed
|
||||||
|
|
||||||
function pause(v) {
|
function pause(v) {
|
||||||
if (v.paused) {
|
if (v.paused) v.play().catch((e) => log(`Play err:${e.message}`, 2));
|
||||||
log("Resuming video", 5);
|
else v.pause();
|
||||||
v.play();
|
|
||||||
} else {
|
|
||||||
log("Pausing video", 5);
|
|
||||||
v.pause();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function resetSpeed(v, target) {
|
// MODIFIED: New simpler resetSpeed function
|
||||||
if (v.playbackRate === target) {
|
function resetSpeedSimple(v, targetActionSpeed) {
|
||||||
if (v.playbackRate === getKeyBindings("reset")) {
|
log(
|
||||||
if (target !== 1.0) {
|
`resetSpeedSimple: Video current: ${v.playbackRate.toFixed(2)}, Target for this action: ${targetActionSpeed.toFixed(2)}`,
|
||||||
log("Resetting playback speed to 1.0", 4);
|
4
|
||||||
setSpeed(v, 1.0);
|
);
|
||||||
} else {
|
const fastPreferredSpeed = getKeyBindings("fast", "value") || 1.8;
|
||||||
log('Toggling playback speed to "fast" speed', 4);
|
|
||||||
setSpeed(v, getKeyBindings("fast"));
|
if (targetActionSpeed === 1.0) {
|
||||||
}
|
// Action was "reset" (R key)
|
||||||
|
if (Math.abs(v.playbackRate - 1.0) < 0.01) {
|
||||||
|
setSpeed(v, fastPreferredSpeed, false);
|
||||||
} else {
|
} else {
|
||||||
log('Toggling playback speed to "reset" speed', 4);
|
setSpeed(v, 1.0, false);
|
||||||
setSpeed(v, getKeyBindings("reset"));
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
log('Toggling playback speed to "reset" speed', 4);
|
// Action was "fast" (G key), targetActionSpeed is the preferred speed
|
||||||
setKeyBindings("reset", v.playbackRate);
|
if (Math.abs(v.playbackRate - targetActionSpeed) < 0.01) {
|
||||||
setSpeed(v, target);
|
setSpeed(v, 1.0, false);
|
||||||
|
} else {
|
||||||
|
setSpeed(v, targetActionSpeed, false);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Remove or comment out the old `resetSpeed` function that uses setKeyBindings and actionBeingProcessedForReset_global
|
||||||
|
/*
|
||||||
|
function resetSpeed(v, target) { // THIS IS THE OLD ONE TO BE REPLACED by resetSpeedSimple
|
||||||
|
// ... original complex logic ...
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
function muted(v) {
|
function muted(v) {
|
||||||
v.muted = v.muted !== true;
|
v.muted = !v.muted;
|
||||||
|
log(`Mute: ${v.muted}`, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
function setMark(v) {
|
function setMark(v) {
|
||||||
log("Adding marker", 5);
|
if (!v.vsc) v.vsc = {};
|
||||||
v.vsc.mark = v.currentTime;
|
v.vsc.mark = v.currentTime;
|
||||||
|
log(`Mark: ${v.vsc.mark.toFixed(2)}`, 5);
|
||||||
}
|
}
|
||||||
|
|
||||||
function jumpToMark(v) {
|
function jumpToMark(v) {
|
||||||
log("Recalling marker", 5);
|
if (v.vsc && typeof v.vsc.mark === "number") v.currentTime = v.vsc.mark;
|
||||||
if (v.vsc.mark && typeof v.vsc.mark === "number") {
|
else log("No mark.", 4);
|
||||||
v.currentTime = v.vsc.mark;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function handleDrag(video, e) {
|
function handleDrag(video, e) {
|
||||||
|
/* ... same original ... */
|
||||||
|
if (!video || !video.vsc || !video.vsc.div || !video.vsc.div.shadowRoot)
|
||||||
|
return;
|
||||||
const controller = video.vsc.div;
|
const controller = video.vsc.div;
|
||||||
const shadowController = controller.shadowRoot.querySelector("#controller");
|
const shadowController = controller.shadowRoot.querySelector("#controller");
|
||||||
|
if (!shadowController) return;
|
||||||
// Find nearest parent of same size as video parent.
|
|
||||||
var parentElement = controller.parentElement;
|
var parentElement = controller.parentElement;
|
||||||
while (
|
while (
|
||||||
|
parentElement &&
|
||||||
parentElement.parentNode &&
|
parentElement.parentNode &&
|
||||||
|
parentElement.parentNode !== document &&
|
||||||
parentElement.parentNode.offsetHeight === parentElement.offsetHeight &&
|
parentElement.parentNode.offsetHeight === parentElement.offsetHeight &&
|
||||||
parentElement.parentNode.offsetWidth === parentElement.offsetWidth
|
parentElement.parentNode.offsetWidth === parentElement.offsetWidth
|
||||||
) {
|
)
|
||||||
parentElement = parentElement.parentNode;
|
parentElement = parentElement.parentNode;
|
||||||
}
|
const dragBoundary = parentElement || video.ownerDocument.body;
|
||||||
|
|
||||||
video.classList.add("vcs-dragging");
|
video.classList.add("vcs-dragging");
|
||||||
shadowController.classList.add("dragging");
|
shadowController.classList.add("dragging");
|
||||||
|
const iXY = [e.clientX, e.clientY],
|
||||||
const initialMouseXY = [e.clientX, e.clientY];
|
iCtrlXY = [
|
||||||
const initialControllerXY = [
|
parseInt(shadowController.style.left, 10) || 0,
|
||||||
parseInt(shadowController.style.left),
|
parseInt(shadowController.style.top, 10) || 0
|
||||||
parseInt(shadowController.style.top)
|
];
|
||||||
];
|
const sD = (mvE) => {
|
||||||
|
let s = shadowController.style;
|
||||||
const startDragging = (e) => {
|
s.left = iCtrlXY[0] + mvE.clientX - iXY[0] + "px";
|
||||||
let style = shadowController.style;
|
s.top = iCtrlXY[1] + mvE.clientY - iXY[1] + "px";
|
||||||
let dx = e.clientX - initialMouseXY[0];
|
mvE.preventDefault();
|
||||||
let dy = e.clientY - initialMouseXY[1];
|
|
||||||
style.left = initialControllerXY[0] + dx + "px";
|
|
||||||
style.top = initialControllerXY[1] + dy + "px";
|
|
||||||
};
|
};
|
||||||
|
const eD = () => {
|
||||||
const stopDragging = () => {
|
dragBoundary.removeEventListener("mousemove", sD);
|
||||||
parentElement.removeEventListener("mousemove", startDragging);
|
dragBoundary.removeEventListener("mouseup", eD);
|
||||||
parentElement.removeEventListener("mouseup", stopDragging);
|
dragBoundary.removeEventListener("mouseleave", eD);
|
||||||
parentElement.removeEventListener("mouseleave", stopDragging);
|
|
||||||
|
|
||||||
shadowController.classList.remove("dragging");
|
shadowController.classList.remove("dragging");
|
||||||
video.classList.remove("vcs-dragging");
|
video.classList.remove("vcs-dragging");
|
||||||
};
|
};
|
||||||
|
dragBoundary.addEventListener("mousemove", sD);
|
||||||
parentElement.addEventListener("mouseup", stopDragging);
|
dragBoundary.addEventListener("mouseup", eD);
|
||||||
parentElement.addEventListener("mouseleave", stopDragging);
|
dragBoundary.addEventListener("mouseleave", eD);
|
||||||
parentElement.addEventListener("mousemove", startDragging);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var timer = null;
|
var timer = null;
|
||||||
function showController(controller) {
|
function showController(controller) {
|
||||||
log("Showing controller", 4);
|
/* ... same original ... */
|
||||||
|
if (!controller || typeof controller.classList === "undefined") return;
|
||||||
controller.classList.add("vcs-show");
|
controller.classList.add("vcs-show");
|
||||||
|
|
||||||
if (timer) clearTimeout(timer);
|
if (timer) clearTimeout(timer);
|
||||||
|
|
||||||
timer = setTimeout(function () {
|
timer = setTimeout(function () {
|
||||||
controller.classList.remove("vcs-show");
|
if (controller && controller.classList)
|
||||||
|
controller.classList.remove("vsc-show");
|
||||||
timer = false;
|
timer = false;
|
||||||
log("Hiding controller", 5);
|
|
||||||
}, 2000);
|
}, 2000);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user