├── .github └── workflows │ └── publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── modules ├── group_utils.py ├── nodes.py ├── server.py ├── utils.py └── video_utils.py ├── pyproject.toml ├── requirements.txt └── web ├── EnhancedGroups ├── enhancedGroups.js ├── utils.js └── versionManager.js ├── OldSpinner ├── spinner.css └── spinner.js ├── VideoPlayer └── videoPlayer.js ├── css └── lnlNodes.css ├── eventHandlers.js ├── images ├── goto_end.png ├── goto_in_point.png ├── goto_out_point.png ├── goto_start.png ├── pause.png ├── play.png ├── set_in_point.png ├── set_out_point.png ├── step_backward.png └── step_forward.png ├── nodes.js ├── styles.js └── utils.js /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to Comfy registry 2 | on: 3 | workflow_dispatch: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | paths: 9 | - "pyproject.toml" 10 | 11 | jobs: 12 | publish-node: 13 | name: Publish Custom Node to registry 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Check out code 17 | uses: actions/checkout@v4 18 | - name: Publish Custom Node 19 | uses: Comfy-Org/publish-node-action@main 20 | with: 21 | ## Add your own personal access token to your Github Repository secrets and reference it here. 22 | personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }} 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *.cover 46 | .hypothesis/ 47 | .pytest_cache/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | db.sqlite3 57 | db.sqlite3-journal 58 | 59 | # Flask stuff: 60 | instance/ 61 | .webassets-cache 62 | 63 | # Scrapy stuff: 64 | .scrapy 65 | 66 | # Sphinx documentation 67 | docs/_build/ 68 | 69 | # PyBuilder 70 | target/ 71 | 72 | # Jupyter Notebook 73 | .ipynb_checkpoints 74 | 75 | # IPython 76 | profile_default/ 77 | ipython_config.py 78 | 79 | # pyenv 80 | .python-version 81 | 82 | # pipenv 83 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 84 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 85 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 86 | # install all needed dependencies. 87 | #Pipfile.lock 88 | 89 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 90 | __pypackages__/ 91 | 92 | # Celery stuff 93 | celerybeat-schedule 94 | celerybeat.pid 95 | 96 | # SageMath parsed files 97 | *.sage.py 98 | 99 | # Environments 100 | .env 101 | .venv 102 | env/ 103 | venv/ 104 | ENV/ 105 | env.bak/ 106 | venv.bak/ 107 | 108 | # Spyder project settings 109 | .spyderproject 110 | .spyproject 111 | 112 | # Rope project settings 113 | .ropeproject 114 | 115 | # mkdocs documentation 116 | /site 117 | 118 | # mypy 119 | .mypy_cache/ 120 | .dmypy.json 121 | dmypy.json 122 | 123 | # Pyre type checker 124 | .pyre/ 125 | 126 | # pytype static type analyzer 127 | .pytype/ 128 | 129 | # Cython debug symbols 130 | cython_debug/ 131 | 132 | # Ignore all local .env files 133 | **/.env 134 | 135 | *.code-workspace 136 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Frame Selector & Sequence Selection Node for ComfyUI 2 | The Late Night Labs (LNL) Frame Selector node for ComfyUI is aimed at enhancing video interaction within the ComfyUI framework. It enables users to upload, playback, and perform basic In/Out on video files directly within the ComfyUI environment. 3 | 4 | ## Features 5 | - Video Upload and Playback: Users can upload video files and utilize standard playback controls including Play, Pause, Scrub, and Rewind. 6 | - Editing Tools: The node offers simple editing capabilities such as setting In/Out points for selecting specific video sections, frame selection for detailed editing, and outputting frames with handles for further processing. Audio can be included. 7 | 8 | ## Structure 9 | The project is structured into two main components: the web directory, containing front-end JavaScript and CSS files, and the modules directory, containing back-end Python scripts. 10 | 11 | ### Web Directory 12 | - eventHandlers.js: Manages event handling for video playback and editing features. 13 | - nodes.js: Defines the Load Video Node structure and integration within ComfyUI. 14 | - utils.js: Contains utility functions for video processing and manipulation. 15 | - widgets.js: Implements UI components for video editing. 16 | - styles.js: Handles dynamic styling of the video node elements. 17 | - css/lnlNodes.css: Provides styling for the Load Video Node components. 18 | - images/: Contains icons used for playback and editing controls. 19 | 20 | ### Modules Directory 21 | - server.py: Back-end server implementation for handling video upload and processing. 22 | - utils.py: Back-end utility functions supporting video editing features. 23 | - nodes.py: Defines the server-side representation of the Load Video Node. 24 | 25 | ## Installation 26 | 1. Ensure you have ComfyUI and its dependencies installed. 27 | 2. Clone this repo into custom_nodes: 28 | ``` 29 | $ cd ComfyUI/custom_nodes 30 | $ git clone https://github.com/latenightlabs/ComfyUI-LNL.git 31 | ``` 32 | 33 | Install dependencies if not downloaded from the Comfy Manager: 34 | ``` 35 | $ cd ComfyUI-LNL 36 | $ pip install -r requirements.txt 37 | ``` 38 | 39 | # Troubleshooting 40 | Make sure you that you have ffmpeg defined in your path. 41 | 42 | # To use the Load Video Node: 43 | 44 | image 45 | 46 | ## Inputs 47 | 1. Choose Video to Upload: Select a video file for processing (in this case, 'input/logo.mp4'). 48 | 49 | ## Outputs 50 | Options include: 51 | 52 | 1. Current image: Current frame being viewed. 53 | 2. Image Batch (in/out): Select a range of frames to process based on in and out points. 54 | 3. Frame count (rel): Display the count of frames relative to in and out points. 55 | 4. Frame count (abs): Absolute count of frames in the uploaded video. 56 | 5. Current frame (rel): The current frame number relative to in and out points. 57 | 6. Current frame (abs): The absolute frame number within the entire video. 58 | 7. Framerate: FPS in the uploaded video. 59 | 8. Audio: Pass audio track if desired. 60 | 61 | ## Playback Controls 62 | 63 | image 64 | 65 | ### Timeline Scrubber 66 | 1. Shows the current frame number out of the total number of frames (in this instance, frame 66 of 149). 67 | 2. In Point is green 68 | 3. Out Point is red 69 | Note: In and Out point is set with the playback controls or in the input fields. 70 | 71 | 72 | ### Media Controls left to right: 73 | 1. Takes the user to the very first frame of the video. 74 | 2. Set 'in_point'. 75 | 3. Takes the user to the 'in_point', which is the frame set as the starting point for a selected range. 76 | 4. Steps backward by one frame, moving the current frame to the previous frame in the video. 77 | 5. Plays the video from the current frame forward. 78 | 6. _Not visible while Play button is displayed: Pause the playback at the current frame._ 79 | 7. Steps forward by one frame at a time. 80 | 8. Takes the user to the 'out_point', the frame set as the ending point for a selected range. 81 | 9. Sets the 'out_point'. 82 | 10. Jumps to the very last frame of the video. 83 | 84 | ### Numeric Input Fields and Controls: 85 | 86 | 1. current_frame: Displays the current frame number and allows you to jump to a specific frame. 87 | 2. in_point and out_point: Fields for setting the start and end points for a range of frames for focused editing of a frame range. 88 | 3. select_every_nth_frame: Specify a pattern for selecting frames (e.g., every 2nd frame, every 3rd frame, etc.). 89 | 90 | 91 | ## Credits 92 | This project uses parts of code and some ideas from the following repositories: 93 | [ComfyUI-Custom-Scripts](https://github.com/pythongosssss/ComfyUI-Custom-Scripts) 94 | [ComfyUI-VideoHelperSuite](https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite) 95 | Make sure to check them out, they both offer awesome tool suites! 96 | 97 | We also use icons for player controls supplied by [Icons8](https://icons8/com). 98 | 99 | # Enhanced Groups with Versioning Support for ComfyUI 100 | This project aims to provide the users with a possibilty to create custom components (specific group versions) which can be reused throughout different projects, or used in different places within the same project. Users can also take advantage of using different versions of the same group/component in the same workflow. Going forward, we're going to be referencing these versioned groups as components. 101 | 102 | ## Adding a ComfyUI group or a Component 103 | By right-clicking on an empty canvas, you're presented with a context menu where the `Add Group` option is presented. By default, ComfyUI creates an empty group called `Group` when you tap that option. Due to installing this library, you'll be taken to another submenu offering options of `Empty group` (the default empty group ComfyUI creates) and a `Versioned group`. Selecting the `Versioned group` option, you'll see all of the components listed (the latest version of each component). If you've just installed this library, you won't see any components because we haven't created any yet. 104 | 105 | ![Adding a ComfyUI group or a Component](https://github.com/user-attachments/assets/bfbcf083-93d7-43b7-9701-ea85f4f73450) 106 | 107 | ## Creating a component 108 | Let's create an empty ComfyUI group by right-clicking an empty canvas, selecting `Add Group` -> `Empty group`. You can name the group anything you like e.g. `Test group`. Bear in mind that the group name isn't tied to the component name, meaning each component version can have a different group name. 109 | 110 | Add a `Load image` node (use the default `example.png` image pre-installed with ComfyUI), and connect it to a `Preview image` node. Make sure both are inside our group. Right-click inside our group, and select `Edit Group` -> `Versions` -> `Save`. 111 | 112 | ![Creating a component 01](https://github.com/user-attachments/assets/4a29b1b2-0ec6-498b-bf6f-e5c977746e7c) 113 | 114 | Once selected, you'll be asked to enter a component name. Let's call it `First component` and hit `OK`. 115 | 116 | ![Creating a component 02](https://github.com/user-attachments/assets/33804fbb-afe7-4136-bf8d-a11358b4d06d) 117 | 118 | This will create a component out of this group, and you'll see additional info in the group header appear, such as the component name and component version. 119 | 120 | ![Creating a component 03](https://github.com/user-attachments/assets/903ab107-40c4-4785-a8a1-8d57811901f0) 121 | 122 | ## Loading a component 123 | Now, once our component is created, let's clear the workflow by selecting `Clear` from the ComfyUI menu. Right-click on an empty canvas again, and from `Add Group` -> `Versioned group` select our component. 124 | 125 | ![Loading a component 01](https://github.com/user-attachments/assets/8b3929a8-938a-4199-98fd-8097c6765fcb) 126 | 127 | This will add our previously saved component to the workflow. You can do it a couple of times more, e.g. twice, to add the component on different parts of the canvas. 128 | 129 | ![Loading a component 02](https://github.com/user-attachments/assets/55756640-c101-4fbf-ab99-4dc8d3593aff) 130 | 131 | ## Saving a new version of the component 132 | Let's select one of our component's and shuffle the nodes around a bit, maybe even change the group size and name. We'll do it on the left topmost one for our example. 133 | 134 | ![Saving a new version of the component 01](https://github.com/user-attachments/assets/7aca3cf4-8061-482f-9767-d6b057e9a935) 135 | 136 | Now, once the changes have been made, right-click on the group, and select `Edit Group` -> `Versions` -> `Save as new version`. This will create a new version of our component, version 2. The changes will also be reflected in the group's header. 137 | 138 | ![Saving a new version of the component 02](https://github.com/user-attachments/assets/124c665e-416f-4a72-8914-75f9b7a32f3f) 139 | 140 | Do note that, should you wish to add another component to the workflow, you'll be offered to add the component's last version (as initially mentioned). That would now be the version 2. 141 | 142 | ![Saving a new version of the component 03](https://github.com/user-attachments/assets/7a813c7b-c62a-4092-a080-e8810e5c3426) 143 | 144 | ## Loading a specific component version 145 | By now, we've already seen how to add the latest component version to our workflow. But if we want to load a specific version, we must right-click on the group and select `Edit Group` -> `Versions` -> `Load version` and select a specific version. To make navigating different versions easier, each version is labeled with its last change date and time. 146 | 147 | ![Loading a specific component version version 01](https://github.com/user-attachments/assets/cbfa46e2-732e-4f6b-bacd-1e6db9505df3) 148 | 149 | In our example, let's load v2 in our top-right component. We'll end up with two v2 `First component` components and one v1 `First component` component. 150 | 151 | ![Loading a specific component version 02](https://github.com/user-attachments/assets/0a312bdb-d870-44ae-872b-007bd494172d) 152 | 153 | ## Undoing changes to a specific component version 154 | Provided we've made some changes to one of our components but haven't saved them (can be the latest or one of the previous versions) and we want to undo them, we can select `Edit Group` -> `Versions` -> `Refresh`. In our example, we chose to modify the bottom-right component's node locations and the group title. Selecting `Refresh` will reset the changes, or rather reload the v1 of the component. 155 | 156 | ![Undoing changes to a specific component version](https://github.com/user-attachments/assets/7d2d4c6d-368e-414e-9be8-af9385e55e93) 157 | 158 | ## Refreshing a component due to a change in a different place 159 | If we've changed a component in a different part of a workflow (or even in a different workflow altogether), and wish to update a component with that same version, we can select the `Refresh` option from the example above as well. 160 | 161 | # Contributing 162 | Contributions to the Load Video Node project are welcome. Please 163 | 164 | # License 165 | This project is licensed under the GNU General Public License. 166 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from .modules.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS 2 | 3 | from .modules import server 4 | from .modules import group_utils 5 | 6 | WEB_DIRECTORY = "./web" 7 | __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"] -------------------------------------------------------------------------------- /modules/group_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from folder_paths import base_path 4 | 5 | group_extension_folder_path = "" 6 | 7 | def setup_version_data(group_data): 8 | storage_data = { 9 | "node_data": {}, 10 | } 11 | 12 | if "nodes" in group_data: 13 | storage_data["node_data"]["nodes"] = group_data["nodes"] 14 | if "links" in group_data: 15 | storage_data["node_data"]["links"] = group_data["links"] 16 | if "group" in group_data: 17 | storage_data["node_data"]["group"] = group_data["group"] 18 | 19 | return storage_data 20 | 21 | def setup_group_extension_folders(base_path, source_control_output_path): 22 | path = source_control_output_path 23 | if not os.path.isabs(source_control_output_path): 24 | path = os.path.join(base_path, source_control_output_path) 25 | 26 | if not os.path.exists(path): 27 | os.makedirs(path) 28 | 29 | return path 30 | 31 | group_extension_folder_path = setup_group_extension_folders(base_path, "lnl_enhanced_groups") 32 | -------------------------------------------------------------------------------- /modules/nodes.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import torch 4 | import numpy as np 5 | from .video_utils import * 6 | from .utils import lnl_fix_path 7 | 8 | import folder_paths 9 | 10 | """ 11 | Attribution: ComfyUI-VideoHelperSuite 12 | 13 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 14 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 15 | 16 | """ 17 | def getImageBatch(full_video_path, number_of_frames_to_process, select_every_nth_frame, starting_frame, force_size, custom_width, custom_height): 18 | generatedImages = lnl_cv_frame_generator(full_video_path, number_of_frames_to_process, starting_frame, select_every_nth_frame) 19 | (width, height, target_frame_time) = next(generatedImages) 20 | width = int(width) 21 | height = int(height) 22 | 23 | imageBatch = torch.from_numpy(np.fromiter(generatedImages, np.dtype((np.float32, (height, width, 3))))) 24 | if len(imageBatch) == 0: 25 | raise RuntimeError("No frames generated") 26 | 27 | if force_size != "Disabled": 28 | new_size = lnl_target_size(width, height, force_size, custom_width, custom_height) 29 | if new_size[0] != width or new_size[1] != height: 30 | s = imageBatch.movedim(-1,1) 31 | s = lnl_common_upscale(s, new_size[0], new_size[1], "lanczos", "center") 32 | imageBatch = s.movedim(1,-1) 33 | 34 | return (imageBatch, target_frame_time) 35 | 36 | class FrameSelectorV3(): 37 | 38 | supported_video_extensions = ['webm', 'mp4', 'mkv'] 39 | 40 | @classmethod 41 | def INPUT_TYPES(s): 42 | input_dir = folder_paths.get_input_directory() 43 | files = [] 44 | for f in os.listdir(input_dir): 45 | if os.path.isfile(os.path.join(input_dir, f)): 46 | file_parts = f.split('.') 47 | if len(file_parts) > 1 and (file_parts[-1] in FrameSelectorV3.supported_video_extensions): 48 | files.append(f) 49 | return { 50 | "required": { 51 | "video_path": (sorted(files),), 52 | "force_size": (["Disabled", "Custom Height", "Custom Width", "Custom", "256x?", "?x256", "256x256", "512x?", "?x512", "512x512"],), 53 | "custom_width": ("INT", {"default": 512, "min": 0, "max": 8192, "step": 8}), 54 | "custom_height": ("INT", {"default": 512, "min": 0, "max": 8192, "step": 8}), 55 | }, 56 | "hidden": { 57 | "prompt": "PROMPT", 58 | "unique_id": "UNIQUE_ID" 59 | }, 60 | } 61 | 62 | RETURN_TYPES = ("IMAGE", "IMAGE", "INT", "INT", "STRING", "INT", "INT", "INT", "INT", "INT", "VHS_AUDIO",) 63 | RETURN_NAMES = ("Current image", "Image Batch (in/out)", "Frame in", "Frame out", "Filename", "Frame count (rel)", "Frame count (abs)", "Current frame (rel)", "Current frame (abs)", "Frame rate", "audio",) 64 | OUTPUT_NODE = True 65 | CATEGORY = "LNL" 66 | FUNCTION = "process_video" 67 | 68 | def process_video( 69 | self, 70 | video_path, 71 | force_size, 72 | custom_width, 73 | custom_height, 74 | prompt=None, 75 | unique_id=None 76 | ): 77 | prompt_inputs = prompt[unique_id]["inputs"] 78 | full_video_path = lnl_fix_path(video_path) 79 | 80 | in_point = prompt_inputs["in_out_point_slider"]["startMarkerFrame"] 81 | out_point = prompt_inputs["in_out_point_slider"]["endMarkerFrame"] 82 | current_frame = prompt_inputs["in_out_point_slider"]["currentFrame"] 83 | total_frames = prompt_inputs["in_out_point_slider"]["totalFrames"] 84 | frame_rate = prompt_inputs["in_out_point_slider"]["frameRate"] 85 | 86 | select_every_nth_frame = prompt_inputs["select_every_nth_frame"] 87 | 88 | frames_to_process = out_point - in_point + 1 89 | starting_frame = in_point 90 | 91 | (current_image, _) = getImageBatch(full_video_path, 1, 1, current_frame - 1, force_size, custom_width, custom_height) 92 | (in_out_images, target_frame_time) = getImageBatch(full_video_path, frames_to_process, select_every_nth_frame, starting_frame - 1, force_size, custom_width, custom_height) 93 | self.target_frame_time = target_frame_time 94 | 95 | audio = lambda: lnl_get_audio(full_video_path, starting_frame * target_frame_time, 96 | frames_to_process*target_frame_time*select_every_nth_frame) 97 | 98 | return ( 99 | current_image, 100 | in_out_images, 101 | in_point, 102 | out_point, 103 | video_path, 104 | frames_to_process, 105 | total_frames, 106 | current_frame - in_point + 1, 107 | current_frame, 108 | frame_rate, 109 | lnl_lazy_eval(audio), 110 | ) 111 | 112 | class FrameSelectorV4(FrameSelectorV3): 113 | 114 | RETURN_TYPES = ("IMAGE", "IMAGE", "INT", "INT", "STRING", "INT", "INT", "INT", "INT", "INT", "FLOAT", "AUDIO",) 115 | RETURN_NAMES = ("Current image", "Image Batch (in/out)", "Frame in", "Frame out", "Filename", "Frame count (rel)", "Frame count (abs)", "Current frame (rel)", "Current frame (abs)", "Frame rate (INT)", "Frame rate (FLOAT)", "audio",) 116 | OUTPUT_NODE = True 117 | CATEGORY = "LNL" 118 | FUNCTION = "process_video" 119 | 120 | def process_video( 121 | self, 122 | video_path, 123 | force_size, 124 | custom_width, 125 | custom_height, 126 | prompt=None, 127 | unique_id=None 128 | ): 129 | prompt_inputs = prompt[unique_id]["inputs"] 130 | full_video_path = lnl_fix_path(video_path) 131 | 132 | in_point = prompt_inputs["in_out_point_slider"]["startMarkerFrame"] 133 | out_point = prompt_inputs["in_out_point_slider"]["endMarkerFrame"] 134 | current_frame = prompt_inputs["in_out_point_slider"]["currentFrame"] 135 | total_frames = prompt_inputs["in_out_point_slider"]["totalFrames"] 136 | frame_rate = prompt_inputs["in_out_point_slider"]["frameRate"] 137 | 138 | select_every_nth_frame = prompt_inputs["select_every_nth_frame"] 139 | 140 | frames_to_process = out_point - in_point + 1 141 | starting_frame = in_point 142 | 143 | result = super().process_video(video_path, force_size, custom_width, custom_height, prompt, unique_id) 144 | 145 | audio = lnl_lazy_get_audio(full_video_path, starting_frame * self.target_frame_time, 146 | frames_to_process*self.target_frame_time*select_every_nth_frame) 147 | 148 | return result[:9] + (int(result[9]), result[9], audio,) 149 | 150 | NODE_CLASS_MAPPINGS = { 151 | "LNL_FrameSelectorV4": FrameSelectorV4, 152 | "LNL_FrameSelectorV3": FrameSelectorV3 153 | } 154 | NODE_DISPLAY_NAME_MAPPINGS = { 155 | "LNL_FrameSelectorV4": "LNL Frame Selector V2", 156 | "LNL_FrameSelectorV3": "LNL Frame Selector [Deprecated] ⛔️" 157 | } 158 | -------------------------------------------------------------------------------- /modules/server.py: -------------------------------------------------------------------------------- 1 | import server 2 | web = server.web 3 | 4 | import time 5 | import json 6 | from uuid import uuid4 7 | 8 | from .utils import lnl_fix_path 9 | from .video_utils import * 10 | from .group_utils import group_extension_folder_path, setup_version_data 11 | import os 12 | 13 | @server.PromptServer.instance.routes.post("/process_video_entry") 14 | async def route_hander_method(request): 15 | json_data = await request.json() 16 | video_path = json_data['path'] 17 | 18 | video_path = lnl_fix_path(video_path) 19 | 20 | frame_rate, total_frames, duration = get_video_info(video_path) 21 | return web.json_response({"frame_rate": frame_rate, "total_frames": total_frames, "duration": duration}) 22 | 23 | @server.PromptServer.instance.routes.get("/fetch_groups_data") 24 | async def route_hander_method(request): 25 | json_files = [file for file in os.listdir(group_extension_folder_path) if file.endswith('.json')] 26 | 27 | group_data = [] 28 | for file in json_files: 29 | with open(os.path.join(group_extension_folder_path, file), 'r') as f: 30 | data = json.load(f) 31 | data["versions"] = list(map(lambda x: {"id": x["id"], "timestamp": x["last_change_timestamp"]}, sorted(data["versions"], key=lambda x: x["id"], reverse=True))) 32 | group_data.append(data) 33 | group_data = sorted(group_data, key=lambda x: x["name"]) 34 | 35 | return web.json_response(group_data) 36 | 37 | @server.PromptServer.instance.routes.get("/fetch_group_data") 38 | async def route_hander_method(request): 39 | group_id = request.query.get("groupId") 40 | group_file = os.path.join(group_extension_folder_path, f"{group_id}.json") 41 | if not os.path.exists(group_file): 42 | return web.json_response({"error": "Group data not found"}) 43 | 44 | with open(group_file, 'r') as f: 45 | data = json.load(f) 46 | data["versions"] = sorted(data["versions"], key=lambda x: x["id"], reverse=True) 47 | 48 | return web.json_response(data) 49 | 50 | # TODO: See not to return absolutely everything loaded from the group file if not needed 51 | @server.PromptServer.instance.routes.post("/save_group_data") 52 | async def route_hander_method(request): 53 | save_as_new = request.query.get("saveAsNew") == "true" 54 | json_data = await request.json() 55 | if not "group_data" in json_data: 56 | return web.json_response({"error": "Invalid data"}) 57 | 58 | group_data = json_data["group_data"] 59 | storage_version_data = setup_version_data(group_data) 60 | 61 | versioning_data = group_data["versioning_data"] 62 | if not "object_id" in versioning_data: 63 | object_id = str(uuid4()) 64 | versioning_data["object_id"] = object_id 65 | 66 | last_change_timestamp = int(time.time() * 1000) 67 | group_file = os.path.join(group_extension_folder_path, f"{versioning_data['object_id']}.json") 68 | if not os.path.exists(group_file): 69 | object_version = 1 70 | versioning_data = { 71 | "object_id": versioning_data["object_id"], 72 | "object_name": versioning_data["object_name"], 73 | "object_version": object_version 74 | } 75 | storage_version_data["node_data"]["group"]["versioning_data"] = versioning_data 76 | fresh_file_data = { 77 | "id": versioning_data["object_id"], 78 | "name": versioning_data["object_name"], 79 | "versions": [ 80 | { 81 | "id": object_version, 82 | "last_change_timestamp": last_change_timestamp, 83 | "node_data": storage_version_data["node_data"] 84 | } 85 | ], 86 | } 87 | with open(group_file, 'w') as f: 88 | json.dump(fresh_file_data, f, indent=4) 89 | return web.json_response(fresh_file_data) 90 | else: 91 | with open(group_file, 'r') as f: 92 | data = json.load(f) 93 | if save_as_new: 94 | data["versions"] = sorted(data["versions"], key=lambda x: x["id"], reverse=True) 95 | new_version_id = data["versions"][0]["id"] + 1 96 | new_version_data = { 97 | "id": new_version_id, 98 | "last_change_timestamp": last_change_timestamp, 99 | "node_data": storage_version_data["node_data"] 100 | } 101 | new_version_data["node_data"]["group"]["versioning_data"]["object_version"] = new_version_id 102 | data["versions"].insert(0, new_version_data) 103 | with open(group_file, 'w') as f: 104 | json.dump(data, f, indent=4) 105 | return web.json_response(data) 106 | else: 107 | object_version = versioning_data["object_version"] 108 | versions = data["versions"] 109 | index = next((i for i, version in enumerate(versions) if version["id"] == object_version), -1) 110 | if index == -1: 111 | return web.json_response({"error": "Version not found"}) 112 | 113 | versions[index]["node_data"] = storage_version_data["node_data"] 114 | versions[index]["last_change_timestamp"] = last_change_timestamp 115 | data["versions"] = versions 116 | with open(group_file, 'w') as f: 117 | json.dump(data, f, indent=4) 118 | return web.json_response(data) 119 | 120 | -------------------------------------------------------------------------------- /modules/utils.py: -------------------------------------------------------------------------------- 1 | import folder_paths 2 | 3 | import subprocess 4 | import shutil 5 | import os 6 | 7 | import cv2 8 | import numpy as np 9 | import torch 10 | 11 | from PIL import Image 12 | 13 | """ 14 | Attribution: ComfyUI-VideoHelperSuite 15 | 16 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 17 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 18 | 19 | """ 20 | 21 | def __lnl_ffmpeg_suitability(path): 22 | try: 23 | version = subprocess.run([path, "-version"], check=True, 24 | capture_output=True).stdout.decode("utf-8") 25 | except: 26 | return 0 27 | score = 0 28 | #rough layout of the importance of various features 29 | simple_criterion = [("libvpx", 20),("264",10), ("265",3), 30 | ("svtav1",5),("libopus", 1)] 31 | for criterion in simple_criterion: 32 | if version.find(criterion[0]) >= 0: 33 | score += criterion[1] 34 | #obtain rough compile year from copyright information 35 | copyright_index = version.find('2000-2') 36 | if copyright_index >= 0: 37 | copyright_year = version[copyright_index+6:copyright_index+9] 38 | if copyright_year.isnumeric(): 39 | score += int(copyright_year) 40 | return score 41 | 42 | def lnl_get_audio(file, start_time=0, duration=0): 43 | args = [ffmpeg_path, "-v", "error", "-i", file] 44 | if start_time > 0: 45 | args += ["-ss", str(start_time)] 46 | if duration > 0: 47 | args += ["-t", str(duration)] 48 | return subprocess.run(args + ["-f", "wav", "-"], 49 | stdout=subprocess.PIPE, check=True).stdout 50 | 51 | def lnl_lazy_eval(func): 52 | class Cache: 53 | def __init__(self, func): 54 | self.res = None 55 | self.func = func 56 | def get(self): 57 | if self.res is None: 58 | self.res = self.func() 59 | return self.res 60 | cache = Cache(func) 61 | return lambda : cache.get() 62 | 63 | def lnl_cv_frame_generator(video, frame_load_cap, skip_first_frames, select_every_nth): 64 | try: 65 | video_cap = cv2.VideoCapture(video) 66 | if not video_cap.isOpened(): 67 | raise ValueError(f"{video} could not be loaded with cv.") 68 | # set video_cap to look at start_index frame 69 | total_frame_count = 0 70 | total_frames_evaluated = -1 71 | frames_added = 0 72 | base_frame_time = 1/video_cap.get(cv2.CAP_PROP_FPS) 73 | width = video_cap.get(cv2.CAP_PROP_FRAME_WIDTH) 74 | height = video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT) 75 | prev_frame = None 76 | 77 | target_frame_time = base_frame_time 78 | yield (width, height, target_frame_time) 79 | 80 | time_offset=target_frame_time - base_frame_time 81 | while video_cap.isOpened(): 82 | if time_offset < target_frame_time: 83 | is_returned = video_cap.grab() 84 | # if didn't return frame, video has ended 85 | if not is_returned: 86 | break 87 | time_offset += base_frame_time 88 | if time_offset < target_frame_time: 89 | continue 90 | time_offset -= target_frame_time 91 | # if not at start_index, skip doing anything with frame 92 | total_frame_count += 1 93 | if total_frame_count <= skip_first_frames: 94 | continue 95 | else: 96 | total_frames_evaluated += 1 97 | 98 | # if should not be selected, skip doing anything with frame 99 | if total_frames_evaluated%select_every_nth != 0: 100 | frames_added += 1 101 | if total_frame_count >= frame_load_cap + skip_first_frames: 102 | break 103 | continue 104 | 105 | # opencv loads images in BGR format (yuck), so need to convert to RGB for ComfyUI use 106 | # follow up: can videos ever have an alpha channel? 107 | # To my testing: No. opencv has no support for alpha 108 | unused, frame = video_cap.retrieve() 109 | frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 110 | # convert frame to comfyui's expected format 111 | # TODO: frame contains no exif information. Check if opencv2 has already applied 112 | frame = np.array(frame, dtype=np.float32) / 255.0 113 | if prev_frame is not None: 114 | inp = yield prev_frame 115 | if inp is not None: 116 | #ensure the finally block is called 117 | return 118 | prev_frame = frame 119 | frames_added += 1 120 | # if cap exists and we've reached it, stop processing frames 121 | if frame_load_cap > 0 and frames_added >= frame_load_cap: 122 | break 123 | if prev_frame is not None: 124 | yield prev_frame 125 | finally: 126 | video_cap.release() 127 | 128 | def lnl_bislerp(samples, width, height): 129 | def slerp(b1, b2, r): 130 | '''slerps batches b1, b2 according to ratio r, batches should be flat e.g. NxC''' 131 | 132 | c = b1.shape[-1] 133 | 134 | #norms 135 | b1_norms = torch.norm(b1, dim=-1, keepdim=True) 136 | b2_norms = torch.norm(b2, dim=-1, keepdim=True) 137 | 138 | #normalize 139 | b1_normalized = b1 / b1_norms 140 | b2_normalized = b2 / b2_norms 141 | 142 | #zero when norms are zero 143 | b1_normalized[b1_norms.expand(-1,c) == 0.0] = 0.0 144 | b2_normalized[b2_norms.expand(-1,c) == 0.0] = 0.0 145 | 146 | #slerp 147 | dot = (b1_normalized*b2_normalized).sum(1) 148 | omega = torch.acos(dot) 149 | so = torch.sin(omega) 150 | 151 | #technically not mathematically correct, but more pleasing? 152 | res = (torch.sin((1.0-r.squeeze(1))*omega)/so).unsqueeze(1)*b1_normalized + (torch.sin(r.squeeze(1)*omega)/so).unsqueeze(1) * b2_normalized 153 | res *= (b1_norms * (1.0-r) + b2_norms * r).expand(-1,c) 154 | 155 | #edge cases for same or polar opposites 156 | res[dot > 1 - 1e-5] = b1[dot > 1 - 1e-5] 157 | res[dot < 1e-5 - 1] = (b1 * (1.0-r) + b2 * r)[dot < 1e-5 - 1] 158 | return res 159 | 160 | def generate_bilinear_data(length_old, length_new, device): 161 | coords_1 = torch.arange(length_old, dtype=torch.float32, device=device).reshape((1,1,1,-1)) 162 | coords_1 = torch.nn.functional.interpolate(coords_1, size=(1, length_new), mode="bilinear") 163 | ratios = coords_1 - coords_1.floor() 164 | coords_1 = coords_1.to(torch.int64) 165 | 166 | coords_2 = torch.arange(length_old, dtype=torch.float32, device=device).reshape((1,1,1,-1)) + 1 167 | coords_2[:,:,:,-1] -= 1 168 | coords_2 = torch.nn.functional.interpolate(coords_2, size=(1, length_new), mode="bilinear") 169 | coords_2 = coords_2.to(torch.int64) 170 | return ratios, coords_1, coords_2 171 | 172 | orig_dtype = samples.dtype 173 | samples = samples.float() 174 | n,c,h,w = samples.shape 175 | h_new, w_new = (height, width) 176 | 177 | #linear w 178 | ratios, coords_1, coords_2 = generate_bilinear_data(w, w_new, samples.device) 179 | coords_1 = coords_1.expand((n, c, h, -1)) 180 | coords_2 = coords_2.expand((n, c, h, -1)) 181 | ratios = ratios.expand((n, 1, h, -1)) 182 | 183 | pass_1 = samples.gather(-1,coords_1).movedim(1, -1).reshape((-1,c)) 184 | pass_2 = samples.gather(-1,coords_2).movedim(1, -1).reshape((-1,c)) 185 | ratios = ratios.movedim(1, -1).reshape((-1,1)) 186 | 187 | result = slerp(pass_1, pass_2, ratios) 188 | result = result.reshape(n, h, w_new, c).movedim(-1, 1) 189 | 190 | #linear h 191 | ratios, coords_1, coords_2 = generate_bilinear_data(h, h_new, samples.device) 192 | coords_1 = coords_1.reshape((1,1,-1,1)).expand((n, c, -1, w_new)) 193 | coords_2 = coords_2.reshape((1,1,-1,1)).expand((n, c, -1, w_new)) 194 | ratios = ratios.reshape((1,1,-1,1)).expand((n, 1, -1, w_new)) 195 | 196 | pass_1 = result.gather(-2,coords_1).movedim(1, -1).reshape((-1,c)) 197 | pass_2 = result.gather(-2,coords_2).movedim(1, -1).reshape((-1,c)) 198 | ratios = ratios.movedim(1, -1).reshape((-1,1)) 199 | 200 | result = slerp(pass_1, pass_2, ratios) 201 | result = result.reshape(n, h_new, w_new, c).movedim(-1, 1) 202 | return result.to(orig_dtype) 203 | 204 | def lnl_lanczos(samples, width, height): 205 | images = [Image.fromarray(np.clip(255. * image.movedim(0, -1).cpu().numpy(), 0, 255).astype(np.uint8)) for image in samples] 206 | images = [image.resize((width, height), resample=Image.Resampling.LANCZOS) for image in images] 207 | images = [torch.from_numpy(np.array(image).astype(np.float32) / 255.0).movedim(-1, 0) for image in images] 208 | result = torch.stack(images) 209 | return result.to(samples.device, samples.dtype) 210 | 211 | def lnl_common_upscale(samples, width, height, upscale_method, crop): 212 | if crop == "center": 213 | old_width = samples.shape[3] 214 | old_height = samples.shape[2] 215 | old_aspect = old_width / old_height 216 | new_aspect = width / height 217 | x = 0 218 | y = 0 219 | if old_aspect > new_aspect: 220 | x = round((old_width - old_width * (new_aspect / old_aspect)) / 2) 221 | elif old_aspect < new_aspect: 222 | y = round((old_height - old_height * (old_aspect / new_aspect)) / 2) 223 | s = samples[:,:,y:old_height-y,x:old_width-x] 224 | else: 225 | s = samples 226 | 227 | if upscale_method == "bislerp": 228 | return lnl_bislerp(s, width, height) 229 | elif upscale_method == "lanczos": 230 | return lnl_lanczos(s, width, height) 231 | else: 232 | return torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method) 233 | 234 | def lnl_target_size(width, height, force_size, custom_width, custom_height) -> tuple[int, int]: 235 | if force_size == "Custom": 236 | return (custom_width, custom_height) 237 | elif force_size == "Custom Height": 238 | force_size = "?x"+str(custom_height) 239 | elif force_size == "Custom Width": 240 | force_size = str(custom_width)+"x?" 241 | 242 | if force_size != "Disabled": 243 | force_size = force_size.split("x") 244 | if force_size[0] == "?": 245 | width = (width*int(force_size[1]))//height 246 | #Limit to a multple of 8 for latent conversion 247 | width = int(width)+4 & ~7 248 | height = int(force_size[1]) 249 | elif force_size[1] == "?": 250 | height = (height*int(force_size[0]))//width 251 | height = int(height)+4 & ~7 252 | width = int(force_size[0]) 253 | else: 254 | width = int(force_size[0]) 255 | height = int(force_size[1]) 256 | return (width, height) 257 | 258 | def lnl_fix_path(video_path): 259 | annotated_path = os.path.join(folder_paths.base_path, video_path) 260 | if not os.path.exists(annotated_path): 261 | annotated_path = folder_paths.get_annotated_filepath(video_path) 262 | return annotated_path 263 | 264 | ffmpeg_paths = [] 265 | try: 266 | from imageio_ffmpeg import get_ffmpeg_exe 267 | imageio_ffmpeg_path = get_ffmpeg_exe() 268 | ffmpeg_paths.append(imageio_ffmpeg_path) 269 | except: 270 | print("Failed to import imageio_ffmpeg") 271 | system_ffmpeg = shutil.which("ffmpeg") 272 | if system_ffmpeg is not None: 273 | ffmpeg_paths.append(system_ffmpeg) 274 | 275 | if len(ffmpeg_paths) == 0: 276 | print("No valid ffmpeg found.") 277 | ffmpeg_path = None 278 | elif len(ffmpeg_paths) == 1: 279 | ffmpeg_path = ffmpeg_paths[0] 280 | else: 281 | ffmpeg_path = max(ffmpeg_paths, key=__lnl_ffmpeg_suitability) 282 | -------------------------------------------------------------------------------- /modules/video_utils.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import shutil 3 | import os 4 | import re 5 | from collections.abc import Mapping 6 | 7 | import cv2 8 | import numpy as np 9 | import torch 10 | 11 | from PIL import Image 12 | 13 | from folder_paths import base_path 14 | 15 | """ 16 | Attribution: ComfyUI-VideoHelperSuite 17 | 18 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 19 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 20 | 21 | """ 22 | 23 | def __lnl_ffmpeg_suitability(path): 24 | try: 25 | version = subprocess.run([path, "-version"], check=True, 26 | capture_output=True).stdout.decode("utf-8") 27 | except: 28 | return 0 29 | score = 0 30 | #rough layout of the importance of various features 31 | simple_criterion = [("libvpx", 20),("264",10), ("265",3), 32 | ("svtav1",5),("libopus", 1)] 33 | for criterion in simple_criterion: 34 | if version.find(criterion[0]) >= 0: 35 | score += criterion[1] 36 | #obtain rough compile year from copyright information 37 | copyright_index = version.find('2000-2') 38 | if copyright_index >= 0: 39 | copyright_year = version[copyright_index+6:copyright_index+9] 40 | if copyright_year.isnumeric(): 41 | score += int(copyright_year) 42 | return score 43 | 44 | def lnl_get_audio(file, start_time=0, duration=0): 45 | args = [ffmpeg_path, "-v", "error", "-i", file] 46 | if start_time > 0: 47 | args += ["-ss", str(start_time)] 48 | if duration > 0: 49 | args += ["-t", str(duration)] 50 | return subprocess.run(args + ["-f", "wav", "-"], 51 | stdout=subprocess.PIPE, check=True).stdout 52 | 53 | def lnl_lazy_eval(func): 54 | class Cache: 55 | def __init__(self, func): 56 | self.res = None 57 | self.func = func 58 | def get(self): 59 | if self.res is None: 60 | self.res = self.func() 61 | return self.res 62 | cache = Cache(func) 63 | return lambda : cache.get() 64 | 65 | def _lnl_get_audio(file, start_time=0, duration=0): 66 | args = [ffmpeg_path, "-i", file] 67 | if start_time > 0: 68 | args += ["-ss", str(start_time)] 69 | if duration > 0: 70 | args += ["-t", str(duration)] 71 | try: 72 | #TODO: scan for sample rate and maintain 73 | res = subprocess.run(args + ["-f", "f32le", "-"], 74 | capture_output=True, check=True) 75 | audio = torch.frombuffer(bytearray(res.stdout), dtype=torch.float32) 76 | match = re.search(', (\\d+) Hz, (\\w+), ',res.stderr.decode('utf-8')) 77 | except subprocess.CalledProcessError as e: 78 | raise Exception(f"VHS failed to extract audio from {file}:\n" \ 79 | + e.stderr.decode("utf-8")) 80 | if match: 81 | ar = int(match.group(1)) 82 | #NOTE: Just throwing an error for other channel types right now 83 | #Will deal with issues if they come 84 | ac = {"mono": 1, "stereo": 2}[match.group(2)] 85 | else: 86 | ar = 44100 87 | ac = 2 88 | audio = audio.reshape((-1,ac)).transpose(0,1).unsqueeze(0) 89 | return {'waveform': audio, 'sample_rate': ar} 90 | 91 | class LNLLazyAudioMap(Mapping): 92 | def __init__(self, file, start_time, duration): 93 | self.file = file 94 | self.start_time=start_time 95 | self.duration=duration 96 | self._dict=None 97 | def __getitem__(self, key): 98 | if self._dict is None: 99 | self._dict = _lnl_get_audio(self.file, self.start_time, self.duration) 100 | return self._dict[key] 101 | def __iter__(self): 102 | if self._dict is None: 103 | self._dict = _lnl_get_audio(self.file, self.start_time, self.duration) 104 | return iter(self._dict) 105 | def __len__(self): 106 | if self._dict is None: 107 | self._dict = _lnl_get_audio(self.file, self.start_time, self.duration) 108 | return len(self._dict) 109 | 110 | def lnl_lazy_get_audio(file, start_time=0, duration=0): 111 | return LNLLazyAudioMap(file, start_time, duration) 112 | 113 | def lnl_cv_frame_generator(video, number_of_frames_to_process, skip_first_frames, select_every_nth): 114 | try: 115 | video_cap = cv2.VideoCapture(video) 116 | if not video_cap.isOpened(): 117 | raise ValueError(f"{video} could not be loaded with cv.") 118 | # set video_cap to look at start_index frame 119 | total_frame_count = 0 120 | total_frames_evaluated = -1 121 | frames_added = 0 122 | base_frame_time = 1/video_cap.get(cv2.CAP_PROP_FPS) 123 | width = video_cap.get(cv2.CAP_PROP_FRAME_WIDTH) 124 | height = video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT) 125 | prev_frame = None 126 | 127 | target_frame_time = base_frame_time 128 | yield (width, height, target_frame_time) 129 | 130 | time_offset=target_frame_time - base_frame_time 131 | while video_cap.isOpened(): 132 | if time_offset < target_frame_time: 133 | is_returned = video_cap.grab() 134 | # if didn't return frame, video has ended 135 | if not is_returned: 136 | break 137 | time_offset += base_frame_time 138 | if time_offset < target_frame_time: 139 | continue 140 | time_offset -= target_frame_time 141 | # if not at start_index, skip doing anything with frame 142 | total_frame_count += 1 143 | if total_frame_count < skip_first_frames: 144 | continue 145 | else: 146 | total_frames_evaluated += 1 147 | 148 | # if should not be selected, skip doing anything with frame 149 | if total_frames_evaluated%select_every_nth != 0: 150 | frames_added += 1 151 | if total_frame_count >= number_of_frames_to_process + skip_first_frames: 152 | break 153 | continue 154 | 155 | # opencv loads images in BGR format (yuck), so need to convert to RGB for ComfyUI use 156 | # follow up: can videos ever have an alpha channel? 157 | # To my testing: No. opencv has no support for alpha 158 | unused, frame = video_cap.retrieve() 159 | frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 160 | # convert frame to comfyui's expected format 161 | # TODO: frame contains no exif information. Check if opencv2 has already applied 162 | frame = np.array(frame, dtype=np.float32) / 255.0 163 | if prev_frame is not None: 164 | inp = yield prev_frame 165 | if inp is not None: 166 | #ensure the finally block is called 167 | return 168 | prev_frame = frame 169 | frames_added += 1 170 | # if cap exists and we've reached it, stop processing frames 171 | if number_of_frames_to_process > 0 and frames_added >= number_of_frames_to_process: 172 | break 173 | if prev_frame is not None: 174 | yield prev_frame 175 | finally: 176 | video_cap.release() 177 | 178 | def lnl_bislerp(samples, width, height): 179 | def slerp(b1, b2, r): 180 | '''slerps batches b1, b2 according to ratio r, batches should be flat e.g. NxC''' 181 | 182 | c = b1.shape[-1] 183 | 184 | #norms 185 | b1_norms = torch.norm(b1, dim=-1, keepdim=True) 186 | b2_norms = torch.norm(b2, dim=-1, keepdim=True) 187 | 188 | #normalize 189 | b1_normalized = b1 / b1_norms 190 | b2_normalized = b2 / b2_norms 191 | 192 | #zero when norms are zero 193 | b1_normalized[b1_norms.expand(-1,c) == 0.0] = 0.0 194 | b2_normalized[b2_norms.expand(-1,c) == 0.0] = 0.0 195 | 196 | #slerp 197 | dot = (b1_normalized*b2_normalized).sum(1) 198 | omega = torch.acos(dot) 199 | so = torch.sin(omega) 200 | 201 | #technically not mathematically correct, but more pleasing? 202 | res = (torch.sin((1.0-r.squeeze(1))*omega)/so).unsqueeze(1)*b1_normalized + (torch.sin(r.squeeze(1)*omega)/so).unsqueeze(1) * b2_normalized 203 | res *= (b1_norms * (1.0-r) + b2_norms * r).expand(-1,c) 204 | 205 | #edge cases for same or polar opposites 206 | res[dot > 1 - 1e-5] = b1[dot > 1 - 1e-5] 207 | res[dot < 1e-5 - 1] = (b1 * (1.0-r) + b2 * r)[dot < 1e-5 - 1] 208 | return res 209 | 210 | def generate_bilinear_data(length_old, length_new, device): 211 | coords_1 = torch.arange(length_old, dtype=torch.float32, device=device).reshape((1,1,1,-1)) 212 | coords_1 = torch.nn.functional.interpolate(coords_1, size=(1, length_new), mode="bilinear") 213 | ratios = coords_1 - coords_1.floor() 214 | coords_1 = coords_1.to(torch.int64) 215 | 216 | coords_2 = torch.arange(length_old, dtype=torch.float32, device=device).reshape((1,1,1,-1)) + 1 217 | coords_2[:,:,:,-1] -= 1 218 | coords_2 = torch.nn.functional.interpolate(coords_2, size=(1, length_new), mode="bilinear") 219 | coords_2 = coords_2.to(torch.int64) 220 | return ratios, coords_1, coords_2 221 | 222 | orig_dtype = samples.dtype 223 | samples = samples.float() 224 | n,c,h,w = samples.shape 225 | h_new, w_new = (height, width) 226 | 227 | #linear w 228 | ratios, coords_1, coords_2 = generate_bilinear_data(w, w_new, samples.device) 229 | coords_1 = coords_1.expand((n, c, h, -1)) 230 | coords_2 = coords_2.expand((n, c, h, -1)) 231 | ratios = ratios.expand((n, 1, h, -1)) 232 | 233 | pass_1 = samples.gather(-1,coords_1).movedim(1, -1).reshape((-1,c)) 234 | pass_2 = samples.gather(-1,coords_2).movedim(1, -1).reshape((-1,c)) 235 | ratios = ratios.movedim(1, -1).reshape((-1,1)) 236 | 237 | result = slerp(pass_1, pass_2, ratios) 238 | result = result.reshape(n, h, w_new, c).movedim(-1, 1) 239 | 240 | #linear h 241 | ratios, coords_1, coords_2 = generate_bilinear_data(h, h_new, samples.device) 242 | coords_1 = coords_1.reshape((1,1,-1,1)).expand((n, c, -1, w_new)) 243 | coords_2 = coords_2.reshape((1,1,-1,1)).expand((n, c, -1, w_new)) 244 | ratios = ratios.reshape((1,1,-1,1)).expand((n, 1, -1, w_new)) 245 | 246 | pass_1 = result.gather(-2,coords_1).movedim(1, -1).reshape((-1,c)) 247 | pass_2 = result.gather(-2,coords_2).movedim(1, -1).reshape((-1,c)) 248 | ratios = ratios.movedim(1, -1).reshape((-1,1)) 249 | 250 | result = slerp(pass_1, pass_2, ratios) 251 | result = result.reshape(n, h_new, w_new, c).movedim(-1, 1) 252 | return result.to(orig_dtype) 253 | 254 | def lnl_lanczos(samples, width, height): 255 | images = [Image.fromarray(np.clip(255. * image.movedim(0, -1).cpu().numpy(), 0, 255).astype(np.uint8)) for image in samples] 256 | images = [image.resize((width, height), resample=Image.Resampling.LANCZOS) for image in images] 257 | images = [torch.from_numpy(np.array(image).astype(np.float32) / 255.0).movedim(-1, 0) for image in images] 258 | result = torch.stack(images) 259 | return result.to(samples.device, samples.dtype) 260 | 261 | def lnl_common_upscale(samples, width, height, upscale_method, crop): 262 | if crop == "center": 263 | old_width = samples.shape[3] 264 | old_height = samples.shape[2] 265 | old_aspect = old_width / old_height 266 | new_aspect = width / height 267 | x = 0 268 | y = 0 269 | if old_aspect > new_aspect: 270 | x = round((old_width - old_width * (new_aspect / old_aspect)) / 2) 271 | elif old_aspect < new_aspect: 272 | y = round((old_height - old_height * (old_aspect / new_aspect)) / 2) 273 | s = samples[:,:,y:old_height-y,x:old_width-x] 274 | else: 275 | s = samples 276 | 277 | if upscale_method == "bislerp": 278 | return lnl_bislerp(s, width, height) 279 | elif upscale_method == "lanczos": 280 | return lnl_lanczos(s, width, height) 281 | else: 282 | return torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method) 283 | 284 | def lnl_target_size(width, height, force_size, custom_width, custom_height) -> tuple[int, int]: 285 | if force_size == "Custom": 286 | return (custom_width, custom_height) 287 | elif force_size == "Custom Height": 288 | force_size = "?x"+str(custom_height) 289 | elif force_size == "Custom Width": 290 | force_size = str(custom_width)+"x?" 291 | 292 | if force_size != "Disabled": 293 | force_size = force_size.split("x") 294 | if force_size[0] == "?": 295 | width = (width*int(force_size[1]))//height 296 | #Limit to a multple of 8 for latent conversion 297 | width = int(width)+4 & ~7 298 | height = int(force_size[1]) 299 | elif force_size[1] == "?": 300 | height = (height*int(force_size[0]))//width 301 | height = int(height)+4 & ~7 302 | width = int(force_size[0]) 303 | else: 304 | width = int(force_size[0]) 305 | height = int(force_size[1]) 306 | return (width, height) 307 | 308 | def get_video_info(video_path): 309 | if ffmpeg_path is None: 310 | raise Exception("FFMPEG path not set") 311 | 312 | full_video_path = os.path.join(base_path, video_path) 313 | if not os.path.exists(full_video_path): 314 | raise Exception(f"Video path does not exist: {full_video_path}") 315 | 316 | cmd = ['ffprobe', '-v', 'error', '-select_streams', 'v:0', 317 | '-show_entries', 'stream=r_frame_rate,nb_frames', '-show_entries', 'format=duration', 318 | '-of', 'default=noprint_wrappers=1:nokey=1', 319 | full_video_path] 320 | process = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True) 321 | output = process.stdout.splitlines() 322 | 323 | frame_rate_str = output[0] 324 | try: 325 | num, den = map(float, frame_rate_str.split('/')) 326 | frame_rate = num / den 327 | except ValueError: 328 | frame_rate = float(frame_rate_str) 329 | 330 | total_frames = int(output[1]) + 1 331 | duration = float(output[2]) 332 | 333 | return frame_rate, total_frames, duration 334 | 335 | ffmpeg_paths = [] 336 | try: 337 | from imageio_ffmpeg import get_ffmpeg_exe 338 | imageio_ffmpeg_path = get_ffmpeg_exe() 339 | ffmpeg_paths.append(imageio_ffmpeg_path) 340 | except: 341 | print("Failed to import imageio_ffmpeg") 342 | system_ffmpeg = shutil.which("ffmpeg") 343 | if system_ffmpeg is not None: 344 | ffmpeg_paths.append(system_ffmpeg) 345 | 346 | if len(ffmpeg_paths) == 0: 347 | print("No valid ffmpeg found.") 348 | ffmpeg_path = None 349 | elif len(ffmpeg_paths) == 1: 350 | ffmpeg_path = ffmpeg_paths[0] 351 | else: 352 | ffmpeg_path = max(ffmpeg_paths, key=__lnl_ffmpeg_suitability) 353 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "comfyui-lnl" 3 | description = "Frame Selector & Sequence Selection Node for ComfyUI." 4 | version = "1.0.0" 5 | license = "LICENSE" 6 | dependencies = ["opencv-python", "imageio-ffmpeg"] 7 | 8 | [project.urls] 9 | Repository = "https://github.com/latenightlabs/ComfyUI-LNL" 10 | # Used by Comfy Registry https://comfyregistry.org 11 | 12 | [tool.comfy] 13 | PublisherId = "latenightlabs" 14 | DisplayName = "ComfyUI-LNL" 15 | Icon = "" 16 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | opencv-python 2 | imageio-ffmpeg 3 | Pillow -------------------------------------------------------------------------------- /web/EnhancedGroups/enhancedGroups.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { app } from "../../../scripts/app.js"; // For LiteGraph 4 | 5 | import { addGroupVersionToGraph, updateGroupFromJSONData } from "./utils.js"; 6 | 7 | import VersionManager from "./versionManager.js"; 8 | const versionManager = new VersionManager(); 9 | 10 | var initialGroupNodeRecomputed = false; 11 | const groupInitialVersioningData = new WeakMap(); 12 | 13 | async function saveGroup(menuItem, options, e, menu, groupNode, saveAsNew) { 14 | const groupHasVersioningData = groupNode.versioning_data !== undefined; 15 | 16 | const groupData = { 17 | versioning_data: groupNode.versioning_data 18 | }; 19 | // Get component name if needed 20 | if (!groupHasVersioningData) { 21 | const componentName = prompt("Enter the component name:"); 22 | if (!componentName) { 23 | return; 24 | } 25 | groupData.versioning_data = { object_name: componentName }; 26 | } 27 | 28 | // Get group nodes 29 | groupData.nodes = groupNode._nodes.map(node => { 30 | return node.serialize(); 31 | }); 32 | 33 | // Process and remove links that are not between group nodes 34 | { 35 | const groupLinkIds = new Set([]); 36 | // TODO: Make sure that we're not saving links that are not between group nodes 37 | const groupNodeIds = groupNode._nodes.map(node => node.id); 38 | for (const node of groupNode._nodes) { 39 | if (node.inputs) { 40 | node.inputs.forEach(input => { 41 | if (input.link) { 42 | groupLinkIds.add(input.link); 43 | } 44 | }); 45 | } 46 | 47 | if (node.outputs) { 48 | node.outputs.forEach(output => { 49 | if (output.links) { 50 | output.links.forEach(link => { 51 | groupLinkIds.add(link); 52 | }); 53 | } 54 | }); 55 | } 56 | } 57 | groupData.links = Array.from(groupLinkIds).map(linkId => { 58 | let linkIndex = -1; 59 | if (typeof app.graph.links === 'object') { 60 | Object.keys(app.graph.links).forEach(link => { 61 | if (app.graph.links[link].id === linkId) { 62 | linkIndex = linkId; 63 | } 64 | }); 65 | } 66 | else { 67 | linkIndex = app.graph.links.findIndex(link => { 68 | return link ? link.id === linkId : false; 69 | }); 70 | } 71 | if (linkIndex === -1) { 72 | return null; 73 | } 74 | return app.graph.links[linkIndex].serialize(); 75 | }).filter(link => link !== null); 76 | } 77 | 78 | // Add group data 79 | groupData.group = groupNode.serialize(); 80 | 81 | const jsonData = await versionManager.saveGroupData(groupData, saveAsNew); 82 | if (jsonData.error) { 83 | console.error(jsonData.error); 84 | return; 85 | } 86 | 87 | updateGroupFromJSONData(groupNode, jsonData); 88 | app.graph.setDirtyCanvas(true, true); 89 | } 90 | 91 | function saveGroupAsNewVersion(menuItem, options, e, menu, groupNode) { 92 | const saveAsNew = true; 93 | saveGroup(menuItem, options, e, menu, groupNode, saveAsNew); 94 | } 95 | 96 | async function loadGroup(menuItem, options, e, menu, groupNode) { 97 | const data = await versionManager.loadGroupData(menuItem.extra.group.id); 98 | if (data["versions"].length === 0) { 99 | return; 100 | } 101 | 102 | addGroupVersionToGraph(app, data, groupNode, menuItem.extra.touchPos, menuItem.extra.groupVersion, menuItem.extra.refresh); 103 | } 104 | 105 | function extendCanvasMenu() { 106 | const oldProcessContextMenu = LGraphCanvas.prototype.processContextMenu; 107 | LGraphCanvas.prototype.processContextMenu = function(node, event) { 108 | var group = app.graph.getGroupOnPos( 109 | event.canvasX, 110 | event.canvasY 111 | ); 112 | const touchPos = [event.canvasX, event.canvasY]; 113 | if (!group) { 114 | const oldCanvasMenu = LGraphCanvas.prototype.getCanvasMenuOptions; 115 | LGraphCanvas.prototype.getCanvasMenuOptions = function() { 116 | const enhancedCanvasMenu = oldCanvasMenu.apply(this, arguments); 117 | const index = enhancedCanvasMenu.findIndex((o) => o?.content === "Add Group"); 118 | if (index === -1) { 119 | return enhancedCanvasMenu; 120 | } 121 | 122 | enhancedCanvasMenu[index] = { 123 | content: "Add Group", has_submenu: true, submenu: { 124 | title: "Add Group", 125 | options: [ 126 | { content: "Empty group", callback: LGraphCanvas.onGroupAdd }, 127 | { 128 | content: "Versioned group", has_submenu: true, submenu: { 129 | title: "Groups", 130 | options: versionManager.versionedGroups().map(group => { 131 | const latestVersion = group.versions[0]; 132 | const groupTitle = `${group.name} (v${latestVersion.id})`; 133 | return { content: groupTitle, callback: loadGroup, extra: { group, touchPos, groupVersion: latestVersion } }; 134 | }), 135 | } 136 | }, 137 | ], 138 | } 139 | }; 140 | 141 | return enhancedCanvasMenu; 142 | }; 143 | } 144 | 145 | oldProcessContextMenu.apply(this, arguments); 146 | }; 147 | } 148 | 149 | function extendGroupContextMenu() { 150 | 151 | const oldGroupContextMenu = LGraphCanvas.prototype.getGroupMenuOptions; 152 | LGraphCanvas.prototype.getGroupMenuOptions = function(group) { 153 | var enhancedContextMenu = oldGroupContextMenu(group); 154 | enhancedContextMenu.push(null); 155 | 156 | const groupHasVersioningData = group.versioning_data !== undefined; 157 | const submenuOptions = [ 158 | { content: "Save", callback: saveGroup }, 159 | ]; 160 | if (groupHasVersioningData) { 161 | let optionsObjects = []; 162 | const groupIndex = versionManager.versionedGroups().findIndex(obj => obj.id === group.versioning_data.object_id); 163 | let currentGroupData = null; 164 | if (groupIndex !== -1) { 165 | currentGroupData = versionManager.versionedGroups()[groupIndex]; 166 | optionsObjects = currentGroupData.versions.map(groupVersion => { 167 | const lastModificationDatetime = new Date(groupVersion.timestamp).toLocaleString(); 168 | const groupTitle = `v${groupVersion.id} [${lastModificationDatetime}]`; 169 | return { content: groupTitle, callback: loadGroup, extra: { group: currentGroupData, touchPos: undefined, groupVersion } }; 170 | }); 171 | } 172 | if (!currentGroupData || !currentGroupData.versions || currentGroupData.versions.length === 0) { 173 | return enhancedContextMenu; 174 | } 175 | const currentGroupVersion = currentGroupData.versions.find(v => v.id === group.versioning_data.object_version); 176 | const versionedGroupOptions = [ 177 | { content: "Save as new version", callback: saveGroupAsNewVersion }, 178 | null, 179 | { 180 | content: "Load version", has_submenu: true, submenu: { 181 | title: "Available Versions", 182 | extra: group, 183 | options: optionsObjects 184 | } 185 | }, 186 | { content: "Refresh", callback: loadGroup, extra: { group: currentGroupData, touchPos: undefined, groupVersion: currentGroupVersion, refresh: true } }, 187 | ]; 188 | submenuOptions.push(...versionedGroupOptions); 189 | } 190 | const versionControlMenu = { 191 | content: "Versions", 192 | has_submenu: true, 193 | submenu: { 194 | title: "Version Control", 195 | extra: group, 196 | options: submenuOptions 197 | }, 198 | }; 199 | enhancedContextMenu.push(versionControlMenu); 200 | return enhancedContextMenu; 201 | }; 202 | } 203 | 204 | function extendGroupDrawingContext() { 205 | const drawGroups = LGraphCanvas.prototype.drawGroups; 206 | LGraphCanvas.prototype.drawGroups = function(canvas, ctx) { 207 | drawGroups.apply(this, arguments); 208 | if (!app.graph) { 209 | return; 210 | } 211 | 212 | var groups = app.graph._groups; 213 | 214 | ctx.save(); 215 | ctx.globalAlpha = 0.5 * app.editor_alpha; 216 | 217 | for (var i = 0; i < groups.length; ++i) { 218 | var group = groups[i]; 219 | 220 | if (!app.canvas || 221 | !LiteGraph.overlapBounding(app.canvas.visible_area, group._bounding) || 222 | !group.versioning_data 223 | ) { 224 | continue; 225 | } 226 | 227 | ctx.fillStyle = group.color || "#335"; 228 | ctx.strokeStyle = group.color || "#335"; 229 | var pos = group._pos; 230 | var size = group._size; 231 | var font_size = group.font_size || LiteGraph.DEFAULT_GROUP_FONT_SIZE; 232 | 233 | ctx.font = (font_size - 10) + "px Arial"; 234 | ctx.textAlign = "right"; 235 | const infoText = `[${group.versioning_data.object_name} (v${group.versioning_data.object_version})]`; 236 | ctx.fillText(infoText, pos[0] - 4 + size[0], pos[1] + font_size); 237 | } 238 | ctx.restore(); 239 | } 240 | } 241 | 242 | export function setupConfigAndSerialization() { 243 | 244 | function removeVersioningDataIfNeeded(groupNode) { 245 | // In case we've loaded a versioned group which doesn't have history 246 | // in the version manager (e.g. a workflow was transferred from another 247 | // machine without the respective JSON file), we should remove the 248 | // versioning data and make it behave as a regular group. 249 | if (groupNode.versioning_data && !versionManager.versionedGroups().find(obj => obj.id === groupNode.versioning_data.object_id)) { 250 | delete groupNode.versioning_data; 251 | } 252 | app.graph.setDirtyCanvas(true, true); 253 | } 254 | 255 | const serialize = LGraphGroup.prototype.serialize; 256 | LGraphGroup.prototype.serialize = function() { 257 | if (!initialGroupNodeRecomputed) { 258 | this.recomputeInsideNodes(); 259 | initialGroupNodeRecomputed = true; 260 | } 261 | const object = serialize.apply(this, arguments); 262 | if (this.versioning_data) { 263 | const versioningData = { 264 | object_id: this.versioning_data?.object_id || null, 265 | object_name: this.versioning_data?.object_name || null, 266 | object_version: this.versioning_data?.object_version || null, 267 | }; 268 | object.versioning_data = versioningData; 269 | } 270 | else if (groupInitialVersioningData.has(this)) { 271 | const initialVersioningData = groupInitialVersioningData.get(this); 272 | const versioningData = { 273 | object_id: initialVersioningData.object_id || null, 274 | object_name: initialVersioningData.object_name || null, 275 | object_version: initialVersioningData.object_version || null, 276 | }; 277 | this.versioning_data = versioningData; 278 | object.versioning_data = versioningData; 279 | } 280 | removeVersioningDataIfNeeded(object); 281 | return object; 282 | }; 283 | 284 | const configure = LGraphGroup.prototype.configure; 285 | LGraphGroup.prototype.configure = function(data) { 286 | configure.apply(this, arguments); 287 | if (data.versioning_data) { 288 | groupInitialVersioningData.set(this, data.versioning_data); 289 | this.versioning_data = data.versioning_data; 290 | } 291 | removeVersioningDataIfNeeded(this); 292 | }; 293 | } 294 | 295 | export async function registerGroupExtensions() { 296 | extendGroupDrawingContext(); 297 | await versionManager.loadVersionedGroups(); 298 | 299 | extendGroupContextMenu(); 300 | extendCanvasMenu(); 301 | } 302 | -------------------------------------------------------------------------------- /web/EnhancedGroups/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { app } from "../../../scripts/app.js"; // For LiteGraph 4 | import { api } from "../../../scripts/api.js"; 5 | 6 | // API utils 7 | export async function fetchGroupsData() { 8 | const result = await api.fetchApi("/fetch_groups_data", { method: "GET" }); 9 | if (result.error) { 10 | console.error(`fetchGroupsData error: ${result.error}`); 11 | return undefined; 12 | } 13 | const jsonData = await result.json(); 14 | return jsonData; 15 | } 16 | 17 | export async function fetchGroupData(groupId) { 18 | const result = await api.fetchApi(`/fetch_group_data?groupId=${groupId}`, { method: "GET" }); 19 | if (result.error) { 20 | console.error(`fetchGroupsData error: ${result.error}`); 21 | return undefined; 22 | } 23 | const jsonData = await result.json(); 24 | return jsonData; 25 | } 26 | 27 | export async function saveGroupData(groupData, saveAsNew) { 28 | const body = { 29 | group_data: groupData 30 | }; 31 | const result = await api.fetchApi(`/save_group_data?saveAsNew=${saveAsNew === true}`, { method: "POST", body: JSON.stringify(body) }); 32 | if (result.error) { 33 | console.error(`saveGroupData error: ${result.error}`); 34 | return; 35 | } 36 | const jsonData = await result.json(); 37 | return jsonData; 38 | } 39 | 40 | // Litegraph utils 41 | export function addGroupVersionToGraph(app, data, groupNodeSelected, touchPos, groupVersion, isRefresh) { 42 | const groupIndex = data["versions"].findIndex((o) => o?.id === groupVersion.id); 43 | if (groupIndex === -1) { 44 | console.error(`Group version ${groupVersion.id} not found in group data`); 45 | return; 46 | } 47 | const specificVersionData = data["versions"][groupIndex]; 48 | if (!specificVersionData) { 49 | return; 50 | } 51 | const groupVersionData = specificVersionData["node_data"]; 52 | if (!groupVersionData) { 53 | return; 54 | } 55 | 56 | // Remove the existing group and its nodes if we're loading another (or reload the same) version of the same group 57 | if (groupNodeSelected) { 58 | app.canvas.selectNodes(groupNodeSelected._nodes, false); 59 | app.canvas.deleteSelectedNodes(); 60 | LGraphCanvas.onMenuNodeRemove(null, null, null, null, groupNodeSelected); 61 | } 62 | 63 | /// Recalculate positions based on click coordinates which tell us where the 64 | /// lower-left corner of the group should be 65 | const nodes = groupVersionData.nodes; 66 | const nodesGroup = groupVersionData.group; 67 | if (!nodes || !nodesGroup) { 68 | return; 69 | } 70 | 71 | { 72 | if (!touchPos && groupNodeSelected) { 73 | touchPos = [groupNodeSelected.pos[0], groupNodeSelected.pos[1] + groupNodeSelected.size[1]]; 74 | } 75 | // 1) Make node positions relative to group's 76 | for (let i = 0; i < nodes.length; ++i) { 77 | const node = nodes[i]; 78 | node.pos[0] = node.pos[0] - nodesGroup.bounding[0]; 79 | node.pos[1] = node.pos[1] - nodesGroup.bounding[1]; 80 | } 81 | // 2) Make group lower-left position the same as touch position 82 | nodesGroup.bounding[0] = touchPos[0]; 83 | nodesGroup.bounding[1] = touchPos[1] - nodesGroup.bounding[3]; 84 | // 3) Make node positions absolute 85 | for (let i = 0; i < nodes.length; ++i) { 86 | const node = nodes[i]; 87 | node.pos[0] = node.pos[0] + nodesGroup.bounding[0]; 88 | node.pos[1] = node.pos[1] + nodesGroup.bounding[1]; 89 | } 90 | } 91 | 92 | /// Remap node IDs 93 | const nodeIDMapping = {}; 94 | for (let i = 0; i < nodes.length; ++i) { 95 | const node = nodes[i]; 96 | nodeIDMapping[node.id] = app.graph.last_node_id + i + 1; 97 | node.id = nodeIDMapping[node.id]; 98 | } 99 | 100 | /// Remap link IDs and link's origin/target node IDs 101 | const links = groupVersionData.links; 102 | const linkIDMapping = {}; 103 | if (links && links.constructor === Array) { 104 | for (let i = 0; i < links.length; ++i) { 105 | const link = links[i]; 106 | if (link === null) { 107 | continue; 108 | } 109 | linkIDMapping[link[0]] = app.graph.last_link_id + i + 1; 110 | link[0] = linkIDMapping[link[0]]; 111 | link[1] = nodeIDMapping[link[1]]; 112 | link[3] = nodeIDMapping[link[3]]; 113 | } 114 | } 115 | 116 | /// Remap nodes' input/output links 117 | for (let i = 0; i < nodes.length; ++i) { 118 | const node = nodes[i]; 119 | 120 | const linkArrays = []; 121 | if (node.inputs) { 122 | linkArrays.push(node.inputs); 123 | } 124 | if (node.outputs) { 125 | linkArrays.push(node.outputs); 126 | } 127 | for (let j = 0; j < linkArrays.length; ++j) { 128 | const inOutItem = linkArrays[j]; 129 | for (let k = 0; k < inOutItem.length; ++k) { 130 | const connection = inOutItem[k]; 131 | if (connection.links) { 132 | for (let l = 0; l < connection.links.length; ++l) { 133 | connection.links[l] = linkIDMapping[connection.links[l]]; 134 | } 135 | } 136 | if (connection.link) { 137 | connection.link = linkIDMapping[connection.link]; 138 | } 139 | } 140 | } 141 | } 142 | 143 | /// Add links 144 | if (links && links.constructor === Array) { 145 | const preparedInitialLinks = []; 146 | const preparedLinks = []; 147 | for (let i = 0; i < links.length; ++i) { 148 | const link_data = links[i]; 149 | 150 | var link = new LiteGraph.LLink(); 151 | link.configure(link_data); 152 | 153 | // ComfyUI handles initial loading of links, and adding of links once some exist differently 154 | preparedInitialLinks[link.id] = link; 155 | preparedLinks.push(link); 156 | } 157 | if (links.length > 0) { 158 | if (!app.graph.links || app.graph.links.constructor !== Array || app.graph.links.length === 0) { 159 | app.graph.links = preparedInitialLinks; 160 | } 161 | else { 162 | app.graph.links.push(...preparedLinks); 163 | } 164 | app.graph.last_link_id += links.length; 165 | } 166 | } 167 | 168 | /// Add nodes 169 | { 170 | // Create new nodes 171 | for (let i = 0; i < nodes.length; ++i) { 172 | const n_info = nodes[i]; 173 | const node = LiteGraph.createNode(n_info.type, n_info.title); 174 | 175 | node.id = n_info.id; 176 | app.graph.add(node, true); 177 | } 178 | 179 | // Configure nodes with saved data 180 | for (let i = 0; i < nodes.length; ++i) { 181 | const n_info = nodes[i]; 182 | const node = app.graph.getNodeById(n_info.id); 183 | if (node) { 184 | node.configure(n_info); 185 | } 186 | } 187 | } 188 | 189 | /// Add group 190 | { 191 | var group = new LiteGraph.LGraphGroup(); 192 | group.configure(nodesGroup); 193 | 194 | const versioningData = { 195 | object_id: data.id, 196 | object_name: data.name, 197 | object_version: specificVersionData.id, 198 | }; 199 | group.versioning_data = versioningData; 200 | 201 | app.graph.add(group); 202 | app.graph.updateExecutionOrder(); 203 | } 204 | 205 | /// Update the canvas 206 | { 207 | if (app.graph.onConfigure) { 208 | app.graph.onConfigure(groupVersionData); 209 | } 210 | 211 | app.graph._version++; 212 | app.graph.setDirtyCanvas(true, true); 213 | } 214 | } 215 | 216 | export function updateGroupFromJSONData(group, data) { 217 | if (!data.versions || 218 | data.versions.length === 0 || 219 | !data.versions[0].node_data || 220 | !data.versions[0].node_data.group || 221 | !data.versions[0].node_data.group.versioning_data) 222 | { 223 | return; 224 | } 225 | group.versioning_data = data.versions[0].node_data.group.versioning_data; 226 | } -------------------------------------------------------------------------------- /web/EnhancedGroups/versionManager.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { fetchGroupsData, fetchGroupData, saveGroupData } from "./utils.js"; 4 | 5 | export default class VersionManager { 6 | 7 | #versionedGroups = []; 8 | 9 | async loadVersionedGroups() { 10 | const result = await fetchGroupsData(); 11 | this.#versionedGroups = result; 12 | } 13 | 14 | async loadGroupData(groupId) { 15 | const result = await fetchGroupData(groupId); 16 | return result; 17 | } 18 | 19 | async saveGroupData(groupData, saveAsNew) { 20 | const result = await saveGroupData(groupData, saveAsNew); 21 | if (result.error) { 22 | return result; 23 | } 24 | 25 | const newVersionedGroupData = { 26 | id: result.id, 27 | name: result.name, 28 | versions: result.versions.map(v => ({id: v.id, timestamp: v.last_change_timestamp})), 29 | }; 30 | const index = this.#versionedGroups.findIndex(obj => obj.id === result.id); 31 | if (index === -1) { 32 | this.#versionedGroups.push(newVersionedGroupData); 33 | } else { 34 | this.#versionedGroups[index] = newVersionedGroupData; 35 | } 36 | 37 | return result; 38 | } 39 | 40 | versionedGroups() { 41 | return this.#versionedGroups; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /web/OldSpinner/spinner.css: -------------------------------------------------------------------------------- 1 | .lnl-lds-ring { 2 | display: inline-block; 3 | position: relative; 4 | width: 1em; 5 | height: 1em; 6 | } 7 | .lnl-lds-ring div { 8 | box-sizing: border-box; 9 | display: block; 10 | position: absolute; 11 | width: 100%; 12 | height: 100%; 13 | border: 0.15em solid #fff; 14 | border-radius: 50%; 15 | animation: lds-ring 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite; 16 | border-color: #fff transparent transparent transparent; 17 | } 18 | .lnl-lds-ring div:nth-child(1) { 19 | animation-delay: -0.45s; 20 | } 21 | .lnl-lds-ring div:nth-child(2) { 22 | animation-delay: -0.3s; 23 | } 24 | .lnl-lds-ring div:nth-child(3) { 25 | animation-delay: -0.15s; 26 | } 27 | @keyframes lnl-lds-ring { 28 | 0% { 29 | transform: rotate(0deg); 30 | } 31 | 100% { 32 | transform: rotate(360deg); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /web/OldSpinner/spinner.js: -------------------------------------------------------------------------------- 1 | import { lnlAddStylesheet, lnlGetUrl } from "../utils.js"; 2 | 3 | lnlAddStylesheet(lnlGetUrl("./spinner.css", import.meta.url)); 4 | 5 | export function createLNLSpinner() { 6 | const div = document.createElement("div"); 7 | div.innerHTML = `
`; 8 | return div.firstElementChild; 9 | } 10 | -------------------------------------------------------------------------------- /web/VideoPlayer/videoPlayer.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { app } from "../../../scripts/app.js"; // For LiteGraph 4 | import { api } from "../../../scripts/api.js"; 5 | import { $el } from "../../../scripts/ui.js"; 6 | import { createLNLSpinner } from "../OldSpinner/spinner.js"; 7 | 8 | import { clamp, lnlGetUrl, lnlUploadFile } from "../utils.js"; 9 | import { getLNLPositionStyle } from "../styles.js"; 10 | import { handleLNLMouseEvent } from "../eventHandlers.js"; 11 | import { processVideoEntry } from "../utils.js"; 12 | 13 | // Double slider widget 14 | function createDoubleSliderWidget(hostNode, widgetName) { 15 | const doubleSliderWidget = { 16 | type: "double_slider", 17 | name: widgetName, 18 | options: { min: 0, max: 100, step: 1, precision: 1, read_only: false }, 19 | value: { current: 0 , startMarkerFrame: 0, endMarkerFrame: 100, currentFrame: 1, totalFrames: 1 }, 20 | marker: true, 21 | draw(ctx, node, widget_width, y, widget_height) { 22 | Object.assign(this.inputEl.style, getLNLPositionStyle(ctx, widget_width, y, node, widget_height)); 23 | }, 24 | onWidgetChanged(widget_name, new_value, old_value, widget) { 25 | console.log(`Widget ${widget_name} changed from ${old_value} to ${new_value}`); 26 | }, 27 | mouse(event, pos, node) { 28 | return handleLNLMouseEvent(event, pos, node, this.positionUpdatedCallback); 29 | }, 30 | }; 31 | doubleSliderWidget.inputEl = $el("doubleSliderWidget", { src: null }); 32 | doubleSliderWidget.positionUpdatedCallback = (value) => { 33 | pauseVideoIfPlaying(hostNode.previewWidget, hostNode.playerControlsWidget); 34 | const frameAtValue = hostNode.previewWidget.videoEl.getFrameForNValue(value); 35 | const clampedValue = clamp(frameAtValue, 1, doubleSliderWidget.value.totalFrames); 36 | hostNode.previewWidget.videoEl.setCurrentFrame(clampedValue); 37 | }; 38 | 39 | return doubleSliderWidget; 40 | } 41 | 42 | // Player controls widget 43 | const PlayerControls = { 44 | gotoStart: 0, 45 | setInPoint: 1, 46 | gotoInPoint: 2, 47 | stepBackward: 3, 48 | playPause: 4, 49 | stepForward: 5, 50 | gotoOutPoint: 6, 51 | setOutPoint: 7, 52 | gotoEnd: 8, 53 | }; 54 | 55 | function createPlayerControlsWidget(widgetName, hostNode, controlClickHandler) { 56 | const element = document.createElement("div"); 57 | const playerControlsWidget = hostNode.addDOMWidget(widgetName, "player_controls_widget", element, { 58 | serialize: false, 59 | hideOnZoom: false, 60 | }); 61 | playerControlsWidget.computeSize = function (width) { 62 | return [width, LiteGraph.NODE_WIDGET_HEIGHT * 2]; 63 | } 64 | playerControlsWidget.parentEl = document.createElement("div"); 65 | playerControlsWidget.parentEl.className = "player-controls-container"; 66 | element.appendChild(playerControlsWidget.parentEl); 67 | 68 | playerControlsWidget.controlsEl = document.createElement("div"); 69 | playerControlsWidget.controlsEl.className = "player-grid-container"; 70 | playerControlsWidget.parentEl.appendChild(playerControlsWidget.controlsEl); 71 | 72 | // Images downloaded from Icons8 (https://icons8/com). 73 | const images = [ 74 | lnlGetUrl("../images/goto_start.png", import.meta.url), 75 | lnlGetUrl("../images/set_in_point.png", import.meta.url), 76 | lnlGetUrl("../images/goto_in_point.png", import.meta.url), 77 | lnlGetUrl("../images/step_backward.png", import.meta.url), 78 | lnlGetUrl("../images/pause.png", import.meta.url), 79 | lnlGetUrl("../images/step_forward.png", import.meta.url), 80 | lnlGetUrl("../images/goto_out_point.png", import.meta.url), 81 | lnlGetUrl("../images/set_out_point.png", import.meta.url), 82 | lnlGetUrl("../images/goto_end.png", import.meta.url), 83 | ]; 84 | const tooltips = [ 85 | "Go to start", 86 | "Set in-point", 87 | "Go to in-point", 88 | "Step backward", 89 | "Play/Pause", 90 | "Step forward", 91 | "Go to out-point", 92 | "Mark out-point", 93 | "Go to end", 94 | ]; 95 | for (let i = 0; i < 9; i++) { 96 | const cell = document.createElement("div"); 97 | cell.title = tooltips[i]; 98 | cell.innerHTML = ``; 99 | playerControlsWidget.controlsEl.appendChild(cell); 100 | 101 | cell.addEventListener("mousedown", function () { 102 | this.style.opacity = 0.7; 103 | if (controlClickHandler) { 104 | controlClickHandler(i); 105 | } 106 | }); 107 | cell.addEventListener("mouseup", function () { 108 | this.style.opacity = 1.0; 109 | }); 110 | cell.addEventListener("mouseleave", function () { 111 | this.style.opacity = 1.0; 112 | }); 113 | cell.addEventListener("touchstart", function (e) { 114 | this.style.opacity = 0.7; 115 | e.preventDefault(); 116 | if (controlClickHandler) { 117 | controlClickHandler(i); 118 | } 119 | }); 120 | cell.addEventListener("touchend", function (e) { 121 | this.style.opacity = 1.0; 122 | e.preventDefault(); 123 | }); 124 | } 125 | 126 | return playerControlsWidget; 127 | } 128 | 129 | // Video preview widget 130 | function createVideoPreviewWidget(hostNode) { 131 | const infiniteAR = 1000; 132 | const element = document.createElement("div"); 133 | const previewWidget = hostNode.addDOMWidget("video_preview_widget", "preview", element, { 134 | serialize: false, 135 | hideOnZoom: false, 136 | getValue() { 137 | return element.value; 138 | }, 139 | setValue(v) { 140 | element.value = v; 141 | }, 142 | }); 143 | 144 | previewWidget.computeSize = function (width) { 145 | if (this.aspectRatio && !this.parentEl.hidden) { 146 | let height = (hostNode.size[0] - 20) / this.aspectRatio + 10; 147 | if (!(height > 0)) { 148 | height = 0; 149 | } 150 | this.computedHeight = height + 10; 151 | return [width, height]; 152 | } 153 | return [width, -4]; 154 | } 155 | previewWidget.aspectRatio = infiniteAR; 156 | previewWidget.value = { hidden: false, paused: false, params: {} } 157 | previewWidget.parentEl = document.createElement("div"); 158 | previewWidget.parentEl.style['position'] = "relative"; 159 | previewWidget.parentEl.style['width'] = "100%" 160 | element.appendChild(previewWidget.parentEl); 161 | previewWidget.videoEl = document.createElement("video"); 162 | previewWidget.videoEl.controls = false; 163 | previewWidget.videoEl.loop = false; 164 | previewWidget.videoEl.muted = true; 165 | previewWidget.videoEl.style['width'] = "100%" 166 | previewWidget.videoEl.style['pointer-events'] = "none" 167 | 168 | previewWidget.videoEl.addEventListener("loadedmetadata", async () => { 169 | previewWidget.aspectRatio = previewWidget.videoEl.videoWidth / previewWidget.videoEl.videoHeight; 170 | previewWidget.loaderEl.style['visibility'] = "visible"; 171 | 172 | let params = {} 173 | Object.assign(params, previewWidget.value.params); 174 | if (params.filename) { 175 | const jsonData = await processVideoEntry(params.filename, previewWidget.videoEl.duration); 176 | if (jsonData) { 177 | previewWidget.loaderEl.style['visibility'] = "hidden"; 178 | 179 | [hostNode.inPointWidget, hostNode.outPointWidget, hostNode.currentFrameWidget].forEach((widget) => { 180 | widget.options.min = 1; 181 | widget.options.max = jsonData.total_frames; 182 | }); 183 | 184 | const componentCreated = hostNode.componentCreated; 185 | const componentLoadedOrRefreshed = hostNode.currentFrameWidget.value != -1; 186 | previewWidget.value.params.frameDuration = jsonData.frame_duration; 187 | previewWidget.value.params.duration = jsonData.duration; 188 | previewWidget.value.params.totalFrames = jsonData.total_frames; 189 | hostNode.doubleSliderWidget.value.frameRate = jsonData.frame_rate; 190 | if (!componentCreated) { 191 | hostNode.doubleSliderWidget.value.startMarkerFrame = 1; 192 | hostNode.doubleSliderWidget.value.endMarkerFrame = jsonData.total_frames; 193 | 194 | hostNode.inPointWidget.value = 1; 195 | hostNode.outPointWidget.value = jsonData.total_frames; 196 | 197 | updateSliderValues(hostNode.doubleSliderWidget, hostNode, 1, jsonData.total_frames); 198 | } 199 | else { 200 | if (!componentLoadedOrRefreshed) { 201 | // Component is created from scratch, not loaded or refreshed 202 | hostNode.currentFrameWidget.value = hostNode.currentFrameWidget.options.min; 203 | hostNode.inPointWidget.value = hostNode.inPointWidget.options.min; 204 | hostNode.outPointWidget.value = hostNode.outPointWidget.options.max; 205 | } 206 | 207 | previewWidget.videoEl.setCurrentFrame(hostNode.currentFrameWidget.value); 208 | previewWidget.videoEl.setInPoint(hostNode.inPointWidget.value); 209 | previewWidget.videoEl.setOutPoint(hostNode.outPointWidget.value); 210 | updateSliderValues(hostNode.doubleSliderWidget, hostNode, hostNode.currentFrameWidget.value, previewWidget.value.params.totalFrames); 211 | } 212 | 213 | let lastTime = 0; 214 | function checkFrame() { 215 | if (previewWidget.videoEl.currentTime !== lastTime) { 216 | lastTime = previewWidget.videoEl.currentTime; 217 | 218 | const currentFrame = clamp(previewWidget.videoEl.getCurrentFrame(), 1, hostNode.doubleSliderWidget.value.totalFrames); 219 | hostNode.currentFrameWidget.value = currentFrame; 220 | updateSliderValues(hostNode.doubleSliderWidget, hostNode, currentFrame, jsonData.total_frames); 221 | } 222 | requestAnimationFrame(checkFrame); 223 | } 224 | previewWidget.videoEl.addEventListener('playing', (event) => { 225 | checkFrame(); 226 | 227 | hostNode.doubleSliderWidget.pointerIsDown = false; 228 | }); 229 | previewWidget.videoEl.addEventListener('ended', (event) => { 230 | setPlayIcon(hostNode.playerControlsWidget); 231 | }); 232 | 233 | if (!componentCreated || (componentCreated && !componentLoadedOrRefreshed)) { 234 | previewWidget.videoEl.play(); 235 | setPauseIcon(hostNode.playerControlsWidget); 236 | } 237 | else { 238 | checkFrame(); 239 | setPlayIcon(hostNode.playerControlsWidget); 240 | } 241 | } 242 | } 243 | setTimeout(() => { 244 | lnl_fitHeight(hostNode); 245 | }, 10); 246 | }); 247 | 248 | previewWidget.videoEl.addEventListener("error", () => { 249 | previewWidget.aspectRatio = infiniteAR; 250 | previewWidget.loaderEl.style['visibility'] = "hidden"; 251 | 252 | setTimeout(() => { 253 | previewWidget.value.params.frameDuration = 1; 254 | previewWidget.value.params.totalFrames = 1; 255 | 256 | hostNode.currentFrameWidget.value = 1; 257 | hostNode.inPointWidget.value = 1; 258 | hostNode.outPointWidget.value = 1; 259 | 260 | hostNode.doubleSliderWidget.value.startMarkerFrame = 1; 261 | hostNode.doubleSliderWidget.value.endMarkerFrame = 1; 262 | hostNode.doubleSliderWidget.value.frameRate = 1; 263 | 264 | if (this) { 265 | this.currentTime = 1; 266 | } 267 | 268 | updateSliderValues(hostNode.doubleSliderWidget, hostNode, 1, 1); 269 | lnl_fitHeight(hostNode); 270 | }, 100); 271 | }); 272 | 273 | previewWidget.updateSource = function () { 274 | let params = {} 275 | Object.assign(params, this.value.params); 276 | this.parentEl.hidden = this.value.hidden; 277 | this.videoEl.autoplay = false; 278 | let target_width = 256 279 | if (element.style?.width) { 280 | target_width = element.style.width.slice(0, -2) * 2; 281 | } 282 | if (!params.force_size || params.force_size.includes("?") || params.force_size == "Disabled") { 283 | params.force_size = target_width + "x?" 284 | } else { 285 | let size = params.force_size.split("x") 286 | let ar = parseInt(size[0]) / parseInt(size[1]) 287 | params.force_size = target_width + "x" + (target_width / ar) 288 | } 289 | previewWidget.videoEl.src = api.apiURL('/view?' + new URLSearchParams(params)); 290 | this.videoEl.hidden = false; 291 | } 292 | 293 | previewWidget.updateParameters = (params) => { 294 | Object.assign(previewWidget.value.params, params) 295 | previewWidget.updateSource(); 296 | }; 297 | previewWidget.parentEl.appendChild(previewWidget.videoEl); 298 | 299 | previewWidget.videoEl.getFrameForNValue = function (nvalue) { 300 | const frameAtValue = parseInt(nvalue * previewWidget.value.params.totalFrames / 100); 301 | return frameAtValue; 302 | }; 303 | 304 | previewWidget.videoEl.getCurrentFrame = function () { 305 | const currentFrame = Math.round(this.currentTime / previewWidget.value.params.frameDuration) + 1; 306 | return currentFrame; 307 | }; 308 | previewWidget.videoEl.getStartFrame = function () { 309 | const startFrame = 1; 310 | return startFrame; 311 | }; 312 | previewWidget.videoEl.getInPointFrame = function () { 313 | const inFrame = hostNode.doubleSliderWidget.value.startMarkerFrame; 314 | return inFrame; 315 | }; 316 | previewWidget.videoEl.getOutPointFrame = function () { 317 | const outFrame = hostNode.doubleSliderWidget.value.endMarkerFrame; 318 | return outFrame; 319 | }; 320 | previewWidget.videoEl.getEndFrame = function () { 321 | const endFrame = previewWidget.value.params.totalFrames; 322 | return endFrame; 323 | }; 324 | previewWidget.videoEl.setCurrentFrame = function (frame) { 325 | const clampedFrame = clamp(frame, 1, hostNode.doubleSliderWidget.value.totalFrames); 326 | this.currentTime = clampedFrame / hostNode.doubleSliderWidget.value.totalFrames * previewWidget.value.params.duration - previewWidget.value.params.frameDuration; 327 | hostNode.currentFrameWidget.value = clampedFrame; 328 | }; 329 | previewWidget.videoEl.advanceOneFrame = function () { 330 | const endFrame = this.getEndFrame(); 331 | const nextFrame = Math.min(this.getCurrentFrame() + 1, endFrame); 332 | this.setCurrentFrame(nextFrame); 333 | }; 334 | previewWidget.videoEl.regressOneFrame = function () { 335 | const startFrame = this.getStartFrame(); 336 | const previousFrame = Math.max(this.getCurrentFrame() - 1, startFrame); 337 | this.setCurrentFrame(previousFrame); 338 | }; 339 | previewWidget.videoEl.gotoInPoint = function () { 340 | const inFrame = this.getInPointFrame(); 341 | this.setCurrentFrame(inFrame); 342 | }; 343 | previewWidget.videoEl.gotoOutPoint = function () { 344 | const outFrame = this.getOutPointFrame(); 345 | this.setCurrentFrame(outFrame); 346 | }; 347 | previewWidget.videoEl.gotoStart = function () { 348 | const startFrame = this.getStartFrame(); 349 | this.setCurrentFrame(startFrame); 350 | }; 351 | previewWidget.videoEl.gotoEnd = function () { 352 | const endFrame = this.getEndFrame(); 353 | this.setCurrentFrame(endFrame); 354 | }; 355 | previewWidget.videoEl.setInPoint = function (value) { 356 | const currentFrame = this.getCurrentFrame(); 357 | const valueToSet = value ? value : currentFrame; 358 | hostNode.doubleSliderWidget.value.startMarkerFrame = valueToSet; 359 | hostNode.inPointWidget.value = valueToSet; 360 | 361 | const outPointFrame = this.getOutPointFrame(); 362 | if (valueToSet > outPointFrame) { 363 | hostNode.doubleSliderWidget.value.endMarkerFrame = this.getEndFrame(); 364 | hostNode.outPointWidget.value = this.getEndFrame(); 365 | } 366 | }; 367 | previewWidget.videoEl.setOutPoint = function (value) { 368 | const currentFrame = this.getCurrentFrame(); 369 | const valueToSet = value ? value : currentFrame; 370 | hostNode.doubleSliderWidget.value.endMarkerFrame = valueToSet; 371 | hostNode.outPointWidget.value = valueToSet; 372 | 373 | const inPointFrame = this.getInPointFrame(); 374 | if (valueToSet < inPointFrame) { 375 | hostNode.doubleSliderWidget.value.startMarkerFrame = this.getStartFrame(); 376 | hostNode.inPointWidget.value = this.getStartFrame(); 377 | } 378 | }; 379 | previewWidget.playPauseTriggeredCallback = () => { 380 | updatePlayPauseControl(previewWidget, hostNode.playerControlsWidget) 381 | }; 382 | 383 | createLoaderOverlay(previewWidget); 384 | return previewWidget; 385 | } 386 | 387 | // Video preview widget helpers 388 | function createLoaderOverlay(previewWidget) { 389 | previewWidget.playPauseOverlayEl = document.createElement("div"); 390 | previewWidget.playPauseOverlayEl.className = "video-loading-overlay-container"; 391 | previewWidget.playPauseOverlayEl.addEventListener('click', function () { 392 | previewWidget.playPauseTriggeredCallback?.call(); 393 | if (!isVideoPlaying(previewWidget)) { 394 | previewWidget.videoEl.play(); 395 | } else { 396 | previewWidget.videoEl.pause(); 397 | } 398 | }); 399 | previewWidget.parentEl.appendChild(previewWidget.playPauseOverlayEl); 400 | 401 | previewWidget.loaderEl = document.createElement("div"); 402 | previewWidget.loaderEl.className = "video-loading-overlay"; 403 | previewWidget.parentEl.appendChild(previewWidget.loaderEl); 404 | 405 | previewWidget.spinnerEl = document.createElement("div"); 406 | previewWidget.spinnerEl.className = "video-loading-spinner"; 407 | previewWidget.spinnerEl.innerHTML = createLNLSpinner().outerHTML + "
Processing..."; 408 | previewWidget.loaderEl.appendChild(previewWidget.spinnerEl); 409 | } 410 | 411 | // Utility 412 | function updateSliderValues(widget, node, currentFrame, totalFrames) { 413 | widget.value.current = (currentFrame / totalFrames) * 100; 414 | widget.value.currentFrame = currentFrame; 415 | widget.value.totalFrames = totalFrames; 416 | widget.label = `Frame: ${currentFrame} / ${totalFrames}`; 417 | node.graph?.setDirtyCanvas(true); 418 | } 419 | 420 | function updatePlayPauseControl(previewWidget, playerControlsWidget) { 421 | isVideoPlaying(previewWidget) 422 | ? setPlayIcon(playerControlsWidget) 423 | : setPauseIcon(playerControlsWidget); 424 | } 425 | 426 | function setPlayIcon(playerControlsWidget) { 427 | const imageHTML = ``; 428 | assignPlayPauseControlImage(playerControlsWidget, imageHTML); 429 | } 430 | 431 | function setPauseIcon(playerControlsWidget) { 432 | const imageHTML = ``; 433 | assignPlayPauseControlImage(playerControlsWidget, imageHTML); 434 | } 435 | 436 | function assignPlayPauseControlImage(playerControlsWidget, imageHTML) { 437 | playerControlsWidget.controlsEl.children[PlayerControls.playPause].innerHTML = imageHTML; 438 | playerControlsWidget.controlsEl.children[PlayerControls.playPause].style.opacity = 1.0; 439 | } 440 | 441 | function isVideoPlaying(previewWidget) { 442 | return !(previewWidget.videoEl.paused || previewWidget.videoEl.ended); 443 | } 444 | 445 | function pauseVideoIfPlaying(previewWidget, playerControlsWidget) { 446 | if (!isVideoPlaying(previewWidget)) { 447 | return; 448 | } 449 | updatePlayPauseControl(previewWidget, playerControlsWidget); 450 | previewWidget.videoEl.pause(); 451 | } 452 | 453 | 454 | /* 455 | Attribution: ComfyUI-VideoHelperSuite 456 | 457 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 458 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 459 | */ 460 | function createUploadWidget(hostNode, pathWidget) { 461 | const fileInput = document.createElement("input"); 462 | Object.assign(fileInput, { 463 | type: "file", 464 | accept: "video/webm,video/mp4,video/mkv", 465 | style: "display: none", 466 | onchange: async () => { 467 | if (fileInput.files.length) { 468 | if (await lnlUploadFile(fileInput.files[0]) != 200) { 469 | //upload failed and file can not be added to options 470 | return; 471 | } 472 | const filename = fileInput.files[0].name; 473 | const fullFilePath = `${filename}`; 474 | pathWidget.options.values.push(fullFilePath); 475 | pathWidget.options.values.sort(); 476 | pathWidget.value = fullFilePath; 477 | if (pathWidget.callback) { 478 | pathWidget.callback(fullFilePath) 479 | } 480 | } 481 | }, 482 | }); 483 | document.body.append(fileInput); 484 | let uploadWidget = hostNode.addWidget("button", "choose video to upload", "image", () => { 485 | //clear the active click event 486 | app.canvas.node_widget = null 487 | 488 | fileInput.click(); 489 | }); 490 | uploadWidget.options.serialize = false; 491 | return uploadWidget; 492 | } 493 | 494 | /* 495 | Attribution: ComfyUI-VideoHelperSuite 496 | 497 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 498 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 499 | */ 500 | function injectHidden(widget) { 501 | widget.computeSize = (target_width) => { 502 | if (widget.hidden) { 503 | return [0, -4]; 504 | } 505 | return [target_width, 20]; 506 | }; 507 | widget._type = widget.type 508 | Object.defineProperty(widget, "type", { 509 | set : function(value) { 510 | widget._type = value; 511 | }, 512 | get : function() { 513 | if (widget.hidden) { 514 | return "hidden"; 515 | } 516 | return widget._type; 517 | } 518 | }); 519 | widget.hidden = true; 520 | } 521 | 522 | function updateCustomSizeLogic(sizeWidget, customWidthWidget, customHeightWidget) { 523 | switch (sizeWidget.value) { 524 | case "Custom Width": 525 | customWidthWidget.hidden = false; 526 | customHeightWidget.hidden = true; 527 | break; 528 | case "Custom Height": 529 | customWidthWidget.hidden = true; 530 | customHeightWidget.hidden = false; 531 | break; 532 | case "Custom": 533 | customWidthWidget.hidden = false; 534 | customHeightWidget.hidden = false; 535 | break; 536 | default: 537 | customWidthWidget.hidden = true; 538 | customHeightWidget.hidden = true; 539 | break; 540 | } 541 | } 542 | 543 | // Create widgets 544 | export async function createFrameSelectorWidgets(nodeType) { 545 | const originalNodeCreated = nodeType.prototype.onNodeCreated; 546 | nodeType.prototype.onNodeCreated = function () { 547 | originalNodeCreated?.apply(this, arguments); 548 | 549 | const that = this; 550 | 551 | // Create double slider widget 552 | const doubleSliderWidget = createDoubleSliderWidget(this, "in_out_point_slider"); 553 | this.doubleSliderWidget = doubleSliderWidget; 554 | updateSliderValues(doubleSliderWidget, this, 1, 1); 555 | 556 | // Add path widget 557 | const pathWidget = this.widgets.find((w) => w.name === "video_path"); 558 | pathWidget.callback = (value, componentCreated) => { 559 | if (typeof componentCreated === "boolean" && componentCreated === true) { 560 | this.componentCreated = true; 561 | } 562 | else { 563 | this.componentCreated = false; 564 | } 565 | if (!value) { 566 | that.previewWidget.updateParameters({}); 567 | return; 568 | } 569 | 570 | let extension_index = value.lastIndexOf("."); 571 | let extension = value.slice(extension_index+1); 572 | let format = "video" 573 | format += "/" + extension; 574 | let params = {filename : value, type: "input", format: format}; 575 | that.previewWidget.updateParameters(params); 576 | }; 577 | this.pathWidget = pathWidget; 578 | 579 | // Add upload widget 580 | const uploadWidget = createUploadWidget(this, pathWidget); 581 | this.uploadWidget = uploadWidget; 582 | 583 | /* 584 | Attribution: ComfyUI-VideoHelperSuite 585 | 586 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 587 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 588 | */ 589 | // Add video preview widget 590 | const previewWidget = createVideoPreviewWidget(this); 591 | this.previewWidget = previewWidget; 592 | 593 | const sizeWidget = this.widgets.find((w) => w.name === 'force_size'); 594 | const customWidthWidget = this.widgets.find((w) => w.name === 'custom_width'); 595 | const customHeightWidget = this.widgets.find((w) => w.name === 'custom_height'); 596 | if (sizeWidget !== undefined) { 597 | injectHidden(customWidthWidget); 598 | injectHidden(customHeightWidget); 599 | sizeWidget.callback = (value) => { 600 | updateCustomSizeLogic(sizeWidget, customWidthWidget, customHeightWidget); 601 | lnl_fitHeight(that); 602 | }; 603 | } 604 | 605 | // Add double slider widget 606 | document.body.appendChild(doubleSliderWidget.inputEl); 607 | this.addCustomWidget(doubleSliderWidget); 608 | 609 | // Create player controls widget 610 | const playerControlsWidget = createPlayerControlsWidget("player_controls", that, (control) => { 611 | switch (control) { 612 | case PlayerControls.gotoStart: 613 | pauseVideoIfPlaying(previewWidget, playerControlsWidget); 614 | previewWidget.videoEl.gotoStart(); 615 | break; 616 | case PlayerControls.setInPoint: 617 | previewWidget.videoEl.setInPoint(); 618 | that.inPointWidget.value = doubleSliderWidget.value.startMarkerFrame; 619 | that.graph?.setDirtyCanvas(true); 620 | break; 621 | case PlayerControls.gotoInPoint: 622 | pauseVideoIfPlaying(previewWidget, playerControlsWidget); 623 | previewWidget.videoEl.gotoInPoint(); 624 | break; 625 | case PlayerControls.stepBackward: 626 | pauseVideoIfPlaying(previewWidget, playerControlsWidget); 627 | previewWidget.videoEl.regressOneFrame(); 628 | break; 629 | case PlayerControls.playPause: 630 | updatePlayPauseControl(previewWidget, playerControlsWidget); 631 | if (!isVideoPlaying(previewWidget)) { 632 | previewWidget.videoEl.play(); 633 | } else { 634 | previewWidget.videoEl.pause(); 635 | } 636 | break; 637 | case PlayerControls.stepForward: 638 | pauseVideoIfPlaying(previewWidget, playerControlsWidget); 639 | previewWidget.videoEl.advanceOneFrame(); 640 | break; 641 | case PlayerControls.gotoOutPoint: 642 | pauseVideoIfPlaying(previewWidget, playerControlsWidget); 643 | previewWidget.videoEl.gotoOutPoint(); 644 | break; 645 | case PlayerControls.setOutPoint: 646 | previewWidget.videoEl.setOutPoint(); 647 | that.outPointWidget.value = doubleSliderWidget.value.endMarkerFrame; 648 | that.graph?.setDirtyCanvas(true); 649 | break; 650 | case PlayerControls.gotoEnd: 651 | pauseVideoIfPlaying(previewWidget, playerControlsWidget); 652 | previewWidget.videoEl.gotoEnd(); 653 | break; 654 | } 655 | }); 656 | this.playerControlsWidget = playerControlsWidget; 657 | 658 | // Add In/Out point and frame widgets 659 | const currentFrameWidget = this.addWidget("number", "current_frame", -1, (value) => { 660 | previewWidget.videoEl.setCurrentFrame(value); 661 | }, { min: 1, max: 1, step: 10, precision: 0 }); 662 | this.currentFrameWidget = currentFrameWidget; 663 | 664 | const inPointWidget = this.addWidget("number", "in_point", -1, (value) => { 665 | previewWidget.videoEl.setInPoint(value); 666 | }, { min: 1, max: 1, step: 10, precision: 0 }); 667 | this.inPointWidget = inPointWidget; 668 | 669 | const outPointWidget = this.addWidget("number", "out_point", -1, (value) => { 670 | previewWidget.videoEl.setOutPoint(value); 671 | }, { min: 1, max: 1, step: 10, precision: 0 }); 672 | this.outPointWidget = outPointWidget; 673 | 674 | // Select every nth frame 675 | const selectEveryNthFrameWidget = this.addWidget("number", "select_every_nth_frame", 1, (value) => {}, { min: 1, step: 10, precision: 0 }); 676 | this.selectEveryNthFrameWidget = selectEveryNthFrameWidget; 677 | 678 | // Make sure to reload video after refreshing 679 | setTimeout(() => { 680 | pathWidget.callback(pathWidget.value, true); 681 | this.graph?.setDirtyCanvas(true); 682 | }, 10); 683 | 684 | // Cleanup 685 | this.serialize_widgets = true; 686 | 687 | const originalOnRemoved = this.onRemoved; 688 | this.onRemoved = function () { 689 | originalOnRemoved?.apply(this, arguments); 690 | doubleSliderWidget.inputEl.remove(); 691 | }; 692 | this.setSize(this.computeSize()); 693 | }; 694 | 695 | // Loading serialized data 696 | const originalOnConfigure = nodeType.prototype.onConfigure; 697 | nodeType.prototype.onConfigure = function (info) { 698 | originalOnConfigure?.apply(this, arguments); 699 | 700 | const sizeWidget = this.widgets.find((w) => w.name === 'force_size'); 701 | const customWidthWidget = this.widgets.find((w) => w.name === 'custom_width'); 702 | const customHeightWidget = this.widgets.find((w) => w.name === 'custom_height'); 703 | if (sizeWidget !== undefined) { 704 | updateCustomSizeLogic(sizeWidget, customWidthWidget, customHeightWidget); 705 | lnl_fitHeight(this); 706 | } 707 | }; 708 | } 709 | 710 | /* 711 | Attribution: ComfyUI-VideoHelperSuite 712 | 713 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 714 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 715 | */ 716 | function lnl_fitHeight(node) { 717 | node.setSize([node.size[0], node.computeSize([node.size[0], node.size[1]])[1]]) 718 | node?.graph?.setDirtyCanvas(true); 719 | } 720 | -------------------------------------------------------------------------------- /web/css/lnlNodes.css: -------------------------------------------------------------------------------- 1 | .player-controls-container { 2 | width: 100%; 3 | height: 100%; 4 | min-width: 290px; 5 | } 6 | 7 | .player-grid-container { 8 | display: grid; 9 | grid-template-columns: repeat(9, 30px); 10 | justify-content: center; 11 | align-content: center; 12 | gap: 10px; 13 | } 14 | 15 | .player-grid-item { 16 | text-align: center; 17 | width: 80%; 18 | height: 80%; 19 | object-fit: contain; 20 | } 21 | 22 | .video-loading-overlay-container { 23 | position: absolute; 24 | display: block; 25 | top: 0px; 26 | bottom: 4px; 27 | left: 0px; 28 | z-index: 100; 29 | width: 100%; 30 | background: rgba(0, 0, 0, 0.0); 31 | } 32 | 33 | .video-loading-overlay { 34 | position: absolute; 35 | display: block; 36 | top: 0px; 37 | bottom: 4px; 38 | left: 0px; 39 | z-index: 9999; 40 | width: 100%; 41 | background: rgba(0, 0, 0, 0.85); 42 | visibility: hidden; 43 | } 44 | 45 | .video-loading-spinner { 46 | position: relative; 47 | text-align: center; 48 | top: 50%; 49 | transform: translateY(-50%); 50 | font-family: Tahoma, sans-serif; 51 | font-size: 120%; 52 | } 53 | -------------------------------------------------------------------------------- /web/eventHandlers.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { app } from "../../scripts/app.js"; // For LiteGraph 4 | 5 | import { clamp } from "./utils.js"; 6 | 7 | export function handleLNLMouseEvent(event, pos, node, positionUpdatedCallback) { 8 | const width = node.size[0]; 9 | 10 | for (var i = 0; i < node.widgets.length; ++i) { 11 | const w = node.widgets[i]; 12 | const widget_width = (w.width || width) - 2*w.width_margin; 13 | const x = pos[0] - w.width_margin; 14 | 15 | if (event.type == LiteGraph.pointerevents_method+"down") { 16 | w.pointerIsDown = true; 17 | } 18 | else if (event.type == LiteGraph.pointerevents_method+"up") { 19 | w.pointerIsDown = false; 20 | } 21 | switch (w.type) { 22 | case "double_slider": 23 | var old_value = w.value.current; 24 | var nvalue = clamp((x) / (widget_width), 0, 1); 25 | w.value.current = w.options.min + (w.options.max - w.options.min) * nvalue; 26 | if (old_value != w.value.current) { 27 | setTimeout(function() { 28 | positionUpdatedCallback(w.value.current); 29 | }, 20); 30 | } 31 | break; 32 | default: 33 | break; 34 | } 35 | } 36 | return false; 37 | } 38 | -------------------------------------------------------------------------------- /web/images/goto_end.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/goto_end.png -------------------------------------------------------------------------------- /web/images/goto_in_point.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/goto_in_point.png -------------------------------------------------------------------------------- /web/images/goto_out_point.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/goto_out_point.png -------------------------------------------------------------------------------- /web/images/goto_start.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/goto_start.png -------------------------------------------------------------------------------- /web/images/pause.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/pause.png -------------------------------------------------------------------------------- /web/images/play.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/play.png -------------------------------------------------------------------------------- /web/images/set_in_point.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/set_in_point.png -------------------------------------------------------------------------------- /web/images/set_out_point.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/set_out_point.png -------------------------------------------------------------------------------- /web/images/step_backward.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/step_backward.png -------------------------------------------------------------------------------- /web/images/step_forward.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/asteriafilmco/ComfyUI-LNL/ab48dfba0098dbcdd7757bfcbcb31a86d74bd60d/web/images/step_forward.png -------------------------------------------------------------------------------- /web/nodes.js: -------------------------------------------------------------------------------- 1 | import { app } from "../../scripts/app.js"; 2 | 3 | import { createFrameSelectorWidgets } from "./VideoPlayer/videoPlayer.js"; 4 | import { registerGroupExtensions, setupConfigAndSerialization } from "./EnhancedGroups/enhancedGroups.js"; 5 | 6 | import { lnlAddStylesheet, lnlGetUrl } from "./utils.js"; 7 | 8 | function setupFrameSelectorNodeHandlers(nodeType) { 9 | const originalOnExecutionStart = nodeType.prototype.onExecutionStart; 10 | nodeType.prototype.onExecutionStart = function () { 11 | this.previewWidget.videoEl.pause(); 12 | 13 | originalOnExecutionStart?.apply(this, arguments); 14 | }; 15 | 16 | const originalOnExecuted = nodeType.prototype.onExecuted; 17 | nodeType.prototype.onExecuted = function (output) { 18 | originalOnExecuted?.apply(this, arguments); 19 | }; 20 | 21 | const originalSetSize = nodeType.prototype.setSize; 22 | nodeType.prototype.setSize = function (size) { 23 | originalSetSize?.apply(this, arguments); 24 | 25 | const clampedWidth = Math.max(size[0], 390); 26 | this.size = [clampedWidth, size[1]]; 27 | }; 28 | } 29 | 30 | app.registerExtension({ 31 | name: "LNL.Core", 32 | 33 | async init() { 34 | lnlAddStylesheet(lnlGetUrl("css/lnlNodes.css", import.meta.url)); 35 | 36 | setupConfigAndSerialization(); 37 | }, 38 | async setup() { 39 | registerGroupExtensions(); 40 | }, 41 | async beforeRegisterNodeDef(nodeType, nodeData) { 42 | if (nodeData?.name.indexOf("LNL_FrameSelector") !== -1) { 43 | await createFrameSelectorWidgets(nodeType); 44 | 45 | setupFrameSelectorNodeHandlers(nodeType); 46 | } 47 | }, 48 | }); 49 | -------------------------------------------------------------------------------- /web/styles.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { clamp } from "./utils.js"; 4 | 5 | export function getLNLPositionStyle(ctx, widget_width, y, node, widget_height) { 6 | const margin = 10; 7 | const scale = ctx.getTransform().a; 8 | const showText = scale > 0.6; 9 | 10 | const h = LiteGraph.NODE_WIDGET_HEIGHT; 11 | for (var i = 0; i < node.widgets.length; ++i) { 12 | const w = node.widgets[i]; 13 | 14 | if(w.disabled) { 15 | ctx.globalAlpha *= 0.5; 16 | } 17 | switch (w.type) { 18 | case "double_slider": 19 | w.width_margin = margin; 20 | ctx.fillStyle = LiteGraph.WIDGET_BGCOLOR; 21 | ctx.fillRect(margin, y, widget_width - margin * 2, h); 22 | var range = w.options.max - w.options.min; 23 | var nvalue = (w.value.current - w.options.min) / range; 24 | if(nvalue < 0.0) nvalue = 0.0; 25 | if(nvalue > 1.0) nvalue = 1.0; 26 | 27 | //// Draw progress bar backgrounds 28 | // Start marker 29 | let startNValue = 0.0; 30 | if (w.value.startMarkerFrame !== undefined) { 31 | const markerPosition = w.value.startMarkerFrame * 100 / w.value.totalFrames; 32 | startNValue = clamp((markerPosition - w.options.min) / range, 0.0, 1.0); 33 | 34 | ctx.fillStyle = "#99B8AA"; 35 | ctx.fillRect(margin, y, Math.min(startNValue, nvalue) * (widget_width - margin * 2), h); 36 | } 37 | 38 | // End marker 39 | let endNValue = 1.0; 40 | if (w.value.endMarkerFrame !== undefined) { 41 | const markerPosition = w.value.endMarkerFrame * 100 / w.value.totalFrames; 42 | endNValue = clamp((markerPosition - w.options.min) / range, 0.0, 1.0); 43 | 44 | if (nvalue > endNValue) { 45 | ctx.fillStyle = "#BA6C6A"; 46 | ctx.fillRect(margin + endNValue * (widget_width - margin * 2), y, (Math.min(1.0, nvalue) - endNValue) * (widget_width - margin * 2), h); 47 | } 48 | } 49 | 50 | // Position marker 51 | if (nvalue > startNValue) { 52 | ctx.fillStyle = w.options.hasOwnProperty("slider_color") ? w.options.slider_color : "#678"; 53 | ctx.fillRect(margin + startNValue * (widget_width - margin * 2), y, (Math.min(nvalue, endNValue) - startNValue) * (widget_width - margin * 2), h); 54 | } 55 | 56 | //// Draw markers 57 | // Start marker 58 | if (w.value.startMarkerFrame !== undefined) { 59 | ctx.fillStyle = "#16C172"; 60 | ctx.fillRect(margin + startNValue * (widget_width - margin * 2), y - h * 0.125, 2, h * 1.25); 61 | } 62 | 63 | // End marker 64 | if (w.value.endMarkerFrame !== undefined) { 65 | ctx.fillStyle = "#C12926"; 66 | ctx.fillRect(margin + endNValue * (widget_width - margin * 2), y - h * 0.125, 2, h * 1.25); 67 | } 68 | 69 | // Position marker 70 | if (w.pointerIsDown && w.marker) { 71 | const markerPosition = w.value.currentFrame * 100 / w.value.totalFrames; 72 | var marker_nvalue = clamp((markerPosition - w.options.min) / range, 0.0, 1.0); 73 | ctx.fillStyle = w.options.hasOwnProperty("marker_color") ? w.options.marker_color : "#AA9"; 74 | ctx.fillRect(margin + marker_nvalue * (widget_width - margin * 2), y - h * 0.125, 2, h * 1.25); 75 | 76 | ctx.strokeStyle = ctx.fillStyle; 77 | ctx.strokeRect(margin + marker_nvalue * (widget_width - margin * 2) - 3, y - h * 0.125 - 5, 8, h * 1.25 + 10); 78 | } 79 | 80 | if (showText) { 81 | ctx.textAlign = "center"; 82 | ctx.fillStyle = LiteGraph.WIDGET_TEXT_COLOR; 83 | ctx.fillText( 84 | w.label || w.name + " " + Number(w.value.current).toFixed( 85 | w.options.precision != null 86 | ? w.options.precision 87 | : 3 88 | ), 89 | widget_width * 0.5, 90 | y + h * 0.7 91 | ); 92 | } 93 | break; 94 | default: 95 | break; 96 | } 97 | } 98 | 99 | const elRect = ctx.canvas.getBoundingClientRect(); 100 | const transform = new DOMMatrix() 101 | .scaleSelf(elRect.width / ctx.canvas.width, elRect.height / ctx.canvas.height) 102 | .multiplySelf(ctx.getTransform()) 103 | .translateSelf(margin, margin + y); 104 | 105 | return { 106 | transformOrigin: '0 0', 107 | transform: transform, 108 | left: `0px`, 109 | top: `0px`, 110 | position: "absolute", 111 | maxWidth: `${widget_width - margin * 2}px`, 112 | maxHeight: `${widget_height - margin*2}px`, 113 | width: `auto`, 114 | height: `auto`, 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /web/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | import { api } from "../../../scripts/api.js"; 4 | import { $el } from "../../../scripts/ui.js"; 5 | 6 | export async function processVideoEntry(path) { 7 | const body = { 8 | path: path, 9 | }; 10 | const result = await api.fetchApi("/process_video_entry", { method: "POST", body: JSON.stringify(body) }); 11 | if (result.error) { 12 | console.error(`processVideoEntry error: ${result.error}`); 13 | return undefined; 14 | } 15 | const jsonData = await result.json(); 16 | const frameDuration = jsonData.duration / jsonData.total_frames; 17 | jsonData.frame_duration = frameDuration; 18 | return jsonData; 19 | } 20 | 21 | /* 22 | Attribution: ComfyUI-Custom-Scripts 23 | 24 | Portions of this code are adapted from GitHub repository `https://github.com/pythongosssss/ComfyUI-Custom-Scripts`, 25 | which is licensed under the MIT License: 26 | */ 27 | export function lnlAddStylesheet(url) { 28 | $el("link", { 29 | parent: document.head, 30 | rel: "stylesheet", 31 | type: "text/css", 32 | href: url.startsWith("http") ? url : lnlGetUrl(url), 33 | }); 34 | } 35 | 36 | /* 37 | Attribution: ComfyUI-Custom-Scripts 38 | 39 | Portions of this code are adapted from GitHub repository `https://github.com/pythongosssss/ComfyUI-Custom-Scripts`, 40 | which is licensed under the MIT License: 41 | */ 42 | export function lnlGetUrl(path, baseUrl) { 43 | if (baseUrl) { 44 | return new URL(path, baseUrl).toString(); 45 | } 46 | else { 47 | return new URL("../" + path, import.meta.url).toString(); 48 | } 49 | } 50 | 51 | /* 52 | Attribution: ComfyUI-VideoHelperSuite 53 | 54 | Portions of this code are adapted from GitHub repository `https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite`, 55 | which is licensed under the GNU General Public License version 3 (GPL-3.0): 56 | */ 57 | export async function lnlUploadFile(file) { 58 | //TODO: Add uploaded file to cache with Cache.put()? 59 | try { 60 | // Wrap file in formdata so it includes filename 61 | const body = new FormData(); 62 | const i = file.webkitRelativePath.lastIndexOf('/'); 63 | const subfolder = file.webkitRelativePath.slice(0,i+1) 64 | const new_file = new File([file], file.name, { 65 | type: file.type, 66 | lastModified: file.lastModified, 67 | }); 68 | body.append("image", new_file); 69 | if (i > 0) { 70 | body.append("subfolder", subfolder); 71 | } 72 | const resp = await api.fetchApi("/upload/image", { 73 | method: "POST", 74 | body, 75 | }); 76 | 77 | if (resp.status === 200) { 78 | return resp.status 79 | } else { 80 | alert(resp.status + " - " + resp.statusText); 81 | } 82 | } catch (error) { 83 | alert(error); 84 | } 85 | } 86 | 87 | export function clamp(value, min, max) { 88 | return Math.max(min, Math.min(value, max)); 89 | } 90 | --------------------------------------------------------------------------------