├── LICENSE ├── README.md ├── thumbfast.conf └── thumbfast.lua /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at https://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. 374 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # thumbfast 2 | High-performance on-the-fly thumbnailer for mpv. 3 | 4 | **The script does not display thumbnails on its own,** it is meant to be used alongside a UI script that calls thumbfast. 5 | 6 | [Preview of thumbfast on different UIs](https://user-images.githubusercontent.com/42466980/199102896-65f9e989-4189-4734-82a7-bda8ee63c7a6.webm) 7 | 8 | ## Installation 9 | Place thumbfast.lua in your mpv `scripts` folder. 10 | Default settings are listed in thumbfast.conf, copy it to your mpv `script-opts` folder to customize. 11 | 12 | For the vanilla UI, you also have to install [osc.lua](https://github.com/po5/thumbfast/blob/vanilla-osc/player/lua/osc.lua) (identical to the mpv default, with added thumbfast support) into your `scripts` folder. 13 | For third-party UIs, refer to their respective installation instructions. [See the list of supported UIs.](#ui-support) 14 | 15 | ## Features 16 | No dependencies, no background thumbnail generation hogging your CPU. 17 | Customizable sizes, interval between thumbnails, cropping support, respects applied video filters. 18 | Supports web videos e.g. YouTube (disabled by default), mixed aspect ratio videos. 19 | 20 | This script makes an effort to run on mpv versions as old as 0.29.0 (Windows, Linux) and 0.33.0 (Mac). 21 | Note that most custom UIs will not support vintage mpv builds, update before submitting an issue and mention if behavior is the same. 22 | Support for <0.33.0 on Linux requires socat. 23 | 24 | ## Usage 25 | Once the lua file is in your scripts directory, and you are using a UI that supports thumbfast, you are done. 26 | Hover on the timeline for nice thumbnails. 27 | 28 | ## UI support 29 | - [uosc](https://github.com/tomasklaen/uosc) 30 | - [osc.lua](https://github.com/po5/thumbfast/blob/vanilla-osc/player/lua/osc.lua) (use this fork for vanilla UI) 31 | - [progressbar](https://github.com/torque/mpv-progressbar) 32 | - [tethys](https://github.com/Zren/mpv-osc-tethys) (PR pending, [lua](https://github.com/po5/mpv-osc-tethys/blob/thumbfast/osc_tethys.lua)) 33 | - [modern](https://github.com/maoiscat/mpv-osc-modern/tree/with.thumbfast) (separate branch) 34 | - [ModernX](https://github.com/cyl0/ModernX) 35 | - [oscc](https://github.com/longtermfree/oscc) 36 | - [mfpbar](https://codeberg.org/NRK/mpv-toolbox/src/branch/master/mfpbar) 37 | 38 | ## mpv frontends 39 | [ImPlay](https://tsl0922.github.io/ImPlay/) is auto-detected, but if you encounter issues set `mpv_path=ImPlay` in `script-opts/thumbfast.conf`. 40 | 41 | [mpv.net](https://github.com/mpvnet-player/mpv.net) is directly supported since v7, no special configuration is required. 42 | 43 | Other frontends and older versions of mpv.net will need [standalone mpv](https://mpv.io/installation/) accessible within [Path](https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee537574(v=office.14)#to-add-a-path-to-the-path-environment-variable). 44 | The easiest way is to copy standalone mpv files inside of your frontend's installation folder. 45 | It will be used in the background to generate thumbnails. 46 | 47 | ## MacOS 48 | If your mpv install is an app bundle (e.g. stolendata builds), the script will work but you may notice the Dock shakes when generating the first thumbnail. 49 | To get rid of the shaking, make sure the app is in your Applications folder, then run: `sudo ln -s /Applications/mpv.app/Contents/MacOS/mpv /usr/local/mpv` 50 | If you installed mpv via [Homebrew](https://brew.sh/), there are no issues. 51 | 52 | ## Configuration 53 | `socket`: On Windows, a plain string. On Linux and Mac, a directory path for temporary files. Leave empty for auto. 54 | `thumbnail`: Path for the temporary thumbnail file (must not be a directory). Leave empty for auto. 55 | `max_height`, `max_width`: Maximum thumbnail generation size in pixels (scaled down to fit). Values are scaled when hidpi is enabled. Defaults to 200x200. 56 | `scale_factor`: Scale factor for thumbnail display size (requires mpv 0.38+). Lower quality than increasing max_height and max_width. Defaults to 1. 57 | `tone_mapping`: Apply tone-mapping, no to disable. Defaults to auto, which copies your mpv config. 58 | `overlay_id`: Overlay id for thumbnails. Leave blank unless you know what you're doing. 59 | `spawn_first`: Spawn thumbnailer on file load for faster initial thumbnails. Defaults to no. 60 | `quit_after_inactivity`: Close thumbnailer process after an inactivity period in seconds. Defaults to 0 (disabled). 61 | `network`: Enable on remote files. Defaults to no. 62 | `audio`: Enable on audio files. Defaults to no. 63 | `hwdec`: Enable hardware decoding. Defaults to no. 64 | `direct_io`: Windows only: write directly to pipe (requires LuaJIT). Should improve performance, ymmv. 65 | `mpv_path`: Custom path to the mpv executable. Defaults to mpv. 66 | 67 | ## For UI developers: How to add thumbfast support to your script 68 | This API usage example code is [CC0 (public domain)](https://creativecommons.org/share-your-work/public-domain/cc0/). 69 | 70 | Declare the thumbfast state variable near the top of your script. 71 | *Do not manually modify those values, they are automatically updated by the script and changes will be overwritten.* 72 | ```lua 73 | local thumbfast = { 74 | width = 0, 75 | height = 0, 76 | disabled = true, 77 | available = false 78 | } 79 | ``` 80 | Register the state setter near the end of your script, or near where your other script messages are. 81 | You are expected to have required `mp.utils` (for this example, into a `utils` variable). 82 | ```lua 83 | mp.register_script_message("thumbfast-info", function(json) 84 | local data = utils.parse_json(json) 85 | if type(data) ~= "table" or not data.width or not data.height then 86 | msg.error("thumbfast-info: received json didn't produce a table with thumbnail information") 87 | else 88 | thumbfast = data 89 | end 90 | end) 91 | ``` 92 | Now for the actual functionality. You are in charge of supplying the time hovered (in seconds), and x/y coordinates for the top-left corner of the thumbnail. 93 | In this example, the thumbnail is horizontally centered on the cursor, respects a 10px margin on both sides, and displays 10px above the cursor. 94 | This code should be run when the user hovers on the seekbar. Don't worry even if this is called on every render, thumbfast won't be bogged down. 95 | ```lua 96 | -- below are examples of what these values may look like 97 | -- margin_left = 10 98 | -- margin_right = 10 99 | -- cursor_x, cursor_y = mp.get_mouse_pos() 100 | -- display_width = mp.get_property_number("osd-width") 101 | -- hovered_seconds = video_duration * cursor_x / display_width 102 | 103 | if not thumbfast.disabled then 104 | mp.commandv("script-message-to", "thumbfast", "thumb", 105 | -- hovered time in seconds 106 | hovered_seconds, 107 | -- x 108 | math.min(display_width - thumbfast.width - margin_right, math.max(margin_left, cursor_x - thumbfast.width / 2)), 109 | -- y 110 | cursor_y - 10 - thumbfast.height 111 | ) 112 | end 113 | ``` 114 | This code should be run when the user leaves the seekbar. 115 | ```lua 116 | if thumbfast.available then 117 | mp.commandv("script-message-to", "thumbfast", "clear") 118 | end 119 | ``` 120 | If you did all that, your script can now display thumbnails! 121 | Look at existing integrations for more concrete examples. 122 | 123 | If positioning isn't enough and you want complete control over rendering: 124 | Register a `thumbfast-render` script message. 125 | When requesting the thumbnail, set x and y to empty strings and supply your script's name as the 4th argument. 126 | You will recieve a json object with the keys `width`, `height`, `x`, `y`, `socket`, `thumbnail`, `overlay_id` when the thumbnail is ready. 127 | -------------------------------------------------------------------------------- /thumbfast.conf: -------------------------------------------------------------------------------- 1 | # Socket path (leave empty for auto) 2 | socket= 3 | 4 | # Thumbnail path (leave empty for auto) 5 | thumbnail= 6 | 7 | # Maximum thumbnail generation size in pixels (scaled down to fit) 8 | # Values are scaled when hidpi is enabled 9 | max_height=200 10 | max_width=200 11 | 12 | # Scale factor for thumbnail display size (requires mpv 0.38+) 13 | # Note that this is lower quality than increasing max_height and max_width 14 | scale_factor=1 15 | 16 | # Apply tone-mapping, no to disable 17 | tone_mapping=auto 18 | 19 | # Overlay id 20 | overlay_id=42 21 | 22 | # Spawn thumbnailer on file load for faster initial thumbnails 23 | spawn_first=no 24 | 25 | # Close thumbnailer process after an inactivity period in seconds, 0 to disable 26 | quit_after_inactivity=0 27 | 28 | # Enable on network playback 29 | network=no 30 | 31 | # Enable on audio playback 32 | audio=no 33 | 34 | # Enable hardware decoding 35 | hwdec=no 36 | 37 | # Windows only: use native Windows API to write to pipe (requires LuaJIT) 38 | direct_io=no 39 | 40 | # Custom path to the mpv executable 41 | mpv_path=mpv 42 | -------------------------------------------------------------------------------- /thumbfast.lua: -------------------------------------------------------------------------------- 1 | -- thumbfast.lua 2 | -- 3 | -- High-performance on-the-fly thumbnailer 4 | -- 5 | -- Built for easy integration in third-party UIs. 6 | 7 | --[[ 8 | This Source Code Form is subject to the terms of the Mozilla Public 9 | License, v. 2.0. If a copy of the MPL was not distributed with this 10 | file, You can obtain one at https://mozilla.org/MPL/2.0/. 11 | ]] 12 | 13 | local options = { 14 | -- Socket path (leave empty for auto) 15 | socket = "", 16 | 17 | -- Thumbnail path (leave empty for auto) 18 | thumbnail = "", 19 | 20 | -- Maximum thumbnail generation size in pixels (scaled down to fit) 21 | -- Values are scaled when hidpi is enabled 22 | max_height = 200, 23 | max_width = 200, 24 | 25 | -- Scale factor for thumbnail display size (requires mpv 0.38+) 26 | -- Note that this is lower quality than increasing max_height and max_width 27 | scale_factor = 1, 28 | 29 | -- Apply tone-mapping, no to disable 30 | tone_mapping = "auto", 31 | 32 | -- Overlay id 33 | overlay_id = 42, 34 | 35 | -- Spawn thumbnailer on file load for faster initial thumbnails 36 | spawn_first = false, 37 | 38 | -- Close thumbnailer process after an inactivity period in seconds, 0 to disable 39 | quit_after_inactivity = 0, 40 | 41 | -- Enable on network playback 42 | network = false, 43 | 44 | -- Enable on audio playback 45 | audio = false, 46 | 47 | -- Enable hardware decoding 48 | hwdec = false, 49 | 50 | -- Windows only: use native Windows API to write to pipe (requires LuaJIT) 51 | direct_io = false, 52 | 53 | -- Custom path to the mpv executable 54 | mpv_path = "mpv" 55 | } 56 | 57 | mp.utils = require "mp.utils" 58 | mp.options = require "mp.options" 59 | mp.options.read_options(options, "thumbfast") 60 | 61 | local properties = {} 62 | local pre_0_30_0 = mp.command_native_async == nil 63 | local pre_0_33_0 = true 64 | local support_media_control = mp.get_property_native("media-controls") ~= nil 65 | 66 | function subprocess(args, async, callback) 67 | callback = callback or function() end 68 | 69 | if not pre_0_30_0 then 70 | if async then 71 | return mp.command_native_async({name = "subprocess", playback_only = true, args = args, env = "PATH="..os.getenv("PATH")}, callback) 72 | else 73 | return mp.command_native({name = "subprocess", playback_only = false, capture_stdout = true, args = args, env = "PATH="..os.getenv("PATH")}) 74 | end 75 | else 76 | if async then 77 | return mp.utils.subprocess_detached({args = args}, callback) 78 | else 79 | return mp.utils.subprocess({args = args}) 80 | end 81 | end 82 | end 83 | 84 | local winapi = {} 85 | if options.direct_io then 86 | local ffi_loaded, ffi = pcall(require, "ffi") 87 | if ffi_loaded then 88 | winapi = { 89 | ffi = ffi, 90 | C = ffi.C, 91 | bit = require("bit"), 92 | socket_wc = "", 93 | 94 | -- WinAPI constants 95 | CP_UTF8 = 65001, 96 | GENERIC_WRITE = 0x40000000, 97 | OPEN_EXISTING = 3, 98 | FILE_FLAG_WRITE_THROUGH = 0x80000000, 99 | FILE_FLAG_NO_BUFFERING = 0x20000000, 100 | PIPE_NOWAIT = ffi.new("unsigned long[1]", 0x00000001), 101 | 102 | INVALID_HANDLE_VALUE = ffi.cast("void*", -1), 103 | 104 | -- don't care about how many bytes WriteFile wrote, so allocate something to store the result once 105 | _lpNumberOfBytesWritten = ffi.new("unsigned long[1]"), 106 | } 107 | -- cache flags used in run() to avoid bor() call 108 | winapi._createfile_pipe_flags = winapi.bit.bor(winapi.FILE_FLAG_WRITE_THROUGH, winapi.FILE_FLAG_NO_BUFFERING) 109 | 110 | ffi.cdef[[ 111 | void* __stdcall CreateFileW(const wchar_t *lpFileName, unsigned long dwDesiredAccess, unsigned long dwShareMode, void *lpSecurityAttributes, unsigned long dwCreationDisposition, unsigned long dwFlagsAndAttributes, void *hTemplateFile); 112 | bool __stdcall WriteFile(void *hFile, const void *lpBuffer, unsigned long nNumberOfBytesToWrite, unsigned long *lpNumberOfBytesWritten, void *lpOverlapped); 113 | bool __stdcall CloseHandle(void *hObject); 114 | bool __stdcall SetNamedPipeHandleState(void *hNamedPipe, unsigned long *lpMode, unsigned long *lpMaxCollectionCount, unsigned long *lpCollectDataTimeout); 115 | int __stdcall MultiByteToWideChar(unsigned int CodePage, unsigned long dwFlags, const char *lpMultiByteStr, int cbMultiByte, wchar_t *lpWideCharStr, int cchWideChar); 116 | ]] 117 | 118 | winapi.MultiByteToWideChar = function(MultiByteStr) 119 | if MultiByteStr then 120 | local utf16_len = winapi.C.MultiByteToWideChar(winapi.CP_UTF8, 0, MultiByteStr, -1, nil, 0) 121 | if utf16_len > 0 then 122 | local utf16_str = winapi.ffi.new("wchar_t[?]", utf16_len) 123 | if winapi.C.MultiByteToWideChar(winapi.CP_UTF8, 0, MultiByteStr, -1, utf16_str, utf16_len) > 0 then 124 | return utf16_str 125 | end 126 | end 127 | end 128 | return "" 129 | end 130 | 131 | else 132 | options.direct_io = false 133 | end 134 | end 135 | 136 | local file 137 | local file_bytes = 0 138 | local spawned = false 139 | local disabled = false 140 | local force_disabled = false 141 | local spawn_waiting = false 142 | local spawn_working = false 143 | local script_written = false 144 | 145 | local dirty = false 146 | 147 | local x, y 148 | local last_x, last_y 149 | 150 | local last_seek_time 151 | 152 | local effective_w, effective_h = options.max_width, options.max_height 153 | local real_w, real_h 154 | local last_real_w, last_real_h 155 | 156 | local script_name 157 | 158 | local show_thumbnail = false 159 | 160 | local filters_reset = {["lavfi-crop"]=true, ["crop"]=true} 161 | local filters_runtime = {["hflip"]=true, ["vflip"]=true} 162 | local filters_all = {["hflip"]=true, ["vflip"]=true, ["lavfi-crop"]=true, ["crop"]=true} 163 | 164 | local tone_mappings = {["none"]=true, ["clip"]=true, ["linear"]=true, ["gamma"]=true, ["reinhard"]=true, ["hable"]=true, ["mobius"]=true} 165 | local last_tone_mapping 166 | 167 | local last_vf_reset = "" 168 | local last_vf_runtime = "" 169 | 170 | local last_rotate = 0 171 | 172 | local par = "" 173 | local last_par = "" 174 | 175 | local last_crop = nil 176 | 177 | local last_has_vid = 0 178 | local has_vid = 0 179 | 180 | local file_timer 181 | local file_check_period = 1/60 182 | 183 | local allow_fast_seek = true 184 | 185 | local client_script = [=[ 186 | #!/usr/bin/env bash 187 | MPV_IPC_FD=0; MPV_IPC_PATH="%s" 188 | trap "kill 0" EXIT 189 | while [[ $# -ne 0 ]]; do case $1 in --mpv-ipc-fd=*) MPV_IPC_FD=${1/--mpv-ipc-fd=/} ;; esac; shift; done 190 | if echo "print-text thumbfast" >&"$MPV_IPC_FD"; then echo -n > "$MPV_IPC_PATH"; tail -f "$MPV_IPC_PATH" >&"$MPV_IPC_FD" & while read -r -u "$MPV_IPC_FD" 2>/dev/null; do :; done; fi 191 | ]=] 192 | 193 | local function get_os() 194 | local raw_os_name = "" 195 | 196 | if jit and jit.os and jit.arch then 197 | raw_os_name = jit.os 198 | else 199 | if package.config:sub(1,1) == "\\" then 200 | -- Windows 201 | local env_OS = os.getenv("OS") 202 | if env_OS then 203 | raw_os_name = env_OS 204 | end 205 | else 206 | raw_os_name = subprocess({"uname", "-s"}).stdout 207 | end 208 | end 209 | 210 | raw_os_name = (raw_os_name):lower() 211 | 212 | local os_patterns = { 213 | ["windows"] = "windows", 214 | ["linux"] = "linux", 215 | 216 | ["osx"] = "darwin", 217 | ["mac"] = "darwin", 218 | ["darwin"] = "darwin", 219 | 220 | ["^mingw"] = "windows", 221 | ["^cygwin"] = "windows", 222 | 223 | ["bsd$"] = "darwin", 224 | ["sunos"] = "darwin" 225 | } 226 | 227 | -- Default to linux 228 | local str_os_name = "linux" 229 | 230 | for pattern, name in pairs(os_patterns) do 231 | if raw_os_name:match(pattern) then 232 | str_os_name = name 233 | break 234 | end 235 | end 236 | 237 | return str_os_name 238 | end 239 | 240 | local os_name = mp.get_property("platform") or get_os() 241 | 242 | local path_separator = os_name == "windows" and "\\" or "/" 243 | 244 | if options.socket == "" then 245 | if os_name == "windows" then 246 | options.socket = "thumbfast" 247 | else 248 | options.socket = "/tmp/thumbfast" 249 | end 250 | end 251 | 252 | if options.thumbnail == "" then 253 | if os_name == "windows" then 254 | options.thumbnail = os.getenv("TEMP").."\\thumbfast.out" 255 | else 256 | options.thumbnail = "/tmp/thumbfast.out" 257 | end 258 | end 259 | 260 | local unique = mp.utils.getpid() 261 | 262 | options.socket = options.socket .. unique 263 | options.thumbnail = options.thumbnail .. unique 264 | 265 | if options.direct_io then 266 | if os_name == "windows" then 267 | winapi.socket_wc = winapi.MultiByteToWideChar("\\\\.\\pipe\\" .. options.socket) 268 | end 269 | 270 | if winapi.socket_wc == "" then 271 | options.direct_io = false 272 | end 273 | end 274 | 275 | options.scale_factor = math.floor(options.scale_factor) 276 | 277 | local mpv_path = options.mpv_path 278 | local frontend_path 279 | 280 | if mpv_path == "mpv" and os_name == "windows" then 281 | frontend_path = mp.get_property_native("user-data/frontend/process-path") 282 | mpv_path = frontend_path or mpv_path 283 | end 284 | 285 | if mpv_path == "mpv" and os_name == "darwin" and unique then 286 | -- TODO: look into ~~osxbundle/ 287 | mpv_path = string.gsub(subprocess({"ps", "-o", "comm=", "-p", tostring(unique)}).stdout, "[\n\r]", "") 288 | if mpv_path ~= "mpv" then 289 | mpv_path = string.gsub(mpv_path, "/mpv%-bundle$", "/mpv") 290 | local mpv_bin = mp.utils.file_info("/usr/local/mpv") 291 | if mpv_bin and mpv_bin.is_file then 292 | mpv_path = "/usr/local/mpv" 293 | else 294 | local mpv_app = mp.utils.file_info("/Applications/mpv.app/Contents/MacOS/mpv") 295 | if mpv_app and mpv_app.is_file then 296 | mp.msg.warn("symlink mpv to fix Dock icons: `sudo ln -s /Applications/mpv.app/Contents/MacOS/mpv /usr/local/mpv`") 297 | else 298 | mp.msg.warn("drag to your Applications folder and symlink mpv to fix Dock icons: `sudo ln -s /Applications/mpv.app/Contents/MacOS/mpv /usr/local/mpv`") 299 | end 300 | end 301 | end 302 | end 303 | 304 | local function vo_tone_mapping() 305 | local passes = mp.get_property_native("vo-passes") 306 | if passes and passes["fresh"] then 307 | for k, v in pairs(passes["fresh"]) do 308 | for k2, v2 in pairs(v) do 309 | if k2 == "desc" and v2 then 310 | local tone_mapping = string.match(v2, "([0-9a-z.-]+) tone map") 311 | if tone_mapping then 312 | return tone_mapping 313 | end 314 | end 315 | end 316 | end 317 | end 318 | end 319 | 320 | local function vf_string(filters, full) 321 | local vf = "" 322 | local vf_table = properties["vf"] 323 | 324 | if (properties["video-crop"] or "") ~= "" then 325 | vf = "lavfi-crop="..string.gsub(properties["video-crop"], "(%d*)x?(%d*)%+(%d+)%+(%d+)", "w=%1:h=%2:x=%3:y=%4").."," 326 | local width = properties["video-out-params"] and properties["video-out-params"]["dw"] 327 | local height = properties["video-out-params"] and properties["video-out-params"]["dh"] 328 | if width and height then 329 | vf = string.gsub(vf, "w=:h=:", "w="..width..":h="..height..":") 330 | end 331 | end 332 | 333 | if vf_table and #vf_table > 0 then 334 | for i = #vf_table, 1, -1 do 335 | if filters[vf_table[i].name] then 336 | local args = "" 337 | for key, value in pairs(vf_table[i].params) do 338 | if args ~= "" then 339 | args = args .. ":" 340 | end 341 | args = args .. key .. "=" .. value 342 | end 343 | vf = vf .. vf_table[i].name .. "=" .. args .. "," 344 | end 345 | end 346 | end 347 | 348 | if (full and options.tone_mapping ~= "no") or options.tone_mapping == "auto" then 349 | if properties["video-params"] and properties["video-params"]["primaries"] == "bt.2020" then 350 | local tone_mapping = options.tone_mapping 351 | if tone_mapping == "auto" then 352 | tone_mapping = last_tone_mapping or properties["tone-mapping"] 353 | if tone_mapping == "auto" and properties["current-vo"] == "gpu-next" then 354 | tone_mapping = vo_tone_mapping() 355 | end 356 | end 357 | if not tone_mappings[tone_mapping] then 358 | tone_mapping = "hable" 359 | end 360 | last_tone_mapping = tone_mapping 361 | vf = vf .. "zscale=transfer=linear,format=gbrpf32le,tonemap="..tone_mapping..",zscale=transfer=bt709," 362 | end 363 | end 364 | 365 | if full then 366 | vf = vf.."scale=w="..effective_w..":h="..effective_h..par..",pad=w="..effective_w..":h="..effective_h..":x=-1:y=-1,format=bgra" 367 | end 368 | 369 | return vf 370 | end 371 | 372 | local function calc_dimensions() 373 | local width = properties["video-out-params"] and properties["video-out-params"]["dw"] 374 | local height = properties["video-out-params"] and properties["video-out-params"]["dh"] 375 | if not width or not height then return end 376 | 377 | local scale = properties["display-hidpi-scale"] or 1 378 | 379 | if width / height > options.max_width / options.max_height then 380 | effective_w = math.floor(options.max_width * scale + 0.5) 381 | effective_h = math.floor(height / width * effective_w + 0.5) 382 | else 383 | effective_h = math.floor(options.max_height * scale + 0.5) 384 | effective_w = math.floor(width / height * effective_h + 0.5) 385 | end 386 | 387 | local v_par = properties["video-out-params"] and properties["video-out-params"]["par"] or 1 388 | if v_par == 1 then 389 | par = ":force_original_aspect_ratio=decrease" 390 | else 391 | par = "" 392 | end 393 | end 394 | 395 | local info_timer = nil 396 | 397 | local function info(w, h) 398 | local rotate = properties["video-params"] and properties["video-params"]["rotate"] 399 | local image = properties["current-tracks/video"] and properties["current-tracks/video"]["image"] 400 | local albumart = image and properties["current-tracks/video"]["albumart"] 401 | 402 | disabled = (w or 0) == 0 or (h or 0) == 0 or 403 | has_vid == 0 or 404 | (properties["demuxer-via-network"] and not options.network) or 405 | (albumart and not options.audio) or 406 | (image and not albumart) or 407 | force_disabled 408 | 409 | if info_timer then 410 | info_timer:kill() 411 | info_timer = nil 412 | elseif has_vid == 0 or (rotate == nil and not disabled) then 413 | info_timer = mp.add_timeout(0.05, function() info(w, h) end) 414 | end 415 | 416 | local json, err = mp.utils.format_json({width=w * options.scale_factor, height=h * options.scale_factor, scale_factor=options.scale_factor, disabled=disabled, available=true, socket=options.socket, thumbnail=options.thumbnail, overlay_id=options.overlay_id}) 417 | if pre_0_30_0 then 418 | mp.command_native({"script-message", "thumbfast-info", json}) 419 | else 420 | mp.command_native_async({"script-message", "thumbfast-info", json}, function() end) 421 | end 422 | end 423 | 424 | local function remove_thumbnail_files() 425 | if file then 426 | file:close() 427 | file = nil 428 | file_bytes = 0 429 | end 430 | os.remove(options.thumbnail) 431 | os.remove(options.thumbnail..".bgra") 432 | end 433 | 434 | local activity_timer 435 | 436 | local function spawn(time) 437 | if disabled then return end 438 | 439 | local path = properties["path"] 440 | if path == nil then return end 441 | 442 | if options.quit_after_inactivity > 0 then 443 | if show_thumbnail or activity_timer:is_enabled() then 444 | activity_timer:kill() 445 | end 446 | activity_timer:resume() 447 | end 448 | 449 | local open_filename = properties["stream-open-filename"] 450 | local ytdl = open_filename and properties["demuxer-via-network"] and path ~= open_filename 451 | if ytdl then 452 | path = open_filename 453 | end 454 | 455 | remove_thumbnail_files() 456 | 457 | local vid = properties["vid"] 458 | has_vid = vid or 0 459 | 460 | local args = { 461 | mpv_path, "--no-config", "--msg-level=all=no", "--idle", "--pause", "--keep-open=always", "--really-quiet", "--no-terminal", 462 | "--load-scripts=no", "--osc=no", "--ytdl=no", "--load-stats-overlay=no", "--load-osd-console=no", "--load-auto-profiles=no", 463 | "--edition="..(properties["edition"] or "auto"), "--vid="..(vid or "auto"), "--no-sub", "--no-audio", 464 | "--start="..time, allow_fast_seek and "--hr-seek=no" or "--hr-seek=yes", 465 | "--ytdl-format=worst", "--demuxer-readahead-secs=0", "--demuxer-max-bytes=128KiB", 466 | "--vd-lavc-skiploopfilter=all", "--vd-lavc-software-fallback=1", "--vd-lavc-fast", "--vd-lavc-threads=2", "--hwdec="..(options.hwdec and "auto" or "no"), 467 | "--vf="..vf_string(filters_all, true), 468 | "--sws-scaler=fast-bilinear", 469 | "--video-rotate="..last_rotate, 470 | "--ovc=rawvideo", "--of=image2", "--ofopts=update=1", "--o="..options.thumbnail 471 | } 472 | 473 | if not pre_0_30_0 then 474 | table.insert(args, "--sws-allow-zimg=no") 475 | end 476 | 477 | if support_media_control then 478 | table.insert(args, "--media-controls=no") 479 | end 480 | 481 | if os_name == "darwin" and properties["macos-app-activation-policy"] then 482 | table.insert(args, "--macos-app-activation-policy=accessory") 483 | end 484 | 485 | if os_name == "windows" or pre_0_33_0 then 486 | table.insert(args, "--input-ipc-server="..options.socket) 487 | elseif not script_written then 488 | local client_script_path = options.socket..".run" 489 | local script = io.open(client_script_path, "w+") 490 | if script == nil then 491 | mp.msg.error("client script write failed") 492 | return 493 | else 494 | script_written = true 495 | script:write(string.format(client_script, options.socket)) 496 | script:close() 497 | subprocess({"chmod", "+x", client_script_path}, true) 498 | table.insert(args, "--scripts="..client_script_path) 499 | end 500 | else 501 | local client_script_path = options.socket..".run" 502 | table.insert(args, "--scripts="..client_script_path) 503 | end 504 | 505 | table.insert(args, "--") 506 | table.insert(args, path) 507 | 508 | spawned = true 509 | spawn_waiting = true 510 | 511 | subprocess(args, true, 512 | function(success, result) 513 | if spawn_waiting and (success == false or (result.status ~= 0 and result.status ~= -2)) then 514 | spawned = false 515 | spawn_waiting = false 516 | options.tone_mapping = "no" 517 | mp.msg.error("mpv subprocess create failed") 518 | if not spawn_working then -- notify users of required configuration 519 | if options.mpv_path == "mpv" then 520 | if properties["current-vo"] == "libmpv" then 521 | if options.mpv_path == mpv_path then -- attempt to locate ImPlay 522 | mpv_path = "ImPlay" 523 | spawn(time) 524 | else -- ImPlay not in path 525 | if os_name ~= "darwin" then 526 | force_disabled = true 527 | info(real_w or effective_w, real_h or effective_h) 528 | end 529 | mp.commandv("show-text", "thumbfast: ERROR! cannot create mpv subprocess", 5000) 530 | mp.commandv("script-message-to", "implay", "show-message", "thumbfast initial setup", "Set mpv_path=PATH_TO_ImPlay in thumbfast config:\n" .. string.gsub(mp.command_native({"expand-path", "~~/script-opts/thumbfast.conf"}), "[/\\]", path_separator).."\nand restart ImPlay") 531 | end 532 | else 533 | mp.commandv("show-text", "thumbfast: ERROR! cannot create mpv subprocess", 5000) 534 | if os_name == "windows" and frontend_path == nil then 535 | mp.commandv("script-message-to", "mpvnet", "show-text", "thumbfast: ERROR! install standalone mpv, see README", 5000, 20) 536 | mp.commandv("script-message", "mpv.net", "show-text", "thumbfast: ERROR! install standalone mpv, see README", 5000, 20) 537 | end 538 | end 539 | else 540 | mp.commandv("show-text", "thumbfast: ERROR! cannot create mpv subprocess", 5000) 541 | -- found ImPlay but not defined in config 542 | mp.commandv("script-message-to", "implay", "show-message", "thumbfast", "Set mpv_path=PATH_TO_ImPlay in thumbfast config:\n" .. string.gsub(mp.command_native({"expand-path", "~~/script-opts/thumbfast.conf"}), "[/\\]", path_separator).."\nand restart ImPlay") 543 | end 544 | end 545 | elseif success == true and (result.status == 0 or result.status == -2) then 546 | if not spawn_working and properties["current-vo"] == "libmpv" and options.mpv_path ~= mpv_path then 547 | mp.commandv("script-message-to", "implay", "show-message", "thumbfast initial setup", "Set mpv_path=ImPlay in thumbfast config:\n" .. string.gsub(mp.command_native({"expand-path", "~~/script-opts/thumbfast.conf"}), "[/\\]", path_separator).."\nand restart ImPlay") 548 | end 549 | spawn_working = true 550 | spawn_waiting = false 551 | end 552 | end 553 | ) 554 | end 555 | 556 | local function run(command) 557 | if not spawned then return end 558 | 559 | if options.direct_io then 560 | local hPipe = winapi.C.CreateFileW(winapi.socket_wc, winapi.GENERIC_WRITE, 0, nil, winapi.OPEN_EXISTING, winapi._createfile_pipe_flags, nil) 561 | if hPipe ~= winapi.INVALID_HANDLE_VALUE then 562 | local buf = command .. "\n" 563 | winapi.C.SetNamedPipeHandleState(hPipe, winapi.PIPE_NOWAIT, nil, nil) 564 | winapi.C.WriteFile(hPipe, buf, #buf + 1, winapi._lpNumberOfBytesWritten, nil) 565 | winapi.C.CloseHandle(hPipe) 566 | end 567 | 568 | return 569 | end 570 | 571 | local command_n = command.."\n" 572 | 573 | if os_name == "windows" then 574 | if file and file_bytes + #command_n >= 4096 then 575 | file:close() 576 | file = nil 577 | file_bytes = 0 578 | end 579 | if not file then 580 | file = io.open("\\\\.\\pipe\\"..options.socket, "r+b") 581 | end 582 | elseif pre_0_33_0 then 583 | subprocess({"/usr/bin/env", "sh", "-c", "echo '" .. command .. "' | socat - " .. options.socket}) 584 | return 585 | elseif not file then 586 | file = io.open(options.socket, "r+") 587 | end 588 | if file then 589 | file_bytes = file:seek("end") 590 | file:write(command_n) 591 | file:flush() 592 | end 593 | end 594 | 595 | local function draw(w, h, script) 596 | if not w or not show_thumbnail then return end 597 | if x ~= nil then 598 | local scale_w, scale_h = options.scale_factor ~= 1 and (w * options.scale_factor) or nil, options.scale_factor ~= 1 and (h * options.scale_factor) or nil 599 | if pre_0_30_0 then 600 | mp.command_native({"overlay-add", options.overlay_id, x, y, options.thumbnail..".bgra", 0, "bgra", w, h, (4*w), scale_w, scale_h}) 601 | else 602 | mp.command_native_async({"overlay-add", options.overlay_id, x, y, options.thumbnail..".bgra", 0, "bgra", w, h, (4*w), scale_w, scale_h}, function() end) 603 | end 604 | elseif script then 605 | local json, err = mp.utils.format_json({width=w, height=h, scale_factor=options.scale_factor, x=x, y=y, socket=options.socket, thumbnail=options.thumbnail, overlay_id=options.overlay_id}) 606 | mp.commandv("script-message-to", script, "thumbfast-render", json) 607 | end 608 | end 609 | 610 | local function real_res(req_w, req_h, filesize) 611 | local count = filesize / 4 612 | local diff = (req_w * req_h) - count 613 | 614 | if (properties["video-params"] and properties["video-params"]["rotate"] or 0) % 180 == 90 then 615 | req_w, req_h = req_h, req_w 616 | end 617 | 618 | if diff == 0 then 619 | return req_w, req_h 620 | else 621 | local threshold = 5 -- throw out results that change too much 622 | local long_side, short_side = req_w, req_h 623 | if req_h > req_w then 624 | long_side, short_side = req_h, req_w 625 | end 626 | for a = short_side, short_side - threshold, -1 do 627 | if count % a == 0 then 628 | local b = count / a 629 | if long_side - b < threshold then 630 | if req_h < req_w then return b, a else return a, b end 631 | end 632 | end 633 | end 634 | return nil 635 | end 636 | end 637 | 638 | local function move_file(from, to) 639 | if os_name == "windows" then 640 | os.remove(to) 641 | end 642 | -- move the file because it can get overwritten while overlay-add is reading it, and crash the player 643 | os.rename(from, to) 644 | end 645 | 646 | local function seek(fast) 647 | if last_seek_time then 648 | run("async seek " .. last_seek_time .. (fast and " absolute+keyframes" or " absolute+exact")) 649 | end 650 | end 651 | 652 | local seek_period = 3/60 653 | local seek_period_counter = 0 654 | local seek_timer 655 | seek_timer = mp.add_periodic_timer(seek_period, function() 656 | if seek_period_counter == 0 then 657 | seek(allow_fast_seek) 658 | seek_period_counter = 1 659 | else 660 | if seek_period_counter == 2 then 661 | if allow_fast_seek then 662 | seek_timer:kill() 663 | seek() 664 | end 665 | else seek_period_counter = seek_period_counter + 1 end 666 | end 667 | end) 668 | seek_timer:kill() 669 | 670 | local function request_seek() 671 | if seek_timer:is_enabled() then 672 | seek_period_counter = 0 673 | else 674 | seek_timer:resume() 675 | seek(allow_fast_seek) 676 | seek_period_counter = 1 677 | end 678 | end 679 | 680 | local function check_new_thumb() 681 | -- the slave might start writing to the file after checking existance and 682 | -- validity but before actually moving the file, so move to a temporary 683 | -- location before validity check to make sure everything stays consistant 684 | -- and valid thumbnails don't get overwritten by invalid ones 685 | local tmp = options.thumbnail..".tmp" 686 | move_file(options.thumbnail, tmp) 687 | local finfo = mp.utils.file_info(tmp) 688 | if not finfo then return false end 689 | spawn_waiting = false 690 | local w, h = real_res(effective_w, effective_h, finfo.size) 691 | if w then -- only accept valid thumbnails 692 | move_file(tmp, options.thumbnail..".bgra") 693 | 694 | real_w, real_h = w, h 695 | if real_w and (real_w ~= last_real_w or real_h ~= last_real_h) then 696 | last_real_w, last_real_h = real_w, real_h 697 | info(real_w, real_h) 698 | end 699 | if not show_thumbnail then 700 | file_timer:kill() 701 | end 702 | return true 703 | end 704 | 705 | return false 706 | end 707 | 708 | file_timer = mp.add_periodic_timer(file_check_period, function() 709 | if check_new_thumb() then 710 | draw(real_w, real_h, script_name) 711 | end 712 | end) 713 | file_timer:kill() 714 | 715 | local function clear() 716 | file_timer:kill() 717 | seek_timer:kill() 718 | if options.quit_after_inactivity > 0 then 719 | if show_thumbnail or activity_timer:is_enabled() then 720 | activity_timer:kill() 721 | end 722 | activity_timer:resume() 723 | end 724 | last_seek_time = nil 725 | show_thumbnail = false 726 | last_x = nil 727 | last_y = nil 728 | if script_name then return end 729 | if pre_0_30_0 then 730 | mp.command_native({"overlay-remove", options.overlay_id}) 731 | else 732 | mp.command_native_async({"overlay-remove", options.overlay_id}, function() end) 733 | end 734 | end 735 | 736 | local function quit() 737 | activity_timer:kill() 738 | if show_thumbnail then 739 | activity_timer:resume() 740 | return 741 | end 742 | run("quit") 743 | spawned = false 744 | real_w, real_h = nil, nil 745 | clear() 746 | end 747 | 748 | activity_timer = mp.add_timeout(options.quit_after_inactivity, quit) 749 | activity_timer:kill() 750 | 751 | local function thumb(time, r_x, r_y, script) 752 | if disabled then return end 753 | 754 | time = tonumber(time) 755 | if time == nil then return end 756 | 757 | if r_x == "" or r_y == "" then 758 | x, y = nil, nil 759 | else 760 | x, y = math.floor(r_x + 0.5), math.floor(r_y + 0.5) 761 | end 762 | 763 | script_name = script 764 | if last_x ~= x or last_y ~= y or not show_thumbnail then 765 | show_thumbnail = true 766 | last_x, last_y = x, y 767 | draw(real_w, real_h, script) 768 | end 769 | 770 | if options.quit_after_inactivity > 0 then 771 | if show_thumbnail or activity_timer:is_enabled() then 772 | activity_timer:kill() 773 | end 774 | activity_timer:resume() 775 | end 776 | 777 | if time == last_seek_time then return end 778 | last_seek_time = time 779 | if not spawned then spawn(time) end 780 | request_seek() 781 | if not file_timer:is_enabled() then file_timer:resume() end 782 | end 783 | 784 | local function watch_changes() 785 | if not dirty or not properties["video-out-params"] then return end 786 | dirty = false 787 | 788 | local old_w = effective_w 789 | local old_h = effective_h 790 | 791 | calc_dimensions() 792 | 793 | local vf_reset = vf_string(filters_reset) 794 | local rotate = properties["video-rotate"] or 0 795 | 796 | local resized = old_w ~= effective_w or 797 | old_h ~= effective_h or 798 | last_vf_reset ~= vf_reset or 799 | (last_rotate % 180) ~= (rotate % 180) or 800 | par ~= last_par or last_crop ~= properties["video-crop"] 801 | 802 | if resized then 803 | last_rotate = rotate 804 | info(effective_w, effective_h) 805 | elseif last_has_vid ~= has_vid and has_vid ~= 0 then 806 | info(effective_w, effective_h) 807 | end 808 | 809 | if spawned then 810 | if resized then 811 | -- mpv doesn't allow us to change output size 812 | local seek_time = last_seek_time 813 | run("quit") 814 | clear() 815 | spawned = false 816 | spawn(seek_time or mp.get_property_number("time-pos", 0)) 817 | file_timer:resume() 818 | else 819 | if rotate ~= last_rotate then 820 | run("set video-rotate "..rotate) 821 | end 822 | local vf_runtime = vf_string(filters_runtime) 823 | if vf_runtime ~= last_vf_runtime then 824 | run("vf set "..vf_string(filters_all, true)) 825 | last_vf_runtime = vf_runtime 826 | end 827 | end 828 | else 829 | last_vf_runtime = vf_string(filters_runtime) 830 | end 831 | 832 | last_vf_reset = vf_reset 833 | last_rotate = rotate 834 | last_par = par 835 | last_crop = properties["video-crop"] 836 | last_has_vid = has_vid 837 | 838 | if not spawned and not disabled and options.spawn_first and resized then 839 | spawn(mp.get_property_number("time-pos", 0)) 840 | file_timer:resume() 841 | end 842 | end 843 | 844 | local function update_property(name, value) 845 | properties[name] = value 846 | end 847 | 848 | local function update_property_dirty(name, value) 849 | properties[name] = value 850 | dirty = true 851 | if name == "tone-mapping" then 852 | last_tone_mapping = nil 853 | end 854 | end 855 | 856 | local function update_tracklist(name, value) 857 | -- current-tracks shim 858 | for _, track in ipairs(value) do 859 | if track.type == "video" and track.selected then 860 | properties["current-tracks/video"] = track 861 | return 862 | end 863 | end 864 | end 865 | 866 | local function sync_changes(prop, val) 867 | update_property(prop, val) 868 | if val == nil then return end 869 | 870 | if type(val) == "boolean" then 871 | if prop == "vid" then 872 | has_vid = 0 873 | last_has_vid = 0 874 | info(effective_w, effective_h) 875 | clear() 876 | return 877 | end 878 | val = val and "yes" or "no" 879 | end 880 | 881 | if prop == "vid" then 882 | has_vid = 1 883 | end 884 | 885 | if not spawned then return end 886 | 887 | run("set "..prop.." "..val) 888 | dirty = true 889 | end 890 | 891 | local function file_load() 892 | clear() 893 | spawned = false 894 | real_w, real_h = nil, nil 895 | last_real_w, last_real_h = nil, nil 896 | last_tone_mapping = nil 897 | last_seek_time = nil 898 | if info_timer then 899 | info_timer:kill() 900 | info_timer = nil 901 | end 902 | 903 | calc_dimensions() 904 | info(effective_w, effective_h) 905 | end 906 | 907 | local function shutdown() 908 | run("quit") 909 | remove_thumbnail_files() 910 | if os_name ~= "windows" then 911 | os.remove(options.socket) 912 | os.remove(options.socket..".run") 913 | end 914 | end 915 | 916 | local function on_duration(prop, val) 917 | allow_fast_seek = (val or 30) >= 30 918 | end 919 | 920 | mp.observe_property("current-tracks/video", "native", function(name, value) 921 | if pre_0_33_0 then 922 | mp.unobserve_property(update_tracklist) 923 | pre_0_33_0 = false 924 | end 925 | update_property(name, value) 926 | end) 927 | 928 | mp.observe_property("track-list", "native", update_tracklist) 929 | mp.observe_property("display-hidpi-scale", "native", update_property_dirty) 930 | mp.observe_property("video-out-params", "native", update_property_dirty) 931 | mp.observe_property("video-params", "native", update_property_dirty) 932 | mp.observe_property("vf", "native", update_property_dirty) 933 | mp.observe_property("tone-mapping", "native", update_property_dirty) 934 | mp.observe_property("demuxer-via-network", "native", update_property) 935 | mp.observe_property("stream-open-filename", "native", update_property) 936 | mp.observe_property("macos-app-activation-policy", "native", update_property) 937 | mp.observe_property("current-vo", "native", update_property) 938 | mp.observe_property("video-rotate", "native", update_property) 939 | mp.observe_property("video-crop", "native", update_property) 940 | mp.observe_property("path", "native", update_property) 941 | mp.observe_property("vid", "native", sync_changes) 942 | mp.observe_property("edition", "native", sync_changes) 943 | mp.observe_property("duration", "native", on_duration) 944 | 945 | mp.register_script_message("thumb", thumb) 946 | mp.register_script_message("clear", clear) 947 | 948 | mp.register_event("file-loaded", file_load) 949 | mp.register_event("shutdown", shutdown) 950 | 951 | mp.register_idle(watch_changes) 952 | --------------------------------------------------------------------------------