HTML5 Audio/Video Keyboard Shortcuts With OSD

Adds keyboard shortcuts for controlling HTML5 media player (audio/video) with OSD support. Seek media to 0%, 5%, 10%, ..., or 95%. Rewind and fast fordward media by 30 seconds, 1 minute, and 5 minutes. Change media speed even beyond YouTube's speed limit. Change audio volume to 20%, 40%, 60%, 80%, or 100%. Change video aspect ratio for TV and letterbox content (for widescreen monitors).

  1. // ==UserScript==
  2. // @name HTML5 Audio/Video Keyboard Shortcuts With OSD
  3. // @namespace https://greasyfork.org/en/users/85671-jcunews
  4. // @version 1.4.21
  5. // @license AGPLv3
  6. // @author jcunews
  7. // @description Adds keyboard shortcuts for controlling HTML5 media player (audio/video) with OSD support. Seek media to 0%, 5%, 10%, ..., or 95%. Rewind and fast fordward media by 30 seconds, 1 minute, and 5 minutes. Change media speed even beyond YouTube's speed limit. Change audio volume to 20%, 40%, 60%, 80%, or 100%. Change video aspect ratio for TV and letterbox content (for widescreen monitors).
  8. // @match *://*/*
  9. // @grant none
  10. // @run-at document-start
  11. // ==/UserScript==
  12.  
  13. /*
  14. Notes:
  15.  
  16. - Some shortcuts won't work on non US keyboards. Non US keyboard users will need to manually edit the keys in the script.
  17. - In YouTube, if the video speed is below 0.25x or above 2x, the YouTube setting display will be capped to 0.1x or 2x.
  18. - Web browser video speeds: Firefox = 0.25 to 5.0; Chrome = 0.1 to 16.0.
  19.  
  20.  
  21. Keyboard Shortcuts:
  22.  
  23. CTRL+, = Rewind media by 1/30th second
  24. CTRL+. = Fast forward media by 1/30th second
  25. CTRL+SHIFT+/ = Next frame (when paused; Firefox only)
  26. SHIFT+LEFT = Rewind media by 30 seconds
  27. SHIFT+RIGHT = Fast forward media by 30 seconds
  28. CTRL+LEFT = Rewind media by 1 minute
  29. CTRL+RIGHT = Fast forward media by 1 minute
  30. CTRL+SHIFT+LEFT = Rewind media by 5 minutes
  31. CTRL+SHIFT+RIGHT = Fast forward media by 5 minutes
  32. CTRL+/ = Fast forward media by 1.5 minutes
  33. 0 to 9 = Seek media to 0%, 10%, 20%,...90%
  34. SHIFT+0 to SHIFT+9 = Seek media to 5%, 15%, 25%,...95%
  35. CTRL+1 to CTRL+5 = Change audio volume to 20%, 40%, 60$, 80%, 100%
  36. CTRL+[ = Decrease media speed by 0.2x (by default)
  37. CTRL+] = Increase media speed by 0.2x (by default)
  38. CTRL+; = Reset media speed
  39. CTRL+' = Change custom media speed
  40. CTRL+\ = Change unit of media speed increment/decrement
  41.  
  42. For Widescreen Video Viewport:
  43. CTRL+6 = Change video aspect ratio for widescreen content. Fix widescreen content shrunk to 4:3 TV format.
  44. CTRL+7 = Change video aspect ratio for letterbox content. Fix 4:3 letterbox content stretched to widescreen format.
  45. CTRL+8 = Change video aspect ratio for TV content. Fix 4:3 TV content stretched to widescreen format.
  46.  
  47. For 4:3 TV Video Viewport:
  48. CTRL+SHIFT+6 = Change video aspect ratio for ultra widescreen content. Fix ultra widescreen content compressed into 4:3 TV format.
  49. CTRL+SHIFT+7 = Zoom 4:3 letterbox content to remove half of top+bottom borders, but also remove left+right content a little.
  50. This can also be used to half-zoom ultra widescreen content on widescreen viewport. i.e. half-zoom of CTRL+6.
  51. CTRL+SHIFT+8 = Change video aspect ratio for widescreen content. Fix widescreen content compressed into 4:3 TV format.
  52.  
  53. For Any Video Viewport:
  54. CTRL+9 = Reset video aspect ratio
  55. ALT+P = Toggle Picture-In-Picture / Video popout (Chrome/ium only. Use Ctrl+Shift+] for Firefox)
  56. ALT+S = Take screenshot of current video frame (in its original size and aspect ratio)
  57. */
  58.  
  59. ((eleOSD, osdTimer) => {
  60.  
  61. //=== CONFIGURATION BEGIN ===
  62.  
  63. //Video speed increment/decrement unit.
  64. var incrementUnit = 0.2;
  65.  
  66. //Duration (in milliseconds) to display On Screen Display (OSD) when changing playback rate. Set to zero or less to disable.
  67. var osdTimeout = 3000;
  68.  
  69. //Image format for video frame screenshot
  70. var imageFormat = "jpeg"; //can be jpeg or png
  71.  
  72. //Keyboard shortcuts.
  73. //key = Key name. String type if single shortcut, or array of string if multiple shortcut (for single function multiple shortcuts).
  74. // Each key name can either be the character which is produced by the key (e.g. `A`, `4`, `*`, etc.),
  75. // or the code name for the key (e.g. `Digit2`, `BracketLeft`, etc.).
  76. // When SHIFT modifier is used with keys which produces a character, key code name should be used if the character is important.
  77. // A list of key code names can be found here: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code/code_values
  78. //caseSensitive = `true` if key name is case-sensitive. If omitted, the default is not case-sensitive.
  79. //modifiers = Any combinations of uppercased "C", "S", and "A", for Ctrl, Shift, and Alt keys. If omitted, the default is "".
  80. //videoOnly = Apply only if a video element exist. If omitted, the default is always apply.
  81. //func = Function to be called. Function arguments: elementObj, pressedKey, matchingKeyIndex
  82. // elementObj : The video/audio element.
  83. // pressedKey : The pressed key. Uppercased if matching keyboard shortcut is not case-sensitive.
  84. // matchingKeyIndex: If multiple keys is specified, the index of the key array. `null` otherwise.
  85. // keyObject : The matching keyboard shortcut object in `keys` array.
  86. var keys = [
  87. { //ctrl+space: seek media to next frame (only when paused. firefox only)
  88. key: " ", modifiers: "C",
  89. func: (ele, key) => ele.seekToNextFrame && ele.seekToNextFrame()
  90. },
  91. { //0 to 9: seek media to 0%,10%,20%,...90%
  92. key: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], modifiers: "",
  93. func: (ele, key, keyIndex) => ele.currentTime = keyIndex / 10 * ele.duration
  94. },
  95. { //shift+0 to shift+9: seek media to 5%,15%,25%,...95%
  96. key: [")", "!", "@", "#", "$", "%", "^", "&", "*", "("], modifiers: "S",
  97. func: (ele, key, keyIndex) => ele.currentTime = (keyIndex + 0.5) / 10 * ele.duration
  98. },
  99. { //ctrl+1 to ctrl+5: set audio volume to 20%,40%,60%,80%,100%
  100. key: ["1", "2", "3", "4", "5"], modifiers: "C",
  101. func: (ele, key, keyIndex) => updAudioVolume(ele, (parseInt(key) * 2) / 10)
  102. },
  103. { //shift+left: rewind media by 30 seconds
  104. key: "ArrowLeft", modifiers: "S",
  105. func: (ele, key) => ele.currentTime -= 30
  106. },
  107. { //ctrl+left: rewind media by 1 minute
  108. key: "ArrowLeft", modifiers: "C",
  109. func: (ele, key) => ele.currentTime -= 60
  110. },
  111. { //ctrl+shift+left: rewind media by 5 minutes
  112. key: "ArrowLeft", modifiers: "CS",
  113. func: (ele, key) => ele.currentTime -= 300
  114. },
  115. { //ctrl+,: rewind media by 1/30 second
  116. key: ",", modifiers: "C",
  117. func: (ele, key) => ele.currentTime -= 1/30
  118. },
  119. { //shift+right: fast forward media by 30 seconds
  120. key: "ArrowRight", modifiers: "S",
  121. func: (ele, key) => ele.currentTime += 30
  122. },
  123. { //ctrl+right: fast forward media by 1 minute
  124. key: "ArrowRight", modifiers: "C",
  125. func: (ele, key) => ele.currentTime += 60
  126. },
  127. { //ctrl+shift+right: fast forward media by 5 minutes
  128. key: "ArrowRight", modifiers: "CS",
  129. func: (ele, key) => ele.currentTime += 300
  130. },
  131. { //ctrl+.: fast forward media by 1/30th second
  132. key: ".", modifiers: "C",
  133. func: (ele, key) => ele.currentTime += 1/30
  134. },
  135. { //ctrl+shift+/: next frame (when paused; firefox only)
  136. key: "?", modifiers: "CS",
  137. func: (ele, key) => ele.seekToNextFrame && ele.seekToNextFrame()
  138. },
  139. { //ctrl+/: fast forward media by 1.5 minutes
  140. key: "/", modifiers: "C",
  141. func: (ele, key) => ele.currentTime += 87
  142. },
  143. { //ctrl+[: decrease media speed
  144. key: "[", modifiers: "C",
  145. func: (ele, key) => {
  146. key = ele.playbackRate - incrementUnit;
  147. if (key < 0.1) {
  148. key = 0.1;
  149. } else if ((key < 1) && (ele.playbackRate > 1)) key = 1;
  150. updVideoSpeed(ele, key);
  151. }
  152. },
  153. { //ctrl+]: increase media speed
  154. key: "]", modifiers: "C",
  155. func: (ele, key) => {
  156. key = ele.playbackRate + incrementUnit;
  157. if (key > 16) {
  158. key = 16;
  159. } else if ((key > 1) && (ele.playbackRate < 1)) key = 1;
  160. updVideoSpeed(ele, key);
  161. }
  162. },
  163. { //ctrl+;: reset media speed to 1x
  164. key: ";", modifiers: "C",
  165. func: (ele, key) => updVideoSpeed(ele, 1)
  166. },
  167. { //ctrl+': use custom media speed
  168. key: "'", modifiers: "C",
  169. func: (ele, key) => {
  170. if ((key = prompt("Enter media speed from 0.1 to 16 (inclusive).\ne.g.: 1 = Normal, 0.5 = Half, 2 = Double, 3 = Triple, etc.", ele.playbackRate)) === null) return;
  171. if (isNaN(key = parseFloat(key.trim()))) {
  172. alert("Input must be a number.");
  173. return;
  174. }
  175. updVideoSpeed(ele, (key = parseFloat(key.toFixed(1))) < 0.1 ? 0.1 : (key > 16 ? 16 : key));
  176. }
  177. },
  178. { //ctrl+\: change unit of media speed increment/decrement
  179. key: "\\", modifiers: "C",
  180. func: (ele, key) => {
  181. if ((key = prompt("Enter unit of media speed increment/decrement from 0.1 to 4 (inclusive).", incrementUnit)) === null) return;
  182. if (!isNaN(key = parseFloat(key.trim()))) {
  183. incrementUnit = (key = parseFloat(key.toFixed(1))) < 0.1 ? 0.1 : (key > 4 ? 4 : key);
  184. } else alert("Input must be a number.");
  185. }
  186. },
  187. { //ctrl+6: Widescreen aspect ratio
  188. key: "6", modifiers: "C", videoOnly: true,
  189. func: (ele, key) => updVideoAspect("scaleX(1.3333)", "Widescreen")
  190. },
  191. { //ctrl+7: Letterbox aspect ratio
  192. key: "7", modifiers: "C", videoOnly: true,
  193. func: (ele, key) => updVideoAspect("scaleY(1.3333)", "Letterbox")
  194. },
  195. { //ctrl+8: TV aspect ratio
  196. key: "8", modifiers: "C", videoOnly: true,
  197. func: (ele, key) => updVideoAspect("scaleX(0.75)", "TV")
  198. },
  199. { //ctrl+shift+6: Ultra widescreen aspect ratio
  200. key: "Digit6", modifiers: "CS", videoOnly: true,
  201. func: (ele, key) => updVideoAspect("scaleY(0.7168)", "Ultra Widescreen")
  202. },
  203. { //ctrl+shift+7: Half-zoom letterbox
  204. key: "Digit7", modifiers: "CS", videoOnly: true,
  205. func: (ele, key) => updVideoAspect("scale(1.1666)", "Letterbox Half-Zoom")
  206. },
  207. { //ctrl+shift+8: Widescreen on TV
  208. key: "Digit8", modifiers: "CS", videoOnly: true,
  209. func: (ele, key) => updVideoAspect("scaleY(0.5625)", "Widescreen On TV")
  210. },
  211. { //ctrl+9: reset video aspect ratio
  212. key: "9", modifiers: "C", videoOnly: true,
  213. func: (ele, key) => updVideoAspect("", "Reset")
  214. },
  215. { //alt+p: toggle Picture-In-Picture / Video popout (Chrome/ium only)
  216. key: "P", modifiers: "A", videoOnly: true,
  217. func: (ele, key) => document.pictureInPictureEnabled && (document.pictureInPictureElement ? document.exitPictureInPicture() : ele.requestPictureInPicture())
  218. },
  219. { //alt+s: take screenshot of current video frame
  220. key: "S", modifiers: "A", videoOnly: true,
  221. func: (ele, key, cv, a) => {
  222. cv = document.createElement("CANVAS");
  223. if (cv.width = ele.videoWidth) {
  224. cv.height = ele.videoHeight;
  225. cv.getContext("2d").drawImage(ele, 0, 0);
  226. a = document.createElement("A");
  227. a.href = cv.toDataURL("image/" + imageFormat);
  228. a.download = `video_frame_${ele.currentTime}.${imageFormat === "jpeg" ? "jpg" : imageFormat}`;
  229. a.style.display = "none";
  230. document.body.appendChild(a).click();
  231. return a.remove()
  232. }
  233. }
  234. }
  235. ];
  236. keys.forEach((k, s, m) => {
  237. if ((k.modifiers === undefined) || !k.modifiers.toUpperCase) k.modifiers = "";
  238. s = k.modifiers.toUpperCase();
  239. k.modifiers = {ctrl: s.includes("C"), shift: s.includes("S"), alt: s.includes("A")}
  240. });
  241.  
  242. //=== CONFIGURATION END ===
  243.  
  244. var to = {createHTML: s => s}, tp = window.trustedTypes?.createPolicy ? trustedTypes.createPolicy("", to) : to, html = s => tp.createHTML(s);
  245.  
  246. function showOSD(s) {
  247. if (osdTimeout < 0) return;
  248. if (eleOSD) {
  249. eleOSD.textContent = s;
  250. } else {
  251. eleOSD = document.createElement("DIV");
  252. eleOSD.style.cssText = "position:fixed;z-index:999999999;right:.5rem;bottom:.5rem;margin:0;padding:.2rem .5rem .1rem .5rem;width:auto;height:auto;font:normal 16pt/normal sans-serif;background:#444;color:#fff";
  253. eleOSD.textContent = s;
  254. document.body.appendChild(eleOSD);
  255. }
  256. clearTimeout(osdTimer);
  257. osdTimer = setTimeout(() => {
  258. eleOSD.remove();
  259. eleOSD = null;
  260. }, osdTimeout);
  261. }
  262.  
  263. function stopEvent(ev) {
  264. ev.preventDefault();
  265. ev.stopPropagation();
  266. ev.stopImmediatePropagation();
  267. }
  268.  
  269. function updVideoSpeed(ele, spd, e) {
  270. // if ((location.hostname === "www.youtube.com") && (e = ele.parentNode.parentNode).setPlaybackRate && (spd >= 0.25) && (spd <= 2)) {
  271. // e.setPlaybackRate(spd = parseFloat(spd.toFixed(1)));
  272. // } else ele.playbackRate = spd = parseFloat(spd.toFixed(1));
  273. ele.playbackRate = spd = parseFloat(spd.toFixed(1));
  274. showOSD("Speed " + spd + "x");
  275. }
  276.  
  277. function updVideoAspect(asp, label, s) {
  278. if (!(s = document.getElementById("vidAspOvr"))) document.body.appendChild(s = document.createElement("STYLE")).id = "vidAspOvr";
  279. s.innerHTML = html(asp ? `video{transform:${asp}!important}` : "");
  280. showOSD("Ratio: " + label);
  281. }
  282.  
  283. function updAudioVolume(ele, vol, e) {
  284. if ((location.hostname === "www.youtube.com") && (e = ele.parentNode.parentNode).setVolume) {
  285. e.setVolume(vol * 100);
  286. } else ele.volume = vol;
  287. showOSD("Audio " + (vol * 100) + "%");
  288. }
  289.  
  290. function isVisible(ele) {
  291. while (ele && ele.tagName) {
  292. if (getComputedStyle(ele).display === "none") return false;
  293. ele = ele.parentNode
  294. }
  295. return true
  296. }
  297.  
  298. incrementUnit = parseFloat((incrementUnit < 0.1 ? 0.1 : (incrementUnit > 1 ? 1 : incrementUnit)).toFixed(1));
  299. addEventListener("keydown", function(ev, ele, evkey, evcode, kkey) {
  300. if ((!(ele = document.activeElement) || !((ele.contentEditable === "true") || ["BUTTON", "INPUT", "SELECT", "TEXTAREA"].includes(ele.tagName))) && (ele = document.querySelector("video,audio"))) {
  301. keys.some((k, a, i) => {
  302. a = !!k.key.sort;
  303. evkey = k.caseSensitive ? ev.key : ev.key.toUpperCase();
  304. evcode = k.caseSensitive ? ev.code : ev.code.toUpperCase();
  305. kkey = k.caseSensitive ? k.key : (a ? k.key.map(s => s.toUpperCase()) : k.key.toUpperCase());
  306. if (
  307. ((!a && ((kkey === evcode) || (kkey === evkey))) || (a && (((i = kkey.indexOf(evcode)) >= 0) || ((i = kkey.indexOf(evkey)) >= 0)))) &&
  308. (k.modifiers.ctrl === ev.ctrlKey) && (k.modifiers.shift === ev.shiftKey) && (k.modifiers.alt === ev.altKey) &&
  309. (!k.videoOnly || (ele.tagName === "VIDEO")) && (isVisible(ele) || (ele.tagName === "AUDIO"))
  310. ) {
  311. stopEvent(ev);
  312. k.func?.(ele, evkey, a ? i : null, k);
  313. return true;
  314. }
  315. });
  316. }
  317. }, true);
  318.  
  319. })();