[
  {
    "path": "LICENSE.md",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "# quality-menu\nA userscript for MPV that allows you to change the streamed video and audio quality (ytdl-format) on the fly.\n\nSimply open the video or audio menu, select your prefered format and confirm your choice. The keybindings for opening the menus are configured in input.conf, and everthing else is configured in quality-menu.conf.\n\nNote: Version 4.2.0 and later require mpv 0.39.0. Anyone on an older version of mpv can use version 4.1.2 instead.\n\n![screenshot](preview.jpg)\n\n## Features\n\n- Currently playing format is marked and selected when opening the menu\n- Remembers selected format for every url in the current session (e.g. going back to previous playlist item automatically selects the prefered format)\n- Controllable entirely by mouse or keyboard (opening by mouse requires either the OSC extension, [uosc](https://github.com/tomasklaen/uosc) or an additional entry in [`input.conf`](https://mpv.io/manual/stable/#input-conf))\n- All format related information from yt-dlp/youtube-dl can be shown\n- Columns that are identical for all formats are automatically hidden\n- Formats can be sorted based on resolution, fps, bitrate, etc.\n- Simple reload functionality\n- Columns and their order are configurable\n- **(optional)** Graphical menu via [uosc](https://github.com/tomasklaen/uosc) integration  \n    Note: Requires uosc 5.0.0 or newer.\n\n## OSC extension\n**(optional)** An extended version of the OSC is available that includes a button to display the quality menu.\n\n![screenshot](quality-menu-preview-osc.jpg)\n\n**PLEASE NOTE:** This conflicts with other scripts that modify the OSC. Merging this OSC modification others is certainly possible. Depending on how the osc is modified, the [osc.patch](osc.patch) might apply cleanly, but you have to make sure the filename in the patch lines up with the filename of your files.\n\n## Installation\n1. Save the `quality-menu.lua` into your [scripts directory](https://mpv.io/manual/stable/#script-location)\n2. Set key bindings in [`input.conf`](https://mpv.io/manual/stable/#input-conf)\n    ```\n    F     script-binding quality_menu/video_formats_toggle\n    Alt+f script-binding quality_menu/audio_formats_toggle\n    ```\n    **(optional)** `Ctrl+r script-binding quality_menu/reload`\n\n3. **(optional)** Save the `quality-menu.conf` into your `script-opts` directory (next to the [scripts directory](https://mpv.io/manual/stable/#script-location), create if it doesn't exist)\n4. **(optional)** UI integration (pick one)\n    - For OSC: Save the `quality-menu-osc.lua` into your [scripts directory](https://mpv.io/manual/stable/#script-location)  and put `osc=no` in your [mpv.conf](https://mpv.io/manual/stable/#location-and-syntax)\n    - For [uosc](https://github.com/tomasklaen/uosc) (each is optional)\n        1. Add the video and audio menu to the uosc menu by appending `#! ...` to your key bindings in [`input.conf`](https://mpv.io/manual/stable/#input-conf)\n        ```\n        F     script-binding quality_menu/video_formats_toggle #! Stream Quality > Video\n        Alt+f script-binding quality_menu/audio_formats_toggle #! Stream Quality > Audio\n        ```\n        2. quality-menu already overwrites the builtin uosc command `stream-quality`, so it already works well out of the box.\n            For even deeper UI integration you can add buttons to the `contols=` option in your [`uosc.conf`](https://github.com/tomasklaen/uosc/blob/main/script-opts/uosc.conf)\n            1. `<!has_many_video,video,stream>command:theaters:script-binding quality_menu/video_formats_toggle#@vformats>1?Video`\n            2. `<!has_many_audio,has_audio,stream>command:graphic_eq:script-binding quality_menu/audio_formats_toggle#@aformats>1?Audio`\n\n## Plans For Future Enhancement\n- [x] Visual indication of what the current quality level is\n- [x] Option to populate the quality list automatically with the exact formats available for a given video\n- [x] Optional OSC extension\n- [x] [uosc](https://github.com/tomasklaen/uosc) integration\n- [ ] *\\[your suggestion here\\]*\n\n## Credit\n- [reload.lua](https://github.com/4e6/mpv-reload/), for the function to reload a video while preserving the playlist.\n- [mpv-playlistmanager](https://github.com/jonniek/mpv-playlistmanager), for the menu formatting config.\n- ytdl_hook.lua, much of the  code to fetch the format list with youtube-dl came from there.\n- somebody on /mpv/ for the idea\n"
  },
  {
    "path": "osc.patch",
    "content": "diff --git a/../mpv/player/lua/osc.lua b/osc.lua\nindex 6132aa9..5c73229 100644\n--- a/osc.lua\n+++ b/osc.lua\n@@ -1711,6 +1711,13 @@ local function bar_layout(direction, slim)\n     lo.geometry = geo\n     lo.style = osc_styles.smallButtonsBar\n \n+    -- START quality-menu\n+    geo = { x = geo.x - geo.w - padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n+    lo = add_layout(\"quality-menu\")\n+    lo.geometry = geo\n+    lo.style = osc_styles.smallButtonsBar\n+    -- END quality-menu\n+\n     -- Volume\n     geo = { x = geo.x - geo.w - padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n     lo = add_layout(\"volume\")\n@@ -2136,6 +2143,17 @@ local function osc_init()\n             string.format(\"%3.0fs\", sec))\n     end\n \n+    -- START quality-menu\n+    ne = new_element(\"quality-menu\", \"button\")\n+    ne.content = function()\n+        return (\"≚\")\n+    end\n+    ne.eventresponder[\"mbtn_left_up\"] =\n+        function () mp.commandv(\"script-message\", \"video_formats_toggle\") end\n+    ne.eventresponder[\"mbtn_right_up\"] =\n+        function () mp.commandv(\"script-message\", \"audio_formats_toggle\") end\n+    -- END quality-menu\n+\n     -- volume\n     ne = new_element(\"volume\", \"button\")\n \n"
  },
  {
    "path": "quality-menu-osc.lua",
    "content": "local assdraw = require 'mp.assdraw'\nlocal msg = require 'mp.msg'\nlocal opt = require 'mp.options'\n\n--\n-- Parameters\n--\n-- default user option values\n-- do not touch, change them in osc.conf\nlocal user_opts = {\n    showwindowed = true,        -- show OSC when windowed?\n    showfullscreen = true,      -- show OSC when fullscreen?\n    idlescreen = true,          -- show mpv logo on idle\n    scalewindowed = 1,          -- scaling of the controller when windowed\n    scalefullscreen = 1,        -- scaling of the controller when fullscreen\n    vidscale = \"auto\",          -- scale the controller with the video?\n    valign = 0.8,               -- vertical alignment, -1 (top) to 1 (bottom)\n    halign = 0,                 -- horizontal alignment, -1 (left) to 1 (right)\n    barmargin = 0,              -- vertical margin of top/bottombar\n    boxalpha = 80,              -- alpha of the background box,\n                                -- 0 (opaque) to 255 (fully transparent)\n    hidetimeout = 500,          -- duration in ms until the OSC hides if no\n                                -- mouse movement. enforced non-negative for the\n                                -- user, but internally negative is \"always-on\".\n    fadeduration = 200,         -- duration of fade out (and fade in, if enabled) in ms, 0 = no fade\n    fadein = false,             -- whether to enable fade-in effect\n    deadzonesize = 0.5,         -- size of deadzone\n    minmousemove = 0,           -- minimum amount of pixels the mouse has to\n                                -- move between ticks to make the OSC show up\n    layout = \"bottombar\",\n    seekbarstyle = \"bar\",       -- bar, diamond or knob\n    seekbarhandlesize = 0.6,    -- size ratio of the diamond and knob handle\n    seekrangestyle = \"inverted\",-- bar, line, slider, inverted or none\n    seekrangeseparate = true,   -- whether the seekranges overlay on the bar-style seekbar\n    seekrangealpha = 200,       -- transparency of seekranges\n    seekbarkeyframes = true,    -- use keyframes when dragging the seekbar\n    scrollcontrols = true,      -- allow scrolling when hovering certain OSC elements\n    title = \"${!playlist-count==1:[${playlist-pos-1}/${playlist-count}] }${media-title}\",\n                                -- to be shown as OSC title\n    tooltipborder = 1,          -- border of tooltip in bottom/topbar\n    timetotal = false,          -- display total time instead of remaining time?\n    remaining_playtime = true,  -- display the remaining time in playtime or video-time mode\n                                -- playtime takes speed into account, whereas video-time doesn't\n    timems = false,             -- display timecodes with milliseconds?\n    tcspace = 100,              -- timecode spacing (compensate font size estimation)\n    visibility = \"auto\",        -- only used at init to set visibility_mode(...)\n    visibility_modes = \"never_auto_always\", -- visibility modes to cycle through\n    boxmaxchars = 80,           -- title crop threshold for box layout\n    boxvideo = false,           -- apply osc_param.video_margins to video\n    windowcontrols = \"auto\",    -- whether to show window controls\n    windowcontrols_alignment = \"right\", -- which side to show window controls on\n    windowcontrols_title = \"${media-title}\", -- same as title but for windowcontrols\n    greenandgrumpy = false,     -- disable santa hat\n    livemarkers = true,         -- update seekbar chapter markers on duration change\n    chapter_fmt = \"Chapter: %s\", -- chapter print format for seekbar-hover. \"no\" to disable\n    unicodeminus = false,       -- whether to use the Unicode minus sign character\n\n    background_color = \"#000000\",     -- background color of the osc\n    timecode_color = \"#FFFFFF\",       -- color of the progress bar and time color\n    title_color = \"#FFFFFF\",          -- color of the title\n    time_pos_color = \"#FFFFFF\",       -- color of the timecode at hovered position\n    buttons_color = \"#FFFFFF\",        -- color of big buttons, wc buttons, and bar small buttons\n    small_buttonsL_color = \"#FFFFFF\", -- color of left small buttons\n    small_buttonsR_color = \"#FFFFFF\", -- color of right small buttons\n    top_buttons_color = \"#FFFFFF\",    -- color of top buttons\n    held_element_color = \"#999999\",   -- color of an element while held down\n\n    time_pos_outline_color = \"#000000\",   -- color of the border timecodes in slimbox and TimePosBar\n\n    tick_delay = 1 / 60,                   -- minimum interval between OSC redraws in seconds\n    tick_delay_follow_display_fps = false, -- use display fps as the minimum interval\n\n    -- luacheck: push ignore\n    -- luacheck: max line length\n    menu_mbtn_left_command = \"script-binding select/menu; script-message-to osc osc-hide\",\n    menu_mbtn_mid_command = \"\",\n    menu_mbtn_right_command = \"\",\n\n    playlist_prev_mbtn_left_command = \"playlist-prev\",\n    playlist_prev_mbtn_mid_command = \"show-text ${playlist} 3000\",\n    playlist_prev_mbtn_right_command = \"script-binding select/select-playlist; script-message-to osc osc-hide\",\n\n    playlist_next_mbtn_left_command = \"playlist-next\",\n    playlist_next_mbtn_mid_command = \"show-text ${playlist} 3000\",\n    playlist_next_mbtn_right_command = \"script-binding select/select-playlist; script-message-to osc osc-hide\",\n\n    title_mbtn_left_command = \"script-binding stats/display-page-5\",\n    title_mbtn_mid_command = \"show-text ${path}\",\n    title_mbtn_right_command = \"script-binding select/select-watch-history; script-message-to osc osc-hide\",\n\n    play_pause_mbtn_left_command = \"cycle pause\",\n    play_pause_mbtn_mid_command = \"cycle-values loop-playlist inf no\",\n    play_pause_mbtn_right_command = \"cycle-values loop-file inf no\",\n\n    chapter_prev_mbtn_left_command = \"osd-msg add chapter -1\",\n    chapter_prev_mbtn_mid_command = \"show-text ${chapter-list} 3000\",\n    chapter_prev_mbtn_right_command = \"script-binding select/select-chapter; script-message-to osc osc-hide\",\n\n    chapter_next_mbtn_left_command = \"osd-msg add chapter 1\",\n    chapter_next_mbtn_mid_command = \"show-text ${chapter-list} 3000\",\n    chapter_next_mbtn_right_command = \"script-binding select/select-chapter; script-message-to osc osc-hide\",\n\n    audio_track_mbtn_left_command = \"cycle audio\",\n    audio_track_mbtn_mid_command = \"cycle audio down\",\n    audio_track_mbtn_right_command = \"script-binding select/select-aid; script-message-to osc osc-hide\",\n    audio_track_wheel_down_command = \"cycle audio\",\n    audio_track_wheel_up_command = \"cycle audio down\",\n\n    sub_track_mbtn_left_command = \"cycle sub\",\n    sub_track_mbtn_mid_command = \"cycle sub down\",\n    sub_track_mbtn_right_command = \"script-binding select/select-sid; script-message-to osc osc-hide\",\n    sub_track_wheel_down_command = \"cycle sub\",\n    sub_track_wheel_up_command = \"cycle sub down\",\n\n    volume_mbtn_left_command = \"no-osd cycle mute\",\n    volume_mbtn_mid_command = \"\",\n    volume_mbtn_right_command = \"script-binding select/select-audio-device; script-message-to osc osc-hide\",\n    volume_wheel_down_command = \"add volume -5\",\n    volume_wheel_up_command = \"add volume 5\",\n\n    fullscreen_mbtn_left_command = \"cycle fullscreen\",\n    fullscreen_mbtn_mid_command = \"\",\n    fullscreen_mbtn_right_command = \"cycle window-maximized\",\n    -- luacheck: pop\n}\n\nfor i = 1, 99 do\n    user_opts[\"custom_button_\" .. i .. \"_content\"] = \"\"\n    user_opts[\"custom_button_\" .. i .. \"_mbtn_left_command\"] = \"\"\n    user_opts[\"custom_button_\" .. i .. \"_mbtn_mid_command\"] = \"\"\n    user_opts[\"custom_button_\" .. i .. \"_mbtn_right_command\"] = \"\"\n    user_opts[\"custom_button_\" .. i .. \"_wheel_down_command\"] = \"\"\n    user_opts[\"custom_button_\" .. i .. \"_wheel_up_command\"] = \"\"\nend\n\nlocal icon_font = \"mpv-osd-symbols\"\n\n-- Running this in Lua 5.3+ or LuaJIT converts a hexadecimal Unicode code point\n-- to the decimal value of every byte for Lua 5.1 and 5.2 compatibility:\n-- glyph='\\u{e000}' output=''\n-- for i = 1, #glyph do output = output .. '\\\\' .. string.byte(glyph, i) end\n-- print(output)\nlocal icons = {\n    menu = \"\\238\\132\\130\",           -- E102\n    prev = \"\\238\\132\\144\",           -- E110\n    next = \"\\238\\132\\129\",           -- E101\n    pause = \"\\238\\128\\130\",          -- E002\n    play = \"\\238\\132\\129\",           -- E101\n    play_backward = \"\\238\\132\\144\",  -- E110\n    skip_backward = \"\\238\\128\\132\",  -- E004\n    skip_forward = \"\\238\\128\\133\",   -- E005\n    chapter_prev = \"\\238\\132\\132\",   -- E104\n    chapter_next = \"\\238\\132\\133\",   -- E105\n    audio = \"\\238\\132\\134\",          -- E106\n    subtitle = \"\\238\\132\\135\",       -- E107\n    mute = \"\\238\\132\\138\",           -- E10A\n    volume = {\"\\238\\132\\139\", \"\\238\\132\\140\", \"\\238\\132\\141\", \"\\238\\132\\142\"},-- E10B E10C E10D E10E\n    fullscreen = \"\\238\\132\\136\",     -- E108\n    exit_fullscreen = \"\\238\\132\\137\",-- E109\n    close = \"\\238\\132\\149\",          -- E115\n    minimize = \"\\238\\132\\146\",       -- E112\n    maximize = \"\\238\\132\\147\",       -- E113\n    unmaximize = \"\\238\\132\\148\",     -- E114\n}\n\nlocal osc_param = { -- calculated by osc_init()\n    playresy = 0,                           -- canvas size Y\n    playresx = 0,                           -- canvas size X\n    display_aspect = 1,\n    unscaled_y = 0,\n    areas = {},\n    video_margins = {\n        l = 0, r = 0, t = 0, b = 0,         -- left/right/top/bottom\n    },\n}\n\nlocal margins_opts = {\n    {\"l\", \"video-margin-ratio-left\"},\n    {\"r\", \"video-margin-ratio-right\"},\n    {\"t\", \"video-margin-ratio-top\"},\n    {\"b\", \"video-margin-ratio-bottom\"},\n}\n\nlocal tick_delay = 1 / 60\nlocal audio_track_count = 0\nlocal sub_track_count = 0\nlocal window_control_box_width = 80\nlocal layouts = {}\nlocal is_december = os.date(\"*t\").month == 12\nlocal UNICODE_MINUS = string.char(0xe2, 0x88, 0x92)  -- UTF-8 for U+2212 MINUS SIGN\nlocal last_custom_button = 0\n\nlocal function osc_color_convert(color)\n    return color:sub(6,7) .. color:sub(4,5) ..  color:sub(2,3)\nend\n\n-- luacheck: push ignore\n-- luacheck: max line length\nlocal osc_styles\n\nlocal function set_osc_styles()\n    osc_styles = {\n        bigButtons = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.buttons_color) .. \"\\\\3c&HFFFFFF\\\\fs50\\\\fn\" .. icon_font .. \"}\",\n        smallButtonsL = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.small_buttonsL_color) .. \"\\\\3c&HFFFFFF\\\\fs19\\\\fn\" .. icon_font .. \"}\",\n        smallButtonsLlabel = \"{\\\\fscx105\\\\fscy105\\\\fn\" .. mp.get_property(\"options/osd-font\") .. \"}\",\n        smallButtonsR = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.small_buttonsR_color) .. \"\\\\3c&HFFFFFF\\\\fs30\\\\fn\" .. icon_font .. \"}\",\n        topButtons = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.top_buttons_color) .. \"\\\\3c&HFFFFFF\\\\fs12\\\\fn\" .. icon_font .. \"}\",\n\n        elementDown = \"{\\\\1c&H\" .. osc_color_convert(user_opts.held_element_color) ..\"}\",\n        timecodes = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.timecode_color) .. \"\\\\3c&HFFFFFF\\\\fs20}\",\n        vidtitle = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.title_color) .. \"\\\\3c&HFFFFFF\\\\fs14\\\\q2}\",\n        box = \"{\\\\rDefault\\\\blur0\\\\bord1\\\\1c&H\" .. osc_color_convert(user_opts.background_color) .. \"\\\\3c&HFFFFFF}\",\n\n        topButtonsBar = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.top_buttons_color) .. \"\\\\3c&HFFFFFF\\\\fs18\\\\fn\" .. icon_font .. \"}\",\n        smallButtonsBar = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.buttons_color) .. \"\\\\3c&HFFFFFF\\\\fs28\\\\fn\" .. icon_font .. \"}\",\n        timecodesBar = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.timecode_color) ..\"\\\\3c&HFFFFFF\\\\fs27}\",\n        timePosBar = \"{\\\\blur0\\\\bord\".. user_opts.tooltipborder ..\"\\\\1c&H\" .. osc_color_convert(user_opts.time_pos_color) .. \"\\\\3c&H\" .. osc_color_convert(user_opts.time_pos_outline_color) .. \"\\\\fs30}\",\n        vidtitleBar = \"{\\\\blur0\\\\bord0\\\\1c&H\" .. osc_color_convert(user_opts.title_color) .. \"\\\\3c&HFFFFFF\\\\fs18\\\\q2}\",\n\n        wcButtons = \"{\\\\1c&H\" .. osc_color_convert(user_opts.buttons_color) .. \"\\\\fs24\\\\fn\" .. icon_font .. \"}\",\n        wcTitle = \"{\\\\1c&H\" .. osc_color_convert(user_opts.title_color) .. \"\\\\fs24\\\\q2}\",\n        wcBar = \"{\\\\1c&H\" .. osc_color_convert(user_opts.background_color) .. \"}\",\n    }\nend\n\n-- internal states, do not touch\nlocal state = {\n    showtime = nil,                         -- time of last invocation (last mouse move)\n    touchtime = nil,                        -- time of last invocation (last touch event)\n    osc_visible = false,\n    anistart = nil,                         -- time when the animation started\n    anitype = nil,                          -- current type of animation\n    animation = nil,                        -- current animation alpha\n    mouse_down_counter = 0,                 -- used for softrepeat\n    active_element = nil,                   -- nil = none, 0 = background, 1+ = see elements[]\n    active_event_source = nil,              -- the \"button\" that issued the current event\n    rightTC_trem = not user_opts.timetotal, -- if the right timecode should display total or remaining time\n    tc_ms = user_opts.timems,               -- Should the timecodes display their time with milliseconds\n    screen_sizeX = nil, screen_sizeY = nil, -- last screen-resolution, to detect resolution changes to issue reINITs\n    initREQ = false,                        -- is a re-init request pending?\n    marginsREQ = false,                     -- is a margins update pending?\n    last_mouseX = nil, last_mouseY = nil,   -- last mouse position, to detect significant mouse movement\n    mouse_in_window = false,\n    fullscreen = false,\n    tick_timer = nil,\n    tick_last_time = 0,                     -- when the last tick() was run\n    hide_timer = nil,\n    cache_state = nil,\n    idle = false,\n    enabled = true,\n    input_enabled = true,\n    showhide_enabled = false,\n    windowcontrols_buttons = false,\n    windowcontrols_title = false,\n    dmx_cache = 0,\n    using_video_margins = false,\n    border = true,\n    maximized = false,\n    osd = mp.create_osd_overlay(\"ass-events\"),\n    chapter_list = {},                      -- sorted by time\n    visibility_modes = {},                  -- visibility_modes to cycle through\n    osc_message_warned = false,             -- deprecation warnings\n    osc_chapterlist_warned = false,\n    osc_playlist_warned = false,\n    osc_tracklist_warned = false,\n}\n\nlocal logo_lines = {\n    -- White border\n    \"{\\\\c&HE5E5E5&\\\\p6}m 895 10 b 401 10 0 410 0 905 0 1399 401 1800 895 1800 1390 1800 1790 1399 1790 905 1790 410 1390 10 895 10 {\\\\p0}\",\n    -- Purple fill\n    \"{\\\\c&H682167&\\\\p6}m 925 42 b 463 42 87 418 87 880 87 1343 463 1718 925 1718 1388 1718 1763 1343 1763 880 1763 418 1388 42 925 42{\\\\p0}\",\n    -- Darker fill\n    \"{\\\\c&H430142&\\\\p6}m 1605 828 b 1605 1175 1324 1456 977 1456 631 1456 349 1175 349 828 349 482 631 200 977 200 1324 200 1605 482 1605 828{\\\\p0}\",\n    -- White fill\n    \"{\\\\c&HDDDBDD&\\\\p6}m 1296 910 b 1296 1131 1117 1310 897 1310 676 1310 497 1131 497 910 497 689 676 511 897 511 1117 511 1296 689 1296 910{\\\\p0}\",\n    -- Triangle\n    \"{\\\\c&H691F69&\\\\p6}m 762 1113 l 762 708 b 881 776 1000 843 1119 911 1000 978 881 1046 762 1113{\\\\p0}\",\n}\n\nlocal santa_hat_lines = {\n    -- Pompoms\n    \"{\\\\c&HC0C0C0&\\\\p6}m 500 -323 b 491 -322 481 -318 475 -311 465 -312 456 -319 446 -318 434 -314 427 -304 417 -297 410 -290 404 -282 395 -278 390 -274 387 -267 381 -265 377 -261 379 -254 384 -253 397 -244 409 -232 425 -228 437 -228 446 -218 457 -217 462 -216 466 -213 468 -209 471 -205 477 -203 482 -206 491 -211 499 -217 508 -222 532 -235 556 -249 576 -267 584 -272 584 -284 578 -290 569 -305 550 -312 533 -309 523 -310 515 -316 507 -321 505 -323 503 -323 500 -323{\\\\p0}\",\n    \"{\\\\c&HE0E0E0&\\\\p6}m 315 -260 b 286 -258 259 -240 246 -215 235 -210 222 -215 211 -211 204 -188 177 -176 172 -151 170 -139 163 -128 154 -121 143 -103 141 -81 143 -60 139 -46 125 -34 129 -17 132 -1 134 16 142 30 145 56 161 80 181 96 196 114 210 133 231 144 266 153 303 138 328 115 373 79 401 28 423 -24 446 -73 465 -123 483 -174 487 -199 467 -225 442 -227 421 -232 402 -242 384 -254 364 -259 342 -250 322 -260 320 -260 317 -261 315 -260{\\\\p0}\",\n    -- Main cap\n    \"{\\\\c&H0000F0&\\\\p6}m 1151 -523 b 1016 -516 891 -458 769 -406 693 -369 624 -319 561 -262 526 -252 465 -235 479 -187 502 -147 551 -135 588 -111 1115 165 1379 232 1909 761 1926 800 1952 834 1987 858 2020 883 2053 912 2065 952 2088 1000 2146 962 2139 919 2162 836 2156 747 2143 662 2131 615 2116 567 2122 517 2120 410 2090 306 2089 199 2092 147 2071 99 2034 64 1987 5 1928 -41 1869 -86 1777 -157 1712 -256 1629 -337 1578 -389 1521 -436 1461 -476 1407 -509 1343 -507 1284 -515 1240 -519 1195 -521 1151 -523{\\\\p0}\",\n    -- Cap shadow\n    \"{\\\\c&H0000AA&\\\\p6}m 1657 248 b 1658 254 1659 261 1660 267 1669 276 1680 284 1689 293 1695 302 1700 311 1707 320 1716 325 1726 330 1735 335 1744 347 1752 360 1761 371 1753 352 1754 331 1753 311 1751 237 1751 163 1751 90 1752 64 1752 37 1767 14 1778 -3 1785 -24 1786 -45 1786 -60 1786 -77 1774 -87 1760 -96 1750 -78 1751 -65 1748 -37 1750 -8 1750 20 1734 78 1715 134 1699 192 1694 211 1689 231 1676 246 1671 251 1661 255 1657 248 m 1909 541 b 1914 542 1922 549 1917 539 1919 520 1921 502 1919 483 1918 458 1917 433 1915 407 1930 373 1942 338 1947 301 1952 270 1954 238 1951 207 1946 214 1947 229 1945 239 1939 278 1936 318 1924 356 1923 362 1913 382 1912 364 1906 301 1904 237 1891 175 1887 150 1892 126 1892 101 1892 68 1893 35 1888 2 1884 -9 1871 -20 1859 -14 1851 -6 1854 9 1854 20 1855 58 1864 95 1873 132 1883 179 1894 225 1899 273 1908 362 1910 451 1909 541{\\\\p0}\",\n    -- Brim and tip pompom\n    \"{\\\\c&HF8F8F8&\\\\p6}m 626 -191 b 565 -155 486 -196 428 -151 387 -115 327 -101 304 -47 273 2 267 59 249 113 219 157 217 213 215 265 217 309 260 302 285 283 373 264 465 264 555 257 608 252 655 292 709 287 759 294 816 276 863 298 903 340 972 324 1012 367 1061 394 1125 382 1167 424 1213 462 1268 482 1322 506 1385 546 1427 610 1479 662 1510 690 1534 725 1566 752 1611 796 1664 830 1703 880 1740 918 1747 986 1805 1005 1863 991 1897 932 1916 880 1914 823 1945 777 1961 725 1979 673 1957 622 1938 575 1912 534 1862 515 1836 473 1790 417 1755 351 1697 305 1658 266 1633 216 1593 176 1574 138 1539 116 1497 110 1448 101 1402 77 1371 37 1346 -16 1295 15 1254 6 1211 -27 1170 -62 1121 -86 1072 -104 1027 -128 976 -133 914 -130 851 -137 794 -162 740 -181 679 -168 626 -191 m 2051 917 b 1971 932 1929 1017 1919 1091 1912 1149 1923 1214 1970 1254 2000 1279 2027 1314 2066 1325 2139 1338 2212 1295 2254 1238 2281 1203 2287 1158 2282 1116 2292 1061 2273 1006 2229 970 2206 941 2167 938 2138 918{\\\\p0}\",\n}\n-- luacheck: pop\n\n\n--\n-- Helper functions\n--\n\nlocal function kill_animation()\n    state.anistart = nil\n    state.animation = nil\n    state.anitype =  nil\nend\n\nlocal function set_osd(res_x, res_y, text, z)\n    if state.osd.res_x == res_x and\n       state.osd.res_y == res_y and\n       state.osd.data == text then\n        return\n    end\n    state.osd.res_x = res_x\n    state.osd.res_y = res_y\n    state.osd.data = text\n    state.osd.z = z\n    state.osd:update()\nend\n\nlocal function set_time_styles(timetotal_changed, timems_changed)\n    if timetotal_changed then\n        state.rightTC_trem = not user_opts.timetotal\n    end\n    if timems_changed then\n        state.tc_ms = user_opts.timems\n    end\nend\n\n-- scale factor for translating between real and virtual ASS coordinates\nlocal function get_virt_scale_factor()\n    local w, h = mp.get_osd_size()\n    if w <= 0 or h <= 0 then\n        return 0, 0\n    end\n    return osc_param.playresx / w, osc_param.playresy / h\nend\n\n-- return mouse position in virtual ASS coordinates (playresx/y)\nlocal function get_virt_mouse_pos()\n    if state.mouse_in_window then\n        local sx, sy = get_virt_scale_factor()\n        local x, y = mp.get_mouse_pos()\n        return x * sx, y * sy\n    else\n        return -1, -1\n    end\nend\n\nlocal function set_virt_mouse_area(x0, y0, x1, y1, name)\n    local sx, sy = get_virt_scale_factor()\n    mp.set_mouse_area(x0 / sx, y0 / sy, x1 / sx, y1 / sy, name)\nend\n\nlocal function scale_value(x0, x1, y0, y1, val)\n    local m = (y1 - y0) / (x1 - x0)\n    local b = y0 - (m * x0)\n    return (m * val) + b\nend\n\n-- returns hitbox spanning coordinates (top left, bottom right corner)\n-- according to alignment\nlocal function get_hitbox_coords(x, y, an, w, h)\n\n    local alignments = {\n      [1] = function () return x, y-h, x+w, y end,\n      [2] = function () return x-(w/2), y-h, x+(w/2), y end,\n      [3] = function () return x-w, y-h, x, y end,\n\n      [4] = function () return x, y-(h/2), x+w, y+(h/2) end,\n      [5] = function () return x-(w/2), y-(h/2), x+(w/2), y+(h/2) end,\n      [6] = function () return x-w, y-(h/2), x, y+(h/2) end,\n\n      [7] = function () return x, y, x+w, y+h end,\n      [8] = function () return x-(w/2), y, x+(w/2), y+h end,\n      [9] = function () return x-w, y, x, y+h end,\n    }\n\n    return alignments[an]()\nend\n\nlocal function get_hitbox_coords_geo(geometry)\n    return get_hitbox_coords(geometry.x, geometry.y, geometry.an,\n        geometry.w, geometry.h)\nend\n\nlocal function get_element_hitbox(element)\n    return element.hitbox.x1, element.hitbox.y1,\n        element.hitbox.x2, element.hitbox.y2\nend\n\nlocal function mouse_hit_coords(bX1, bY1, bX2, bY2)\n    local mX, mY = get_virt_mouse_pos()\n    return (mX >= bX1 and mX <= bX2 and mY >= bY1 and mY <= bY2)\nend\n\nlocal function mouse_hit(element)\n    return mouse_hit_coords(get_element_hitbox(element))\nend\n\nlocal function limit_range(min, max, val)\n    if val > max then\n        val = max\n    elseif val < min then\n        val = min\n    end\n    return val\nend\n\n-- translate value into element coordinates\nlocal function get_slider_ele_pos_for(element, val)\n\n    local ele_pos = scale_value(\n        element.slider.min.value, element.slider.max.value,\n        element.slider.min.ele_pos, element.slider.max.ele_pos,\n        val)\n\n    return limit_range(\n        element.slider.min.ele_pos, element.slider.max.ele_pos,\n        ele_pos)\nend\n\n-- translates global (mouse) coordinates to value\nlocal function get_slider_value_at(element, glob_pos)\n\n    local val = scale_value(\n        element.slider.min.glob_pos, element.slider.max.glob_pos,\n        element.slider.min.value, element.slider.max.value,\n        glob_pos)\n\n    return limit_range(\n        element.slider.min.value, element.slider.max.value,\n        val)\nend\n\n-- get value at current mouse position\nlocal function get_slider_value(element)\n    return get_slider_value_at(element, get_virt_mouse_pos())\nend\n\n-- align:  -1 .. +1\n-- frame:  size of the containing area\n-- obj:    size of the object that should be positioned inside the area\n-- margin: min. distance from object to frame (as long as -1 <= align <= +1)\nlocal function get_align(align, frame, obj, margin)\n    return (frame / 2) + (((frame / 2) - margin - (obj / 2)) * align)\nend\n\n-- multiplies two alpha values, formular can probably be improved\nlocal function mult_alpha(alphaA, alphaB)\n    return 255 - (((1-(alphaA/255)) * (1-(alphaB/255))) * 255)\nend\n\nlocal function add_area(name, x1, y1, x2, y2)\n    -- create area if needed\n    if osc_param.areas[name] == nil then\n        osc_param.areas[name] = {}\n    end\n    table.insert(osc_param.areas[name], {x1=x1, y1=y1, x2=x2, y2=y2})\nend\n\nlocal function ass_append_alpha(ass, alpha, modifier)\n    local ar = {}\n\n    for ai, av in pairs(alpha) do\n        av = mult_alpha(av, modifier)\n        if state.animation then\n            av = mult_alpha(av, state.animation)\n        end\n        ar[ai] = av\n    end\n\n    ass:append(string.format(\"{\\\\1a&H%X&\\\\2a&H%X&\\\\3a&H%X&\\\\4a&H%X&}\",\n               ar[1], ar[2], ar[3], ar[4]))\nend\n\nlocal function ass_draw_rr_h_cw(ass, x0, y0, x1, y1, r1, hexagon, r2)\n    if hexagon then\n        ass:hexagon_cw(x0, y0, x1, y1, r1, r2)\n    else\n        ass:round_rect_cw(x0, y0, x1, y1, r1, r2)\n    end\nend\n\nlocal function ass_draw_rr_h_ccw(ass, x0, y0, x1, y1, r1, hexagon, r2)\n    if hexagon then\n        ass:hexagon_ccw(x0, y0, x1, y1, r1, r2)\n    else\n        ass:round_rect_ccw(x0, y0, x1, y1, r1, r2)\n    end\nend\n\nlocal function get_hidetimeout()\n    if user_opts.visibility == \"always\" then\n        return -1 -- disable autohide\n    end\n    return user_opts.hidetimeout\nend\n\nlocal function get_touchtimeout()\n    if state.touchtime == nil then\n        return 0\n    end\n    return state.touchtime + (get_hidetimeout() / 1000) - mp.get_time()\nend\n\nlocal function cache_enabled()\n    return state.cache_state and #state.cache_state[\"seekable-ranges\"] > 0\nend\n\nlocal function reset_margins()\n    if state.using_video_margins then\n        for _, mopt in ipairs(margins_opts) do\n            mp.set_property_number(mopt[2], 0.0)\n        end\n        state.using_video_margins = false\n    end\nend\n\nlocal function update_margins()\n    local margins = osc_param.video_margins\n\n    -- Don't use margins if it's visible only temporarily.\n    if not state.osc_visible or get_hidetimeout() >= 0 or\n       (state.fullscreen and not user_opts.showfullscreen) or\n       (not state.fullscreen and not user_opts.showwindowed)\n    then\n        margins = {l = 0, r = 0, t = 0, b = 0}\n    end\n\n    if user_opts.boxvideo then\n        -- check whether any margin option has a non-default value\n        local margins_used = false\n\n        if not state.using_video_margins then\n            for _, mopt in ipairs(margins_opts) do\n                if mp.get_property_number(mopt[2], 0.0) ~= 0.0 then\n                    margins_used = true\n                end\n            end\n        end\n\n        if not margins_used then\n            for _, mopt in ipairs(margins_opts) do\n                local v = margins[mopt[1]]\n                if v ~= 0 or state.using_video_margins then\n                    mp.set_property_number(mopt[2], v)\n                    state.using_video_margins = true\n                end\n            end\n        end\n    else\n        reset_margins()\n    end\n\n    mp.set_property_native(\"user-data/osc/margins\", margins)\nend\n\nlocal tick\n-- Request that tick() is called (which typically re-renders the OSC).\n-- The tick is then either executed immediately, or rate-limited if it was\n-- called a small time ago.\nlocal function request_tick()\n    if state.tick_timer == nil then\n        state.tick_timer = mp.add_timeout(0, tick)\n    end\n\n    if not state.tick_timer:is_enabled() then\n        local now = mp.get_time()\n        local timeout = tick_delay - (now - state.tick_last_time)\n        if timeout < 0 then\n            timeout = 0\n        end\n        state.tick_timer.timeout = timeout\n        state.tick_timer:resume()\n    end\nend\n\nlocal function request_init()\n    state.initREQ = true\n    request_tick()\nend\n\n-- Like request_init(), but also request an immediate update\nlocal function request_init_resize()\n    request_init()\n    -- ensure immediate update\n    state.tick_timer:kill()\n    state.tick_timer.timeout = 0\n    state.tick_timer:resume()\nend\n\nlocal function render_wipe()\n    msg.trace(\"render_wipe()\")\n    state.osd.data = \"\" -- allows set_osd to immediately update on enable\n    state.osd:remove()\nend\n\n\n--\n-- Tracklist Management\n--\n\n-- updates the OSC internal playlists, should be run each time the track-layout changes\nlocal function update_tracklist()\n    audio_track_count, sub_track_count = 0, 0\n\n    for _, track in pairs(mp.get_property_native(\"track-list\")) do\n        if track.type == \"audio\" then\n            audio_track_count = audio_track_count + 1\n        elseif track.type == \"sub\" then\n            sub_track_count = sub_track_count + 1\n        end\n    end\nend\n\n-- WindowControl helpers\nlocal function window_controls_enabled()\n    local val = user_opts.windowcontrols\n    if val == \"auto\" then\n        return not (state.border and state.title_bar)\n    else\n        return val ~= \"no\"\n    end\nend\n\nlocal function window_controls_alignment()\n    return user_opts.windowcontrols_alignment\nend\n\n\n--\n-- Element Management\n--\n\nlocal elements = {}\n\nlocal function prepare_elements()\n\n    -- remove elements without layout or invisible\n    local elements2 = {}\n    for _, element in pairs(elements) do\n        if element.layout ~= nil and element.visible then\n            table.insert(elements2, element)\n        end\n    end\n    elements = elements2\n\n    local function elem_compare (a, b)\n        return a.layout.layer < b.layout.layer\n    end\n\n    table.sort(elements, elem_compare)\n\n\n    for _,element in pairs(elements) do\n\n        local elem_geo = element.layout.geometry\n\n        -- Calculate the hitbox\n        local bX1, bY1, bX2, bY2 = get_hitbox_coords_geo(elem_geo)\n        element.hitbox = {x1 = bX1, y1 = bY1, x2 = bX2, y2 = bY2}\n\n        local style_ass = assdraw.ass_new()\n\n        -- prepare static elements\n        style_ass:append(\"{}\") -- hack to troll new_event into inserting a \\n\n        style_ass:new_event()\n        style_ass:pos(elem_geo.x, elem_geo.y)\n        style_ass:an(elem_geo.an)\n        style_ass:append(element.layout.style)\n\n        element.style_ass = style_ass\n\n        local static_ass = assdraw.ass_new()\n\n\n        if element.type == \"box\" then\n            --draw box\n            static_ass:draw_start()\n            ass_draw_rr_h_cw(static_ass, 0, 0, elem_geo.w, elem_geo.h,\n                             element.layout.box.radius, element.layout.box.hexagon)\n            static_ass:draw_stop()\n\n        elseif element.type == \"slider\" then\n            --draw static slider parts\n\n            local r1 = 0\n            local r2 = 0\n            local slider_lo = element.layout.slider\n            -- offset between element outline and drag-area\n            local foV = slider_lo.border + slider_lo.gap\n\n            -- calculate positions of min and max points\n            if slider_lo.stype ~= \"bar\" then\n                r1 = elem_geo.h / 2\n                element.slider.min.ele_pos = elem_geo.h / 2\n                element.slider.max.ele_pos = elem_geo.w - (elem_geo.h / 2)\n                if slider_lo.stype == \"diamond\" then\n                    r2 = (elem_geo.h - 2 * slider_lo.border) / 2\n                elseif slider_lo.stype == \"knob\" then\n                    r2 = r1\n                end\n            else\n                element.slider.min.ele_pos =\n                    slider_lo.border + slider_lo.gap\n                element.slider.max.ele_pos =\n                    elem_geo.w - (slider_lo.border + slider_lo.gap)\n            end\n\n            element.slider.min.glob_pos =\n                element.hitbox.x1 + element.slider.min.ele_pos\n            element.slider.max.glob_pos =\n                element.hitbox.x1 + element.slider.max.ele_pos\n\n            -- -- --\n\n            static_ass:draw_start()\n\n            -- the box\n            ass_draw_rr_h_cw(static_ass, 0, 0, elem_geo.w, elem_geo.h, r1,\n                             slider_lo.stype == \"diamond\")\n\n            -- the \"hole\"\n            ass_draw_rr_h_ccw(static_ass, slider_lo.border, slider_lo.border,\n                              elem_geo.w - slider_lo.border, elem_geo.h - slider_lo.border,\n                              r2, slider_lo.stype == \"diamond\")\n\n            -- marker nibbles\n            if element.slider.markerF ~= nil and slider_lo.gap > 0 then\n                local markers = element.slider.markerF()\n                for _,marker in pairs(markers) do\n                    if marker > element.slider.min.value and\n                        marker < element.slider.max.value then\n\n                        local s = get_slider_ele_pos_for(element, marker)\n\n                        if slider_lo.gap > 1 then -- draw triangles\n\n                            local a = slider_lo.gap / 0.5 --0.866\n\n                            --top\n                            if slider_lo.nibbles_top then\n                                static_ass:move_to(s - (a / 2), slider_lo.border)\n                                static_ass:line_to(s + (a / 2), slider_lo.border)\n                                static_ass:line_to(s, foV)\n                            end\n\n                            --bottom\n                            if slider_lo.nibbles_bottom then\n                                static_ass:move_to(s - (a / 2),\n                                    elem_geo.h - slider_lo.border)\n                                static_ass:line_to(s,\n                                    elem_geo.h - foV)\n                                static_ass:line_to(s + (a / 2),\n                                    elem_geo.h - slider_lo.border)\n                            end\n\n                        else -- draw 2x1px nibbles\n\n                            --top\n                            if slider_lo.nibbles_top then\n                                static_ass:rect_cw(s - 1, slider_lo.border,\n                                    s + 1, slider_lo.border + slider_lo.gap);\n                            end\n\n                            --bottom\n                            if slider_lo.nibbles_bottom then\n                                static_ass:rect_cw(s - 1,\n                                    elem_geo.h -slider_lo.border -slider_lo.gap,\n                                    s + 1, elem_geo.h - slider_lo.border);\n                            end\n                        end\n                    end\n                end\n            end\n        end\n\n        element.static_ass = static_ass\n\n\n        -- if the element is supposed to be disabled,\n        -- style it accordingly and kill the eventresponders\n        if not element.enabled then\n            element.layout.alpha[1] = 136\n            element.eventresponder = nil\n        end\n    end\nend\n\n\n--\n-- Element Rendering\n--\n\n-- returns nil or a chapter element from the native property chapter-list\nlocal function get_chapter(possec)\n    local cl = state.chapter_list  -- sorted, get latest before possec, if any\n\n    for n=#cl,1,-1 do\n        if possec >= cl[n].time then\n            return cl[n]\n        end\n    end\nend\n\nlocal function render_elements(master_ass)\n    -- when the slider is dragged or hovered and we have a target chapter name\n    -- then we use it instead of the normal title. we calculate it before the\n    -- render iterations because the title may be rendered before the slider.\n    state.forced_title = nil\n    local se, ae = state.slider_element, elements[state.active_element]\n    if user_opts.chapter_fmt ~= \"no\" and se and (ae == se or (not ae and mouse_hit(se))) then\n        local dur = mp.get_property_number(\"duration\", 0)\n        if dur > 0 then\n            local possec = get_slider_value(se) * dur / 100 -- of mouse pos\n            local ch = get_chapter(possec)\n            if ch and ch.title and ch.title ~= \"\" then\n                state.forced_title = string.format(user_opts.chapter_fmt, ch.title)\n            end\n        end\n    end\n\n    for n=1, #elements do\n        local element = elements[n]\n\n        local style_ass = assdraw.ass_new()\n        style_ass:merge(element.style_ass)\n        ass_append_alpha(style_ass, element.layout.alpha, 0)\n\n        if element.eventresponder and (state.active_element == n) then\n\n            -- run render event functions\n            if element.eventresponder.render ~= nil then\n                element.eventresponder.render(element)\n            end\n\n            if mouse_hit(element) then\n                -- mouse down styling\n                if element.styledown then\n                    style_ass:append(osc_styles.elementDown)\n                end\n\n                if element.softrepeat and state.mouse_down_counter >= 15\n                    and state.mouse_down_counter % 5 == 0 then\n\n                    element.eventresponder[state.active_event_source..\"_down\"](element)\n                end\n                state.mouse_down_counter = state.mouse_down_counter + 1\n            end\n\n        end\n\n        local elem_ass = assdraw.ass_new()\n\n        elem_ass:merge(style_ass)\n\n        if element.type ~= \"button\" then\n            elem_ass:merge(element.static_ass)\n        end\n\n        if element.type == \"slider\" then\n\n            local slider_lo = element.layout.slider\n            local elem_geo = element.layout.geometry\n            local s_min = element.slider.min.value\n            local s_max = element.slider.max.value\n\n            -- draw pos marker\n            local foH, xp\n            local pos = element.slider.posF()\n            local foV = slider_lo.border + slider_lo.gap\n            local innerH = elem_geo.h - (2 * foV)\n            local seekRanges = element.slider.seekRangesF()\n            local seekRangeLineHeight = innerH / 5\n\n            if slider_lo.stype ~= \"bar\" then\n                foH = elem_geo.h / 2\n            else\n                foH = slider_lo.border + slider_lo.gap\n            end\n\n            if pos then\n                xp = get_slider_ele_pos_for(element, pos)\n\n                if slider_lo.stype ~= \"bar\" then\n                    local r = (user_opts.seekbarhandlesize * innerH) / 2\n                    ass_draw_rr_h_cw(elem_ass, xp - r, foH - r,\n                                     xp + r, foH + r,\n                                     r, slider_lo.stype == \"diamond\")\n                else\n                    local h = 0\n                    if seekRanges and user_opts.seekrangeseparate and\n                       slider_lo.rtype ~= \"inverted\" then\n                        h = seekRangeLineHeight\n                    end\n                    elem_ass:rect_cw(foH, foV, xp, elem_geo.h - foV - h)\n\n                    if seekRanges and not user_opts.seekrangeseparate and\n                       slider_lo.rtype ~= \"inverted\" then\n                        -- Punch holes for the seekRanges to be drawn later\n                        for _,range in pairs(seekRanges) do\n                            if range[\"start\"] < pos then\n                                local pstart = get_slider_ele_pos_for(element, range[\"start\"])\n                                local pend = xp\n\n                                if pos > range[\"end\"] then\n                                    pend = get_slider_ele_pos_for(element, range[\"end\"])\n                                end\n                                elem_ass:rect_ccw(pstart, elem_geo.h - foV - seekRangeLineHeight,\n                                                  pend, elem_geo.h - foV)\n                            end\n                        end\n                    end\n                end\n\n                if slider_lo.rtype == \"slider\" then\n                    ass_draw_rr_h_cw(elem_ass, foH - innerH / 6, foH - innerH / 6,\n                                     xp, foH + innerH / 6,\n                                     innerH / 6, slider_lo.stype == \"diamond\", 0)\n                    ass_draw_rr_h_cw(elem_ass, xp, foH - innerH / 15,\n                                     elem_geo.w - foH + innerH / 15, foH + innerH / 15,\n                                     0, slider_lo.stype == \"diamond\", innerH / 15)\n                    for _,range in pairs(seekRanges or {}) do\n                        local pstart = get_slider_ele_pos_for(element, range[\"start\"])\n                        local pend = get_slider_ele_pos_for(element, range[\"end\"])\n                        ass_draw_rr_h_ccw(elem_ass, pstart, foH - innerH / 21,\n                                          pend, foH + innerH / 21,\n                                          innerH / 21, slider_lo.stype == \"diamond\")\n                    end\n                end\n            end\n\n            if seekRanges then\n                if slider_lo.rtype ~= \"inverted\" then\n                    elem_ass:draw_stop()\n                    elem_ass:merge(element.style_ass)\n                    ass_append_alpha(elem_ass, element.layout.alpha, user_opts.seekrangealpha)\n                    elem_ass:merge(element.static_ass)\n                end\n\n                for _,range in pairs(seekRanges) do\n                    local pstart = get_slider_ele_pos_for(element, range[\"start\"])\n                    local pend = get_slider_ele_pos_for(element, range[\"end\"])\n\n                    if slider_lo.rtype == \"slider\" then\n                        ass_draw_rr_h_cw(elem_ass, pstart, foH - innerH / 21,\n                                         pend, foH + innerH / 21,\n                                         innerH / 21, slider_lo.stype == \"diamond\")\n                    elseif slider_lo.rtype == \"line\" then\n                        if slider_lo.stype == \"bar\" then\n                            elem_ass:rect_cw(pstart, elem_geo.h - foV - seekRangeLineHeight,\n                                             pend, elem_geo.h - foV)\n                        else\n                            ass_draw_rr_h_cw(elem_ass, pstart - innerH / 8, foH - innerH / 8,\n                                             pend + innerH / 8, foH + innerH / 8,\n                                             innerH / 8, slider_lo.stype == \"diamond\")\n                        end\n                    elseif slider_lo.rtype == \"bar\" then\n                        if slider_lo.stype ~= \"bar\" then\n                            ass_draw_rr_h_cw(elem_ass, pstart - innerH / 2, foV,\n                                             pend + innerH / 2, foV + innerH,\n                                             innerH / 2, slider_lo.stype == \"diamond\")\n                        elseif range[\"end\"] >= (pos or 0) then\n                            elem_ass:rect_cw(pstart, foV, pend, elem_geo.h - foV)\n                        else\n                            elem_ass:rect_cw(pstart, elem_geo.h - foV - seekRangeLineHeight, pend,\n                                             elem_geo.h - foV)\n                        end\n                    elseif slider_lo.rtype == \"inverted\" then\n                        if slider_lo.stype ~= \"bar\" then\n                            ass_draw_rr_h_ccw(elem_ass, pstart, (elem_geo.h / 2) - 1, pend,\n                                              (elem_geo.h / 2) + 1,\n                                              1, slider_lo.stype == \"diamond\")\n                        else\n                            elem_ass:rect_ccw(pstart, (elem_geo.h / 2) - 1, pend,\n                                              (elem_geo.h / 2) + 1)\n                        end\n                    end\n                end\n            end\n\n            elem_ass:draw_stop()\n\n            -- add tooltip\n            if element.slider.tooltipF ~= nil then\n                if mouse_hit(element) then\n                    local sliderpos = get_slider_value(element)\n                    local tooltiplabel = element.slider.tooltipF(sliderpos)\n\n                    local an = slider_lo.tooltip_an\n\n                    local ty\n\n                    if an == 2 then\n                        ty = element.hitbox.y1 - slider_lo.border\n                    else\n                        ty = element.hitbox.y1 + elem_geo.h / 2\n                    end\n\n                    local tx = get_virt_mouse_pos()\n                    if slider_lo.adjust_tooltip then\n                        if an == 2 then\n                            if sliderpos < (s_min + 3) then\n                                an = an - 1\n                            elseif sliderpos > (s_max - 3) then\n                                an = an + 1\n                            end\n                        elseif sliderpos > (s_max+s_min) / 2 then\n                            an = an + 1\n                            tx = tx - 5\n                        else\n                            an = an - 1\n                            tx = tx + 10\n                        end\n                    end\n\n                    -- tooltip label\n                    elem_ass:new_event()\n                    elem_ass:pos(tx, ty)\n                    elem_ass:an(an)\n                    elem_ass:append(slider_lo.tooltip_style)\n                    ass_append_alpha(elem_ass, slider_lo.alpha, 0)\n                    elem_ass:append(tooltiplabel)\n\n                end\n            end\n\n        elseif element.type == \"button\" then\n\n            local buttontext\n            if type(element.content) == \"function\" then\n                buttontext = element.content() -- function objects\n            elseif element.content ~= nil then\n                buttontext = element.content -- text objects\n            end\n\n            local maxchars = element.layout.button.maxchars\n            if maxchars ~= nil and #buttontext > maxchars then\n                local max_ratio = 1.25  -- up to 25% more chars while shrinking\n                local limit = math.max(0, math.floor(maxchars * max_ratio) - 3)\n                if #buttontext > limit then\n                    while (#buttontext > limit) do\n                        buttontext = buttontext:gsub(\".[\\128-\\191]*$\", \"\")\n                    end\n                    buttontext = buttontext .. \"...\"\n                end\n                buttontext = string.format(\"{\\\\fscx%f}\",\n                    (maxchars/#buttontext)*100) .. buttontext\n            end\n\n            elem_ass:append(buttontext)\n        end\n\n        master_ass:merge(elem_ass)\n    end\nend\n\n\n--\n-- Initialisation and Layout\n--\n\nlocal function new_element(name, type)\n    elements[name] = {}\n    elements[name].type = type\n\n    -- add default stuff\n    elements[name].eventresponder = {}\n    elements[name].visible = true\n    elements[name].enabled = true\n    elements[name].softrepeat = false\n    elements[name].styledown = (type == \"button\")\n    elements[name].state = {}\n\n    if type == \"slider\" then\n        elements[name].slider = {min = {value = 0}, max = {value = 100}}\n    end\n\n\n    return elements[name]\nend\n\nlocal function add_layout(name)\n    if elements[name] ~= nil then\n        -- new layout\n        elements[name].layout = {}\n\n        -- set layout defaults\n        elements[name].layout.layer = 50\n        elements[name].layout.alpha = {[1] = 0, [2] = 255, [3] = 255, [4] = 255}\n\n        if elements[name].type == \"button\" then\n            elements[name].layout.button = {\n                maxchars = nil,\n            }\n        elseif elements[name].type == \"slider\" then\n            -- slider defaults\n            elements[name].layout.slider = {\n                border = 1,\n                gap = 1,\n                nibbles_top = true,\n                nibbles_bottom = true,\n                stype = \"slider\",\n                adjust_tooltip = true,\n                tooltip_style = \"\",\n                tooltip_an = 2,\n                alpha = {[1] = 0, [2] = 255, [3] = 88, [4] = 255},\n            }\n        elseif elements[name].type == \"box\" then\n            elements[name].layout.box = {radius = 0, hexagon = false}\n        end\n\n        return elements[name].layout\n    else\n        msg.error(\"Can't add_layout to element '\"..name..\"', doesn't exist.\")\n    end\nend\n\n-- Window Controls\nlocal function window_controls(topbar)\n    local wc_geo = {\n        x = 0,\n        y = 30 + user_opts.barmargin,\n        an = 1,\n        w = osc_param.playresx,\n        h = 30,\n    }\n\n    local alignment = window_controls_alignment()\n    local controlbox_w = window_control_box_width\n    local titlebox_w = wc_geo.w - controlbox_w\n\n    -- Default alignment is \"right\"\n    local controlbox_left = wc_geo.w - controlbox_w\n    local titlebox_left = wc_geo.x\n    local titlebox_right = wc_geo.w - controlbox_w\n\n    if alignment == \"left\" then\n        controlbox_left = wc_geo.x\n        titlebox_left = wc_geo.x + controlbox_w\n        titlebox_right = wc_geo.w\n    end\n\n    add_area(\"window-controls\",\n             get_hitbox_coords(controlbox_left, wc_geo.y, wc_geo.an,\n                               controlbox_w, wc_geo.h))\n\n    local lo\n\n    -- Background Bar\n    new_element(\"wcbar\", \"box\")\n    lo = add_layout(\"wcbar\")\n    lo.geometry = wc_geo\n    lo.layer = 10\n    lo.style = osc_styles.wcBar\n    lo.alpha[1] = user_opts.boxalpha\n\n    local button_y = wc_geo.y - (wc_geo.h / 2)\n    local first_geo =\n        {x = controlbox_left + 5, y = button_y, an = 4, w = 25, h = 25}\n    local second_geo =\n        {x = controlbox_left + 30, y = button_y, an = 4, w = 25, h = 25}\n    local third_geo =\n        {x = controlbox_left + 55, y = button_y, an = 4, w = 25, h = 25}\n\n    -- Window control buttons use symbols in the custom mpv osd font\n    -- because the official unicode codepoints are sufficiently\n    -- exotic that a system might lack an installed font with them,\n    -- and libass will complain that they are not present in the\n    -- default font, even if another font with them is available.\n\n    -- Close: 🗙\n    local ne = new_element(\"close\", \"button\")\n    ne.content = icons.close\n    ne.eventresponder[\"mbtn_left_up\"] =\n        function () mp.commandv(\"quit\") end\n    lo = add_layout(\"close\")\n    lo.geometry = alignment == \"left\" and first_geo or third_geo\n    lo.style = osc_styles.wcButtons\n\n    -- Minimize: 🗕\n    ne = new_element(\"minimize\", \"button\")\n    ne.content = icons.minimize\n    ne.eventresponder[\"mbtn_left_up\"] =\n        function () mp.commandv(\"cycle\", \"window-minimized\") end\n    lo = add_layout(\"minimize\")\n    lo.geometry = alignment == \"left\" and second_geo or first_geo\n    lo.style = osc_styles.wcButtons\n\n    -- Maximize: 🗖 /🗗\n    ne = new_element(\"maximize\", \"button\")\n    if state.maximized or state.fullscreen then\n        ne.content = icons.unmaximize\n    else\n        ne.content = icons.maximize\n    end\n    ne.eventresponder[\"mbtn_left_up\"] =\n        function ()\n            if state.fullscreen then\n                mp.commandv(\"cycle\", \"fullscreen\")\n            else\n                mp.commandv(\"cycle\", \"window-maximized\")\n            end\n        end\n    lo = add_layout(\"maximize\")\n    lo.geometry = alignment == \"left\" and third_geo or second_geo\n    lo.style = osc_styles.wcButtons\n\n    -- deadzone below window controls\n    local sh_area_y0, sh_area_y1\n    sh_area_y0 = user_opts.barmargin\n    sh_area_y1 = wc_geo.y + get_align(1 - (2 * user_opts.deadzonesize),\n                                      osc_param.playresy - wc_geo.y, 0, 0)\n    add_area(\"showhide_wc\", wc_geo.x, sh_area_y0, wc_geo.w, sh_area_y1)\n\n    if topbar then\n        -- The title is already there as part of the top bar\n        return\n    else\n        -- Apply boxvideo margins to the control bar\n        osc_param.video_margins.t = wc_geo.h / osc_param.playresy\n    end\n\n    -- Window Title\n    ne = new_element(\"wctitle\", \"button\")\n    ne.content = function ()\n        local title = mp.command_native({\"expand-text\", user_opts.windowcontrols_title})\n        title = title:gsub(\"\\n\", \" \")\n        return title ~= \"\" and mp.command_native({\"escape-ass\", title}) or \"mpv\"\n    end\n    local left_pad = 5\n    local right_pad = 10\n    lo = add_layout(\"wctitle\")\n    lo.geometry =\n        { x = titlebox_left + left_pad, y = wc_geo.y - 3, an = 1,\n          w = titlebox_w, h = wc_geo.h }\n    lo.style = string.format(\"%s{\\\\clip(%f,%f,%f,%f)}\",\n        osc_styles.wcTitle,\n        titlebox_left + left_pad, wc_geo.y - wc_geo.h,\n        titlebox_right - right_pad , wc_geo.y + wc_geo.h)\n\n    add_area(\"window-controls-title\",\n             titlebox_left, 0, titlebox_right, wc_geo.h)\nend\n\n\n--\n-- Layouts\n--\n\n-- Classic box layout\nlayouts[\"box\"] = function ()\n\n    local osc_geo = {\n        w = 550,    -- width\n        h = 138,    -- height\n        r = 10,     -- corner-radius\n        p = 15,     -- padding\n    }\n\n    -- make sure the OSC actually fits into the video\n    if osc_param.playresx < (osc_geo.w + (2 * osc_geo.p)) then\n        osc_param.playresy = (osc_geo.w + (2 * osc_geo.p)) / osc_param.display_aspect\n        osc_param.playresx = osc_param.playresy * osc_param.display_aspect\n    end\n\n    -- position of the controller according to video aspect and valignment\n    local posX = math.floor(get_align(user_opts.halign, osc_param.playresx,\n        osc_geo.w, 0))\n    local posY = math.floor(get_align(user_opts.valign, osc_param.playresy,\n        osc_geo.h, 0))\n\n    -- position offset for contents aligned at the borders of the box\n    local pos_offsetX = (osc_geo.w - (2*osc_geo.p)) / 2\n    local pos_offsetY = (osc_geo.h - (2*osc_geo.p)) / 2\n\n    osc_param.areas = {} -- delete areas\n\n    -- area for active mouse input\n    add_area(\"input\", get_hitbox_coords(posX, posY, 5, osc_geo.w, osc_geo.h))\n\n    -- area for show/hide\n    local sh_area_y0, sh_area_y1\n    if user_opts.valign > 0 then\n        -- deadzone above OSC\n        sh_area_y0 = get_align(-1 + (2*user_opts.deadzonesize),\n            posY - (osc_geo.h / 2), 0, 0)\n        sh_area_y1 = osc_param.playresy\n    else\n        -- deadzone below OSC\n        sh_area_y0 = 0\n        sh_area_y1 = (posY + (osc_geo.h / 2)) +\n            get_align(1 - (2*user_opts.deadzonesize),\n            osc_param.playresy - (posY + (osc_geo.h / 2)), 0, 0)\n    end\n    add_area(\"showhide\", 0, sh_area_y0, osc_param.playresx, sh_area_y1)\n\n    -- fetch values\n    local osc_w, osc_h, osc_r = osc_geo.w, osc_geo.h, osc_geo.r\n\n    local lo\n\n    --\n    -- Background box\n    --\n\n    new_element(\"bgbox\", \"box\")\n    lo = add_layout(\"bgbox\")\n\n    lo.geometry = {x = posX, y = posY, an = 5, w = osc_w, h = osc_h}\n    lo.layer = 10\n    lo.style = osc_styles.box\n    lo.alpha[1] = user_opts.boxalpha\n    lo.alpha[3] = user_opts.boxalpha\n    lo.box.radius = osc_r\n\n    --\n    -- Title row\n    --\n\n    local titlerowY = posY - pos_offsetY - 10\n\n    lo = add_layout(\"title\")\n    lo.geometry = {x = posX, y = titlerowY, an = 8, w = 496, h = 12}\n    lo.style = osc_styles.vidtitle\n    lo.button.maxchars = user_opts.boxmaxchars\n\n    lo = add_layout(\"playlist_prev\")\n    lo.geometry =\n        {x = (posX - pos_offsetX), y = titlerowY, an = 7, w = 12, h = 12}\n    lo.style = osc_styles.topButtons\n\n    lo = add_layout(\"playlist_next\")\n    lo.geometry =\n        {x = (posX + pos_offsetX), y = titlerowY, an = 9, w = 12, h = 12}\n    lo.style = osc_styles.topButtons\n\n    --\n    -- Big buttons\n    --\n\n    local bigbtnrowY = posY - pos_offsetY + 35\n    local bigbtndist = 60\n\n    lo = add_layout(\"play_pause\")\n    lo.geometry =\n        {x = posX, y = bigbtnrowY, an = 5, w = 40, h = 40}\n    lo.style = osc_styles.bigButtons\n\n    lo = add_layout(\"skip_backward\")\n    lo.geometry =\n        {x = posX - bigbtndist, y = bigbtnrowY, an = 5, w = 40, h = 40}\n    lo.style = osc_styles.bigButtons\n\n    lo = add_layout(\"skip_forward\")\n    lo.geometry =\n        {x = posX + bigbtndist, y = bigbtnrowY, an = 5, w = 40, h = 40}\n    lo.style = osc_styles.bigButtons\n\n    lo = add_layout(\"chapter_prev\")\n    lo.geometry =\n        {x = posX - (bigbtndist * 2), y = bigbtnrowY, an = 5, w = 40, h = 40}\n    lo.style = osc_styles.bigButtons\n\n    lo = add_layout(\"chapter_next\")\n    lo.geometry =\n        {x = posX + (bigbtndist * 2), y = bigbtnrowY, an = 5, w = 40, h = 40}\n    lo.style = osc_styles.bigButtons\n\n    lo = add_layout(\"audio_track\")\n    lo.geometry =\n        {x = posX - pos_offsetX, y = bigbtnrowY, an = 1, w = 70, h = 18}\n    lo.style = osc_styles.smallButtonsL\n\n    lo = add_layout(\"sub_track\")\n    lo.geometry =\n        {x = posX - pos_offsetX, y = bigbtnrowY, an = 7, w = 70, h = 18}\n    lo.style = osc_styles.smallButtonsL\n\n    lo = add_layout(\"fullscreen\")\n    lo.geometry =\n        {x = posX+pos_offsetX - 25, y = bigbtnrowY, an = 4, w = 25, h = 25}\n    lo.style = osc_styles.smallButtonsR\n\n    lo = add_layout(\"volume\")\n    lo.geometry =\n        {x = posX+pos_offsetX - (25 * 2) - osc_geo.p,\n         y = bigbtnrowY, an = 4, w = 25, h = 25}\n    lo.style = osc_styles.smallButtonsR\n\n    --\n    -- Seekbar\n    --\n\n    lo = add_layout(\"seekbar\")\n    lo.geometry =\n        {x = posX, y = posY+pos_offsetY-22, an = 2, w = pos_offsetX*2, h = 15}\n    lo.style = osc_styles.timecodes\n    lo.slider.tooltip_style = osc_styles.vidtitle\n    lo.slider.stype = user_opts[\"seekbarstyle\"]\n    lo.slider.rtype = user_opts[\"seekrangestyle\"]\n\n    --\n    -- Timecodes + Cache\n    --\n\n    local bottomrowY = posY + pos_offsetY - 5\n\n    lo = add_layout(\"tc_left\")\n    lo.geometry =\n        {x = posX - pos_offsetX, y = bottomrowY, an = 4, w = 110, h = 18}\n    lo.style = osc_styles.timecodes\n\n    lo = add_layout(\"tc_right\")\n    lo.geometry =\n        {x = posX + pos_offsetX, y = bottomrowY, an = 6, w = 110, h = 18}\n    lo.style = osc_styles.timecodes\n\n    lo = add_layout(\"cache\")\n    lo.geometry =\n        {x = posX, y = bottomrowY, an = 5, w = 110, h = 18}\n    lo.style = osc_styles.timecodes\n\nend\n\n-- slim box layout\nlayouts[\"slimbox\"] = function ()\n\n    local osc_geo = {\n        w = 660,    -- width\n        h = 70,     -- height\n        r = 10,     -- corner-radius\n    }\n\n    -- make sure the OSC actually fits into the video\n    if osc_param.playresx < (osc_geo.w) then\n        osc_param.playresy = (osc_geo.w) / osc_param.display_aspect\n        osc_param.playresx = osc_param.playresy * osc_param.display_aspect\n    end\n\n    -- position of the controller according to video aspect and valignment\n    local posX = math.floor(get_align(user_opts.halign, osc_param.playresx,\n        osc_geo.w, 0))\n    local posY = math.floor(get_align(user_opts.valign, osc_param.playresy,\n        osc_geo.h, 0))\n\n    osc_param.areas = {} -- delete areas\n\n    -- area for active mouse input\n    add_area(\"input\", get_hitbox_coords(posX, posY, 5, osc_geo.w, osc_geo.h))\n\n    -- area for show/hide\n    local sh_area_y0, sh_area_y1\n    if user_opts.valign > 0 then\n        -- deadzone above OSC\n        sh_area_y0 = get_align(-1 + (2*user_opts.deadzonesize),\n            posY - (osc_geo.h / 2), 0, 0)\n        sh_area_y1 = osc_param.playresy\n    else\n        -- deadzone below OSC\n        sh_area_y0 = 0\n        sh_area_y1 = (posY + (osc_geo.h / 2)) +\n            get_align(1 - (2*user_opts.deadzonesize),\n            osc_param.playresy - (posY + (osc_geo.h / 2)), 0, 0)\n    end\n    add_area(\"showhide\", 0, sh_area_y0, osc_param.playresx, sh_area_y1)\n\n    local lo\n\n    local tc_w, ele_h, inner_w = 100, 20, osc_geo.w - 100\n\n    -- styles\n    local styles = {\n        box = \"{\\\\rDefault\\\\blur0\\\\bord1\\\\1c&H\" ..\n              osc_color_convert(user_opts.background_color) .. \"\\\\3c&HFFFFFF}\",\n        timecodes = \"{\\\\1c&H\" .. osc_color_convert(user_opts.timecode_color) .. \"\\\\3c&H\" ..\n                    osc_color_convert(user_opts.time_pos_outline_color) .. \"\\\\fs20\\\\bord2\\\\blur1}\",\n        tooltip = \"{\\\\1c&H\" .. osc_color_convert(user_opts.time_pos_color).. \"\\\\3c&H\" ..\n                  osc_color_convert(user_opts.time_pos_outline_color) .. \"\\\\fs12\\\\bord1\\\\blur0.5}\",\n    }\n\n\n    new_element(\"bgbox\", \"box\")\n    lo = add_layout(\"bgbox\")\n\n    lo.geometry = {x = posX, y = posY - 1, an = 2, w = inner_w, h = ele_h}\n    lo.layer = 10\n    lo.style = osc_styles.box\n    lo.alpha[1] = user_opts.boxalpha\n    lo.alpha[3] = 0\n    if user_opts[\"seekbarstyle\"] ~= \"bar\" then\n        lo.box.radius = osc_geo.r\n        lo.box.hexagon = user_opts[\"seekbarstyle\"] == \"diamond\"\n    end\n\n\n    lo = add_layout(\"seekbar\")\n    lo.geometry =\n        {x = posX, y = posY - 1, an = 2, w = inner_w, h = ele_h}\n    lo.style = osc_styles.timecodes\n    lo.slider.border = 0\n    lo.slider.gap = 1.5\n    lo.slider.tooltip_style = styles.tooltip\n    lo.slider.stype = user_opts[\"seekbarstyle\"]\n    lo.slider.rtype = user_opts[\"seekrangestyle\"]\n    lo.slider.adjust_tooltip = false\n\n    --\n    -- Timecodes\n    --\n\n    lo = add_layout(\"tc_left\")\n    lo.geometry =\n        {x = posX - (inner_w/2) + osc_geo.r, y = posY + 1,\n        an = 7, w = tc_w, h = ele_h}\n    lo.style = styles.timecodes\n    lo.alpha[3] = user_opts.boxalpha\n\n    lo = add_layout(\"tc_right\")\n    lo.geometry =\n        {x = posX + (inner_w/2) - osc_geo.r, y = posY + 1,\n        an = 9, w = tc_w, h = ele_h}\n    lo.style = styles.timecodes\n    lo.alpha[3] = user_opts.boxalpha\n\n    -- Cache\n\n    lo = add_layout(\"cache\")\n    lo.geometry =\n        {x = posX, y = posY + 1,\n        an = 8, w = tc_w, h = ele_h}\n    lo.style = styles.timecodes\n    lo.alpha[3] = user_opts.boxalpha\nend\n\nlocal function bar_layout(direction, slim)\n    local osc_geo = {\n        x = -2,\n        y = nil,\n        an = (direction < 0) and 7 or 1,\n        w = nil,\n        h = slim and 25 or 56,\n    }\n\n    local padX = 9\n    local padY = 3\n    local buttonW = 27\n    local tcW = (state.tc_ms) and 170 or 110\n    if user_opts.tcspace >= 50 and user_opts.tcspace <= 200 then\n        -- adjust our hardcoded font size estimation\n        tcW = tcW * user_opts.tcspace / 100\n    end\n\n    local tsW = 90\n    local minW = (buttonW + padX)*5 + (tcW + padX)*4 + (tsW + padX)*2\n\n    -- Special topbar handling when window controls are present\n    local padwc_l\n    local padwc_r\n    if direction < 0 or not window_controls_enabled() then\n        padwc_l = 0\n        padwc_r = 0\n    elseif window_controls_alignment() == \"left\" then\n        padwc_l = window_control_box_width\n        padwc_r = 0\n    else\n        padwc_l = 0\n        padwc_r = window_control_box_width\n    end\n\n    if osc_param.display_aspect > 0 and osc_param.playresx < minW then\n        osc_param.playresy = minW / osc_param.display_aspect\n        osc_param.playresx = osc_param.playresy * osc_param.display_aspect\n    end\n\n    osc_geo.y = direction * (osc_geo.h - 2 + user_opts.barmargin)\n    osc_geo.w = osc_param.playresx + 4\n    if direction < 0 then\n        osc_geo.y = osc_geo.y + osc_param.playresy\n    end\n\n    if direction < 0 then\n        osc_param.video_margins.b = osc_geo.h / osc_param.playresy\n    else\n        osc_param.video_margins.t = osc_geo.h / osc_param.playresy\n    end\n\n    local line1 = osc_geo.y - direction * (9 + padY)\n    local line2 = osc_geo.y - direction * (36 + padY)\n\n    osc_param.areas = {}\n\n    add_area(\"input\", get_hitbox_coords(osc_geo.x, osc_geo.y, osc_geo.an,\n                                        osc_geo.w, osc_geo.h))\n\n    local sh_area_y0, sh_area_y1\n    if direction > 0 then\n        -- deadzone below OSC\n        sh_area_y0 = user_opts.barmargin\n        sh_area_y1 = osc_geo.y + get_align(1 - (2 * user_opts.deadzonesize),\n                                           osc_param.playresy - osc_geo.y, 0, 0)\n    else\n        -- deadzone above OSC\n        sh_area_y0 = get_align(-1 + (2 * user_opts.deadzonesize), osc_geo.y, 0, 0)\n        sh_area_y1 = osc_param.playresy - user_opts.barmargin\n    end\n    add_area(\"showhide\", 0, sh_area_y0, osc_param.playresx, sh_area_y1)\n\n    local lo, geo\n\n    -- Background bar\n    new_element(\"bgbox\", \"box\")\n    lo = add_layout(\"bgbox\")\n\n    lo.geometry = osc_geo\n    lo.layer = 10\n    lo.style = osc_styles.box\n    lo.alpha[1] = user_opts.boxalpha\n\n\n    -- Menu\n    geo = { x = osc_geo.x + padX + 4, y = line1, an = 4, w = 18, h = 18 - padY }\n    lo = add_layout(\"menu\")\n    lo.geometry = geo\n    lo.style = osc_styles.topButtonsBar\n\n    -- Playlist prev/next\n    geo = { x = geo.x + geo.w + padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n    lo = add_layout(\"playlist_prev\")\n    lo.geometry = geo\n    lo.style = osc_styles.topButtonsBar\n\n    geo = { x = geo.x + geo.w + padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n    lo = add_layout(\"playlist_next\")\n    lo.geometry = geo\n    lo.style = osc_styles.topButtonsBar\n\n    local t_l = geo.x + geo.w + padX\n\n    -- Custom buttons\n    local t_r = osc_geo.x + osc_geo.w\n\n    for i = last_custom_button, 1, -1 do\n        t_r = t_r - padX\n        geo = { x = t_r, y = geo.y, an = 6, w = geo.w, h = geo.h }\n        t_r = t_r - geo.w\n        lo = add_layout(\"custom_button_\" .. i)\n        lo.geometry = geo\n        lo.style = osc_styles.vidtitleBar\n    end\n\n    t_r = t_r - padX\n\n    if slim then\n        -- Fullscreen button\n        geo = { x = t_r, y = geo.y, an = 6, w = buttonW, h = geo.h }\n        lo = add_layout(\"fullscreen\")\n        lo.geometry = geo\n        lo.style = osc_styles.topButtonsBar\n    else\n        -- Cache\n        geo = { x = t_r, y = geo.y, an = 6, w = 150, h = geo.h }\n        lo = add_layout(\"cache\")\n        lo.geometry = geo\n        lo.style = osc_styles.vidtitleBar\n    end\n\n    t_r = t_r - geo.w - padX\n\n    -- Title\n    geo = { x = t_l, y = geo.y, an = 4,\n            w = t_r - t_l, h = geo.h }\n    lo = add_layout(\"title\")\n    lo.geometry = geo\n    lo.style = string.format(\"%s{\\\\clip(%f,%f,%f,%f)}\",\n        osc_styles.vidtitleBar,\n        geo.x, geo.y-geo.h, geo.w, geo.y+geo.h)\n\n    if slim then\n        return\n    end\n\n    -- Playback control buttons\n    geo = { x = osc_geo.x + padX + padwc_l, y = line2, an = 4,\n            w = buttonW, h = 36 - padY*2}\n    lo = add_layout(\"play_pause\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n\n    geo = { x = geo.x + geo.w + padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n    lo = add_layout(\"chapter_prev\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n\n    geo = { x = geo.x + geo.w + padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n    lo = add_layout(\"chapter_next\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n\n    -- Left timecode\n    geo = { x = geo.x + geo.w + padX + tcW, y = geo.y, an = 6,\n            w = tcW, h = geo.h }\n    lo = add_layout(\"tc_left\")\n    lo.geometry = geo\n    lo.style = osc_styles.timecodesBar\n\n    local sb_l = geo.x + padX\n\n    -- Fullscreen button\n    geo = { x = osc_geo.x + osc_geo.w - buttonW - padX - padwc_r, y = geo.y, an = 4,\n            w = buttonW, h = geo.h }\n    lo = add_layout(\"fullscreen\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n\n    -- START quality-menu\n    geo = { x = geo.x - geo.w - padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n    lo = add_layout(\"quality-menu\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n    -- END quality-menu\n\n    -- Volume\n    geo = { x = geo.x - geo.w - padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n    lo = add_layout(\"volume\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n\n    -- Track selection buttons\n    geo = { x = geo.x - tsW - padX, y = geo.y, an = geo.an, w = tsW, h = geo.h }\n    lo = add_layout(\"sub_track\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n\n    geo = { x = geo.x - geo.w - padX, y = geo.y, an = geo.an, w = geo.w, h = geo.h }\n    lo = add_layout(\"audio_track\")\n    lo.geometry = geo\n    lo.style = osc_styles.smallButtonsBar\n\n\n    -- Right timecode\n    geo = { x = geo.x - padX - tcW - 10, y = geo.y, an = geo.an,\n            w = tcW, h = geo.h }\n    lo = add_layout(\"tc_right\")\n    lo.geometry = geo\n    lo.style = osc_styles.timecodesBar\n\n    local sb_r = geo.x - padX\n\n\n    -- Seekbar\n    geo = { x = sb_l, y = geo.y, an = geo.an,\n            w = math.max(0, sb_r - sb_l), h = geo.h }\n    new_element(\"bgbar1\", \"box\")\n    lo = add_layout(\"bgbar1\")\n\n    lo.geometry = geo\n    lo.layer = 15\n    lo.style = osc_styles.timecodesBar\n    lo.alpha[1] =\n        math.min(255, user_opts.boxalpha + (255 - user_opts.boxalpha)*0.8)\n    if user_opts[\"seekbarstyle\"] ~= \"bar\" then\n        lo.box.radius = geo.h / 2\n        lo.box.hexagon = user_opts[\"seekbarstyle\"] == \"diamond\"\n    end\n\n    lo = add_layout(\"seekbar\")\n    lo.geometry = geo\n    lo.style = osc_styles.timecodesBar\n    lo.slider.border = 0\n    lo.slider.gap = 2\n    lo.slider.tooltip_style = osc_styles.timePosBar\n    lo.slider.tooltip_an = 5\n    lo.slider.stype = user_opts[\"seekbarstyle\"]\n    lo.slider.rtype = user_opts[\"seekrangestyle\"]\nend\n\nlayouts[\"bottombar\"] = function()\n    bar_layout(-1)\nend\n\nlayouts[\"topbar\"] = function()\n    bar_layout(1)\nend\n\nlayouts[\"slimbottombar\"] = function()\n    bar_layout(-1, true)\nend\n\nlayouts[\"slimtopbar\"] = function()\n    bar_layout(1, true)\nend\n\n\nlocal function bind_mouse_buttons(element_name)\n    for _, button in pairs({\"mbtn_left\", \"mbtn_mid\", \"mbtn_right\"}) do\n        local command = user_opts[element_name .. \"_\" .. button .. \"_command\"]\n\n        if command ~= \"\" then\n            elements[element_name].eventresponder[button .. \"_up\"] = function ()\n                mp.command(command)\n            end\n        end\n    end\n\n    if user_opts.scrollcontrols then\n        for _, button in pairs({\"wheel_down\", \"wheel_up\"}) do\n            local command = user_opts[element_name .. \"_\" .. button .. \"_command\"]\n\n            if command and command ~= \"\" then\n                elements[element_name].eventresponder[button .. \"_press\"] = function ()\n                    mp.command(command)\n                end\n            end\n        end\n    end\nend\n\nlocal function osc_init()\n    msg.debug(\"osc_init\")\n\n    -- set canvas resolution according to display aspect and scaling setting\n    local baseResY = 720\n    local _, display_h, display_aspect = mp.get_osd_size()\n    local scale\n\n    if state.fullscreen then\n        scale = user_opts.scalefullscreen\n    else\n        scale = user_opts.scalewindowed\n    end\n\n    local scale_with_video\n    if user_opts.vidscale == \"auto\" then\n        scale_with_video = mp.get_property_native(\"osd-scale-by-window\")\n    else\n        scale_with_video = user_opts.vidscale == \"yes\"\n    end\n\n    if scale_with_video then\n        osc_param.unscaled_y = baseResY\n    else\n        osc_param.unscaled_y = display_h\n    end\n    osc_param.playresy = osc_param.unscaled_y / scale\n    if display_aspect > 0 then\n        osc_param.display_aspect = display_aspect\n    end\n    osc_param.playresx = osc_param.playresy * osc_param.display_aspect\n\n    -- stop seeking with the slider to prevent skipping files\n    state.active_element = nil\n\n    osc_param.video_margins = {l = 0, r = 0, t = 0, b = 0}\n\n    elements = {}\n\n    -- some often needed stuff\n    local pl_count = mp.get_property_number(\"playlist-count\", 0)\n    local have_pl = (pl_count > 1)\n    local pl_pos = mp.get_property_number(\"playlist-pos\", 0) + 1\n    local have_ch = (mp.get_property_number(\"chapters\", 0) > 0)\n    local loop = mp.get_property(\"loop-playlist\", \"no\")\n\n    local ne\n\n    -- title\n    ne = new_element(\"title\", \"button\")\n\n    ne.content = function ()\n        local title = state.forced_title or\n                      mp.command_native({\"expand-text\", user_opts.title})\n        title = title:gsub(\"\\n\", \" \")\n        return title ~= \"\" and mp.command_native({\"escape-ass\", title}) or \"mpv\"\n    end\n    bind_mouse_buttons(\"title\")\n\n    -- menu\n    ne = new_element(\"menu\", \"button\")\n    ne.content = icons.menu\n    bind_mouse_buttons(\"menu\")\n\n    -- playlist buttons\n\n    -- prev\n    ne = new_element(\"playlist_prev\", \"button\")\n\n    ne.content = icons.prev\n    ne.enabled = (pl_pos > 1) or (loop ~= \"no\")\n    bind_mouse_buttons(\"playlist_prev\")\n\n    --next\n    ne = new_element(\"playlist_next\", \"button\")\n\n    ne.content = icons.next\n    ne.enabled = (have_pl and (pl_pos < pl_count)) or (loop ~= \"no\")\n    bind_mouse_buttons(\"playlist_next\")\n\n\n    -- big buttons\n\n    --play_pause\n    ne = new_element(\"play_pause\", \"button\")\n\n    ne.content = function ()\n        if not mp.get_property_native(\"pause\") then\n            return icons.pause\n        end\n\n        return mp.get_property(\"play-direction\") == \"forward\"\n            and icons.play\n            or icons.play_backward\n    end\n    bind_mouse_buttons(\"play_pause\")\n\n    --skip_backward\n    ne = new_element(\"skip_backward\", \"button\")\n\n    ne.softrepeat = true\n    ne.content = icons.skip_backward\n    ne.eventresponder[\"mbtn_left_down\"] =\n        function () mp.commandv(\"seek\", -5) end\n    ne.eventresponder[\"mbtn_mid\"] =\n        function () mp.commandv(\"frame-back-step\") end\n    ne.eventresponder[\"mbtn_right_down\"] =\n        function () mp.commandv(\"seek\", -30) end\n\n    --skip_forward\n    ne = new_element(\"skip_forward\", \"button\")\n\n    ne.softrepeat = true\n    ne.content = icons.skip_forward\n    ne.eventresponder[\"mbtn_left_down\"] =\n        function () mp.commandv(\"seek\", 10) end\n    ne.eventresponder[\"mbtn_mid\"] =\n        function () mp.commandv(\"frame-step\") end\n    ne.eventresponder[\"mbtn_right_down\"] =\n        function () mp.commandv(\"seek\", 60) end\n\n    --chapter_prev\n    ne = new_element(\"chapter_prev\", \"button\")\n\n    ne.enabled = have_ch\n    ne.content = icons.chapter_prev\n    bind_mouse_buttons(\"chapter_prev\")\n\n    --chapter_next\n    ne = new_element(\"chapter_next\", \"button\")\n\n    ne.enabled = have_ch\n    ne.content = icons.chapter_next\n    bind_mouse_buttons(\"chapter_next\")\n\n    --\n    update_tracklist()\n\n    --audio_track\n    ne = new_element(\"audio_track\", \"button\")\n\n    ne.enabled = audio_track_count > 0\n    ne.content = function ()\n        return icons.audio .. osc_styles.smallButtonsLlabel .. \" \" ..\n               mp.get_property_number(\"aid\", \"-\") .. \"/\" .. audio_track_count\n    end\n    bind_mouse_buttons(\"audio_track\")\n\n    --sub_track\n    ne = new_element(\"sub_track\", \"button\")\n\n    ne.enabled = sub_track_count > 0\n    ne.content = function ()\n        return icons.subtitle .. osc_styles.smallButtonsLlabel .. \" \" ..\n               mp.get_property_number(\"sid\", \"-\") .. \"/\" .. sub_track_count\n    end\n    bind_mouse_buttons(\"sub_track\")\n\n    --fullscreen\n    ne = new_element(\"fullscreen\", \"button\")\n    ne.content = function ()\n        return state.fullscreen and icons.exit_fullscreen or icons.fullscreen\n    end\n    bind_mouse_buttons(\"fullscreen\")\n\n    --seekbar\n    ne = new_element(\"seekbar\", \"slider\")\n\n    ne.enabled = mp.get_property(\"percent-pos\") ~= nil\n                 and user_opts.layout ~= \"slimbottombar\"\n                 and user_opts.layout ~= \"slimtopbar\"\n    state.slider_element = ne.enabled and ne or nil  -- used for forced_title\n    ne.slider.markerF = function ()\n        local duration = mp.get_property_number(\"duration\")\n        if duration ~= nil then\n            local chapters = mp.get_property_native(\"chapter-list\", {})\n            local markers = {}\n            for n = 1, #chapters do\n                markers[n] = (chapters[n].time / duration * 100)\n            end\n            return markers\n        else\n            return {}\n        end\n    end\n    ne.slider.posF =\n        function () return mp.get_property_number(\"percent-pos\") end\n    ne.slider.tooltipF = function (pos)\n        local duration = mp.get_property_number(\"duration\")\n        if duration ~= nil and pos ~= nil then\n            local possec = duration * (pos / 100)\n            return mp.format_time(possec)\n        else\n            return \"\"\n        end\n    end\n    ne.slider.seekRangesF = function()\n        if user_opts.seekrangestyle == \"none\" or not cache_enabled() then\n            return nil\n        end\n        local duration = mp.get_property_number(\"duration\")\n        if duration == nil or duration <= 0 then\n            return nil\n        end\n        local nranges = {}\n        for _, range in pairs(state.cache_state[\"seekable-ranges\"]) do\n            nranges[#nranges + 1] = {\n                [\"start\"] = 100 * range[\"start\"] / duration,\n                [\"end\"] = 100 * range[\"end\"] / duration,\n            }\n        end\n        return nranges\n    end\n    ne.eventresponder[\"mouse_move\"] = --keyframe seeking when mouse is dragged\n        function (element)\n            if not element.state.mbtn_left then\n                return\n            end\n\n            -- mouse move events may pile up during seeking and may still get\n            -- sent when the user is done seeking, so we need to throw away\n            -- identical seeks\n            local seekto = get_slider_value(element)\n            if element.state.lastseek == nil or\n                element.state.lastseek ~= seekto then\n                    local flags = \"absolute-percent\"\n                    if not user_opts.seekbarkeyframes then\n                        flags = flags .. \"+exact\"\n                    end\n                    mp.commandv(\"seek\", seekto, flags)\n                    element.state.lastseek = seekto\n            end\n\n        end\n    ne.eventresponder[\"mbtn_left_down\"] = function (element)\n        element.state.mbtn_left = true\n        mp.commandv(\"seek\", get_slider_value(element), \"absolute-percent+exact\")\n    end\n    ne.eventresponder[\"mbtn_left_up\"] = function (element)\n        element.state.mbtn_left = false\n    end\n    ne.eventresponder[\"mbtn_right_up\"] = function (element)\n        local chapter\n        local pos = get_slider_value(element)\n        local diff = math.huge\n\n        for i, marker in ipairs(element.slider.markerF()) do\n            if math.abs(pos - marker) < diff then\n                diff = math.abs(pos - marker)\n                chapter = i\n            end\n        end\n\n        if chapter then\n            mp.set_property(\"chapter\", chapter - 1)\n        end\n    end\n    ne.eventresponder[\"reset\"] =\n        function (element) element.state.lastseek = nil end\n\n    if user_opts.scrollcontrols then\n        ne.eventresponder[\"wheel_up_press\"] =\n            function () mp.commandv(\"osd-auto\", \"seek\",  10) end\n        ne.eventresponder[\"wheel_down_press\"] =\n            function () mp.commandv(\"osd-auto\", \"seek\", -10) end\n    end\n\n\n    -- tc_left (current pos)\n    ne = new_element(\"tc_left\", \"button\")\n\n    ne.content = function ()\n        if state.tc_ms then\n            return (mp.get_property_osd(\"playback-time/full\"))\n        else\n            return (mp.get_property_osd(\"playback-time\"))\n        end\n    end\n    ne.eventresponder[\"mbtn_left_up\"] = function ()\n        state.tc_ms = not state.tc_ms\n        request_init()\n    end\n\n    -- tc_right (total/remaining time)\n    ne = new_element(\"tc_right\", \"button\")\n\n    ne.visible = (mp.get_property_number(\"duration\", 0) > 0)\n    ne.content = function ()\n        if state.rightTC_trem then\n            local minus = user_opts.unicodeminus and UNICODE_MINUS or \"-\"\n            local property = user_opts.remaining_playtime and \"playtime-remaining\"\n                                                           or \"time-remaining\"\n            if state.tc_ms then\n                return (minus..mp.get_property_osd(property .. \"/full\"))\n            else\n                return (minus..mp.get_property_osd(property))\n            end\n        else\n            if state.tc_ms then\n                return (mp.get_property_osd(\"duration/full\"))\n            else\n                return (mp.get_property_osd(\"duration\"))\n            end\n        end\n    end\n    ne.eventresponder[\"mbtn_left_up\"] =\n        function () state.rightTC_trem = not state.rightTC_trem end\n\n    -- cache\n    ne = new_element(\"cache\", \"button\")\n\n    ne.content = function ()\n        if not cache_enabled() then\n            return \"\"\n        end\n        local dmx_cache = state.cache_state[\"cache-duration\"]\n        local thresh = math.min(state.dmx_cache * 0.05, 5)  -- 5% or 5s\n        if dmx_cache and math.abs(dmx_cache - state.dmx_cache) >= thresh then\n            state.dmx_cache = dmx_cache\n        else\n            dmx_cache = state.dmx_cache\n        end\n        local min = math.floor(dmx_cache / 60)\n        local sec = math.floor(dmx_cache % 60) -- don't round e.g. 59.9 to 60\n        return \"Cache: \" .. (min > 0 and\n            string.format(\"%sm%02.0fs\", min, sec) or\n            string.format(\"%3.0fs\", sec))\n    end\n\n    -- START quality-menu\n    ne = new_element(\"quality-menu\", \"button\")\n    ne.content = function()\n        return (\"≚\")\n    end\n    ne.eventresponder[\"mbtn_left_up\"] =\n        function () mp.commandv(\"script-message\", \"video_formats_toggle\") end\n    ne.eventresponder[\"mbtn_right_up\"] =\n        function () mp.commandv(\"script-message\", \"audio_formats_toggle\") end\n    -- END quality-menu\n\n    -- volume\n    ne = new_element(\"volume\", \"button\")\n\n    ne.content = function()\n        local volume = mp.get_property_number(\"volume\")\n        if volume == 0 or mp.get_property_native(\"mute\") then\n            return icons.mute\n        end\n\n        return icons.volume[math.min(4, math.ceil(volume / (100/3)))]\n    end\n    bind_mouse_buttons(\"volume\")\n\n\n    -- custom buttons\n    for i = 1, math.huge do\n        local content = user_opts[\"custom_button_\" .. i .. \"_content\"]\n        if not content or content == \"\" then\n            break\n        end\n        ne = new_element(\"custom_button_\" .. i, \"button\")\n        ne.content = content\n        bind_mouse_buttons(\"custom_button_\" .. i)\n        last_custom_button = i\n    end\n\n\n    -- load layout\n    layouts[user_opts.layout]()\n\n    -- load window controls\n    if window_controls_enabled() then\n        window_controls(user_opts.layout == \"topbar\")\n    end\n\n    --do something with the elements\n    prepare_elements()\n\n    update_margins()\nend\n\nlocal function osc_visible(visible)\n    if state.osc_visible ~= visible then\n        state.osc_visible = visible\n        update_margins()\n    end\n    request_tick()\nend\n\nlocal function show_osc()\n    -- show when disabled can happen (e.g. mouse_move) due to async/delayed unbinding\n    if not state.enabled then return end\n\n    msg.trace(\"show_osc\")\n    --remember last time of invocation (mouse move)\n    state.showtime = mp.get_time()\n\n    if user_opts.fadeduration <= 0 then\n        osc_visible(true)\n    elseif user_opts.fadein then\n        if not state.osc_visible then\n            state.anitype = \"in\"\n            request_tick()\n        end\n    else\n        osc_visible(true)\n        state.anitype = nil\n    end\nend\n\nlocal function hide_osc()\n    msg.trace(\"hide_osc\")\n    if not state.enabled then\n        -- typically hide happens at render() from tick(), but now tick() is\n        -- no-op and won't render again to remove the osc, so do that manually.\n        state.osc_visible = false\n        render_wipe()\n    elseif user_opts.fadeduration > 0 then\n        if state.osc_visible then\n            state.anitype = \"out\"\n            request_tick()\n        end\n    else\n        osc_visible(false)\n    end\nend\n\nlocal function pause_state(_, enabled)\n    state.paused = enabled\n    request_tick()\nend\n\nlocal function cache_state(_, st)\n    state.cache_state = st\n    request_tick()\nend\n\nlocal function mouse_leave()\n    if get_hidetimeout() >= 0 and get_touchtimeout() <= 0 then\n        hide_osc()\n    end\n    -- reset mouse position\n    state.last_mouseX, state.last_mouseY = nil, nil\n    state.mouse_in_window = false\nend\n\nlocal function handle_touch()\n    --remember last time of invocation (touch event)\n    state.touchtime = mp.get_time()\nend\n\n\n--\n-- Eventhandling\n--\n\nlocal function element_has_action(element, action)\n    return element and element.eventresponder and\n        element.eventresponder[action]\nend\n\nlocal function process_event(source, what)\n    local action = string.format(\"%s%s\", source,\n        what and (\"_\" .. what) or \"\")\n\n    if what == \"down\" or what == \"press\" then\n\n        for n = 1, #elements do\n\n            if mouse_hit(elements[n]) and\n                elements[n].eventresponder and\n                (elements[n].eventresponder[source .. \"_up\"] or\n                    elements[n].eventresponder[action]) then\n\n                if what == \"down\" then\n                    state.active_element = n\n                    state.active_event_source = source\n                end\n                -- fire the down or press event if the element has one\n                if element_has_action(elements[n], action) then\n                    elements[n].eventresponder[action](elements[n])\n                end\n\n            end\n        end\n\n    elseif what == \"up\" then\n\n        if elements[state.active_element] then\n            local n = state.active_element\n\n            if n == 0 then --luacheck: ignore 542\n                --click on background (does not work)\n            elseif element_has_action(elements[n], action) and\n                mouse_hit(elements[n]) then\n\n                elements[n].eventresponder[action](elements[n])\n            end\n\n            --reset active element\n            if element_has_action(elements[n], \"reset\") then\n                elements[n].eventresponder[\"reset\"](elements[n])\n            end\n\n        end\n        state.active_element = nil\n        state.mouse_down_counter = 0\n\n    elseif source == \"mouse_move\" then\n\n        state.mouse_in_window = true\n\n        local mouseX, mouseY = get_virt_mouse_pos()\n        if user_opts.minmousemove == 0 or\n            ((state.last_mouseX ~= nil and state.last_mouseY ~= nil) and\n                ((math.abs(mouseX - state.last_mouseX) >= user_opts.minmousemove)\n                    or (math.abs(mouseY - state.last_mouseY) >= user_opts.minmousemove)\n                )\n            ) then\n            show_osc()\n        end\n        state.last_mouseX, state.last_mouseY = mouseX, mouseY\n\n        local n = state.active_element\n        if element_has_action(elements[n], action) then\n            elements[n].eventresponder[action](elements[n])\n        end\n    end\n\n    -- ensure rendering after any (mouse) event - icons could change etc\n    request_tick()\nend\n\nlocal function do_enable_keybindings()\n    if state.enabled then\n        if not state.showhide_enabled then\n            mp.enable_key_bindings(\"showhide\", \"allow-vo-dragging+allow-hide-cursor\")\n            mp.enable_key_bindings(\"showhide_wc\", \"allow-vo-dragging+allow-hide-cursor\")\n        end\n        state.showhide_enabled = true\n    end\nend\n\nlocal function enable_osc(enable)\n    state.enabled = enable\n    if enable then\n        do_enable_keybindings()\n    else\n        hide_osc() -- acts immediately when state.enabled == false\n        if state.showhide_enabled then\n            mp.disable_key_bindings(\"showhide\")\n            mp.disable_key_bindings(\"showhide_wc\")\n        end\n        state.showhide_enabled = false\n    end\nend\n\nlocal function render()\n    msg.trace(\"rendering\")\n    local current_screen_sizeX, current_screen_sizeY = mp.get_osd_size()\n    local mouseX, mouseY = get_virt_mouse_pos()\n    local now = mp.get_time()\n\n    -- check if display changed, if so request reinit\n    if state.screen_sizeX ~= current_screen_sizeX\n        or state.screen_sizeY ~= current_screen_sizeY then\n\n        request_init_resize()\n\n        state.screen_sizeX = current_screen_sizeX\n        state.screen_sizeY = current_screen_sizeY\n    end\n\n    -- init management\n    if state.active_element then\n        -- mouse is held down on some element - keep ticking and ignore initReq\n        -- till it's released, or else the mouse-up (click) will misbehave or\n        -- get ignored. that's because osc_init() recreates the osc elements,\n        -- but mouse handling depends on the elements staying unmodified\n        -- between mouse-down and mouse-up (using the index active_element).\n        request_tick()\n    elseif state.initREQ then\n        osc_init()\n        state.initREQ = false\n\n        -- store initial mouse position\n        if (state.last_mouseX == nil or state.last_mouseY == nil)\n            and not (mouseX == nil or mouseY == nil) then\n\n            state.last_mouseX, state.last_mouseY = mouseX, mouseY\n        end\n    end\n\n\n    -- fade animation\n    if state.anitype ~= nil then\n\n        if state.anistart == nil then\n            state.anistart = now\n        end\n\n        if now < state.anistart + (user_opts.fadeduration / 1000) then\n\n            if state.anitype == \"in\" then --fade in\n                osc_visible(true)\n                state.animation = scale_value(state.anistart,\n                    (state.anistart + (user_opts.fadeduration / 1000)),\n                    255, 0, now)\n            elseif state.anitype == \"out\" then --fade out\n                state.animation = scale_value(state.anistart,\n                    (state.anistart + (user_opts.fadeduration / 1000)),\n                    0, 255, now)\n            end\n\n        else\n            if state.anitype == \"out\" then\n                osc_visible(false)\n            end\n            kill_animation()\n        end\n    else\n        kill_animation()\n    end\n\n    --mouse show/hide area\n    for _, cords in pairs(osc_param.areas[\"showhide\"]) do\n        set_virt_mouse_area(cords.x1, cords.y1, cords.x2, cords.y2, \"showhide\")\n    end\n    if osc_param.areas[\"showhide_wc\"] then\n        for _, cords in pairs(osc_param.areas[\"showhide_wc\"]) do\n            set_virt_mouse_area(cords.x1, cords.y1, cords.x2, cords.y2, \"showhide_wc\")\n        end\n    else\n        set_virt_mouse_area(0, 0, 0, 0, \"showhide_wc\")\n    end\n    do_enable_keybindings()\n\n    --mouse input area\n    local mouse_over_osc = false\n\n    for _,cords in ipairs(osc_param.areas[\"input\"]) do\n        if state.osc_visible then -- activate only when OSC is actually visible\n            set_virt_mouse_area(cords.x1, cords.y1, cords.x2, cords.y2, \"input\")\n        end\n        if state.osc_visible ~= state.input_enabled then\n            if state.osc_visible then\n                mp.enable_key_bindings(\"input\")\n            else\n                mp.disable_key_bindings(\"input\")\n            end\n            state.input_enabled = state.osc_visible\n        end\n\n        if mouse_hit_coords(cords.x1, cords.y1, cords.x2, cords.y2) then\n            mouse_over_osc = true\n        end\n    end\n\n    if osc_param.areas[\"window-controls\"] then\n        for _,cords in ipairs(osc_param.areas[\"window-controls\"]) do\n            if state.osc_visible then -- activate only when OSC is actually visible\n                set_virt_mouse_area(cords.x1, cords.y1, cords.x2, cords.y2, \"window-controls\")\n            end\n            if state.osc_visible ~= state.windowcontrols_buttons then\n                if state.osc_visible then\n                    mp.enable_key_bindings(\"window-controls\")\n                else\n                    mp.disable_key_bindings(\"window-controls\")\n                end\n                state.windowcontrols_buttons = state.osc_visible\n            end\n\n            if mouse_hit_coords(cords.x1, cords.y1, cords.x2, cords.y2) then\n                mouse_over_osc = true\n            end\n        end\n    end\n\n    if osc_param.areas[\"window-controls-title\"] then\n        for _,cords in ipairs(osc_param.areas[\"window-controls-title\"]) do\n            if state.osc_visible then -- activate only when OSC is actually visible\n                set_virt_mouse_area(cords.x1, cords.y1, cords.x2, cords.y2, \"window-controls-title\")\n            end\n            if state.osc_visible ~= state.windowcontrols_title then\n                if state.osc_visible then\n                    mp.enable_key_bindings(\"window-controls-title\", \"allow-vo-dragging\")\n                else\n                    mp.disable_key_bindings(\"window-controls-title\", \"allow-vo-dragging\")\n                end\n                state.windowcontrols_title = state.osc_visible\n            end\n\n            if mouse_hit_coords(cords.x1, cords.y1, cords.x2, cords.y2) then\n                mouse_over_osc = true\n            end\n        end\n    end\n\n    -- autohide\n    if state.showtime ~= nil and get_hidetimeout() >= 0 then\n        local timeout = state.showtime + (get_hidetimeout() / 1000) - now\n        if timeout <= 0 and get_touchtimeout() <= 0 then\n            if state.active_element == nil and not mouse_over_osc then\n                hide_osc()\n            end\n        else\n            -- the timer is only used to recheck the state and to possibly run\n            -- the code above again\n            if not state.hide_timer then\n                state.hide_timer = mp.add_timeout(0, tick)\n            end\n            state.hide_timer.timeout = timeout\n            -- re-arm\n            state.hide_timer:kill()\n            state.hide_timer:resume()\n        end\n    end\n\n\n    -- actual rendering\n    local ass = assdraw.ass_new()\n\n    -- actual OSC\n    if state.osc_visible then\n        render_elements(ass)\n    end\n\n    -- submit\n    set_osd(osc_param.playresy * osc_param.display_aspect,\n            osc_param.playresy, ass.text, 1000)\nend\n\n-- called by mpv on every frame\ntick = function()\n    if state.marginsREQ == true then\n        update_margins()\n        state.marginsREQ = false\n    end\n\n    if not state.enabled then return end\n\n    if state.idle then\n\n        -- render idle message\n        msg.trace(\"idle message\")\n        local _, _, display_aspect = mp.get_osd_size()\n        if display_aspect == 0 then\n            return\n        end\n        local display_h = 360\n        local display_w = display_h * display_aspect\n        -- logo is rendered at 2^(6-1) = 32 times resolution with size 1800x1800\n        local icon_x, icon_y = (display_w - 1800 / 32) / 2, 140\n        local line_prefix = (\"{\\\\rDefault\\\\an7\\\\1a&H00&\\\\bord0\\\\shad0\\\\pos(%f,%f)}\"):format(icon_x,\n                                                                                            icon_y)\n\n        local ass = assdraw.ass_new()\n        -- mpv logo\n        if user_opts.idlescreen then\n            for _, line in ipairs(logo_lines) do\n                ass:new_event()\n                ass:append(line_prefix .. line)\n            end\n        end\n\n        -- Santa hat\n        if is_december and user_opts.idlescreen and not user_opts.greenandgrumpy then\n            for _, line in ipairs(santa_hat_lines) do\n                ass:new_event()\n                ass:append(line_prefix .. line)\n            end\n        end\n\n        if user_opts.idlescreen then\n            ass:new_event()\n            ass:pos(display_w / 2, icon_y + 65)\n            ass:an(8)\n            ass:append(\"Drop files or URLs to play here.\")\n        end\n        set_osd(display_w, display_h, ass.text, -1000)\n\n        if state.showhide_enabled then\n            mp.disable_key_bindings(\"showhide\")\n            mp.disable_key_bindings(\"showhide_wc\")\n            state.showhide_enabled = false\n        end\n\n\n    elseif state.fullscreen and user_opts.showfullscreen\n        or (not state.fullscreen and user_opts.showwindowed) then\n\n        -- render the OSC\n        render()\n    else\n        -- Flush OSD\n        render_wipe()\n    end\n\n    state.tick_last_time = mp.get_time()\n\n    if state.anitype ~= nil then\n        -- state.anistart can be nil - animation should now start, or it can\n        -- be a timestamp when it started. state.idle has no animation.\n        if not state.idle and\n           (not state.anistart or\n            mp.get_time() < 1 + state.anistart + user_opts.fadeduration/1000)\n        then\n            -- animating or starting, or still within 1s past the deadline\n            request_tick()\n        else\n            kill_animation()\n        end\n    end\nend\n\nlocal function shutdown()\n    reset_margins()\n    mp.del_property(\"user-data/osc\")\nend\n\n-- duration is observed for the sole purpose of updating chapter markers\n-- positions. live streams with chapters are very rare, and the update is also\n-- expensive (with request_init), so it's only observed when we have chapters\n-- and the user didn't disable the livemarkers option (update_duration_watch).\nlocal function on_duration() request_init() end\n\nlocal duration_watched = false\nlocal function update_duration_watch()\n    local want_watch = user_opts.livemarkers and\n                       (mp.get_property_number(\"chapters\", 0) or 0) > 0 and\n                       true or false  -- ensure it's a boolean\n\n    if want_watch ~= duration_watched then\n        if want_watch then\n            mp.observe_property(\"duration\", \"native\", on_duration)\n        else\n            mp.unobserve_property(on_duration)\n        end\n        duration_watched = want_watch\n    end\nend\n\nlocal function set_tick_delay(_, display_fps)\n    -- may be nil if unavailable or 0 fps is reported\n    if not display_fps or not user_opts.tick_delay_follow_display_fps then\n        tick_delay = user_opts.tick_delay\n        return\n    end\n    tick_delay = 1 / display_fps\nend\n\nmp.register_event(\"shutdown\", shutdown)\nmp.register_event(\"start-file\", request_init)\nmp.observe_property(\"track-list\", \"native\", request_init)\nmp.observe_property(\"playlist-count\", \"native\", request_init)\nmp.observe_property(\"playlist-pos\", \"native\", request_init)\nmp.observe_property(\"chapter-list\", \"native\", function(_, list)\n    list = list or {}  -- safety, shouldn't return nil\n    table.sort(list, function(a, b) return a.time < b.time end)\n    state.chapter_list = list\n    update_duration_watch()\n    request_init()\nend)\n\n-- These are for backwards compatibility only.\nmp.register_script_message(\"osc-message\", function(message, dur)\n    if not state.osc_message_warned then\n        mp.msg.warn(\"osc-message is deprecated and may be removed in the future.\",\n                    \"Use the show-text command instead.\")\n        state.osc_message_warned = true\n    end\n    mp.osd_message(message, dur)\nend)\nmp.register_script_message(\"osc-chapterlist\", function(dur)\n    if not state.osc_chapterlist_warned then\n        mp.msg.warn(\"osc-chapterlist is deprecated and may be removed in the future.\",\n                    \"Use show-text ${chapter-list} instead.\")\n        state.osc_chapterlist_warned = true\n    end\n    mp.command(\"show-text ${chapter-list} \" .. (dur and dur * 1000 or \"\"))\nend)\nmp.register_script_message(\"osc-playlist\", function(dur)\n    if not state.osc_playlist_warned then\n        mp.msg.warn(\"osc-playlist is deprecated and may be removed in the future.\",\n                    \"Use show-text ${playlist} instead.\")\n        state.osc_playlist_warned = true\n    end\n    mp.command(\"show-text ${playlist} \" .. (dur and dur * 1000 or \"\"))\nend)\nmp.register_script_message(\"osc-tracklist\", function(dur)\n    if not state.osc_tracklist_warned then\n        mp.msg.warn(\"osc-tracklist is deprecated and may be removed in the future.\",\n                    \"Use show-text ${track-list} instead.\")\n        state.osc_tracklist_warned = true\n    end\n    mp.command(\"show-text ${track-list} \" .. (dur and dur * 1000 or \"\"))\nend)\n\nmp.observe_property(\"fullscreen\", \"bool\", function(_, val)\n    state.fullscreen = val\n    state.marginsREQ = true\n    request_init_resize()\nend)\nmp.observe_property(\"border\", \"bool\", function(_, val)\n    state.border = val\n    request_init_resize()\nend)\nmp.observe_property(\"title-bar\", \"bool\", function(_, val)\n    state.title_bar = val\n    request_init_resize()\nend)\nmp.observe_property(\"window-maximized\", \"bool\", function(_, val)\n    state.maximized = val\n    request_init_resize()\nend)\nmp.observe_property(\"idle-active\", \"bool\", function(_, val)\n    state.idle = val\n    request_tick()\nend)\n\nmp.observe_property(\"display-fps\", \"number\", set_tick_delay)\nmp.observe_property(\"pause\", \"bool\", pause_state)\nmp.observe_property(\"demuxer-cache-state\", \"native\", cache_state)\nmp.observe_property(\"vo-configured\", \"bool\", request_tick)\nmp.observe_property(\"playback-time\", \"number\", request_tick)\nmp.observe_property(\"osd-dimensions\", \"native\", function()\n    -- (we could use the value instead of re-querying it all the time, but then\n    --  we might have to worry about property update ordering)\n    request_init_resize()\nend)\nmp.observe_property('osd-scale-by-window', 'native', request_init_resize)\nmp.observe_property('touch-pos', 'native', handle_touch)\n\n-- mouse show/hide bindings\nmp.set_key_bindings({\n    {\"mouse_move\",              function() process_event(\"mouse_move\", nil) end},\n    {\"mouse_leave\",             mouse_leave},\n}, \"showhide\", \"force\")\nmp.set_key_bindings({\n    {\"mouse_move\",              function() process_event(\"mouse_move\", nil) end},\n    {\"mouse_leave\",             mouse_leave},\n}, \"showhide_wc\", \"force\")\ndo_enable_keybindings()\n\n--mouse input bindings\nmp.set_key_bindings({\n    {\"mbtn_left\",           function() process_event(\"mbtn_left\", \"up\") end,\n                            function() process_event(\"mbtn_left\", \"down\")  end},\n    {\"mbtn_mid\",            function() process_event(\"mbtn_mid\", \"up\") end,\n                            function() process_event(\"mbtn_mid\", \"down\")  end},\n    {\"mbtn_right\",          function() process_event(\"mbtn_right\", \"up\") end,\n                            function() process_event(\"mbtn_right\", \"down\")  end},\n    -- alias shift+mbtn_left to mbtn_mid for touchpads\n    {\"shift+mbtn_left\",     function() process_event(\"mbtn_mid\", \"up\") end,\n                            function() process_event(\"mbtn_mid\", \"down\")  end},\n    {\"wheel_up\",            function() process_event(\"wheel_up\", \"press\") end},\n    {\"wheel_down\",          function() process_event(\"wheel_down\", \"press\") end},\n    {\"mbtn_left_dbl\",       \"ignore\"},\n    {\"shift+mbtn_left_dbl\", \"ignore\"},\n    {\"mbtn_right_dbl\",      \"ignore\"},\n}, \"input\", \"force\")\nmp.enable_key_bindings(\"input\")\n\nmp.set_key_bindings({\n    {\"mbtn_left\",           function() process_event(\"mbtn_left\", \"up\") end,\n                            function() process_event(\"mbtn_left\", \"down\")  end},\n}, \"window-controls\", \"force\")\nmp.enable_key_bindings(\"window-controls\")\n\nlocal function always_on(val)\n    if state.enabled then\n        if val then\n            show_osc()\n        else\n            hide_osc()\n        end\n    end\nend\n\n-- mode can be auto/always/never/cycle\n-- the modes only affect internal variables and not stored on its own.\nlocal function visibility_mode(mode, no_osd)\n    if mode == \"cycle\" then\n        for i, allowed_mode in ipairs(state.visibility_modes) do\n            if i == #state.visibility_modes then\n                mode = state.visibility_modes[1]\n                break\n            elseif user_opts.visibility == allowed_mode then\n                mode = state.visibility_modes[i + 1]\n                break\n            end\n        end\n    end\n\n    if mode == \"auto\" then\n        always_on(false)\n        enable_osc(true)\n    elseif mode == \"always\" then\n        enable_osc(true)\n        always_on(true)\n    elseif mode == \"never\" then\n        enable_osc(false)\n    else\n        msg.warn(\"Ignoring unknown visibility mode '\" .. mode .. \"'\")\n        return\n    end\n\n    user_opts.visibility = mode\n    mp.set_property_native(\"user-data/osc/visibility\", mode)\n\n    if not no_osd and tonumber(mp.get_property(\"osd-level\")) >= 1 then\n        mp.osd_message(\"OSC visibility: \" .. mode)\n    end\n\n    -- Reset the input state on a mode change. The input state will be\n    -- recalculated on the next render cycle, except in 'never' mode where it\n    -- will just stay disabled.\n    mp.disable_key_bindings(\"input\")\n    mp.disable_key_bindings(\"window-controls\")\n    state.input_enabled = false\n\n    update_margins()\n    request_tick()\nend\n\nlocal function idlescreen_visibility(mode, no_osd)\n    if mode == \"cycle\" then\n        if user_opts.idlescreen then\n            mode = \"no\"\n        else\n            mode = \"yes\"\n        end\n    end\n\n    if mode == \"yes\" then\n        user_opts.idlescreen = true\n    else\n        user_opts.idlescreen = false\n    end\n\n    mp.set_property_native(\"user-data/osc/idlescreen\", user_opts.idlescreen)\n\n    if not no_osd and tonumber(mp.get_property(\"osd-level\")) >= 1 then\n        mp.osd_message(\"OSC logo visibility: \" .. tostring(mode))\n    end\n\n    request_tick()\nend\n\nmp.register_script_message(\"osc-visibility\", visibility_mode)\nmp.register_script_message(\"osc-show\", show_osc)\nmp.register_script_message(\"osc-hide\", function ()\n    if user_opts.visibility == \"auto\" then\n        osc_visible(false)\n    end\nend)\nmp.add_key_binding(nil, \"visibility\", function() visibility_mode(\"cycle\") end)\n\nmp.register_script_message(\"osc-idlescreen\", idlescreen_visibility)\n\n-- Validate string type user options\nlocal function validate_user_opts()\n    if layouts[user_opts.layout] == nil then\n        msg.warn(\"Invalid setting '\"..user_opts.layout..\"' for layout\")\n        user_opts.layout = \"bottombar\"\n    end\n\n    if user_opts.seekbarstyle ~= \"bar\" and\n       user_opts.seekbarstyle ~= \"diamond\" and\n       user_opts.seekbarstyle ~= \"knob\" then\n        msg.warn(\"Invalid setting '\" .. user_opts.seekbarstyle\n            .. \"' for seekbarstyle\")\n        user_opts.seekbarstyle = \"bar\"\n    end\n\n    if user_opts.seekrangestyle ~= \"bar\" and\n       user_opts.seekrangestyle ~= \"line\" and\n       user_opts.seekrangestyle ~= \"slider\" and\n       user_opts.seekrangestyle ~= \"inverted\" and\n       user_opts.seekrangestyle ~= \"none\" then\n        msg.warn(\"Invalid setting '\" .. user_opts.seekrangestyle\n            .. \"' for seekrangestyle\")\n        user_opts.seekrangestyle = \"inverted\"\n    end\n\n    if user_opts.seekrangestyle == \"slider\" and\n       user_opts.seekbarstyle == \"bar\" then\n        msg.warn(\n            \"Using 'slider' seekrangestyle together with 'bar' seekbarstyle is not supported\")\n        user_opts.seekrangestyle = \"inverted\"\n    end\n\n    if user_opts.windowcontrols ~= \"auto\" and\n       user_opts.windowcontrols ~= \"yes\" and\n       user_opts.windowcontrols ~= \"no\" then\n        msg.warn(\"windowcontrols cannot be '\" ..\n                user_opts.windowcontrols .. \"'. Ignoring.\")\n        user_opts.windowcontrols = \"auto\"\n    end\n    if user_opts.windowcontrols_alignment ~= \"right\" and\n       user_opts.windowcontrols_alignment ~= \"left\" then\n        msg.warn(\"windowcontrols_alignment cannot be '\" ..\n                user_opts.windowcontrols_alignment .. \"'. Ignoring.\")\n        user_opts.windowcontrols_alignment = \"right\"\n    end\n\n    local colors = {\n        user_opts.background_color, user_opts.top_buttons_color,\n        user_opts.small_buttonsL_color, user_opts.small_buttonsR_color,\n        user_opts.buttons_color, user_opts.title_color,\n        user_opts.timecode_color, user_opts.time_pos_color,\n        user_opts.held_element_color, user_opts.time_pos_outline_color,\n    }\n    for _, color in pairs(colors) do\n        if color:find(\"^#%x%x%x%x%x%x$\") == nil then\n            msg.warn(\"'\" .. color .. \"' is not a valid color\")\n        end\n    end\n\n    for str in string.gmatch(user_opts.visibility_modes, \"([^_]+)\") do\n        if str ~= \"auto\" and str ~= \"always\" and str ~= \"never\" then\n            msg.warn(\"Ignoring unknown visibility mode '\" .. str ..\"' in list\")\n        else\n            table.insert(state.visibility_modes, str)\n        end\n    end\nend\n\n-- read options from config and command-line\nopt.read_options(user_opts, \"osc\", function(changed)\n    validate_user_opts()\n    set_osc_styles()\n    set_time_styles(changed.timetotal, changed.timems)\n    if changed.tick_delay or changed.tick_delay_follow_display_fps then\n        set_tick_delay(\"display_fps\", mp.get_property_number(\"display_fps\"))\n    end\n    request_tick()\n    visibility_mode(user_opts.visibility, true)\n    update_duration_watch()\n    request_init()\nend)\n\nvalidate_user_opts()\nset_osc_styles()\nset_time_styles(true, true)\nset_tick_delay(\"display_fps\", mp.get_property_number(\"display_fps\"))\nvisibility_mode(user_opts.visibility, true)\nupdate_duration_watch()\n\nset_virt_mouse_area(0, 0, 0, 0, \"input\")\nset_virt_mouse_area(0, 0, 0, 0, \"window-controls\")\nset_virt_mouse_area(0, 0, 0, 0, \"window-controls-title\")\n"
  },
  {
    "path": "quality-menu.conf",
    "content": "# KEY BINDINGS\n\n# move the menu cursor up\nup_binding=UP WHEEL_UP\n# move the menu cursor down\ndown_binding=DOWN WHEEL_DOWN\n# select menu entry\nselect_binding=ENTER MBTN_LEFT\n# close menu\nclose_menu_binding=ESC MBTN_RIGHT\n\n# formatting / cursors\nselected_and_active=▶  - \nselected_and_inactive=●  - \nunselected_and_active=▷ - \nunselected_and_inactive=○ - \n\n# font size scales by window, if false requires larger font and padding sizes\nscale_playlist_by_window=yes\n\n# playlist ass style overrides inside curly brackets, \\keyvalue is one field, extra \\ for escape in lua\n# example {\\\\fnUbuntu\\\\fs10\\\\b0\\\\bord1} equals: font=Ubuntu, size=10, bold=no, border=1\n# read https://aegi.vmoe.info/docs/3.0/ASS_Tags/ for reference of tags\n# undeclared tags will use default osd settings\n# these styles will be used for the whole playlist. More specific styling will need to be hacked in\n#\n# (a monospaced font is recommended but not required)\nstyle_ass_tags={\\\\fnmonospace\\\\fs25\\\\bord1}\n\n# Shift drawing coordinates. Required for mpv.net compatiblity\nshift_x=0\nshift_y=0\n\n# paddings for top left corner\ntext_padding_x=5\ntext_padding_y=10\n\n# Screen dim when menu is open\ncurtain_opacity=0.7\n\n# how many seconds until the quality menu times out\n# setting this to 0 deactivates the timeout\nmenu_timeout=6\n\n# use youtube-dl to fetch a list of available formats (overrides quality_strings)\nfetch_formats=yes\n\n# list of ytdl-format strings to choose from\nquality_strings_video=[ {\"4320p\" : \"bestvideo[height<=?4320p]\"}, {\"2160p\" : \"bestvideo[height<=?2160]\"}, {\"1440p\" : \"bestvideo[height<=?1440]\"}, {\"1080p\" : \"bestvideo[height<=?1080]\"}, {\"720p\" : \"bestvideo[height<=?720]\"}, {\"480p\" : \"bestvideo[height<=?480]\"}, {\"360p\" : \"bestvideo[height<=?360]\"}, {\"240p\" : \"bestvideo[height<=?240]\"}, {\"144p\" : \"bestvideo[height<=?144]\"} ]\nquality_strings_audio=[ {\"default\" : \"bestaudio\"} ]\n\n# show the video format menu after opening an url\nstart_with_menu=no\n\n# include unknown formats in the list\n# Unfortunately choosing which formats are video or audio is not always perfect.\n# Set to true to make sure you don't miss any formats, but then the list\n# might also include formats that aren't actually video or audio.\n# Formats that are known to not be video or audio are still filtered out.\ninclude_unknown=no\n\n# hide columns that are identical for all formats\nhide_identical_columns=yes\n\n# which columns are shown in which order\n# comma separated list, prefix column with \"-\" to align left\n#\n# for the uosc integration it is possible to split the text up into a title and a hint\n# this is done by separating two columns with a \"|\" instead of a comma\n# column order in the hint is reversed\n#\n# columns that might be useful are:\n# resolution, width, height, fps, dynamic_range, tbr, vbr, abr, asr,\n# filesize, filesize_approx, vcodec, acodec, ext, video_ext, audio_ext,\n# language, format, format_note, quality\n#\n# columns that are derived from the above, but with special treatment:\n# size, frame_rate, bitrate_total, bitrate_video, bitrate_audio,\n# codec_video, codec_audio, audio_sample_rate\n#\n# If those still aren't enough or you're just curious, run:\n# yt-dlp -j <url>\n# This outputs unformatted JSON.\n# Format it and look under \"formats\" to see what's available.\n#\n# Not all videos have all columns available.\n# Be careful, misspelled columns simply won't be displayed, there is no error.\ncolumns_video=-resolution,frame_rate,dynamic_range|language,bitrate_total,size,-codec_video,-codec_audio\ncolumns_audio=audio_sample_rate,bitrate_total|size,language,-codec_audio\n\n# columns used for sorting, see \"columns_video\" for available columns\n# comma separated list, prefix column with \"-\" to reverse sorting order\n# Leaving this empty keeps the order from yt-dlp/youtube-dl.\n# Be careful, misspelled columns won't result in an error,\n# but they might influence the result.\nsort_video=height,fps,tbr,size,format_id\nsort_audio=asr,tbr,size,format_id\n"
  },
  {
    "path": "quality-menu.lua",
    "content": "-- quality-menu 4.2.1 - 2025-Jun-29\n-- https://github.com/christoph-heinrich/mpv-quality-menu\n--\n-- Change the stream video and audio quality on the fly.\n--\n-- Usage:\n-- add bindings to input.conf:\n-- F     script-binding quality_menu/video_formats_toggle\n-- Alt+f script-binding quality_menu/audio_formats_toggle\n\nlocal mp = require 'mp'\nlocal utils = require 'mp.utils'\nlocal msg = require 'mp.msg'\nlocal assdraw = require 'mp.assdraw'\nlocal opt = require('mp.options')\nlocal script_name = mp.get_script_name()\n\nlocal opts = {\n    --key bindings\n    up_binding = 'UP WHEEL_UP',\n    down_binding = 'DOWN WHEEL_DOWN',\n    select_binding = 'ENTER MBTN_LEFT',\n    close_menu_binding = 'ESC MBTN_RIGHT',\n\n    --formatting / cursors\n    selected_and_active     = '▶  - ',\n    selected_and_inactive   = '●  - ',\n    unselected_and_active   = '▷ - ',\n    unselected_and_inactive = '○ - ',\n\n    --font size scales by window, if false requires larger font and padding sizes\n    scale_playlist_by_window = true,\n\n    --playlist ass style overrides inside curly brackets, \\keyvalue is one field, extra \\ for escape in lua\n    --example {\\\\fnUbuntu\\\\fs10\\\\b0\\\\bord1} equals: font=Ubuntu, size=10, bold=no, border=1\n    --read http://docs.aegisub.org/3.2/ASS_Tags/ for reference of tags\n    --undeclared tags will use default osd settings\n    --these styles will be used for the whole playlist. More specific styling will need to be hacked in\n    --\n    --(a monospaced font is recommended but not required)\n    style_ass_tags = '{\\\\fnmonospace\\\\fs25\\\\bord1}',\n\n    -- Shift drawing coordinates. Required for mpv.net compatiblity\n    shift_x = 0,\n    shift_y = 0,\n\n    --paddings from window edge\n    text_padding_x = 5,\n    text_padding_y = 10,\n\n    --Screen dim when menu is open\n    curtain_opacity = 0.7,\n\n    --how many seconds until the quality menu times out\n    --setting this to 0 deactivates the timeout\n    menu_timeout = 6,\n\n    --use youtube-dl to fetch a list of available formats (overrides quality_strings)\n    fetch_formats = true,\n\n    --list of ytdl-format strings to choose from\n    quality_strings_video = [[\n    [\n    {\"4320p\" : \"bestvideo[height<=?4320p]\"},\n    {\"2160p\" : \"bestvideo[height<=?2160]\"},\n    {\"1440p\" : \"bestvideo[height<=?1440]\"},\n    {\"1080p\" : \"bestvideo[height<=?1080]\"},\n    {\"720p\" : \"bestvideo[height<=?720]\"},\n    {\"480p\" : \"bestvideo[height<=?480]\"},\n    {\"360p\" : \"bestvideo[height<=?360]\"},\n    {\"240p\" : \"bestvideo[height<=?240]\"},\n    {\"144p\" : \"bestvideo[height<=?144]\"}\n    ]\n    ]],\n    quality_strings_audio = [[\n    [\n    {\"default\" : \"bestaudio/best\"}\n    ]\n    ]],\n\n    --show the video format menu after opening an url\n    start_with_menu = false,\n\n    --include unknown formats in the list\n    --Unfortunately choosing which formats are video or audio is not always perfect.\n    --Set to true to make sure you don't miss any formats, but then the list\n    --might also include formats that aren't actually video or audio.\n    --Formats that are known to not be video or audio are still filtered out.\n    include_unknown = false,\n\n    --hide columns that are identical for all formats\n    hide_identical_columns = true,\n\n    --which columns are shown in which order\n    --comma separated list, prefix column with \"-\" to align left\n    --\n    --for the uosc integration it is possible to split the text up into a title and a hint\n    --this is done by separating two columns with a \"|\" instead of a comma\n    --column order in the hint is reversed\n    --\n    --columns that might be useful are:\n    --resolution, width, height, fps, dynamic_range, tbr, vbr, abr, asr,\n    --filesize, filesize_approx, vcodec, acodec, ext, video_ext, audio_ext,\n    --language, format, format_note, quality\n    --\n    --columns that are derived from the above, but with special treatment:\n    --size, frame_rate, bitrate_total, bitrate_video, bitrate_audio,\n    --codec_video, codec_audio, audio_sample_rate\n    --\n    --If those still aren't enough or you're just curious, run:\n    --yt-dlp -j <url>\n    --This outputs unformatted JSON.\n    --Format it and look under \"formats\" to see what's available.\n    --\n    --Not all videos have all columns available.\n    --Be careful, misspelled columns simply won't be displayed, there is no error.\n    columns_video = '-resolution,frame_rate,dynamic_range|language,bitrate_total,size,-codec_video,-codec_audio',\n    columns_audio = 'audio_sample_rate,bitrate_total|size,language,-codec_audio',\n\n    --columns used for sorting, see \"columns_video\" for available columns\n    --comma separated list, prefix column with \"-\" to reverse sorting order\n    --Leaving this empty keeps the order from yt-dlp/youtube-dl.\n    --Be careful, misspelled columns won't result in an error,\n    --but they might influence the result.\n    sort_video = 'height,fps,tbr,size,format_id',\n    sort_audio = 'asr,tbr,size,format_id',\n}\nopt.read_options(opts, 'quality-menu')\n\n---@alias Format { properties: {[string]: string}, id: string, label?: string, title?: string, hint?: string }\n-- *_active_id == nil means unknown, *_active_id == '' means disabled\n---@alias Data { video_formats: Format[], audio_formats: Format[], video_active_id?: string, audio_active_id?: string }\n---@alias UIState { type: string, type_capitalized: string, name: string , to_other_type: UIState, to_fetching: UIState, to_menu: UIState, is_video: boolean }\n\ndo\n    ---@param option_string string\n    ---@param option_name string\n    ---@return Format[]\n    local function parse_predefined(option_string, option_name)\n        ---@type {[string]: string}[]\n        local json, error = utils.parse_json(option_string)\n        if error then\n            msg.error('Error while parsing JSON of option ' .. option_name .. ': ' .. error)\n            return {}\n        end\n        ---@type Format[]\n        local formats = {}\n        for i, format in ipairs(json) do\n            local label, format_string = next(format)\n            formats[i] = {\n                label = label,\n                title = label,\n                id = format_string,\n            }\n        end\n        return formats\n    end\n\n    ---@type Data\n    opts.predefined_data = {\n        video_formats = parse_predefined(opts.quality_strings_video, 'quality_strings_video'),\n        audio_formats = parse_predefined(opts.quality_strings_audio, 'quality_strings_audio'),\n        video_active_id = nil,\n        audio_active_id = nil,\n    }\nend\n\nopts.font_size = tonumber(opts.style_ass_tags:match('\\\\fs(%d+%.?%d*)')) or mp.get_property_number('osd-font-size') or 25\nopts.curtain_opacity = math.max(math.min(opts.curtain_opacity, 1), 0)\n\n---@param input string\n---@param separator string\n---@return string[]\nlocal function string_split(input, separator)\n    if separator == nil then\n        separator = '%s'\n    end\n    local t = {}\n    for str in string.gmatch(input, '([^' .. separator .. ']+)') do\n        table.insert(t, str)\n    end\n    return t\nend\n\n---@param strings string[]\n---@return string[], boolean[]\nlocal function strip_minus(strings)\n    local stripped_list = {}\n    local had_minus = {}\n    for i, val in ipairs(strings) do\n        if string.sub(val, 1, 1) == '-' then\n            val = string.sub(val, 2)\n            had_minus[val] = true\n        end\n        stripped_list[i] = val\n    end\n    return stripped_list, had_minus\nend\n\ndo\n    ---@param column_definition string\n    ---@return { all: string[], all_align_left: boolean[], title: string[], title_align_left: boolean[], hint?: string[] }\n    local function parse_columns(column_definition)\n        local columns, columns_align_left = strip_minus(string_split(column_definition, '|,'))\n        local title_hint = string_split(column_definition, '|')\n        local title, title_align_left = strip_minus(string_split(title_hint[1], ','))\n\n        local hint = nil\n        if title_hint[2] then\n            hint = strip_minus(string_split(title_hint[2], ','))\n            -- reverse column order\n            local n = #hint\n            for i = 1, n / 2 do\n                hint[i], hint[n - i + 1] = hint[n - i + 1], hint[i]\n            end\n        end\n        return {\n            all = columns, all_align_left = columns_align_left,\n            title = title, title_align_left = title_align_left,\n            hint = hint\n        }\n    end\n\n    ---@type { all: string[], all_align_left: boolean[], title: string[], title_align_left: boolean[], hint?: string[] }\n    ---@diagnostic disable-next-line: param-type-mismatch\n    opts.columns_video = parse_columns(opts.columns_video)\n    ---@type { all: string[], all_align_left: boolean[], title: string[], title_align_left: boolean[], hint?: string[] }\n    ---@diagnostic disable-next-line: param-type-mismatch\n    opts.columns_audio = parse_columns(opts.columns_audio)\nend\n\n-- special thanks to reload.lua (https://github.com/4e6/mpv-reload/)\nlocal function reload_resume()\n    local reload_duration = mp.get_property_native('duration')\n    local time_pos = mp.get_property('time-pos')\n\n    mp.command('playlist-play-index current')\n\n    -- Tries to determine live stream vs. pre-recorded VOD. VOD has non-zero\n    -- duration property. When reloading VOD, to keep the current time position\n    -- we should provide offset from the start. Stream doesn't have fixed start.\n    -- Decent choice would be to reload stream from it's current 'live' position.\n    -- That's the reason we don't pass the offset when reloading streams.\n    if reload_duration and reload_duration > 0 and time_pos then\n        local function seeker()\n            mp.commandv('seek', time_pos, 'absolute+exact')\n            mp.unregister_event(seeker)\n        end\n\n        mp.register_event('file-loaded', seeker)\n    end\nend\n\n---@type { video_menu: UIState, audio_menu: UIState, video_fetching: UIState, audio_fetching: UIState }\nlocal states = {\n    video_menu = { type = 'video', type_capitalized = 'Video', name = 'video_menu', is_video = true },\n    audio_menu = { type = 'audio', type_capitalized = 'Audio', name = 'audio_menu', is_video = false },\n    video_fetching = { type = 'video', type_capitalized = 'Video', name = 'video_fetching', is_video = true },\n    audio_fetching = { type = 'audio', type_capitalized = 'Audio', name = 'audio_fetching', is_video = false },\n}\nstates.video_menu.to_fetching = states.video_fetching\nstates.video_menu.to_menu = states.video_menu\nstates.video_menu.to_other_type = states.audio_menu\nstates.audio_menu.to_fetching = states.audio_fetching\nstates.audio_menu.to_menu = states.audio_menu\nstates.audio_menu.to_other_type = states.video_menu\nstates.video_fetching.to_fetching = states.video_fetching\nstates.video_fetching.to_menu = states.video_menu\nstates.video_fetching.to_other_type = states.audio_fetching\nstates.audio_fetching.to_fetching = states.audio_fetching\nstates.audio_fetching.to_menu = states.audio_menu\nstates.audio_fetching.to_other_type = states.video_fetching\n\n---@type UIState | nil\nlocal open_menu_state = nil\n---@type string | nil\nlocal current_url = nil\n---@type function | nil\nlocal destructor = nil\n\nlocal menu_open\nlocal menu_close\nlocal video_formats_toggle\nlocal audio_formats_toggle\n\nlocal osd = mp.create_osd_overlay('ass-events')\n\nlocal function hide_osd()\n    -- workaround mpv bug, setting to hidden does not cause a redraw\n    -- https://github.com/mpv-player/mpv/issues/10227\n    osd.data = ''\n    osd:update()\n    osd.hidden = true\n    osd:update()\nend\n\nlocal osd_timer = mp.add_timeout(1, function() menu_close() end)\nosd_timer:kill()\n\n---@param message string\n---@param time number\nlocal function osd_message(message, time)\n    osd.res_x = 1280\n    osd.res_y = 720\n    osd.hidden = false\n    osd.data = message\n    osd:update()\n    osd_timer.timeout = time\n    osd_timer:kill()\n    osd_timer:resume()\nend\n\n---@alias FormatRaw {format_id: string, vcodec?: string, acodec?: string, filesize: integer?, filesize_approx?: integer, fps?: number, tbr?: number, vbr?: number, abr?: number, asr?: number}\n\n---@param json {formats: FormatRaw[], requested_formats: FormatRaw, requested_downloads: FormatRaw}\n---@return Data\nlocal function process_json(json)\n    ---@param format FormatRaw\n    ---@return boolean\n    local function is_video(format)\n        -- 'none' means it is not a video\n        -- nil means it is unknown\n        return (opts.include_unknown or format.vcodec) and format.vcodec ~= 'none' or false\n    end\n\n    ---@param format FormatRaw\n    ---@return boolean\n    local function is_audio(format)\n        return (opts.include_unknown or format.acodec) and format.acodec ~= 'none' or false\n    end\n\n    local requested_video = nil\n    local requested_audio = nil\n    local requested_formats = json.requested_formats or json.requested_downloads or {}\n    for _, format in ipairs(requested_formats) do\n        if is_video(format) then\n            requested_video = format.format_id\n        elseif is_audio(format) then\n            requested_audio = format.format_id\n        end\n    end\n\n    local video_formats = {}\n    local audio_formats = {}\n    local all_formats = {}\n    for i = #json.formats, 1, -1 do\n        local format = json.formats[i]\n        if is_video(format) then\n            video_formats[#video_formats + 1] = format\n            all_formats[#all_formats + 1] = format\n        elseif is_audio(format) then\n            audio_formats[#audio_formats + 1] = format\n            all_formats[#all_formats + 1] = format\n        end\n    end\n\n    ---@param format FormatRaw\n    local function populate_special_fields(format)\n        format.size = format.filesize or format.filesize_approx\n        format.frame_rate = format.fps\n        format.bitrate_total = format.tbr\n        format.bitrate_video = format.vbr\n        format.bitrate_audio = format.abr\n        format.codec_video = format.vcodec\n        format.codec_audio = format.acodec\n        format.audio_sample_rate = format.asr\n    end\n\n    for _, format in ipairs(all_formats) do\n        populate_special_fields(format)\n    end\n\n    local sort_video, reverse_video = strip_minus(string_split(opts.sort_video, ','))\n    local sort_audio, reverse_audio = strip_minus(string_split(opts.sort_audio, ','))\n\n    ---@param properties string[]\n    ---@param reverse {[string]: boolean}\n    ---@return fun(a: FormatRaw, b: FormatRaw): boolean\n    local function comp(properties, reverse)\n        return function(a, b)\n            for _, prop in ipairs(properties) do\n                local a_val = a[prop]\n                local b_val = b[prop]\n                if a_val and b_val and type(a_val) ~= 'table' and a_val ~= b_val then\n                    if reverse[prop] then\n                        return a_val < b_val\n                    else\n                        return a_val > b_val\n                    end\n                end\n            end\n            return false\n        end\n    end\n\n    if #sort_video > 0 then\n        table.sort(video_formats, comp(sort_video, reverse_video))\n    end\n    if #sort_audio > 0 then\n        table.sort(audio_formats, comp(sort_audio, reverse_audio))\n    end\n\n    ---@param size integer\n    ---@return string\n    local function scale_filesize(size)\n        if size == nil then\n            return ''\n        end\n\n        local counter = 0\n        while size > 1024 do\n            size = size / 1024\n            counter = counter + 1\n        end\n\n        if counter >= 3 then return string.format('%.1fGiB', size)\n        elseif counter >= 2 then return string.format('%.1fMiB', size)\n        elseif counter >= 1 then return string.format('%.1fKiB', size)\n        else return string.format('%.1fB  ', size)\n        end\n    end\n\n    ---@param bitrate integer\n    ---@return string\n    local function scale_bitrate(bitrate)\n        if bitrate == nil then\n            return ''\n        end\n\n        local counter = 0\n        while bitrate > 1000 do\n            bitrate = bitrate / 1000\n            counter = counter + 1\n        end\n\n        if counter >= 2 then return string.format('%.1fGbps', bitrate)\n        elseif counter >= 1 then return string.format('%.1fMbps', bitrate)\n        else return string.format('%.1fKbps', bitrate)\n        end\n    end\n\n    ---@param format FormatRaw\n    local function format_special_fields(format)\n        local size_prefix = not format.filesize and format.filesize_approx and '~' or ''\n        ---@diagnostic disable-next-line: param-type-mismatch\n        format.size = (size_prefix) .. scale_filesize(format.size)\n        format.frame_rate = format.fps and format.fps .. 'fps' or ''\n        format.bitrate_total = scale_bitrate(format.tbr)\n        format.bitrate_video = scale_bitrate(format.vbr)\n        format.bitrate_audio = scale_bitrate(format.abr)\n        format.codec_video = format.vcodec == nil and 'unknown' or format.vcodec == 'none' and '' or format.vcodec\n        format.codec_audio = format.acodec == nil and 'unknown' or format.acodec == 'none' and '' or format.acodec\n        format.audio_sample_rate = format.asr and tostring(format.asr) .. 'Hz' or ''\n    end\n\n    for _, format in ipairs(all_formats) do\n        format_special_fields(format)\n    end\n\n    ---@param raw_formats { [string]: any }\n    ---@param properties string[]\n    ---@return Format[]\n    local function convert_to_format(raw_formats, properties)\n        ---@type Format[]\n        local formats = {}\n        for i, format in ipairs(raw_formats) do\n            local props = {}\n            for _, prop in ipairs(properties) do\n                props[prop] = tostring(format[prop] or '')\n            end\n            formats[i] = { properties = props, id = format.format_id }\n        end\n        return formats\n    end\n\n    return {\n        video_formats = convert_to_format(video_formats, opts.columns_video.all),\n        audio_formats = convert_to_format(audio_formats, opts.columns_audio.all),\n        video_active_id = requested_video,\n        audio_active_id = requested_audio,\n    }\nend\n\n---@return string | nil\nlocal function get_url()\n    local path, n = mp.get_property('path'), nil\n    if not path then return nil end\n    path, n = path:gsub('^ytdl://', '') -- Strip possible ytdl:// prefix.\n    if n > 0 then return path end\n\n    ---@param str string\n    ---@return boolean\n    local function is_url(str)\n        -- adapted the regex from\n        -- https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url\n        return nil ~=\n            str:match(\n                '^[%w]-://[-a-zA-Z0-9@:%._\\\\+~#=]+%.' ..\n                '[a-zA-Z0-9()][a-zA-Z0-9()]?[a-zA-Z0-9()]?[a-zA-Z0-9()]?[a-zA-Z0-9()]?[a-zA-Z0-9()]?' ..\n                '[-a-zA-Z0-9()@:%_\\\\+.~#?&/=]*')\n    end\n\n    return is_url(path) and path or nil\nend\n\nlocal uosc_available = false\n---@type { [string]: Data }\nlocal url_data = {}\n\nlocal function uosc_set_format_counts()\n    if not uosc_available then return end\n\n    local data = url_data[current_url]\n    if data then\n        mp.commandv('script-message-to', 'uosc', 'set', 'vformats', #data.video_formats)\n        mp.commandv('script-message-to', 'uosc', 'set', 'aformats', #data.audio_formats)\n    else\n        mp.commandv('script-message-to', 'uosc', 'set', 'vformats', 0)\n        mp.commandv('script-message-to', 'uosc', 'set', 'aformats', 0)\n    end\nend\n\n---@param json string\n---@return Data | nil\nlocal function process_json_string(json)\n    local json_table, err = utils.parse_json(json)\n\n    if (json_table == nil) then\n        osd_message('fetching formats failed...', 2)\n        if err == nil then err = 'unexpected error occurred' end\n        msg.error('failed to parse JSON data: ' .. err)\n        return\n    end\n\n    if json_table.formats == nil then\n        return\n    end\n\n    return process_json(json_table)\nend\n\n---Unknown format falls back on highest ranked format if possible\n---@param id string | nil\n---@param formats Format[]\n---@return string\nlocal function sanitize_format_id(id, formats)\n    return id or (formats[1] or {}).id or ''\nend\n\n---@param video_id string\n---@param audio_id string\n---@return string\nlocal function format_string(video_id, audio_id)\n    if #video_id > 0 and #audio_id > 0 then\n        return video_id .. '+' .. audio_id\n    elseif #video_id > 0 then\n        return video_id\n    elseif #audio_id > 0 then\n        return audio_id\n    else\n        return ''\n    end\nend\n\n---@param url string\n---@param video_format string\n---@param audio_format string\nlocal function set_format(url, video_format, audio_format)\n    if (url_data[url].video_active_id ~= video_format or url_data[url].audio_active_id ~= audio_format) then\n        url_data[url].video_active_id = video_format\n        url_data[url].audio_active_id = audio_format\n        if url == mp.get_property('path') then reload_resume() end\n    end\nend\n\n---@param formats Format[]\n---@param active_format string | nil\n---@param menu_type UIState\nlocal function text_menu_open(formats, active_format, menu_type)\n    local active = 0\n    local selected = 1\n    --set the cursor to the current format\n    for i, format in ipairs(formats) do\n        if format.id == active_format then\n            active = i\n            selected = active\n            break\n        end\n    end\n    if active_format == '' then\n        active = #formats + 1\n        selected = active\n    end\n\n    ---@param i integer\n    ---@return string\n    local function choose_prefix(i)\n        if i == selected and i == active then return opts.selected_and_active\n        elseif i == selected then return opts.selected_and_inactive end\n\n        if i ~= selected and i == active then return opts.unselected_and_active\n        elseif i ~= selected then return opts.unselected_and_inactive end\n        return '> ' --shouldn't get here.\n    end\n\n    local width, height\n    local margin_top, margin_bottom = 0, 0\n    local num_options = #formats > 0 and #formats + 2 or 1\n\n    ---@return integer\n    local function get_scrolled_lines()\n        local output_height = height - opts.text_padding_y * 2 - margin_top * height - margin_bottom * height\n        local screen_lines = math.max(math.floor(output_height / opts.font_size), 1)\n        local max_scroll = math.max(num_options - screen_lines, 0)\n        return math.min(math.max(selected - math.ceil(screen_lines / 2), 0), max_scroll)\n    end\n\n    local function draw_menu()\n        local ass = assdraw.ass_new()\n\n        if opts.curtain_opacity > 0 then\n            local alpha = 255 - math.ceil(255 * opts.curtain_opacity)\n            ass.text = string.format('{\\\\pos(0,0)\\\\rDefault\\\\an7\\\\1c&H000000&\\\\alpha&H%X&}', alpha)\n            ass:draw_start()\n            ass:rect_cw(0, 0, width, height)\n            ass:draw_stop()\n            ass:new_event()\n        end\n\n        local scrolled_lines = get_scrolled_lines()\n        local pos_y = opts.shift_y + margin_top * height + opts.text_padding_y - scrolled_lines * opts.font_size\n        ass:pos(opts.shift_x + opts.text_padding_x, pos_y)\n        local clip_top = math.floor(margin_top * height + 0.5)\n        local clip_bottom = math.floor((1 - margin_bottom) * height + 0.5)\n        local clipping_coordinates = '0,' .. clip_top .. ',' .. width .. ',' .. clip_bottom\n        ass:append('{\\\\rDefault\\\\an7\\\\q2\\\\clip(' .. clipping_coordinates .. ')}' .. opts.style_ass_tags)\n\n        if #formats > 0 then\n            for i, format in ipairs(formats) do\n                ass:append(choose_prefix(i) .. format.label .. '\\\\N')\n            end\n            ass:append(choose_prefix(#formats + 1) .. 'Disabled\\\\N')\n            ass:append(choose_prefix(#formats + 2) .. menu_type.to_other_type.type_capitalized .. ' menu')\n        else\n            ass:append('no formats found\\\\N')\n            ass:append(opts.selected_and_inactive .. menu_type.to_other_type.type_capitalized .. ' menu')\n        end\n\n        osd.data = ass.text\n        osd:update()\n    end\n\n    local function update_dimensions()\n        local _, h, aspect = mp.get_osd_size()\n        if opts.scale_playlist_by_window then h = 720 end\n        height = h\n        width = height * aspect\n        osd.res_y = height\n        osd.res_x = width\n        draw_menu()\n    end\n\n    local update_margins = function(_, val)\n        if not val then\n            val = mp.get_property_native('user-data/osc/margins')\n        end\n        if val then\n            margin_top = val.t\n            margin_bottom = val.b\n        else\n            margin_top = 0\n            margin_bottom = 0\n        end\n        draw_menu()\n    end\n    mp.observe_property('user-data/osc/margins', 'native', update_margins)\n\n    update_dimensions()\n    update_margins()\n    mp.observe_property('osd-dimensions', 'native', update_dimensions)\n\n    ---@param amount integer\n    local function selected_move(amount)\n        selected = selected + amount\n        if selected < 1 then selected = num_options\n        elseif selected > num_options then selected = 1 end\n        if osd_timer then\n            osd_timer:kill()\n            osd_timer:resume()\n        end\n        draw_menu()\n    end\n\n    ---@param keys string | nil\n    ---@param name string\n    ---@param func function\n    ---@param opts table | nil\n    local function bind_keys(keys, name, func, opts)\n        if not keys then\n            mp.add_forced_key_binding(keys, name, func, opts)\n            return\n        end\n        local i = 1\n        for key in keys:gmatch('[^%s]+') do\n            local prefix = i == 1 and '' or i\n            mp.add_forced_key_binding(key, name .. prefix, func, opts)\n            i = i + 1\n        end\n    end\n\n    ---@param keys string | nil\n    ---@param name string\n    local function unbind_keys(keys, name)\n        if not keys then\n            mp.remove_key_binding(name)\n            return\n        end\n        local i = 1\n        for key in keys:gmatch('[^%s]+') do\n            local prefix = i == 1 and '' or i\n            mp.remove_key_binding(name .. prefix)\n            i = i + 1\n        end\n    end\n\n    -- make sure observers are cleaned up\n    if open_menu_state and open_menu_state == open_menu_state.to_menu and destructor then destructor() end\n    destructor = function()\n        unbind_keys(opts.up_binding, 'move_up')\n        unbind_keys(opts.down_binding, 'move_down')\n        unbind_keys(opts.select_binding, 'select')\n        unbind_keys(opts.close_menu_binding, 'close')\n        mp.unobserve_property(update_dimensions)\n        mp.unobserve_property(update_margins)\n    end\n\n    osd_timer:kill()\n    if opts.menu_timeout > 0 then\n        osd_timer.timeout = opts.menu_timeout\n        osd_timer:resume()\n    end\n\n    bind_keys(opts.up_binding, 'move_up', function() selected_move( -1) end, { repeatable = true })\n    bind_keys(opts.down_binding, 'move_down', function() selected_move(1) end, { repeatable = true })\n    bind_keys(opts.close_menu_binding, 'close', menu_close)\n    bind_keys(opts.select_binding, 'select', function()\n        if selected == num_options then\n            mp.unobserve_property(update_dimensions)\n            mp.unobserve_property(update_margins)\n            if menu_type.is_video then audio_formats_toggle()\n            else video_formats_toggle() end\n            return\n        end\n        menu_close()\n        if selected == active then return end\n        if current_url == nil then return end\n\n        local video_id, audio_id\n        local id = formats[selected] and formats[selected].id or ''\n        local data = url_data[current_url]\n        if menu_type.is_video then\n            video_id = id\n            audio_id = sanitize_format_id(data.audio_active_id, data.audio_formats)\n        else\n            video_id = sanitize_format_id(data.video_active_id, data.video_formats)\n            audio_id = id\n        end\n        set_format(current_url, video_id, audio_id)\n    end)\n\n    osd.hidden = false\n    draw_menu()\nend\n\n---@param menu table\n---@param menu_type UIState\nlocal function uosc_show_menu(menu, menu_type)\n    local json = utils.format_json(menu)\n    -- always using update wouldn't work, because it doesn't support the on_close command\n    -- therefore opening a different kind requires `open-menu`\n    -- while updating the same kind requires `update-menu`\n    if open_menu_state == menu_type then mp.commandv('script-message-to', 'uosc', 'update-menu', json)\n    else mp.commandv('script-message-to', 'uosc', 'open-menu', json) end\nend\n\n---@param formats Format[]\n---@param active_format string | nil\n---@param menu_type UIState\nlocal function uosc_menu_open(formats, active_format, menu_type)\n    local menu = {\n        title = menu_type.type_capitalized .. ' Formats',\n        items = {},\n        type = 'quality-menu-' .. menu_type.name,\n        keep_open = true,\n        on_close = {\n            'script-message-to',\n            script_name,\n            'uosc-menu-closed',\n            menu_type.name,\n        }\n    }\n\n    menu.items[#menu.items + 1] = {\n        title = menu_type.to_other_type.type_capitalized,\n        italic = true,\n        bold = true,\n        hint = 'open menu',\n        value = {\n            'script-message-to',\n            script_name,\n            menu_type.to_other_type.type .. '_formats_toggle',\n        },\n    }\n    menu.items[#menu.items + 1] = {\n        title = 'Disabled',\n        italic = true,\n        muted = true,\n        hint = '—',\n        active = active_format == '',\n        value = {\n            'script-message-to',\n            script_name,\n            menu_type.type .. '-format-set',\n            current_url,\n            '',\n        }\n    }\n\n    for _, format in ipairs(formats) do\n        menu.items[#menu.items + 1] = {\n            title = format.title,\n            hint = format.hint,\n            active = format.id == active_format,\n            value = {\n                'script-message-to',\n                script_name,\n                menu_type.type .. '-format-set',\n                current_url,\n                format.id,\n            }\n        }\n    end\n\n    uosc_show_menu(menu, menu_type)\n    destructor = function()\n        mp.commandv('script-message-to', 'uosc', 'close-menu', menu.type)\n    end\nend\n\n---Check if property is same for all formats\n---@param formats Format[]\n---@param properties string[]\n---@return { [string]: boolean }\nlocal function identical_for_all(formats, properties)\n    ---@param formats Format[]\n    ---@param prop string\n    ---@return boolean\n    local function all_formats_same_value(formats, prop)\n        local first_value = nil\n        for _, format in ipairs(formats) do\n            first_value = first_value or format.properties[prop]\n            if format.properties[prop] ~= first_value then return false end\n        end\n        return true\n    end\n\n    local identical_props = {}\n    for _, prop in ipairs(properties) do\n        identical_props[prop] = all_formats_same_value(formats, prop)\n    end\n    return identical_props\nend\n\n---@param formats Format[]\n---@param columns string[]\n---@param column_align_left boolean[]\n---@return string[]\nlocal function format_table(formats, columns, column_align_left)\n    local column_widths = {}\n    for _, format in pairs(formats) do\n        for col, prop in ipairs(columns) do\n            local width = format.properties[prop]:len()\n            if not column_widths[col] or column_widths[col] < width then\n                column_widths[col] = width\n            end\n        end\n    end\n\n    local identical_columns = #formats < 2 and {} or identical_for_all(formats, columns)\n\n    local show_columns = {}\n    for i, width in ipairs(column_widths) do\n        local prop = columns[i]\n        if width > 0 and not (opts.hide_identical_columns and identical_columns[prop]) then\n            show_columns[#show_columns + 1] = {\n                prop = prop,\n                width = width,\n                align_left = column_align_left[prop]\n            }\n        end\n    end\n\n    local spacing = 2\n    ---@type string[]\n    local rows = {}\n    for i, format in ipairs(formats) do\n        local row = {}\n        for j, column in ipairs(show_columns) do\n            -- lua errors out with width > 99 (\"invalid conversion specification\")\n            local width = math.min(column.width * (column.align_left and -1 or 1), 99)\n            row[j] = string.format('%' .. width .. 's', format.properties[column.prop] or '')\n        end\n        rows[i] = table.concat(row, string.format('%' .. spacing .. 's', '')):gsub('%s+$', '')\n    end\n    return rows\nend\n\n---@param formats Format[]\n---@param columns string[]\n---@return string[]\nlocal function format_csv(formats, columns)\n    local identical_props = #formats < 2 and {} or identical_for_all(formats, columns)\n    local hints = {}\n    for i, format in ipairs(formats) do\n        local row = {}\n        for _, prop in ipairs(columns) do\n            local val = format.properties[prop]\n            if #val > 0 and not (opts.hide_identical_columns and identical_props[prop]) then\n                row[#row + 1] = val\n            end\n        end\n        hints[i] = table.concat(row, ', ')\n    end\n    return hints\nend\n\n---@param formats Format[]\n---@param menu_type UIState\nlocal function ensure_menu_data_filled(formats, menu_type)\n    if uosc_available then\n        if formats[1] and formats[1].title == nil then\n            local columns = menu_type.is_video and opts.columns_video or opts.columns_audio\n            local titles = format_table(formats, columns.title, columns.title_align_left)\n\n            local hints = {}\n            if columns.hint then\n                hints = format_csv(formats, columns.hint)\n            end\n\n            for i, format in ipairs(formats) do\n                format.title = titles[i]\n                format.hint = hints[i]\n            end\n        end\n    else\n        if formats[1] and formats[1].label == nil then\n            local columns = menu_type.is_video and opts.columns_video or opts.columns_audio\n            local labels = format_table(formats, columns.all, columns.all_align_left)\n            for i, format in ipairs(formats) do format.label = labels[i] end\n        end\n    end\nend\n\n---@param menu_type UIState\nlocal function loading_message(menu_type)\n    menu_type = menu_type.to_fetching\n    if uosc_available then\n        if open_menu_state and open_menu_state == menu_type then return end\n        local menu = {\n            title = menu_type.type_capitalized .. ' Formats',\n            items = { { icon = 'spinner', selectable = false, value = 'ignore' } },\n            type = 'quality-menu-' .. menu_type.name,\n            keep_open = true,\n            on_close = {\n                'script-message-to',\n                script_name,\n                'uosc-menu-closed',\n                menu_type.name\n            }\n        }\n        uosc_show_menu(menu, menu_type)\n        destructor = function()\n            mp.commandv('script-message-to', 'uosc', 'close-menu', menu.type)\n        end\n    else\n        osd_message('fetching available ' .. menu_type.type .. ' formats...', 60)\n    end\n    open_menu_state = menu_type\nend\n\n---@param menu_type UIState\nfunction menu_open(menu_type)\n    if not current_url then return end\n    menu_type = menu_type.to_menu\n\n    local data = url_data[current_url]\n    if not data then\n        if opts.fetch_formats then\n            loading_message(menu_type)\n            return\n        end\n\n        -- shallow clone so that each url has it's own active format ids\n        data = {}\n        for k, v in pairs(opts.predefined_data) do\n            data[k] = v\n        end\n        url_data[current_url] = data\n    end\n    local formats = menu_type.is_video and data.video_formats or data.audio_formats\n    local active_format\n    if menu_type.is_video then active_format = data.video_active_id\n    else active_format = data.audio_active_id end\n\n    msg.verbose('current ytdl-format: ' .. mp.get_property('ytdl-format', ''))\n\n    ensure_menu_data_filled(formats, menu_type)\n    if uosc_available then uosc_menu_open(formats, active_format, menu_type)\n    else text_menu_open(formats, active_format, menu_type) end\n    open_menu_state = menu_type\nend\n\nfunction menu_close()\n    if destructor then\n        destructor()\n        destructor = nil\n    end\n    if not osd.hidden then hide_osd() end\n    open_menu_state = nil\nend\n\n---@param menu_type UIState\nlocal function toggle_menu(menu_type)\n    if open_menu_state and open_menu_state.type == menu_type.type then\n        menu_close()\n        return\n    end\n\n    if current_url == nil then\n        if uosc_available then\n            if menu_type.is_video then\n                mp.commandv('script-binding', 'uosc/video')\n            else\n                mp.commandv('script-binding', 'uosc/audio')\n            end\n        end\n        return\n    end\n\n    menu_open(menu_type)\nend\n\nfunction video_formats_toggle() toggle_menu(states.video_menu) end\nfunction audio_formats_toggle() toggle_menu(states.audio_menu) end\n\n-- keybind to launch menu\nmp.add_key_binding(nil, 'video_formats_toggle', video_formats_toggle)\nmp.add_key_binding(nil, 'audio_formats_toggle', audio_formats_toggle)\nmp.add_key_binding(nil, 'reload', reload_resume)\n\nmp.register_event('start-file', function()\n    local new_url = get_url()\n    local url_changed = current_url ~= new_url\n    current_url = new_url\n    uosc_set_format_counts()\n\n    -- new path isn't an url\n    if not new_url then return menu_close() end\n\n    -- open or update menu\n    if opts.start_with_menu and url_changed or open_menu_state then\n        menu_open(open_menu_state or states.video_menu)\n    end\nend)\n\n-- run before ytdl_hook, which uses a priority of 10\nmp.add_hook('on_load', 9, function()\n    local path = mp.get_property('path')\n    local data = url_data[path]\n    if not (data and data.video_active_id and data.audio_active_id) then return end\n    local format = format_string(data.video_active_id, data.audio_active_id)\n    msg.verbose('setting ytdl-format: ' .. format)\n    mp.set_property('file-local-options/ytdl-format', format)\nend)\n\n---@param url string\n---@param format_id string\nmp.register_script_message('video-format-set', function(url, format_id)\n    menu_close()\n    local data = url_data[url]\n    set_format(url, format_id, sanitize_format_id(data.audio_active_id, data.audio_formats))\nend)\n\n---@param url string\n---@param format_id string\nmp.register_script_message('audio-format-set', function(url, format_id)\n    menu_close()\n    local data = url_data[url]\n    set_format(url, sanitize_format_id(data.video_active_id, data.video_formats), format_id)\nend)\n\n--- check if uosc is running\n---@param version string\nmp.register_script_message('uosc-version', function(version)\n    ---Like the comperator for table.sort, this returns v1 < v2\n    ---Assumes two valid semver strings\n    ---@param v1 string\n    ---@param v2 string\n    ---@return boolean\n    local function semver_comp(v1, v2)\n        local v1_iterator = v1:gmatch('%d+')\n        local v2_iterator = v2:gmatch('%d+')\n        for v2_num_str in v2_iterator do\n            local v1_num_str = v1_iterator()\n            if not v1_num_str then return true end\n            local v1_num = tonumber(v1_num_str)\n            local v2_num = tonumber(v2_num_str)\n            if v1_num < v2_num then return true end\n            if v1_num > v2_num then return false end\n        end\n        return false\n    end\n\n    local min_version = '4.6.0'\n    uosc_available = not semver_comp(version, min_version)\n    if not uosc_available then return end\n    uosc_set_format_counts()\n    mp.commandv(\n        'script-message-to',\n        'uosc',\n        'overwrite-binding',\n        'stream-quality',\n        'script-binding ' .. script_name .. '/video_formats_toggle'\n    )\n    ---@param name string\n    mp.register_script_message('uosc-menu-closed', function(name)\n        -- got closed from the uosc side\n        if open_menu_state and open_menu_state.name == name then\n            destructor = nil\n            menu_close()\n        end\n    end)\nend)\nmp.commandv('script-message-to', 'uosc', 'get-version', mp.get_script_name())\n\nmp.observe_property('user-data/mpv/ytdl/json-subprocess-result', 'native', function(_, ytdl_result)\n    if not ytdl_result then\n        -- property gets deleted in on_after_end_file hook\n        return\n    end\n\n    if not current_url then\n        osd_message('current_url is nil', 2)\n        msg.error('current_url is nil')\n        return\n    end\n\n    local json = ytdl_result.stdout\n\n    if ytdl_result.status ~= 0 or json == '' then\n        json = nil\n        osd_message('fetching formats failed...', 2)\n    elseif json then\n        ---@type Data | nil\n        local data = url_data[current_url]\n        if data == nil then\n            data = process_json_string(json)\n            url_data[current_url] = data\n            uosc_set_format_counts()\n        end\n        if not data then return end\n        if open_menu_state and open_menu_state == open_menu_state.to_fetching then\n            menu_open(open_menu_state)\n        end\n    end\n\nend)\n"
  }
]