Greasy Fork is available in English.

YouTube Player Controls

Fit video to window, set HD definition, repeat button, hide annotations, auto skip ads, disable autoplay, pause at start/end.

2017-07-06 일자. 최신 버전을 확인하세요.

질문, 리뷰하거나, 이 스크립트를 신고하세요.
// ==UserScript==
// @name         YouTube Player Controls
// @namespace    YouTubePlayerControls
// @version      1.0.9
// @description  Fit video to window, set HD definition, repeat button, hide annotations, auto skip ads, disable autoplay, pause at start/end.
// @author       Costas
// @match        http://www.youtube.com/*
// @match        https://www.youtube.com/*
// @grant 		 GM_setValue
// @grant 		 GM_getValue
// @noframes
// ==/UserScript==

//==================================================================
//Userscript specific functions

var doc = document;
var win = window;
//new YT format
var NEWYT = doc.body.id != 'body';
NEWYT ? doc.body.setAttribute("newyt", "") : doc.body.setAttribute("oldyt", "");

if (win.frameElement) throw new Error("Stopped JavaScript.");

function set_pref(preference, new_value) {
    GM_setValue(preference, new_value);
}

function get_pref(preference) {
    return GM_getValue(preference);
}

function init_pref(preference, new_value) {
    var value = get_pref(preference);
    if (value == null) {
        set_pref(preference, new_value);
        value = new_value;
    }
    return value;
}

//==================================================================
//==================================================================


//==================================================================
// Styles

var style_annotations = "\
.html5-video-player .annotation,\
.html5-video-player .video-annotations,\
.html5-video-player .ytp-cards-button,\
.html5-video-player .ytp-cards-teaser,\
.html5-video-player .iv-drawer,\
.html5-video-player .ima-container {display:none !important;}\
";

var style_autoplay = "\
.autoplay-bar,\
.watch-sidebar-separation-line {display:none !important;}\
body[newyt] ytd-compact-autoplay-renderer {display:none !important;}\
"

var style_basic = "\
/* messages */\
.ytpc_message {font:12px/15px arial,sans-serif; text-align:left; white-space:pre; float:left; clear:both; color:black; background:beige; margin:10px 0px 0px 300px; z-index:2147483647;}\
/* options */\
#ytpc_options_popup {position:absolute; top:0px; right:0px; width:230px; box-shadow:0px 0px 5px 5px lightgray; font:11px/11px arial,sans-serif; color:black; background:linear-gradient(#ffffff,#f8f8f8); padding:5px; border-radius:5px; /*z-index:2147483647; z-index:2147483646; */ z-index:10; }\
#ytpc_options_popup input {margin:5px 2px 0px 5px !important;}\
.ytpc_options_group *[hide] {color:steelblue !important;}\
.ytpc_options_group[hide] *[hide] {visibility:hidden;}\
.ytpc_options_text {font-weight:bold; margin-left:5px; margin-top:7px; color:black;}\
.ytpc_options_close {font:14px/14px arial,sans-serif; color:#ff8888; position:absolute; top:5px; right:5px; cursor:pointer;}\
.ytpc_options_close:hover {font-weight:bold; color:red;}\
.ytpc_options_title {font:bold 13px/13px arial,sans-serif; padding:5px !important; color:black;}\
/* buttons */\
#gridtube_title_container {position:absolute; top:5px; right:5px;}\
body[newyt] ytd-video-primary-info-renderer {position:relative !important;}\
#ytpc_ytcontrol_container {position:relative; float:right;}\
#ytpc_ytcontrol_button {position:relative; float:right; width:24px; height:24px; margin:-5px -3px 0px 6px; cursor:pointer; opacity:0.8; background-size:100%; background-image:url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAACXBIWXMAAAWJAAAFiQFtaJ36AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAABf5JREFUeNrsV1tsFFUY/mdmL7O7sxdaqFw0O3gJhoRYI/HJ0H0xMb6wEh/wASyJihiUbUgRReyCqBRKsgaKcjG0AaIi2OXBGn3QJWqMJsQaCRps0gWDVbt0d3bnfvWc2Utn221LwUdOcjKzZ8+e//+///++/yzAnXFnzHHseu/DqPNz76n0wNtHPu5KHjrZdivnETe78diZwbamcLAvX+Qjo/+MsTs3r+cOnhxoW77s/szlkb/BMA1QZKWgaWpGkqSMLIl9B7a/yM12rmu2Dd1HP4ouu4/tW7hgfowTFRjjVaD9gQQG454li2KKjg7x0kBZFlAeOqJpWtwkyLiqqgW0p/+2HOgf+LIrevfiJEF5YHh0HDTdBLeHBq8vkOw+kc6oBsQLnICiN8G0AJAPACRlP9Fa5rZSkEwdD9/LslmaCUVEZMlEFkyrMtG7YRhgEYRtrLpuoWmg70pcPrt749NL8Tk7D51ebVlmbM/L6zrmXAN7j37SFWpqTnppX8WBCWO2wZpTULcmCKVMYfxG4pHlD6QWtTTHfrw0DKhu4odff/78nIuwp//8SDDcxGJ0ncYR6nbE5qRpoXXd0MFFWLBwfhNcz3EgKSqUCuPZg53PLp3VgeOfDg5IqsEKspoxUR5R9O10IBi3gKg3aE7APhkBJypWZa+iSMAXxpNHdrywa0YHBr+9aI0VZRBkDR2AwiFIwMadebYPr3OgMSpWnRMm8MV8QeAKbP+eLTV6knUi03tqdZBhQNRMsEjSrmizXNF2cdWmYSKYDUBUQ1MDXTfK69bEPrtQbXaUncHvQBARi4DktDRcvLAlJqp6jVb1kE5AryoKCHwpaxhaHz6XpKh2jy/Aki6PHW21XmrvyFlZEkAWhbRh6KlpHUBKF8vzUjmCirHJOdY1DYpcPn2gY91TTvA27+sbmN9yV1zG6E1yQhL5rMSX2k90bbowOeW1FGzd+0GU9rhbc/lSHeR6BcrqmiSJKBoxMfkgSRISzYy3nhFVp3U9i6S6MKMOdLxzOOz1+ZMe2hej3N5WN5JXoqJqTvj5YgF6XlnbkL6Hzn1tZXN8GQGsjFB+YtHSVBkUSSwosphGz8S5A69x0+pAR/exqD8USdGBUBxD6UyDJPCY0+yRNzZedf5mQ7I3uurR1uyv13JTHCg/y+kTUABSiYuc7XmVm8KC6mCYQCzMBFprslutaDRduBf4mfRzu98PV/e3d/WGV654MJ0XtSnC5NQMwMwiiKGq8SlF+NJbhx96bOWK1LxIJHblr3EEt1gXvR0Z0n+Pn2lFNB3qSJ1OL1nQBIsWzItLOrBXsqMNIodKUaIgdMQwQ89My4KW5ki8KOux4T+ug2Y4WOA8COcEO0H7WZKAhGRR8NPwqP37xtBD7Qx0VwBVltPTOjCay6c41Ur4mQgWDIdRfMBkAzgtALmi0DBau3gxc1BfKOuJiXUAznZvraMi5fxw8ZtB5eG2J2XS5X6iyoCqMbNBUU1nGD8xerJYSktCaa0qS7+jSWuqMvTb9199Mms33NR9YgSxgCVQH8AU0nUNKJcb0ZKsg3SqAw5HsGbwxaxYzLd+tn/btFezhixQZKldKHIglDgo5nNp7sa/LOMhh5BQ1YnMjBPD6/GyaCZu6Ua0fkdqC6r4oZN7ttg56//iu5FsTmDHOKEObpxjAyGE+wAQRB0SBio6nhsHuVSMfH7wTe6Wb8Vrt/dE1zy+Knvh8jWo3gvKeTaxqGQUUWing+EhN+2PQKUH4LSpolBQJD6V3te5a04paOBnfHS8gORURUaNmrjouB0rSubMux1XZZFPqbKI2rOCcw8il++ThSI7k/GbupbjgaLp++HnS1nK5Y2TbncMMYQlKAo01JY1RbKFBaGQQk2nHaUhi1KSOL9/2y//6x8T51jTuS9KulwxQzdiA/s7N9zOPy3i6rU/n+F5AQQkEqIggihJqN3KIMtoKnLl1qMiFcM3H92+/ZiVvmDZsohrj0AyTwJFkeByucDtdoPH7QGv1ws0TQPto8Hv80Eg4AcmwAATZCAUDEIoFIL/BBgA3x0ZgLeVz5oAAAAASUVORK5CYII='); }\
#ytpc_ytcontrol_button:hover {opacity:1;}\
#ytpc_ytcontrol_loop {position:relative; float:right; height:18px; margin-left:10px; border-radius:5px; cursor:pointer; opacity:0.7; background:white;}\
#ytpc_ytcontrol_loop[loop] {background:lightblue !important;}\
#ytpc_ytcontrol_loop:hover {box-shadow:0px 0px 1px 1px gray; opacity:0.9;}\
#ytpc_ytcontrol_loop img {height:22px; margin-top:-2px; padding:0px 3px;}\
/* masthead */\
#masthead-positioner[ytpc_hide] {visibility:hidden !important;}\
#masthead-positioner-height-offset[ytpc_hide] {display:none !important;}\
body[newyt] #content[ytpc_cinema] #masthead-container[ytpc_hide] {display:none !important;}\
body[newyt] #content[ytpc_cinema][ytpc_top] #page-manager {margin-top:0px !important;}\
";

//loop icon
var loopsrc = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQFJREFUeNrsluENgjAQhYEFcAPcoG6AG3QEHM0NGAG\
               coLqBG+AGeCZtcrmI3J2UGsNL3g8S6Pt6bY9m2aZNy6v0TqYa7LgQRSSIA7jnQBQRKxEgzKeXckY5T+C9IHjnw4Me4CP4Jt1ILXhcyMNcJai6BcODG254EzGcdTIc+fj1bIXHEJfeonDHGYDSV4o+QNe9RBMTA2ga0\
               VT4KgAV2fFOOh5d/yCjWA7VhHB4icIHX95VAN6FjwqASgOAwy0KlwLYiSPNasOxG1KSbthJ1s6Q0n/rdqoN5zMQvf+9Bl3975WrO/gMvmgvFYZspDpLINxKkwBgiGQAP3Hd3vSfegowAOVS0NA3eDs0AAAAAElFTkSuQmCC";


//==============================================================
//basic

function newNode(kind, id, classname, refnode, position) {

    var node = doc.createElement(kind);

    if (node == null) return null;

    if (id != null) node.id = id;

    if (classname != null) node.className = classname;

    if (refnode != null) {
        switch (position) {
            //insert after refnode
            case 'after':
                if (refnode.nextSibling != null)
                    refnode.parentNode.insertBefore(node, refnode.nextSibling);
                else
                    refnode.parentNode.appendChild(node);
                break;

                //insert before refnode
            case 'before':
                refnode.parentNode.insertBefore(node, refnode);
                break;

                //insert as first child of refnode                  
            case 'first':
                var child = refnode.childNodes[0];
                if (child != null)
                    refnode.insertBefore(node, child);
                else
                    refnode.appendChild(node);
                break;

                //insert as last child of refnode
            case 'last':
            default:
                refnode.appendChild(node);
                break;
        }
    }

    return node;
}


function message(str) {
    var node = newNode("div", null, "ytpc_message", doc.body);
    node.textContent = str + "\n";
}


function insertStyle(str, id) {
    var styleNode = null;

    if (id != null) {
        styleNode = doc.getElementById(id);
    }

    if (styleNode == null) {
        styleNode = newNode("style", id, null, doc.head);
        styleNode.setAttribute("type", "text/css");
    }

    if (styleNode.textContent != str)
        styleNode.textContent = str;
}


function injectScript(str, src) {
    var script = doc.createElement("script");
    if (str) script.textContent = str;
    if (src) script.src = src;
    doc.body.appendChild(script);
    if (!src) doc.body.removeChild(script);
}


function simulClick(el) {
    var clickEvent = doc.createEvent('MouseEvents');
    clickEvent.initEvent('click', true, true);
    el.dispatchEvent(clickEvent);
}


function xpath(outer_dom, inner_dom, query) {
    //XPathResult.ORDERED_NODE_SNAPSHOT_TYPE = 7
    return outer_dom.evaluate(query, inner_dom, null, 7, null);
}


function docsearch(query) {
    return xpath(doc, doc, query);
}


function innersearch(inner, query) {
    return xpath(doc, inner, query);
}



//==================================================================
//YT Player

function ytplayer_script() {
    injectScript("function f() {\
                    var a = document.getElementById('c4-player') || document.getElementById('movie_player');\
                    var b = document.getElementById('ytpc_ytplayer_state');\
                    if (a != null && b != null)\
                      if (b.getAttribute('loop') == 'true') {\
                        if (window.location.href.indexOf('list=') == -1) {\
                          if (a.getPlayerState() == 0) {\
                            a.playVideo();\
                          }\
                        }\
                        else {\
                          var d = a.getDuration();\
                          if ((d - a.getCurrentTime() <= 1) && d > 0) {\
                            a.playVideoAt(a.getPlaylistIndex());\
                          }\
                        }\
                      }\
                      else {\
                         if (b.getAttribute('pause_end') == 'true' && b.getAttribute('pause_end_mark') != 'true') {\
                           var d = a.getDuration();\
                           if ((d - a.getCurrentTime() <= 1) && d > 0) {\
                             a.pauseVideo();\
                             b.setAttribute('pause_end_mark', 'true');\
                           }\
                         }\
                      }\
                  }\
                  window.setInterval(f, 1000);\
                  ");
}


function ytplayer_state(attr, value) {
    var node = doc.getElementById('ytpc_ytplayer_state');
    if (!node) {
        node = newNode("div", 'ytpc_ytplayer_state', null, doc.body);
        node.style.display = "none";
    }

    if (!node) return;

    if (attr && value) node.setAttribute(attr, value);
    else if (attr) return node.getAttribute(attr);
}


function set_loop() { ytplayer_state('loop', 'true'); }
function set_noloop() { ytplayer_state('loop', 'false'); }
function set_pause_end() { ytplayer_state('pause_end', 'true'); }
function set_nopause_end() { ytplayer_state('pause_end', 'false'); }
function success_pause() { return ytplayer_state('pause_status') == 'success'; }
function success_quality() { return ytplayer_state('quality_status') == 'success'; }


function adjust_pause_end() {
    var islive = docsearch("//*[@id='watch7-content']/link[(@itemprop='thumbnailUrl') and contains(@href,'_live.jpg')]").snapshotLength > 0 
                 || docsearch("//yt-view-count-renderer/*[contains(.,'watching now')]").snapshotLength > 0; //OLD||NEW
    //message("Is live: " + islive);
    //alert("Is live: " + islive);
    get_pref("ytPauseEnd") && !islive ? set_pause_end() : set_nopause_end();
}


function flip_loop_state() {
    var inloop = !get_pref("ytLoop");

    set_pref("ytLoop", inloop);
    inloop ? set_loop() : set_noloop();

    var node = doc.getElementById('ytpc_ytcontrol_loop');
    if (!node) return;

    if (inloop) {
        node.setAttribute("loop", "true");
        node.title = "Repeat is ON";
    }
    else
        if (node.getAttribute("loop")) {
            node.removeAttribute("loop");
            node.title = "Repeat is OFF";
        }
}


function ytplayer_pause() {
    ytplayer_state('pause_status', 'fail');

    injectScript("var a = document.getElementById('c4-player') || document.getElementById('movie_player');\
                   if (a != null)\
                      if (a.pauseVideo != null){\
                          a.pauseVideo();\
                          var n = document.getElementById('ytpc_ytplayer_state');\
                          if (n) n.setAttribute('pause_status', 'success');\
                      }\
                  ");
}


function ytplayer_quality(def) {
    ytplayer_state('quality_status', 'fail');

    injectScript("var a = document.getElementById('c4-player') || document.getElementById('movie_player');\
                   if (a != null)\
                      if (a.setPlaybackQuality != null){\
                          a.setPlaybackQuality('" + def + "');\
                          var n = document.getElementById('ytpc_ytplayer_state');\
                          if (n) n.setAttribute('quality_status', 'success');\
                      }\
                  ");
}


//==============================================================
//preferences

init_pref("ytPause", false);
init_pref("ytPauseEnd", false);
init_pref("ytDef", "default");
init_pref("ytLoop", false);
init_pref("ytCine", true);
init_pref("ytHide", true);
init_pref("ytAnnot", true);
init_pref("ytAds", true);
init_pref("ytAutoPlay", false);

function close_ytplayer_options() {
    var popup = doc.getElementById("ytpc_options_popup");
    if (popup) popup.parentNode.removeChild(popup);
}


function new_checkbox(prefname, str, node_kind, parent, value, func, hide1, hide2) {
    var div = newNode(node_kind, null, "ytpc_generic", parent);
    var input = newNode("input", null, "ytpc_generic", div);
    input.type = "checkbox";
    if (!value) {
        input.checked = get_pref(prefname);
        if (hide1 && !input.checked) parent.setAttribute("hide", "true");
        input.onclick = function (e) {
            var val = get_pref(prefname);
            set_pref(prefname, !val);
            e.target.checked = !val;
            if (hide1)
                if (!val)
                    parent.removeAttribute("hide");
                else
                    parent.setAttribute("hide", "true");
            if (func) func();
        };
    }
    else {
        input.value = value;
        input.checked = (get_pref(prefname) == input.value);
        input.onclick = function (e) {
            var val = get_pref(prefname);
            set_pref(prefname, e.target.value);
            e.target.checked = true;
            var other = innersearch(parent.parentNode, ".//input[@value='" + val + "']").snapshotItem(0);
            if (other) other.checked = false;
            if (func) func();
        };
    }
    var span = newNode("span", null, "ytpc_generic", div);
    span.textContent = str;
    if (hide2) div.setAttribute("hide", "true");
}


function ytplayer_options() {
    var popup = doc.getElementById("ytpc_options_popup");
    if (popup) return;

    var parent = doc.getElementById("ytpc_ytcontrol_container");
    if (!parent) return;

    popup = newNode("span", "ytpc_options_popup", null, parent.parentNode);
    parent.parentNode.parentNode.style.overflow = "visible";

    var title_node = newNode("div", null, "ytpc_options_title", popup);
    title_node.textContent = "YouTube Player Controls";

    var closemark = newNode("span", null, "ytpc_options_close", popup);
    closemark.textContent = "\u2716";
    closemark.title = "close";
    closemark.onclick = close_ytplayer_options;

    var group0 = newNode("div", null, "ytpc_options_group", popup);
    new_checkbox("ytCine", "Fit to Window", "span", group0, null, function () { resetTheaterMode(); win.location.reload(); }, true, false);
    new_checkbox("ytHide", "Auto Hide Search", "span", group0, null, function () { cinema(0); }, false, true);
    new_checkbox("ytAnnot", "Hide Annotations", "div", popup, null, annotation);
    new_checkbox("ytAds", "Auto Skip Ads", "div", popup);
    new_checkbox("ytAutoPlay", "Disable Autoplay", "div", popup, null, function () { reset_nochanges(); autoplay(20); });
    new_checkbox("ytPause", "Pause at Start", "div", popup);
    new_checkbox("ytPauseEnd", "Pause at End (if no Repeat)", "div", popup, null, adjust_pause_end);
    var div = newNode("div", null, "ytpc_options_text", popup);
    //default, small, medium, large, hd720, hd1080, hd1440, highres;
    div.textContent = "Definition";
    var group1 = newNode("div", null, "ytpc_options_group", popup);
    var group2 = newNode("div", null, "ytpc_options_group", popup);
    new_checkbox("ytDef", "Default", "span", group1, "default");
    new_checkbox("ytDef", "LQ 240", "span", group1, "small");
    new_checkbox("ytDef", "MQ 360", "span", group1, "medium");
    new_checkbox("ytDef", "HQ 480", "span", group1, "large");
    new_checkbox("ytDef", "HD 720", "span", group2, "hd720");
    new_checkbox("ytDef", "HD 1080", "span", group2, "hd1080");
    new_checkbox("ytDef", "HD 1440", "span", group2, "hd1440");
    new_checkbox("ytDef", "MAX", "span", group2, "highres");
}


function build_yt_control() {
    if (doc.getElementById("ytpc_ytcontrol_container")) return;

    var parent = doc.getElementById("gridtube_title_container");
    if (!parent) {
        var pp = doc.getElementById("watch-header") || docsearch("//ytd-video-primary-info-renderer").snapshotItem(0); //OLD||NEW

        if (!pp) { set_noloop(); set_nopause_end(); return; }
        parent = newNode("span", "gridtube_title_container", null, pp, 'first');
    }
    if (!parent) { set_noloop(); set_nopause_end(); return; }

    var node = newNode("span", "ytpc_ytcontrol_container", null, parent);
    if (!node) { set_noloop(); set_nopause_end(); return; }

    //control button
    var control = newNode("span", "ytpc_ytcontrol_button", null, node);
    //control.textContent = "Ctrl";
    control.title = "YouTube Player Controls";
    control.onclick = ytplayer_options;

    //loop button
    var loop = newNode("span", "ytpc_ytcontrol_loop", null, node);
    loop.onclick = flip_loop_state;
    var img = newNode("img", null, null, loop);
    img.src = loopsrc;

    //initialize loop and pause_end
    adjust_pause_end();

    if (get_pref("ytLoop")) {
        loop.setAttribute("loop", "true");
        loop.title = "Repeat is ON";
        set_loop();
    }
    else {
        set_noloop();
        loop.title = "Repeat is OFF";
    }
}


//==================================================================
//Theater mode

function setTheaterMode() {
    var thnode = docsearch("//*[@class='ytp-chrome-controls']//*[@title='Theater mode']").snapshotItem(0);
    if (thnode) simulClick(thnode);
}

function resetTheaterMode() {
    var thnode = docsearch("//*[@class='ytp-chrome-controls']//*[@title='Default view']").snapshotItem(0);
    if (thnode) simulClick(thnode);
}

function showmast() {
    var mast = doc.getElementById("masthead-positioner") || doc.getElementById("masthead-container");//OLD||NEW
    if (mast) { mast.removeAttribute("ytpc_hide"); }
}

function hidemast() {
    var mast = doc.getElementById("masthead-positioner") || doc.getElementById("masthead-container");//OLD||NEW
    if (mast) { mast.setAttribute("ytpc_hide", ""); }
}

function showmastoffset() {
    var mastoffset = doc.getElementById("masthead-positioner-height-offset") || doc.getElementById("masthead-container");//OLD||NEW
    if (mastoffset) { mastoffset.removeAttribute("ytpc_hide"); mastoffset.parentNode.removeAttribute("ytpc_top"); }
}

function hidemastoffset() {
    var mastoffset = doc.getElementById("masthead-positioner-height-offset") || doc.getElementById("masthead-container");//OLD||NEW
    if (mastoffset) { mastoffset.setAttribute("ytpc_hide", ""); mastoffset.parentNode.setAttribute("ytpc_top", ""); }
}

var mast_height = 0;

function get_mast_height() {
    var mastoffset = doc.getElementById("masthead-positioner-height-offset") || doc.getElementById("masthead-container");
    if (mastoffset)
        if (mastoffset.offsetHeight > 0)
            mast_height = mastoffset.clientHeight;
}


function cinema(start_count) {

    get_mast_height();

    //not video page
    if (win.location.href.indexOf("watch?") == -1) {
        showmast();
        showmastoffset();
        insertStyle("", "ytpc_style_cinemode");
        return;
    }

    //video page
    if (!get_pref("ytCine")) return;

    var page = doc.getElementById("page") || docsearch("//ytd-page-manager/ytd-watch").snapshotItem(0); //OLD||NEW
    if (!page) return;

    setTheaterMode();

    if (NEWYT) {
        if (page.hasAttribute("theater"))
            page.parentNode.parentNode.setAttribute("ytpc_cinema", "");
        else 
            page.parentNode.parentNode.removeAttribute("ytpc_cinema");
    }
    else
        if (!page.classList.contains("watch-stage-mode")) {
            page.classList.remove("watch-non-stage-mode");
            page.classList.add("watch-wide");
            page.classList.add("watch-stage-mode");
        }

    var hide = get_pref("ytHide");

    var H = doc.body.clientHeight || doc.documentElement.clientHeight;
    var W = doc.body.clientWidth || doc.documentElement.clientWidth;

    //var height1 = player.offsetTop; //offset from top (equal to search bar height)
    var height = H - (hide ? 0 : mast_height);
    var width = (height * 16) / 9;
    if (width > W) {
        width = W;
        height = (width * 9) / 16;
    }

    if (hide) {
        if (H >= height + mast_height && hide) {
            showmast();
            showmastoffset();
        }
        else {
            hidemastoffset();
            if (doc.body.scrollTop || doc.documentElement.scrollTop)
                showmast();
            else
                hidemast();
        }
    }
    else {
        showmast();
        showmastoffset();
    }

    //resized or first adjustment
    if (start_count > 3) return;

    var left = Math.round((W - width) / 2);
    height = Math.round(height);
    width = Math.round(width);

    if (NEWYT)
        insertStyle("\
            ytd-watch[theater] #player {height: " + height + "px !important; max-height:" + height + "px !important; min-height:" + height + "px !important;}\
            ytd-watch[theater] .html5-main-video {width: " + width + "px !important; height: " + height + "px !important; left: " + left + "px !important; margin-left:0px !important;}\
            ytd-watch[theater] .player-height {height: " + height + "px !important;}\
            ytd-watch[theater] .player-width {width: " + width + "px !important; left: " + left + "px !important; margin-left:0px !important;}\
            ",
            "ytpc_style_cinemode");
    else
        insertStyle("\
            .watch-stage-mode #placeholder-player {overflow:hidden !important;}\
            .watch-stage-mode #theater-background {z-index:1 !important;}\
            .watch-stage-mode .player-height {height: " + height + "px !important;}\
            .watch-stage-mode .player-width {width: " + width + "px !important; left: " + left + "px !important; margin-left:0px !important;}\
            .watch-stage-mode .html5-video-content {width: " + width + "px !important; height: " + height + "px !important;}\
            .watch-stage-mode .html5-main-video {width: " + width + "px !important; height: " + height + "px !important; left:0px !important; top:0px !important;}\
            .watch-stage-mode .webgl canvas {width: " + width + "px !important; height: " + height + "px !important;}\
            .watch-stage-mode #player-playlist .watch-playlist {top: " + (height + 10).toString() + "px !important; transform:translateY(0px) !important; height:auto !important;}\
            ",
            "ytpc_style_cinemode");
}

//==================================================================
// autoplay

function autoplay(start_count) {
    var anode = docsearch("//*[@class='autoplay-bar']").snapshotItem(0) || docsearch("//*[@id='items']/ytd-compact-autoplay-renderer").snapshotItem(0);//OLD||NEW
    var cnode = docsearch("//*[@for='autoplay-checkbox']//*[@class='checked']").snapshotItem(0) || docsearch("//paper-toggle-button").snapshotItem(0);//OLD||NEW
    //if (anode) insertStyle(style_autoplay, "ytpc_style_autoplay");
    if (!anode || !cnode) return;

    if (get_pref("ytAutoPlay")) {
        if (!anode.getAttribute("ytpc_disable_autoplay"))
            if ((!NEWYT && cnode.offsetWidth != 0) || (NEWYT && cnode.getAttribute('aria-pressed') == "true")) {
                if (start_count >= 5) { //give delay for first time
                    var abutton = docsearch("//*[@id='autoplay-checkbox']").snapshotItem(0) || docsearch("//*[@id='toggleButton']").snapshotItem(0);//OLD||NEW
                    if (abutton) {
                        simulClick(abutton);
                    }
                }
            }
            else {
                insertStyle(style_autoplay, "ytpc_style_autoplay");
                anode.setAttribute("ytpc_disable_autoplay", "true");
            }
    }
    else {
        insertStyle("", "ytpc_style_autoplay");
        anode.removeAttribute("ytpc_disable_autoplay");
    }
}


//=================================================================
//annotations

function annotation() {
    insertStyle(get_pref("ytAnnot") ? style_annotations : "", "ytpc_style_annotations");
}


//=================================================================
//ads

function skip_ads() {
    if (!get_pref("ytAds")) return;

    var button = doc.getElementsByClassName("videoAdUiSkipButton videoAdUiAction");
    if (button.length > 0)
        if (button[0].parentNode)
            if (button[0].parentNode.style.display != "none") {
                //message("will click");
                simulClick(button[0]);
            }
}


//==================================================================
// Main

var old_addr = win.location.href;
var nochanges_count = -1;
var start_count = -1;
//for yt_start
var pause_count = 0;
var def_count = 0;
var pref_ytPause = false;
var pref_ytDef = 'default';

ytplayer_script();
insertStyle(style_basic, "ytpc_style_basic");

win.addEventListener("focus", function () { reset_nochanges() }, false);
win.addEventListener("blur", function () { reset_nochanges() }, false);
win.addEventListener("resize", function () { reset_nochanges(); cinema(0); }, false);
win.addEventListener("scroll", function () { reset_nochanges(); cinema(20); }, false);
win.addEventListener("click", function () { reset_nochanges(); }, false);

function reset_nochanges() { nochanges_count = -1; }

function yt_start() {
    if (start_count == 0) {
        pause_count = 0;
        def_count = 0;
        pref_ytPause = get_pref('ytPause');
        pref_ytDef = get_pref('ytDef');
        ytplayer_state("pause_end_mark", "false");
    }

    if (pref_ytPause && pause_count <= 1) {
        ytplayer_pause();
        if (success_pause()) pause_count++;
    }

    if (pref_ytDef != 'default' && def_count <= 1) {
        ytplayer_quality(pref_ytDef);
        if (success_quality()) def_count++;
    }
}


//main routine
function check_changes() {
    if (old_addr == win.location.href) {
        if (nochanges_count < 20) nochanges_count++;
        if (start_count < 20) start_count++;
    }
    else {
        old_addr = win.location.href;
        nochanges_count = 0;
        start_count = 0;
    }

    //no video page
    if (win.location.href.indexOf("watch?") == -1) {
        if (start_count < 20) {
            set_noloop();
            set_nopause_end();
            cinema(20, true); //for showmast
        }
        return;
    }

    //video page
    skip_ads();

    if (start_count < 20) {
        if (start_count == 0) close_ytplayer_options();
        build_yt_control();
        yt_start();
        annotation();
    }

    if (nochanges_count < 20) {
        cinema(start_count);
        autoplay(start_count);
    }
}

win.setInterval(check_changes, 1000);
check_changes();