├── LICENSE ├── README.md ├── SETUP.md ├── rffmpeg └── rffmpeg.yml.sample /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 | 2 | 3 |

4 | License: GPLv3+ 5 | Code Style: Black 6 | 7 | Chat on Matrix 8 | 9 | 10 | Support me on Patreon 11 | 12 | 13 | Support me on GitHub 14 | 15 |

16 | 17 | `rffmpeg` is a remote FFmpeg wrapper used to execute FFmpeg commands on a remote server via SSH. It is most useful in situations involving media servers such as Jellyfin (our reference user), where one might want to perform transcoding actions with FFmpeg on a remote machine or set of machines which can better handle transcoding, take advantage of hardware acceleration, or distribute transcodes across multiple servers for load balancing. 18 | 19 | ## Quick usage 20 | 21 | 1. Install the required Python 3 dependencies: `click`, `yaml` and `subprocess` (`sudo apt install python3-click python3-yaml python3-subprocess` in Debian) and optionally install `psycopg2` with `sudo apt install python3-psycopg2` for Postgresql support. 22 | 23 | 1. Create the directory `/etc/rffmpeg`. 24 | 25 | 1. Optionally, copy the `rffmpeg.yml.sample` file to `/etc/rffmpeg/rffmpeg.yml` and edit it to suit your needs. 26 | 27 | 1. Install `rffmpeg` somewhere useful, for instance at `/usr/local/bin/rffmpeg`. 28 | 29 | 1. Create symlinks for the command names `ffmpeg` and `ffprobe` to `rffmpeg`, for example `sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffmpeg` and `sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffprobe`. 30 | 31 | 1. Initialize the database and add a target host, for example `sudo rffmpeg init && rffmpeg add myhost.domain.tld`. 32 | 33 | 1. Set your media program to use `rffmpeg` via the `ffmpeg` symlink name created above, instead of any other `ffmpeg` binary. 34 | 35 | 1. Profit! 36 | 37 | `rffmpeg` does require a little bit more configuration to work properly however. For a comprehensive installation tutorial based on a reference setup, please see [the SETUP guide](SETUP.md). 38 | 39 | **NOTE** Jellyfin 10.10.x and newer require an additional `TMPDIR` environment variable set to somewhere exported to the remote machine, or these paths will not work properly. Edit your Jellyfin startup/service configuration to set that. See the setup guide for more details. 40 | 41 | ## Setup and Usage 42 | 43 | ### The `rffmpeg` Configuration file 44 | 45 | `rffmpeg` will look at `/etc/rffmpeg/rffmpeg.yml` (or a path specified by the `RFFMPEG_CONFIG` environment variable) for a configuration file. If it doesn't find one, defaults will be used instead. You can use this file to override many configurable default values to better fit your environment. The defaults should be sensible for anyone using [Jellyfin](https://jellyfin.org) and following the [SETUP guide](SETUP.md). 46 | 47 | The example configuration file at `rffmpeg.yml.sample` shows all available options; this file can be copied as-is to the above location and edited to suit your needs; simply uncomment any lines you want to change. Note that if you do specify a file, you *must* ensure that all top-level categories are present or it will error out. 48 | 49 | **NOTE:** If you are running into problems with `rffmpeg`, you must use the config file to adjust `logging` -> `debug` to `true` to obtain more detailed logs before requesting help. 50 | 51 | Each option has an explanatory comment above it detailing its purpose. 52 | 53 | Since the configuration file is YAML, ensure that you do not use "Tab" characters inside of it, only spaces. 54 | 55 | ### CLI interface to `rffmpeg` 56 | 57 | `rffmpeg` is a [Click](https://click.palletsprojects.com)-based application; thus, all commands have a `-h` or `--help` flag to show usage and additional options that may be specified. 58 | 59 | ### Initializing `rffmpeg` 60 | 61 | After first installing `rffmpeg`, you must initialize the database with the `rffmpeg init` command. 62 | 63 | Note that by default, `sudo`/root privilege is required for this command to create the required data paths, but afterwards, `rffmpeg` can be run by anyone in the configured group (by default the `sudo` group). You can bypass the `sudo` requirement with the `--no-root` command, for example when running in a rootless container; this will require the running user to have write permissions to the state and database parent directories, and will not perform any permissions modifications on the resulting files. 64 | 65 | ### Viewing Status 66 | 67 | Once installed and initialized, you can see the status of the `rffmpeg` system with the `rffmpeg status` command. This will show all configured target hosts, their states, and any active commands being run. 68 | 69 | ### Adding or Removing Target Hosts 70 | 71 | To add a target host, use the `rffmpeg add` command. You must add at least one target host for `rffmpeg` to be useful. This command takes the optional `-w`/`--weight` flag to adjust the weight of the target host (see below). A host can also be added more than once for a pseudo-weight, but this is an advanced usage. 72 | 73 | To remove a target host, use the `rffmpeg remove` command. This command takes either a target host name/IP, which affects all instances of that name, or a specific host ID. Removing an in-use target host will not terminate any running processes, though it may result in undefined behaviour within `rffmpeg`. Before removing a host it is best to ensure there is nothing using it. 74 | 75 | ### Viewing the Logfile 76 | 77 | The `rffmpeg` CLI offers a convenient way to view the log file. Use `rffmpeg log` to view the entire logfile in the default pager (usually `less`), or use `rffmpeg log -f` to follow any new log entries after that point (like `tail -0 -f`). 78 | 79 | ## Important Considerations 80 | 81 | ### Localhost and Fallback 82 | 83 | If one of the configured target hosts is called `localhost` or `127.0.0.1`, `rffmpeg` will run the `ffmpeg`/`ffprobe` commands locally without SSH. This can be useful if the local machine is also a powerful transcoding device, but you still want to offload some transcoding jobs to other machines. 84 | 85 | In addition, `rffmpeg` will fall back to `localhost` automatically, even if it is not explicitly configured, should it be unable to find any working remote hosts. This helps prevent situations where `rffmpeg` cannot be run due to none of the remote host(s) being available. 86 | 87 | The exact path to the local `ffmpeg` and `ffprobe` binaries can be overridden in the configuration, should their paths not match those of the remote system(s). 88 | 89 | ### Hardware Acceleration 90 | 91 | Note that if hardware acceleration is configured in the calling application, **the exact same hardware acceleration modes must be available on all configured hosts, and, for fallback to work, the local host as well**, or the `ffmpeg` commands will fail. 92 | 93 | This is an explicit requirement, and there is no easy way around this without rewriting the passed arguments, which is explicitly out-of-scope for `rffmpeg` (see the FAQ entry below about mangling arguments). 94 | 95 | You should always use a lowest-common-denominator approach when deciding what hardware acceleration option(s) to enable, such that any configured host can run any process, or accept that fallback will not work if all remote hosts are unavailable. 96 | 97 | ### Target Host Selection 98 | 99 | When more than one target host is present, `rffmpeg` uses the following rules to select a target host. These rules are evaluated each time a new `rffmpeg` alias process is spawned based on the current state (actively running processes, etc.). 100 | 101 | 1. Any hosts marked `bad` are ignored. 102 | 103 | 1. All remaining hosts are iterated through in an indeterminate order (Python dictionary with root key as the host ID). For each host: 104 | 105 | a. If the host is not `localhost`/`127.0.0.1`, it is tested to ensure it is reachable (responds to `ffmpeg -version` over SSH). If it is not reachable, it is marked `bad` for the duration of this processes' runtime and skipped. 106 | 107 | b. If the host is `idle` (has no running processes), it is immediately chosen and the iteration stops. 108 | 109 | c. If the host is `active` (has at least one running process), it is checked against the host with the current fewest number of processes, adjusted for host weight. If it has the fewest, it takes over this role. 110 | 111 | 1. Once all hosts have been iterated through, at least one host should have been chosen: either the first `idle` host, or the host with the fewest number of active processes. `rffmpeg` will then begin running against this host. If no valid target host was found, `localhost` is used (see section [Localhost and Fallback](#localhost-and-fallback) above). 112 | 113 | ### Target Host Weights and Duplicated Target Hosts 114 | 115 | When adding a host to `rffmpeg`, a weight can be specified. Weights are used during the calculation of the fewest number of processes among hosts. The actual number of processes running on the host is floor divided (rounded down to the nearest divisible integer) by the weight to give a "weighted count", which is then used in the determination. This option allows one host to take on more processes than other nodes, as it will be chosen as the "least busy" host more often. 116 | 117 | For example, consider two hosts: `host1` with weight 1, and `host2` with weight 5. `host2` would have its actual number of processes floor divided by `5`, and thus any number of processes under `5` would count as `0`, any number of processes between `5` and `10` would count as `1`, and so on, resulting in `host2` being chosen over `host1` even if it had several processes. Thus, `host2` would on average handle 5x more `ffmpeg` processes than `host1` would. 118 | 119 | Host weighting is a fairly blunt instrument, and only becomes important when many simultaneous `ffmpeg` processes/transcodes are occurring at once across at least 2 remote hosts, and where the target hosts have significantly different performance profiles. Generally leaving all hosts at weight 1 would be sufficient for most use-cases. 120 | 121 | Furthermore, it is possible to add a host of the same name more than once in the `rffmpeg add` command. This is functionally equivalent to setting the host with a higher weight, but may have some subtle effects on host selection beyond what weight alone can do; this is probably not worthwhile but is left in for the option. 122 | 123 | ### `bad` Hosts 124 | 125 | As mentioned above under [Target Host Selection](#target-host-selection), a host can be marked `bad` if it does not respond to an `ffmpeg -version` command in at least 1 second if it is due to be checked as a target for a new `rffmpeg` alias process. This can happen because a host is offline, unreachable, overloaded, or otherwise unresponsive. 126 | 127 | Once a host is marked `bad`, it will remain so for as long as the `rffmpeg` process that marked it `bad` is running. This can last anywhere from a few seconds (library scan processes, image extraction) to several tens of minutes (a long video transcode). During this time, any new `rffmpeg` processes that start will see that the host is marked as `bad` and thus skip it for target selection. Once the marking `rffmpeg` process completes or is terminated, the `bad` status of that host will be cleared, allowing the next run to try it again. This strikes a balance between always retrying known-unresponsive hosts over and over (and thus delaying process startup), and ensuring that hosts will eventually be retried. 128 | 129 | If for some reason all configured hosts are marked `bad`, fallback will be engaged; see the above section [Localhost and Fallback](#localhost-and-fallback) for details on what occurs in this situation. An explicit `localhost` host entry cannot be marked `bad`. 130 | 131 | ## FAQ 132 | 133 | ### Why did you make `rffmpeg`? 134 | 135 | My virtualization setup (multiple 1U nodes with lots of live migration/failover) didn't lend itself well to passing a GPU into my Jellyfin VM, but I wanted to offload transcoding because doing 4K HEVC transcodes with a CPU performs horribly. I happened to have another machine (my "base" remote headless desktop/gaming server) which had a GPU, so I wanted to find a way to offload the transcoding to it. I came up with `rffmpeg` as a simple wrapper to the `ffmpeg` and `ffprobe` calls that Jellyfin (and Emby, and likely other media servers too) makes which would run them on that host instead. After finding it quite useful myself, I released it publicly as GPLv3 software so that others may benefit as well! It has since received a lot of feedback and feature requests from the community, leading to the tool as it exists today. 136 | 137 | ### What supports `rffmpeg`? 138 | 139 | This depends on what "layer" you're asking at. 140 | 141 | * Media Servers: Jellyfin is officially supported; Emby seems to work fine, with caveats (see [Issue #10](https://github.com/joshuaboniface/rffmpeg/issues/10)); no others have been tested to my knowledge. 142 | * Operating Systems (source): Debian and its derivatives (Ubuntu, Linux Mint, etc.) should all work perfectly; other Linux operating systems should work fine too as the principles are the same; MacOS should work since it has an SSH client built in; Windows will not work as `rffmpeg` depends on some POSIX assumptions internally. 143 | * Operating Systems (target): Any Linux system which [`jellyfin-ffmpeg`](https://github.com/jellyfin/jellyfin-ffmpeg) supports, which is currently just Debian and Ubuntu; Windows *might* work if you can get an SSH server running on it (see [Issue #17](https://github.com/joshuaboniface/rffmpeg/issues/17)). 144 | * Install Methods for Jellyfin: Native packages/installers/archives are recommended; a set of [Jellyfin Docker containers integrating `rffmpeg`](https://github.com/Shadowghost/jellyfin-rffmpeg) has been created by [@Shadowghost](https://github.com/Shadowghost). In addition to this special docker image you can use linuxserver's image with [this mod](https://github.com/linuxserver/docker-mods/tree/jellyfin-rffmpeg). 145 | * Install Methods for `rffmpeg`: Direct installation is recommended; a [Docker container to act as an ffmpeg transcode target](https://github.com/aleksasiriski/rffmpeg-worker) has been created by [@aleksasiriski](https://github.com/aleksasiriski) as well as [another](https://github.com/BasixKOR/rffmpeg-docker) by [@BasixKOR](https://github.com/BasixKOR). 146 | * OUTDATED Cloud: [HCloud Rffmpeg](https://github.com/aleksasiriski/hcloud-rffmpeg) script made to read rffmpeg database and spin up more transcode nodes in Hetzner Cloud. 147 | * Kubernetes: A short guide and example yaml files are available [here](https://github.com/aleksasiriski/rffmpeg-worker/tree/main/Kubernetes). 148 | 149 | ### Can `rffmpeg` mangle/alter FFMPEG arguments? 150 | 151 | Explicitly *no*. `rffmpeg` is not designed to interact with the arguments that the media server passes to `ffmpeg`/`ffprobe` at all, nor will it. 152 | 153 | This is an explicit design decision due to the massive complexity of FFmpeg. FFmpeg has a very large number of possible arguments, many of which are position-dependent or dependent on other arguments elsewhere in the chain. To implement argument mangling, we would need to be aware of every possible FFmpeg argument, exactly how each argument maps to each other argument, and be able to dynamically parse and update arguments based on this. As should hopefully be quite obvious, this is a massive undertaking and not something that I have any desire to implement or manage in such a (relatively) simple utility. 154 | 155 | This has a number of effects: 156 | 157 | * `rffmpeg` cannot adjust any `ffmpeg` options based on the host selected. 158 | * `rffmpeg` does not know whether hardware acceleration is turned on or not (see above caveats under [Hardware Acceleration](#hardware-acceleration)), or what type(s) of hardware acceleration are active. 159 | * `rffmpeg` does not know what media file(s) is is handling or where it's outputting files to, and cannot alter these paths. 160 | 161 | Thus it is imperative that you set up your entire system correctly for `rffmpeg` to work using a "least-common-denominator" approach as required. Please see the [SETUP guide](SETUP.md) for more information. 162 | 163 | ### Can `rffmpeg` do Wake-On-LAN or other similar options to turn on a transcode server? 164 | 165 | Explicitly *no*, though the linuxserver.io [docker mod](https://github.com/linuxserver/docker-mods/tree/jellyfin-rffmpeg) does support this. 166 | 167 | I've thought about implementing this more than once (most recently, in response to [Issue #21](https://github.com/joshuaboniface/rffmpeg/issues/21)) but ultimately I do not believe this is worth the complexity and delays it would introduce when spawning processes. That issue does provide one example of a workaround wrapper script that could accomplish this, but I do not plan for it to be a part of `rffmpeg` itself. 168 | 169 | ### I'm getting an error, help! 170 | 171 | First, run though the setup guide again and make sure that everything is set up correctly. 172 | 173 | If the problem persists, please check the [closed issues](https://github.com/joshuaboniface/rffmpeg/issues?q=is%3Aissue+sort%3Aupdated-desc+is%3Aclosed) and see if it's been reported before (if it's regarding Emby and you get an "error 127", see [Issue #10](https://github.com/joshuaboniface/rffmpeg/issues/10)). 174 | 175 | If it hasn't, you can [ask in our chat](https://matrix.to/#/#rffmpeg:matrix.org) or open a new issue. Ensure you: 176 | 177 | 1. Enable debug logging in `rffmpeg.yml` (`logging` -> `debug` to `true`) and re-run any failing or incorrect command(s) to obtain debug-level logs for analysis. 178 | 179 | 1. For issues, use a descriptive and useful title that quickly explains the problem. 180 | 181 | 1. Clearly explain (in the body of the issue or in your chat message) your setup, what is going wrong, and what you expect should be happening. Don't fret if English isn't your first language or anything like that, as long as you are trying to be clear that's what counts! 182 | 183 | 1. Include your `rffmpeg.log` and Jellyfin/Emby transcode logs as these are absolutely critical in determining what is going on. Use triple-backticks ("```") to enclose logs inline, both in chat and in issues. 184 | 185 | I will probably ask clarifying questions as required; please be prepared to run test commands, etc. as requested and paste the output. 186 | 187 | ### I found a bug/flaw and fixed it, or made a feature improvement; can I share it? 188 | 189 | Absolutely - I'm happy to take pull requests for just about any bugfix or improvement. There is one exception: please refer to the "Can `rffmpeg` mangle/alter FFMPEG arguments?" entry above; unless it's really good work with a very explicitly defined limitation, I probably don't want to go down that route, but I'm more than willing to look at what you've done and consider it on its merits. 190 | 191 | ### Can you help me set up my server? 192 | 193 | I'm always happy to help, though please ensure you try to follow the setup guide first - that's why I wrote it! Support can be found [on Matrix](https://matrix.to/#/#rffmpeg:matrix.org) or via email at `joshua@boniface.me`. Please note though that I may be unresponsive sometimes, though I will get back to you eventually I promise! Please don't open Issues here about setup problems; the Issue tracker is for bugs or feature requests instead. 194 | 195 | ### `rffmpeg-go` - forked project 196 | 197 | There's also a [fork of this script written in Go](https://github.com/aleksasiriski/rffmpeg-go) with semver tags and binaries available, as well as docker images for both the [script](https://github.com/aleksasiriski/rffmpeg-go/pkgs/container/rffmpeg-go) and [Jellyfin](https://github.com/aleksasiriski/jellyfin-rffmpeg). 198 | -------------------------------------------------------------------------------- /SETUP.md: -------------------------------------------------------------------------------- 1 | # Example Setup Guide 2 | 3 | This example setup is the one I use for `rffmpeg` with Jellyfin. It uses 2 servers: a media server running Jellyfin called `jellyfin1`, and a remote transcode server called `transcode1`. Both systems run Debian GNU/Linux, though the commands below should also work on Ubuntu. Throughout this guide I assume you are running as an unprivileged user with `sudo` privileges (i.e. in the group `sudo`). Basic knowledge of Linux CLI usage is assumed. Whenever a verbatim command is specified, it will be prefixed by the relevant host to run it on (either `jellyfin1` or `transcode1`) and then a `$` prompt indicator. Any command output is usually not shown unless it is relevant. 4 | 5 | This guide is provided as a basic starting point - there are myriad possible combinations of systems, and I try to keep `rffmpeg` quite flexible. Feel free to experiment. 6 | 7 | ## Set up the media server (`jellyfin1`) 8 | 9 | ### Basic Setup 10 | 11 | 1. Install Jellyfin (or similar FFMPEG-using media server) on your machine. This guide assumes you're using native `.deb` packages. 12 | 13 | 1. Make note of the Jellyfin service user's details, specifically the UID and any groups (and GIDs) it is a member of; this will be needed later on. 14 | 15 | ``` 16 | jellyfin1 $ id jellyfin 17 | uid=110(jellyfin) gid=117(jellyfin) groups=117(jellyfin) 18 | ``` 19 | 20 | 1. Make note of the Jellyfin data path; this will be needed later on. By default when using native OS packages, this is `/var/lib/jellyfin`. If you choose to move this directory, do so now (I personally use `/srv/jellyfin` but this guide will assume the default). 21 | 22 | To make life easier below, you can store this in a variable that I will reference frequently later: 23 | 24 | ``` 25 | jellyfin1 $ export jellyfin_data_path="/var/lib/jellyfin" 26 | jellyfin1 $ export jellyfin_cache_path="/var/lib/jellyfin" 27 | transcode1 $ export jellyfin_data_path="/var/lib/jellyfin" 28 | transcode1 $ export jellyfin_cache_path="/var/lib/jellyfin" 29 | ``` 30 | 31 | The important subdirectories for `rffmpeg`'s operation are: 32 | 33 | * `$jellyfin_cache_path/`: Used to store cached extracted data. 34 | * `$jellyfin_cache_path/transcodes/`: Used to store on-the-fly transcoding files, and configurable separately in Jellyfin but with `rffmpeg` I recommend leaving it at the default location under the cache path. 35 | * `$jellyfin_data_path/data/subtitles/`: Used to store on-the-fly extracted subtitles so that they can be reused later. 36 | * `$jellyfin_data_path/.ssh/`: This doesn't exist yet but will after the next step. 37 | 38 | **NOTE:** On Docker, these directories are different. The main data directory (our `jellyfin_data_path`) is `/config`, and the cache directory is separate at `/cache`. Both must be exported and mounted on targets for proper operation. 39 | 40 | **NOTE:** On Jellyfin 10.10.x and newer, temporary transient files were moved into the system temporary storage path (on Linux, usually `/tmp`). This will break rffmpeg for certain tasks that use these files, for instance trickplay generation. To restore the previous behaviour, ensure you set the `TMPDIR` environment variable for your Jellyfin service to a path under the data path above, for example `/var/lib/jellyfin/temp`, and create this directory with correct ownership and permissions. 41 | 42 | 1. Create an SSH keypair to use for `rffmpeg`'s login to the remote server. For ease of use with the following steps, use the Jellyfin service user (`jellyfin`) to create the keypair and store it under its home directory (the Jellyfin data path above). I use `rsa` here but you can substitute `ed25519` instead (avoid `dsa` and `ecdsa` for reasons I won't get into here). Once done, copy the public key to `authorized_keys` which will be used to authenticate the key later. 43 | 44 | ``` 45 | jellyfin1 $ sudo -u jellyfin mkdir ${jellyfin_data_path}/.ssh 46 | jellyfin1 $ sudo chmod 700 ${jellyfin_data_path}/.ssh 47 | jellyfin1 $ export keytype="rsa" 48 | jellyfin1 $ sudo -u jellyfin ssh-keygen -t ${keytype} -f ${jellyfin_data_path}/.ssh/id_${keytype} 49 | jellyfin1 $ sudo -u jellyfin cp -a ${jellyfin_data_path}/.ssh/id_${keytype}.pub ${jellyfin_data_path}/.ssh/authorized_keys 50 | ``` 51 | 52 | It is important that you do not alter the permissions under this `.ssh` directory or this can cause SSH to fail later. The SSH *must* occur as the `jellyfin` user for this to work. 53 | 54 | 1. Scan and save the SSH host key of the transcode server(s), to avoid a prompt later: 55 | 56 | ``` 57 | jellyfin1 $ ssh-keyscan transcode1 | sudo -u jellyfin tee -a ${jellyfin_data_path}/.ssh/known_hosts 58 | ``` 59 | 60 | * **NOTE:** Ensure you use the exact name here that you will use in `rffmpeg`. If this is an FQDN (e.g. `jellyfin1.mydomain.tld`) or an IP (e.g. `192.168.0.101`) instead of a short name, use that instead in this command, or repeat it for every possible option (it doesn't hurt). 61 | 62 | ### `rffmpeg` Setup 63 | 64 | 1. Install the required Python3 dependencies of `rffmpeg`: 65 | 66 | ``` 67 | jellyfin1 $ sudo apt -y install python3-yaml 68 | jellyfin1 $ sudo apt -y install python3-click 69 | jellyfin1 $ sudo apt -y install python3-subprocess 70 | ``` 71 | 72 | * **NOTE:** On some Ubuntu versions, `python3-subprocess` does not exist, and should instead be part of the Python standard library. Skip installing this package if it can't be found. 73 | 74 | 1. Clone the `rffmpeg` repository somewhere onto the system, then install the `rffmpeg` binary, make it executable, and prepare symlinks for the command names `ffmpeg` and `ffprobe` to it. I recommend storing these in `/usr/local/bin` for simplicity and so that they are present on the default `$PATH` for most users. 75 | 76 | ``` 77 | jellyfin1 $ git clone https://github.com/joshuaboniface/rffmpeg # or download the files manually 78 | jellyfin1 $ sudo cp rffmpeg/rffmpeg /usr/local/bin/rffmpeg 79 | jellyfin1 $ sudo chmod +x /usr/local/bin/rffmpeg 80 | jellyfin1 $ sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffmpeg 81 | jellyfin1 $ sudo ln -s /usr/local/bin/rffmpeg /usr/local/bin/ffprobe 82 | ``` 83 | 84 | 1. Optional: Create a directory for the `rffmpeg` configuration at `/etc/rffmpeg`, then copy `rffmpeg.yml.sample` to `/etc/rffmpeg/rffmpeg.yml` and edit it to suit your needs if required. Generally, if you're following this guide exactly, you will not need to install this file or adjust anything in in it. If you do require help though, I require debug logging to be enabled via the configuration file, so it's probably best to get this out of the way when installing `rffmpeg`: 85 | 86 | ``` 87 | jellyfin1 $ sudo mkdir -p /etc/rffmpeg 88 | jellyfin1 $ sudo cp rffmpeg/rffmpeg.yml.sample /etc/rffmpeg/rffmpeg.yml 89 | jellyfin1 $ sudo $EDITOR /etc/rffmpeg/rffmpeg.yml # if required 90 | ``` 91 | 92 | 1. Initialize `rffmpeg` (note the `sudo` command) and add at the target host to it. You can add other hosts now or later, and set weights of hosts, if required; for full details see the [main README](README.md) or run `rffmpeg --help` to view the CLI help menu. 93 | 94 | ``` 95 | jellyfin1 $ sudo rffmpeg init --yes 96 | jellyfin1 $ rffmpeg add --weight 1 transcode1 97 | ``` 98 | 99 | ### NFS Setup 100 | 101 | * **WARNING:** This guide assumes your hosts are on the same private local network. It is not recommended to run NFS over the Internet as it is unencrypted, and any rffmpeg connection will be very bandwidth-intensive. If you must have both systems in separate networks, consider other remote filesystems like SSHFS in such cases as these will offer greater privacy and robustness. 102 | 103 | 1. Install the NFS kernel server. We will use NFS to export the various required directories so the transcode machine can read from and write to them. 104 | 105 | ``` 106 | jellyfin1 $ sudo apt -y install nfs-kernel-server 107 | ``` 108 | 109 | 1. Create an `/etc/exports` configuration. What to put here can vary a lot, but here are some important points: 110 | 111 | * Always export the `${jellyfin_data_path}` in full. Advanced users might be able to export the required subdirectories individually, but I find this to be not worth the hassle. 112 | * Note the security options of NFS. It will limit mounts to the IP addresses specified. If your home network is secure, you can use the entire network, e.g. `192.168.0.0/24`, but I would recommend determining the exact IP of your transcode server(s) and use them explicitly, e.g. for this example `192.168.0.101` and `192.168.0.102`. 113 | * If your `transcodes` directory is not on a **native Linux filesystem** (i.e. external to Jellyfin, such as on a NAS exported by NFS, SMB, etc.), then you may experience delays of ~15-60s when playback starts. This is because NFS uses a file attribute cache that in most applications greatly increases performance, however for this usecase it causes a delay in Jellyfin seeing the `.ts` files. The solution for this is to reduce the NFS cache time by adding `sync` and `actimeo=1` to your NFS mount(s) (command or fstab), which will set the NFS file attribute cache to 1 second (reducing the NFS delay to ~1-2 seconds). This time can be further reduced to 0 by setting the `noac` option, but this is not normally recommended because it will negatively impact the performance other NFS applications. Verify that your mount added the `actimeo=1` parameter correctly by checking `mount` or `cat /proc/mounts`, which will show `sync,acregmin=1,acregmax=1,acdirmin=1,acdirmax=1` as parameters for your `transcodes` mount. 114 | * If your media is local to the Jellyfin server (and not already mountable on the transcode host(s) via a remote filesystems like NFS, Samba, CephFS, etc.), also add an export for it as well. 115 | 116 | An example `/etc/exports` file would look like this: 117 | 118 | ``` 119 | # /etc/exports: the access control list for filesystems which may be exported 120 | # to NFS clients. See exports(5). 121 | # 122 | # Other examples removed 123 | 124 | # jellyfin_data_path first host second host, etc. 125 | /var/lib/jellyfin 192.168.0.101/32(rw,sync,no_subtree_check,no_root_squash) 192.168.0.102/32(rw,sync,no_subtree_check,no_root_squash) 126 | # jellyfin_cache_path first host second host, etc. 127 | /var/cache/jellyfin 192.168.0.101/32(rw,sync,no_subtree_check,no_root_squash) 192.168.0.102/32(rw,sync,no_subtree_check,no_root_squash) 128 | # Local media path if required 129 | /srv/mymedia 192.168.0.101/32(rw,sync,no_subtree_check,no_root_squash) 192.168.0.102/32(rw,sync,no_subtree_check,no_root_squash) 130 | ``` 131 | 132 | 1. Reload the exports file and ensure the NFS server is properly exporting it now: 133 | 134 | ``` 135 | jellyfin1 $ sudo exportfs -arfv 136 | jellyfin1 $ sudo exportfs 137 | /var/lib/jellyfin 192.168.0.101/32 138 | /var/lib/jellyfin 192.168.0.102/32 139 | /var/cache/jellyfin 192.168.0.101/32 140 | /var/cache/jellyfin 192.168.0.102/32 141 | ``` 142 | 143 | ## Set up the transcode server (`transcode1`) 144 | 145 | 1. Install and configure anything you need for hardware transcoding, if applicable. For example GPU drivers if using a GPU for transcoding. 146 | 147 | * **NOTE:** Make sure you understand the caveats of using hardware transcoding with `rffmpeg` from [the main README](README.md#hardware-acceleration). 148 | 149 | 1. Install the correct `jellyfin-ffmpeg` package for your version of Jellyfin; check which version is installed on your `jellyfin1` system with `dpkg -l | grep jellyfin-ffmpeg`, then install that version on this host too; follow the same steps as you would to install Jellyfin on the media server, only don't install `jellyfin` (and `jellyfin-server`/`jellyfin-web`) itself, just the `jellyfin-ffmpeg` of the required version. 150 | 151 | ``` 152 | jellyfin1 $ dpkg -l | grep jellyfin-ffmpeg 153 | ii jellyfin-ffmpeg6 6.0.1-8-bookworm amd64 Tools for transcoding, streaming and playing of multimedia files 154 | transcode1 $ sudo apt -y install curl gnupg 155 | transcode1 $ curl -fsSL https://repo.jellyfin.org/ubuntu/jellyfin_team.gpg.key | sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/jellyfin.gpg 156 | transcode1 $ echo "deb [arch=$( dpkg --print-architecture )] https://repo.jellyfin.org/$( awk -F'=' '/^ID=/{ print $NF }' /etc/os-release ) $( awk -F'=' '/^VERSION_CODENAME=/{ print $NF }' /etc/os-release ) main" | sudo tee /etc/apt/sources.list.d/jellyfin.list 157 | transcode1 $ sudo apt update 158 | transcode1 $ sudo apt install jellyfin-ffmpeg6 159 | ``` 160 | 161 | 1. Install the NFS client utilities: 162 | 163 | ``` 164 | transcode1 $ sudo apt install -y nfs-common 165 | ``` 166 | 167 | 1. Create the Jellyfin service user and its default group; ensure you use the exact same UID and GID values you found in the beginning of the last section and adjust the example here to match yours: 168 | 169 | ``` 170 | transcode1 $ sudo groupadd --gid 117 jellyfin 171 | transcode1 $ sudo useradd --uid 110 --gid jellyfin --shell /bin/bash --no-create-home --home-dir ${jellyfin_data_path} jellyfin 172 | ``` 173 | 174 | * **NOTE:** For some hardware acceleration, you might need to add this user to additional groups. For example `--groups video,render`. 175 | 176 | * **NOTE:** The UID and GIDs here are dynamic; on the `jellyfin1` machine, they would have been selected automatically at install time with the next available ID in the range 100-199 (at least in Debian/Ubuntu). However, this means that the exact UID of your Jellyfin service user might not be available on your transcode server, depending on what packages are installed and in what order. If there is a conflict, you must adjust user IDs on one side or the other so that they match on both machines. You can use `sudo usermod` to change a user's ID if required. 177 | 178 | 1. Create the Jellyfin data directory at the same location as on the media server, and set it immutable so that it won't be written to if the NFS mount goes down: 179 | 180 | ``` 181 | transcode1 $ sudo mkdir ${jellyfin_data_path} 182 | transcode1 $ sudo chattr +i ${jellyfin_data_path} 183 | ``` 184 | 185 | * **NOTE:** Don't worry about permissions here; the mount will set those. 186 | 187 | 1. Create the NFS client mount. There are two main ways to do this: 188 | 189 | * Use the traditional `/etc/fstab` by adding a new entry like so, replacing the paths and hostname as required, and then mounting it: 190 | 191 | ``` 192 | transcode1 $ echo "jellyfin1:${jellyfin_data_path} ${jellyfin_data_path} nfs defaults,vers=3,sync" | sudo tee -a /etc/fstab 193 | transcode1 $ echo "jellyfin1:${jellyfin_cache_path} ${jellyfin_cache_path} nfs defaults,vers=3,sync" | sudo tee -a /etc/fstab 194 | transcode1 $ sudo mount ${jellyfin_data_path} 195 | transcode1 $ sudo mount ${jellyfin_cache_path} 196 | ``` 197 | 198 | * Use a SystemD `mount` unit, which is a newer way of doing mounts with SystemD. I personally prefer this method as I find it easier to set up automatically, but this is up to preference. An example based on mine would be: 199 | 200 | ``` 201 | transcode1 $ cat /etc/systemd/system/var-lib-jellyfin.mount 202 | [Unit] 203 | Description = NFS volume for Jellyfin data directory 204 | Requires = network-online.target 205 | After = network-online.target 206 | 207 | [Mount] 208 | type = nfs 209 | What = jellyfin1:/var/lib/jellyfin 210 | Where = /var/lib/jellyfin 211 | Options = _netdev,sync,vers=3 212 | 213 | [Install] 214 | WantedBy = remote-fs.target 215 | ``` 216 | 217 | ``` 218 | transcode1 $ cat /etc/systemd/system/var-cache-jellyfin.mount 219 | [Unit] 220 | Description = NFS volume for Jellyfin cache directory 221 | Requires = network-online.target 222 | After = network-online.target 223 | 224 | [Mount] 225 | type = nfs 226 | What = jellyfin1:/var/cache/jellyfin 227 | Where = /var/cache/jellyfin 228 | Options = _netdev,sync,vers=3 229 | 230 | [Install] 231 | WantedBy = remote-fs.target 232 | ``` 233 | 234 | Once the unit file is created, you can then reload the unit list and mount it: 235 | 236 | ``` 237 | transcode1 $ sudo systemctl daemon-reload 238 | transcode1 $ sudo systemctl enable --now var-lib-jellyfin.mount 239 | transcode1 $ sudo systemctl enable --now var-cache-jellyfin.mount 240 | ``` 241 | 242 | Note that mount units are fairly "new" and can be a bit finicky, be sure to read the SystemD documentation if you get stuck! Generally for new users, I'd recommend the `/etc/fstab` method instead. 243 | 244 | **NOTE:** Don't forget about `actimeo=1` here if you need it! 245 | 246 | 1. Mount your media directories in the **same location(s)** as on the media server. If you exported them via NFS from your media server, use the process above only for those directories instead. 247 | 248 | ## Test the setup 249 | 250 | 1. On the media server, verify that SSH as the Jellyfin service user is working as expected to each transcoding server: 251 | 252 | ``` 253 | jellyfin1 $ sudo -u jellyfin ssh -i ${jellyfin_data_path}/.ssh/id_rsa jellyfin@transcode1 uname -a 254 | Linux transcode1 [...] 255 | ``` 256 | 257 | 1. Validate that `rffmpeg` itself is working by calling its `ffmpeg` and `ffprobe` aliases with the `-version` option: 258 | 259 | ``` 260 | jellyfin1 $ sudo -u jellyfin /usr/local/bin/ffmpeg -version 261 | ffmpeg version 5.0.1-Jellyfin Copyright (c) 2000-2022 the FFmpeg developers 262 | built with gcc 10 (Debian 10.2.1-6) 263 | [...] 264 | jellyfin1 $ sudo -u jellyfin /usr/local/bin/ffprobe -version 265 | ffprobe version 5.0.1-Jellyfin Copyright (c) 2007-2022 the FFmpeg developers 266 | built with gcc 10 (Debian 10.2.1-6) 267 | [...] 268 | ``` 269 | 270 | As long as these steps work, all further steps should as well. If one of these *doesn't* work, double-check all previous steps and confirm that everything is set up right. 271 | 272 | ## Configure Jellyfin to use `rffmpeg` 273 | 274 | **NOTE**: With Jellyfin 10.8.13 and newer, the ability to configure the `ffmpeg` path has been removed from the WebUI due to major security concerns. You must follow this method to change it. 275 | 276 | 1. On the `jellyfin1` system, edit `/etc/default/jellyfin`: 277 | 278 | ``` 279 | jellyfin1 $ sudo $EDITOR /etc/default/jellyfin 280 | ``` 281 | 282 | 1. Change the value of `JELLYFIN_FFMPEG_OPT` to be `--ffmpeg=/usr/local/bin/ffmpeg` (the `rffmpeg` alias name `ffmpeg` in whatever path you installed `rffmpeg` to). 283 | 284 | 1. On Jellyfin 10.10.x or newer, add `TMPDIR=$jellyfin_cache_path/temp`, for instance `TMPDIR=/var/cache/jellyfin/temp`, to ensure this is properly synchronized over the network. 285 | 286 | 1. Save the file and restart Jellyfin: 287 | 288 | ``` 289 | jellyfin1 $ sudo systemctl restart jellyfin 290 | ``` 291 | 292 | If you wish to use hardware transcoding, you must also enable it in Jellyfin's WebUI: 293 | 294 | 1. Navigate to Hamburger Menu -> Administration -> Dashboard, navigate to Playback. 295 | 296 | 1. Configure any hardware acceleration you require and have set up on the remote server(s). 297 | 298 | 1. Save the settings. 299 | 300 | Now, run `rffmpeg log -f` on the `jellyfin1` machine and try to play a video that requires transcoding. You should see `rffmpeg` spawn a process on the `jellyfin1` machine, which then begins running the `ffmpeg` process on the `transcode1` machine, writing data to the configured paths, and playback should begin normally. If anything doesn't work, double-check all previous steps and confirm that everything is set up right. 301 | 302 | ## NOTE for NVEnv/NVDec Hardware Acceleration 303 | 304 | If you are using NVEnv/NVDec, you will need to symlink the `.nv` folder inside the Jellyfin user's homedir (i.e. `/var/lib/jellyfin/.nv`) to somewhere outside of the NFS volume on both the Jellyfin and transcoding hosts. For example: 305 | 306 | ``` 307 | jellyfin1 $ sudo mv /var/lib/jellyfin/.nv /var/lib/nvidia-cache # or "sudo mkdir /var/lib/nvidia-cache" and "sudo chown jellyfin /var/lib/nvidia-cache" if it does not yet exist 308 | jellyfin1 $ sudo ln -s /var/lib/nvidia-cache /var/lib/jellyfin/.nv 309 | transcode1 $ sudo mkdir /var/lib/nvidia-cache 310 | transcode1 $ sudo chown jellyfin /var/lib/nvidia-cache 311 | transcode1 $ ls -alh /var/lib/jellyfin 312 | [...] 313 | lrwxrwxrwx 1 root root 17 Jun 11 15:51 .nv -> /var/lib/nvidia-cache 314 | [...] 315 | ``` 316 | 317 | Be sure to adjust these paths to match your Jellyfin setup. The name of the target doesn't matter too much, as long as `.nv` inside the homedir is symlinked to it and it is owned by the `jellyfin` service user. 318 | 319 | This is because some functions of FFMpeg's NVEnc/NVDec stack - specifically the `scale_cuda` and `tonemap_cuda` filters - leverage this directory to cache their JIT codes, and this can result in very slow startup times and very poor transcoding performance due to NFS locking issues. See https://developer.nvidia.com/blog/cuda-pro-tip-understand-fat-binaries-jit-caching/ for further information. 320 | 321 | Alternatively, based on that link, you might also be able to experiment with the environment variables that control the JIT caching to move it somewhere else, but this has not been tested by the author. Feel free to experiment and find the best solution for your setup. 322 | -------------------------------------------------------------------------------- /rffmpeg: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # rffmpeg.py - Remote FFMPEG transcoding wrapper 4 | # 5 | # Copyright (C) 2019-2022 Joshua M. Boniface 6 | # and Contributors. 7 | # 8 | # This program is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This program is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this program. If not, see . 20 | # 21 | ############################################################################### 22 | 23 | import click 24 | import logging 25 | import os 26 | import signal 27 | import sys 28 | import shlex 29 | import yaml 30 | 31 | from contextlib import contextmanager 32 | from grp import getgrnam 33 | from pathlib import Path 34 | from pwd import getpwnam 35 | from re import search 36 | from sqlite3 import connect as sqlite_connect 37 | from subprocess import run, PIPE 38 | from time import sleep 39 | from datetime import datetime 40 | 41 | 42 | # Set up the logger 43 | log = logging.getLogger("rffmpeg") 44 | 45 | 46 | # Use Postgresql if specified, otherwise use SQLite 47 | DB_TYPE = "SQLITE" 48 | SQL_VAR_SIGN = "?" 49 | SQL_PRIMARY_KEY="INTEGER" 50 | SQL_DATE_TIME="DATETIME" 51 | POSTGRES_DB = os.environ.get("RFFMPEG_POSTGRES_DB", "rffmpeg") 52 | POSTGRES_USER = os.environ.get("RFFMPEG_POSTGRES_USER") 53 | POSTGRES_PASS = os.environ.get("RFFMPEG_POSTGRES_PASS", "") 54 | POSTGRES_PORT = os.environ.get("RFFMPEG_POSTGRES_PORT", "5432") 55 | POSTGRES_HOST = os.environ.get("RFFMPEG_POSTGRES_HOST", "localhost") 56 | 57 | if POSTGRES_USER != None: 58 | DB_TYPE = "POSTGRES" 59 | SQL_VAR_SIGN = "%s" 60 | SQL_PRIMARY_KEY="SERIAL" 61 | SQL_DATE_TIME="TIMESTAMP" 62 | POSTGRES_CREDENTIALS = { 63 | "dbname": POSTGRES_DB, 64 | "user": POSTGRES_USER, 65 | "password": POSTGRES_PASS, 66 | "port": int(POSTGRES_PORT), 67 | "host": POSTGRES_HOST, 68 | } 69 | from psycopg2 import connect as postgres_connect 70 | from psycopg2 import DatabaseError as postgres_error 71 | 72 | 73 | # Open a database connection (context manager) 74 | @contextmanager 75 | def dbconn(config, init = False): 76 | """ 77 | Open a database connection. 78 | """ 79 | if DB_TYPE == "SQLITE": 80 | if not init and not Path(config["db_path"]).is_file(): 81 | fail(f"Failed to find database '{config['db_path']}' - did you forget to run 'rffmpeg init' or add all env vars for Postgresql?") 82 | log.debug("Using SQLite as database.") 83 | conn = sqlite_connect(config["db_path"]) 84 | conn.execute("PRAGMA foreign_keys = 1") 85 | cur = conn.cursor() 86 | yield cur 87 | conn.commit() 88 | conn.close() 89 | log.debug("SQLite connection closed.") 90 | elif DB_TYPE == "POSTGRES": 91 | conn = None 92 | try: 93 | log.debug("Using Postgresql as database. Connecting...") 94 | conn = postgres_connect(**POSTGRES_CREDENTIALS) 95 | cur = conn.cursor() 96 | cur.execute("SELECT version()") 97 | db_version = cur.fetchone() 98 | log.debug(f"Connected to Postgresql version {db_version}") 99 | yield cur 100 | conn.commit() 101 | except (Exception, postgres_error) as error: 102 | print(error) 103 | log.error(error) 104 | finally: 105 | if conn is not None: 106 | conn.close() 107 | log.debug("Postgresql connection closed.") 108 | 109 | 110 | def fail(msg): 111 | """ 112 | Output an error message and terminate. 113 | """ 114 | log.error(msg) 115 | exit(1) 116 | 117 | 118 | def load_config(): 119 | """ 120 | Parse the YAML configuration file (either /etc/rffmpeg/rffmpeg.yml or specified by the envvar 121 | RFFMPEG_CONFIG) and return a standard dictionary of configuration values. 122 | """ 123 | 124 | default_config_file = "/etc/rffmpeg/rffmpeg.yml" 125 | config_file = os.environ.get("RFFMPEG_CONFIG", default_config_file) 126 | 127 | if not Path(config_file).is_file(): 128 | log.info(f"No config found in {config_file}. Using default settings.") 129 | o_config = { 130 | "rffmpeg": {"logging": {}, "directories": {}, "remote": {}, "commands": {}} 131 | } 132 | else: 133 | with open(config_file, "r") as cfgfh: 134 | try: 135 | o_config = yaml.load(cfgfh, Loader=yaml.SafeLoader) 136 | except Exception as e: 137 | fail(f"Failed to parse configuration file: {e}") 138 | 139 | config = dict() 140 | 141 | # Parse the base group ("rffmpeg") 142 | config_base = o_config.get("rffmpeg", dict()) 143 | if not config_base: 144 | fail("Failed to parse configuration file top level key 'rffmpeg'.") 145 | 146 | # Parse the logging group ("rffmpeg" -> "logging") 147 | config_logging = config_base.get("logging", dict()) 148 | if config_logging is None: 149 | config_logging = dict() 150 | 151 | # Parse the directories group ("rffmpeg" -> "directories") 152 | config_directories = config_base.get("directories", dict()) 153 | if config_directories is None: 154 | config_directories = dict() 155 | 156 | # Parse the remote group ("rffmpeg" -> "remote") 157 | config_remote = config_base.get("remote", dict()) 158 | if config_remote is None: 159 | config_remote = dict() 160 | 161 | # Parse the commands group ("rffmpeg" -> "commands") 162 | config_commands = config_base.get("commands", dict()) 163 | if config_commands is None: 164 | config_commands = dict() 165 | 166 | # Parse the keys from the logging group 167 | config["log_to_file"] = config_logging.get("log_to_file", True) 168 | config["logfile"] = config_logging.get("logfile", "/var/log/jellyfin/rffmpeg.log") 169 | config["datedlogfiles"] = config_logging.get("datedlogfiles", False) 170 | if config["datedlogfiles"] is True: 171 | config["datedlogdir"] = config_logging.get("datedlogdir", "/var/log/jellyfin") 172 | config["logfile"] = ( 173 | config["datedlogdir"] 174 | + "/" 175 | + datetime.today().strftime("%Y%m%d") 176 | + "_rffmpeg.log" 177 | ) 178 | config["logdebug"] = config_logging.get("debug", False) 179 | 180 | # Parse the keys from the state group 181 | config["state_dir"] = config_directories.get("state", "/var/lib/rffmpeg") 182 | config["persist_dir"] = config_directories.get("persist", "/run/shm") 183 | config["dir_owner"] = config_directories.get("owner", "jellyfin") 184 | config["dir_group"] = config_directories.get("group", "sudo") 185 | 186 | # Parse the keys from the remote group 187 | config["remote_user"] = config_remote.get("user", "") 188 | config["remote_args"] = config_remote.get( 189 | "args", ["-i", "/var/lib/jellyfin/.ssh/id_rsa"] 190 | ) 191 | if config["remote_args"] is None: 192 | config["remote_args"] = [] 193 | config["persist_time"] = config_remote.get("persist", 300) 194 | 195 | # Parse the keys from the commands group 196 | config["ssh_command"] = config_commands.get("ssh", "/usr/bin/ssh") 197 | config["pre_commands"] = config_commands.get("pre", []) 198 | if config["pre_commands"] is None: 199 | config["pre_commands"] = [] 200 | config["ffmpeg_command"] = config_commands.get( 201 | "ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg" 202 | ) 203 | config["ffprobe_command"] = config_commands.get( 204 | "ffprobe", "/usr/lib/jellyfin-ffmpeg/ffprobe" 205 | ) 206 | config["fallback_ffmpeg_command"] = config_commands.get( 207 | "fallback_ffmpeg", "/usr/lib/jellyfin-ffmpeg/ffmpeg" 208 | ) 209 | config["fallback_ffprobe_command"] = config_commands.get( 210 | "fallback_ffprobe", "/usr/lib/jellyfin-ffmpeg/ffprobe" 211 | ) 212 | 213 | # Set the database path 214 | config["db_path"] = config["state_dir"] + "/rffmpeg.db" 215 | 216 | 217 | # Set a list of special flags that cause different behaviour 218 | config["special_flags"] = [ 219 | "-version", 220 | "-encoders", 221 | "-decoders", 222 | "-hwaccels", 223 | "-filters", 224 | "-h", 225 | "-muxers", 226 | "-fp_format", 227 | ] + config_commands.get("special_flags", []) 228 | 229 | # Set the current PID of this process 230 | config["current_pid"] = os.getpid() 231 | 232 | return config 233 | 234 | 235 | def cleanup(signum="", frame=""): 236 | """ 237 | Clean up this processes stored transient data. 238 | """ 239 | global config 240 | 241 | log.debug(f"Cleaning up after signal {signum} PID {config['current_pid']}") 242 | 243 | with dbconn(config) as cur: 244 | cur.execute( 245 | f"DELETE FROM states WHERE process_id = {SQL_VAR_SIGN}", 246 | (config["current_pid"],), 247 | ) 248 | cur.execute( 249 | f"DELETE FROM processes WHERE process_id = {SQL_VAR_SIGN}", 250 | (config["current_pid"],), 251 | ) 252 | 253 | 254 | def generate_ssh_command(config, target_hostname): 255 | """ 256 | Generate an SSH command for use. 257 | """ 258 | ssh_command = list() 259 | 260 | # Add SSH component 261 | ssh_command.append(config["ssh_command"]) 262 | ssh_command.append("-q") 263 | ssh_command.append("-t") 264 | 265 | # Set our connection details 266 | ssh_command.extend(["-o", "ConnectTimeout=1"]) 267 | ssh_command.extend(["-o", "ConnectionAttempts=1"]) 268 | ssh_command.extend(["-o", "StrictHostKeyChecking=no"]) 269 | ssh_command.extend(["-o", "UserKnownHostsFile=/dev/null"]) 270 | 271 | # Use SSH control persistence to keep sessions alive for subsequent commands 272 | if config["persist_time"] > 0: 273 | ssh_command.extend(["-o", "ControlMaster=auto"]) 274 | ssh_command.extend( 275 | ["-o", f"ControlPath={config['persist_dir']}/ssh-%r@%h:%p"] 276 | ) 277 | ssh_command.extend(["-o", f"ControlPersist={config['persist_time']}"]) 278 | 279 | # Add the remote config args 280 | for arg in config["remote_args"]: 281 | if arg: 282 | ssh_command.append(arg) 283 | 284 | # Add user+host string 285 | ssh_command.append(f"{config['remote_user']}@{target_hostname}") 286 | 287 | return ssh_command 288 | 289 | 290 | def run_command(command, stdin, stdout, stderr): 291 | """ 292 | Execute the command using subprocess. 293 | """ 294 | p = run( 295 | command, 296 | shell=False, 297 | bufsize=0, 298 | universal_newlines=True, 299 | stdin=stdin, 300 | stdout=stdout, 301 | stderr=stderr, 302 | ) 303 | return p 304 | 305 | 306 | def get_target_host(config): 307 | """ 308 | Determine an optimal target host via data on currently active processes and states. 309 | """ 310 | log.debug("Determining optimal target host") 311 | # Select all hosts and active processes from the database 312 | with dbconn(config) as cur: 313 | cur.execute("SELECT * FROM hosts") 314 | hosts = cur.fetchall() 315 | cur.execute("SELECT * FROM processes") 316 | processes = cur.fetchall() 317 | 318 | # Generate a mapping dictionary of hosts and processes 319 | host_mappings = dict() 320 | for host in hosts: 321 | hid, servername, hostname, weight, created = host 322 | 323 | # Get the latest state 324 | with dbconn(config) as cur: 325 | cur.execute( 326 | f"SELECT * FROM states WHERE host_id = {SQL_VAR_SIGN} ORDER BY id DESC", 327 | (hid,), 328 | ) 329 | current_state = cur.fetchone() 330 | 331 | if not current_state: 332 | current_state = "idle" 333 | marking_pid = "N/A" 334 | else: 335 | sid, host_id, process_id, state = current_state 336 | current_state = state 337 | marking_pid = process_id 338 | 339 | # Create the mappings entry 340 | host_mappings[hid] = { 341 | "hostname": hostname, 342 | "weight": weight, 343 | "servername": servername, 344 | "current_state": current_state, 345 | "marking_pid": marking_pid, 346 | "commands": [proc[2] for proc in processes if proc[1] == hid], 347 | } 348 | 349 | lowest_count = 9999 350 | target_hid = None 351 | target_hostname = None 352 | target_servername = None 353 | # For each host in the mapping, let's determine if it is suitable 354 | for hid, host in host_mappings.items(): 355 | log.debug(f"Trying host ID {hid} '{host['hostname']}'") 356 | # If it's marked as bad, continue 357 | if host["current_state"] == "bad": 358 | log.debug(f"Host previously marked bad by PID {host['marking_pid']}") 359 | continue 360 | 361 | # Try to connect to the host and run a very quick command to determine if it is workable 362 | if host["hostname"] not in ["localhost", "127.0.0.1"]: 363 | log.debug("Running SSH test") 364 | test_ssh_command = generate_ssh_command(config, host["hostname"]) 365 | test_ssh_command.remove("-q") 366 | test_ssh_command = [arg.replace('@', '', 1) if arg.startswith('@') else arg for arg in test_ssh_command] 367 | test_ffmpeg_command = [config["ffmpeg_command"], "-version"] 368 | ret = run_command(test_ssh_command + test_ffmpeg_command, PIPE, PIPE, PIPE) 369 | if ret.returncode != 0: 370 | # Mark the host as bad 371 | log.warning(f"Marking host {host['hostname']} ({host['servername']}) as bad due to retcode {ret.returncode}") 372 | log.debug(f"SSH test command was: {' '.join(test_ssh_command + test_ffmpeg_command)}") 373 | log.debug(f"SSH test command stdout: {ret.stdout}") 374 | log.debug(f"SSH test command stderr: {ret.stderr}") 375 | with dbconn(config) as cur: 376 | cur.execute( 377 | f"INSERT INTO states (host_id, process_id, state) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})", 378 | (hid, config["current_pid"], "bad"), 379 | ) 380 | continue 381 | log.debug(f"SSH test succeeded with retcode {ret.returncode}") 382 | 383 | # If the host state is idle, we can use it immediately 384 | if host["current_state"] == "idle": 385 | target_hid = hid 386 | target_hostname = host["hostname"] 387 | target_servername = host["servername"] 388 | log.debug("Selecting host as idle") 389 | break 390 | 391 | # Get the modified count of the host 392 | raw_proc_count = len(host["commands"]) 393 | weighted_proc_count = raw_proc_count // host["weight"] 394 | 395 | # If this host is currently the least used, provisionally set it as the target 396 | if weighted_proc_count < lowest_count: 397 | lowest_count = weighted_proc_count 398 | target_hid = hid 399 | target_hostname = host["hostname"] 400 | target_servername = host["servername"] 401 | log.debug(f"Selecting host as current lowest proc count (raw count: {raw_proc_count}, weighted count: {weighted_proc_count})") 402 | 403 | log.debug(f"Found optimal host ID {target_hid} '{target_hostname}' ({target_servername})") 404 | return target_hid, target_hostname, target_servername 405 | 406 | 407 | def run_local_command(config, target_hid, command, command_args, stderr_as_stdout = False, mapped_cmd = None): 408 | """ 409 | Run command locally, either because "localhost" is the target host, or because no good target 410 | host was found by get_target_host(). 411 | """ 412 | rffmpeg_command = [mapped_cmd or command] 413 | 414 | # Prepare our default stdin/stdout/stderr 415 | stdin = sys.stdin 416 | stderr = sys.stderr 417 | 418 | if stderr_as_stdout: 419 | stdout = sys.stderr 420 | else: 421 | stdout = sys.stdout 422 | 423 | # Append all the passed arguments directly 424 | for arg in command_args: 425 | rffmpeg_command.append(f"{arg}") 426 | 427 | log.info("Running command on host 'localhost'") 428 | log.debug(f"Local command: {' '.join(rffmpeg_command)}") 429 | 430 | if target_hid is None: 431 | target_hid = 0 432 | log.debug(f"Could not find any host, using fallback 'localhost'") 433 | 434 | with dbconn(config) as cur: 435 | cur.execute( 436 | f"INSERT INTO processes (host_id, process_id, cmd) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})", 437 | (target_hid, config["current_pid"], command + ' ' + ' '.join(command_args)), 438 | ) 439 | cur.execute( 440 | f"INSERT INTO states (host_id, process_id, state) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})", 441 | (target_hid, config["current_pid"], "active"), 442 | ) 443 | 444 | return run_command(rffmpeg_command, stdin, stdout, stderr) 445 | 446 | 447 | def run_local_ffmpeg(config, target_hid, ffmpeg_args): 448 | """ 449 | Run ffmpeg locally, either because "localhost" is the target host, or because no good target 450 | host was found by get_target_host(). 451 | """ 452 | if "ffprobe" in cmd_name: 453 | return run_local_command(config, target_hid, cmd_name, ffmpeg_args, mapped_cmd=config["fallback_ffprobe_command"]) 454 | else: 455 | return run_local_command(config, target_hid, cmd_name, ffmpeg_args, stderr_as_stdout=not any(item in config["special_flags"] for item in ffmpeg_args), mapped_cmd=config["fallback_ffmpeg_command"]) 456 | 457 | 458 | def run_remote_command( 459 | config, target_hid, target_hostname, target_servername, command, command_args, stderr_as_stdout = False, mapped_cmd = None, pre_commands = [] 460 | ): 461 | """ 462 | Run command against the remote target_hostname. 463 | """ 464 | rffmpeg_ssh_command = generate_ssh_command(config, target_hostname) 465 | rffmpeg_ssh_command = [arg.replace('@', '', 1) if arg.startswith('@') else arg for arg in rffmpeg_ssh_command] 466 | 467 | rffmpeg_command = list() 468 | 469 | # Add any pre commands 470 | for cmd in pre_commands: 471 | if cmd: 472 | rffmpeg_command.append(cmd) 473 | 474 | rffmpeg_command.append(mapped_cmd or command) 475 | 476 | # Prepare our default stdin/stderr 477 | stdin = sys.stdin 478 | stderr = sys.stderr 479 | 480 | if stderr_as_stdout: 481 | stdout = sys.stderr 482 | else: 483 | stdout = sys.stdout 484 | 485 | rffmpeg_command.extend(map(shlex.quote, command_args)) 486 | 487 | log.info(f"Running command on host '{target_hostname}' ({target_servername})") 488 | log.debug(f"Remote command: {' '.join(rffmpeg_ssh_command + rffmpeg_command)}") 489 | 490 | with dbconn(config) as cur: 491 | cur.execute( 492 | f"INSERT INTO processes (host_id, process_id, cmd) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})", 493 | (target_hid, config["current_pid"], command + ' ' + ' '.join(command_args)), 494 | ) 495 | cur.execute( 496 | f"INSERT INTO states (host_id, process_id, state) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})", 497 | (target_hid, config["current_pid"], "active"), 498 | ) 499 | 500 | return run_command( 501 | rffmpeg_ssh_command + rffmpeg_command, stdin, stdout, stderr 502 | ) 503 | 504 | 505 | def run_remote_ffmpeg( 506 | config, target_hid, target_hostname, target_servername, ffmpeg_args 507 | ): 508 | """ 509 | Run ffmpeg against the remote target_hostname. 510 | """ 511 | if "ffprobe" in cmd_name: 512 | # If we're in ffprobe mode use that command and sys.stdout as stdout 513 | return run_remote_command(config, target_hid, target_hostname, target_servername, cmd_name, ffmpeg_args, mapped_cmd=config["ffprobe_command"], pre_commands=config["pre_commands"]) 514 | else: 515 | # Otherwise, we use stderr as stdout 516 | return run_remote_command(config, target_hid, target_hostname, target_servername, cmd_name, ffmpeg_args, stderr_as_stdout=not any(item in config["special_flags"] for item in ffmpeg_args), mapped_cmd=config["ffmpeg_command"], pre_commands=config["pre_commands"]) 517 | 518 | 519 | def setup_logging(config): 520 | """ 521 | Set up logging. 522 | """ 523 | if config["logdebug"] is True: 524 | logging_level = logging.DEBUG 525 | else: 526 | logging_level = logging.INFO 527 | 528 | if config["log_to_file"]: 529 | logging.basicConfig( 530 | filename=config["logfile"], 531 | level=logging_level, 532 | format="%(asctime)s - %(name)s[%(process)s] - %(levelname)s - %(message)s", 533 | ) 534 | else: 535 | logging.basicConfig( 536 | level=logging_level, 537 | format="%(asctime)s - %(name)s[%(process)s] - %(levelname)s - %(message)s", 538 | ) 539 | 540 | 541 | def hook_signals(): 542 | signal.signal(signal.SIGTERM, cleanup) 543 | signal.signal(signal.SIGINT, cleanup) 544 | signal.signal(signal.SIGQUIT, cleanup) 545 | signal.signal(signal.SIGHUP, cleanup) 546 | 547 | 548 | def run_ffmpeg(config, ffmpeg_args): 549 | """ 550 | Entrypoint for an ffmpeg/ffprobe aliased process. 551 | """ 552 | hook_signals() 553 | 554 | setup_logging(config) 555 | 556 | log.info(f"Starting rffmpeg as {cmd_name} with args: {' '.join(ffmpeg_args)}") 557 | 558 | target_hid, target_hostname, target_servername = get_target_host(config) 559 | 560 | try: 561 | returncode = 200 562 | if not target_hostname or target_hostname == "localhost": 563 | ret = run_local_ffmpeg(config, None, ffmpeg_args) 564 | returncode = ret.returncode 565 | else: 566 | ret = run_remote_ffmpeg( 567 | config, target_hid, target_hostname, target_servername, ffmpeg_args 568 | ) 569 | returncode = ret.returncode 570 | finally: 571 | cleanup() 572 | if returncode == 0: 573 | log.info(f"Finished rffmpeg with return code {ret.returncode}") 574 | else: 575 | log.error(f"Finished rffmpeg with return code {ret.returncode}") 576 | exit(returncode) 577 | 578 | 579 | def run_control(config): 580 | """ 581 | Entrypoint for the Click CLI for managing the rffmpeg system. 582 | """ 583 | CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"], max_content_width=120) 584 | 585 | @click.group(context_settings=CONTEXT_SETTINGS) 586 | def rffmpeg_click(): 587 | """ 588 | rffmpeg CLI interface 589 | """ 590 | if ( 591 | not Path(config["state_dir"]).is_dir() 592 | or not Path(config["db_path"]).is_file() 593 | ): 594 | return 595 | 596 | # List all DB migrations here 597 | did_alter_0001AddServername = False 598 | # Check conditions for migrations 599 | with dbconn(config) as cur: 600 | # Migration for new servername (PR #36) 601 | cur.execute( 602 | "SELECT COUNT(*) AS CNTREC FROM pragma_table_info('hosts') WHERE name='servername'" 603 | ) 604 | if cur.fetchone()[0] == 0: 605 | cur.execute( 606 | "ALTER TABLE hosts ADD servername TEXT NOT NULL DEFAULT 'invalid'" 607 | ) 608 | did_alter_0001AddServername = True 609 | # Migration for new servername (PR #36) 610 | if did_alter_0001AddServername: 611 | with dbconn(config) as cur: 612 | cur.execute("SELECT * FROM hosts") 613 | for host in cur.fetchall(): 614 | hid, servername, hostname, weight, created = host 615 | if servername == "invalid": 616 | cur.execute( 617 | f"UPDATE hosts SET servername = {SQL_VAR_SIGN} WHERE hostname = {SQL_VAR_SIGN}", 618 | (hostname, hostname), 619 | ) 620 | 621 | @click.command(name="init", short_help="Initialize the system.") 622 | @click.option( 623 | "--no-root", 624 | "no_root_flag", 625 | is_flag=True, 626 | default=False, 627 | help="Bypass root check and permission adjustments; if destinations aren't writable, init will fail.", 628 | ) 629 | @click.option( 630 | "-y", 631 | "--yes", 632 | "confirm_flag", 633 | is_flag=True, 634 | default=False, 635 | help="Confirm initialization.", 636 | ) 637 | def rffmpeg_click_init(no_root_flag, confirm_flag): 638 | """ 639 | Initialize the rffmpeg system and database; this will erase all hosts and current state. 640 | 641 | By default this command should be run as "sudo" before any attempts to use rffmpeg. If you 642 | do not require root permissions to write to your configured state and database paths, you 643 | may pass the "--no-root" option. 644 | """ 645 | if not no_root_flag and os.getuid() != 0: 646 | click.echo("Error: This command requires root privileges.") 647 | exit(1) 648 | 649 | if not confirm_flag: 650 | try: 651 | click.confirm( 652 | "Are you sure you want to (re)initialize the database", 653 | prompt_suffix="? ", 654 | abort=True, 655 | ) 656 | except Exception: 657 | fail("Aborting due to failed confirmation.") 658 | 659 | click.echo("Initializing database") 660 | 661 | if not Path(config["state_dir"]).is_dir(): 662 | try: 663 | os.makedirs(config["state_dir"]) 664 | except OSError as e: 665 | fail(f"Failed to create state directory '{config['state_dir']}': {e}") 666 | 667 | try: 668 | with dbconn(config, True) as cur: 669 | cur.execute("DROP TABLE IF EXISTS hosts") 670 | cur.execute("DROP TABLE IF EXISTS processes") 671 | cur.execute("DROP TABLE IF EXISTS states") 672 | cur.execute(f"CREATE TABLE hosts (id {SQL_PRIMARY_KEY} PRIMARY KEY, servername TEXT NOT NULL UNIQUE, hostname TEXT NOT NULL, weight INTEGER DEFAULT 1, created {SQL_DATE_TIME} NOT NULL)") 673 | cur.execute(f"CREATE TABLE processes (id {SQL_PRIMARY_KEY} PRIMARY KEY, host_id INTEGER, process_id INTEGER, cmd TEXT)") 674 | cur.execute(f"CREATE TABLE states (id {SQL_PRIMARY_KEY} PRIMARY KEY, host_id INTEGER, process_id INTEGER, state TEXT)") 675 | except Exception as e: 676 | fail(f"Failed to create database: {e}") 677 | 678 | if not no_root_flag: 679 | os.chown( 680 | config["state_dir"], 681 | getpwnam(config["dir_owner"]).pw_uid, 682 | getgrnam(config["dir_group"]).gr_gid, 683 | ) 684 | os.chmod(config["state_dir"], 0o770) 685 | 686 | if DB_TYPE == "SQLITE": 687 | os.chown( 688 | config["db_path"], 689 | getpwnam(config["dir_owner"]).pw_uid, 690 | getgrnam(config["dir_group"]).gr_gid, 691 | ) 692 | os.chmod(config["db_path"], 0o660) 693 | 694 | rffmpeg_click.add_command(rffmpeg_click_init) 695 | 696 | @click.command(name="status", short_help="Show hosts and status.") 697 | def rffmpeg_click_status(): 698 | """ 699 | Show the current status of all rffmpeg target hosts and active processes. 700 | """ 701 | with dbconn(config) as cur: 702 | cur.execute("SELECT * FROM hosts") 703 | hosts = cur.fetchall() 704 | cur.execute("SELECT * FROM processes") 705 | processes = cur.fetchall() 706 | cur.execute("SELECT * FROM states") 707 | states = cur.fetchall() 708 | 709 | # Determine if there are any fallback processes running 710 | fallback_processes = list() 711 | for process in processes: 712 | pid, host_id, process_id, cmd = process 713 | if host_id == 0: 714 | fallback_processes.append(process) 715 | 716 | # Generate a mapping dictionary of hosts and processes 717 | host_mappings = dict() 718 | 719 | if len(fallback_processes) > 0: 720 | host_mappings[0] = { 721 | "hostname": "localhost (fallback)", 722 | "servername": "localhost (fallback)", 723 | "weight": 0, 724 | "current_state": "fallback", 725 | "commands": fallback_processes, 726 | } 727 | 728 | for host in hosts: 729 | hid, servername, hostname, weight, created = host 730 | 731 | # Get the latest state 732 | with dbconn(config) as cur: 733 | cur.execute( 734 | f"SELECT * FROM states WHERE host_id = {SQL_VAR_SIGN} ORDER BY id DESC", 735 | (hid,), 736 | ) 737 | current_state = cur.fetchone() 738 | 739 | if not current_state: 740 | current_state = "idle" 741 | else: 742 | sid, host_id, process_id, state = current_state 743 | current_state = state 744 | 745 | # Create the mappings entry 746 | host_mappings[hid] = { 747 | "hostname": hostname, 748 | "servername": servername, 749 | "weight": weight, 750 | "current_state": current_state, 751 | "commands": [proc for proc in processes if proc[1] == hid], 752 | } 753 | 754 | hostname_length = 9 755 | servername_length = 11 756 | hid_length = 3 757 | weight_length = 7 758 | state_length = 6 759 | for hid, host in host_mappings.items(): 760 | if len(host["hostname"]) + 1 > hostname_length: 761 | hostname_length = len(host["hostname"]) + 1 762 | if len(host["servername"]) + 1 > servername_length: 763 | servername_length = len(host["servername"]) + 1 764 | if len(str(hid)) + 1 > hid_length: 765 | hid_length = len(str(hid)) + 1 766 | if len(str(host["weight"])) + 1 > weight_length: 767 | weight_length = len(str(host["weight"])) + 1 768 | if len(host["current_state"]) + 1 > state_length: 769 | state_length = len(host["current_state"]) + 1 770 | 771 | output = list() 772 | output.append( 773 | "{bold}{hostname: <{hostname_length}} {servername: <{servername_length}} {hid: <{hid_length}} {weight: <{weight_length}} {state: <{state_length}} {commands}{end_bold}".format( 774 | bold="\033[1m", 775 | end_bold="\033[0m", 776 | hostname="Hostname", 777 | hostname_length=hostname_length, 778 | servername="Servername", 779 | servername_length=servername_length, 780 | hid="ID", 781 | hid_length=hid_length, 782 | weight="Weight", 783 | weight_length=weight_length, 784 | state="State", 785 | state_length=state_length, 786 | commands="Active Commands", 787 | ) 788 | ) 789 | 790 | for hid, host in host_mappings.items(): 791 | if len(host["commands"]) < 1: 792 | first_command = "N/A" 793 | else: 794 | first_command = f"PID {host['commands'][0][2]}: {host['commands'][0][3]}" 795 | 796 | host_entry = list() 797 | host_entry.append( 798 | "{hostname: <{hostname_length}} {servername: <{servername_length}} {hid: <{hid_length}} {weight: <{weight_length}} {state: <{state_length}} {commands}".format( 799 | hostname=host["hostname"], 800 | hostname_length=hostname_length, 801 | servername=host["servername"], 802 | servername_length=servername_length, 803 | hid=hid, 804 | hid_length=hid_length, 805 | weight=host["weight"], 806 | weight_length=weight_length, 807 | state=host["current_state"], 808 | state_length=state_length, 809 | commands=first_command, 810 | ) 811 | ) 812 | 813 | for idx, command in enumerate(host["commands"]): 814 | if idx == 0: 815 | continue 816 | host_entry.append( 817 | "{hostname: <{hostname_length}} {servername: <{servername_length}} {hid: <{hid_length}} {weight: <{weight_length}} {state: <{state_length}} {commands}".format( 818 | hostname="", 819 | hostname_length=hostname_length, 820 | servername="", 821 | servername_length=servername_length, 822 | hid="", 823 | hid_length=hid_length, 824 | weight="", 825 | weight_length=weight_length, 826 | state="", 827 | state_length=state_length, 828 | commands=f"PID {command[2]}: {command[3]}", 829 | ) 830 | ) 831 | 832 | output.append("\n".join(host_entry)) 833 | 834 | click.echo("\n".join(output)) 835 | 836 | rffmpeg_click.add_command(rffmpeg_click_status) 837 | 838 | @click.command(name="add", short_help="Add a host.") 839 | @click.option( 840 | "-w", 841 | "--weight", 842 | "weight", 843 | required=False, 844 | default=1, 845 | help="The weight of the host.", 846 | ) 847 | @click.option( 848 | "-n", 849 | "--name", 850 | "name", 851 | required=False, 852 | default=None, 853 | help="The name of the host (if different from the HOST).", 854 | ) 855 | @click.argument("host") 856 | def rffmpeg_click_add(weight, name, host): 857 | """ 858 | Add a new host with IP or hostname HOST to the database. 859 | """ 860 | created = datetime.now() 861 | if name is None: 862 | name = host 863 | click.echo(f"Adding new host '{host}' ({name})") 864 | with dbconn(config) as cur: 865 | cur.execute( 866 | f"INSERT INTO hosts (servername, hostname, weight, created) VALUES ({SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN}, {SQL_VAR_SIGN})", 867 | (name, host, weight, created), 868 | ) 869 | 870 | rffmpeg_click.add_command(rffmpeg_click_add) 871 | 872 | @click.command(name="remove", short_help="Remove a host.") 873 | @click.argument("host") 874 | def rffmpeg_click_remove(host): 875 | """ 876 | Remove a host with internal ID/IP/hostname/servername HOST from the database. 877 | """ 878 | try: 879 | host = int(host) 880 | field = "id" 881 | except ValueError: 882 | field = "servername" 883 | fieldAlt = "hostname" 884 | 885 | with dbconn(config) as cur: 886 | cur.execute(f"SELECT * FROM hosts WHERE {field} = {SQL_VAR_SIGN}", (host,)) 887 | entry = cur.fetchall() 888 | if len(entry) < 1: 889 | cur.execute( 890 | f"SELECT * FROM hosts WHERE {fieldAlt} = {SQL_VAR_SIGN}", (host,) 891 | ) 892 | entry = cur.fetchall() 893 | if len(entry) < 1: 894 | fail("No hosts found to delete!") 895 | 896 | if len(entry) == 1: 897 | click.echo(f"Removing {len(entry)} host:") 898 | else: 899 | click.echo(f"Removing {len(entry)} hosts:") 900 | for host in entry: 901 | hid, servername, hostname, weight, created = host 902 | click.echo(f"\tID: {hid}\tHostname: {hostname}\tServername: {servername}") 903 | cur.execute(f"DELETE FROM hosts WHERE id = {SQL_VAR_SIGN}", (hid,)) 904 | 905 | rffmpeg_click.add_command(rffmpeg_click_remove) 906 | 907 | @click.command(name="run", short_help="Run a command.", context_settings={ 908 | "ignore_unknown_options": True 909 | }) 910 | @click.option("--stderr-as-stdout", "stderr_as_stdout", is_flag=True, default=False, help="Use stderr as stdout for the command.") 911 | @click.argument('full_command', nargs=-1, type=click.UNPROCESSED) 912 | def rffmpeg_click_run(stderr_as_stdout, full_command): 913 | """ 914 | Run a command on the optimal host. 915 | """ 916 | hook_signals() 917 | 918 | setup_logging(config) 919 | 920 | command = full_command[0] 921 | command_args = full_command[1:] 922 | 923 | log.info(f"Starting rffmpeg as {command} with args: {' '.join(command_args)}") 924 | 925 | target_hid, target_hostname, target_servername = get_target_host(config) 926 | 927 | if not target_hostname or target_hostname == "localhost": 928 | ret = run_local_command(config, target_hid, command, command_args) 929 | else: 930 | ret = run_remote_command( 931 | config, 932 | target_hid, 933 | target_hostname, 934 | target_servername, 935 | command, 936 | command_args, 937 | stderr_as_stdout=stderr_as_stdout 938 | ) 939 | 940 | cleanup() 941 | if ret.returncode == 0: 942 | log.info(f"Finished rffmpeg with return code {ret.returncode}") 943 | else: 944 | log.error(f"Finished rffmpeg with return code {ret.returncode}") 945 | exit(ret.returncode) 946 | 947 | rffmpeg_click.add_command(rffmpeg_click_run) 948 | 949 | @click.command(name="log", short_help="View the rffmpeg log.") 950 | @click.option( 951 | "-f", 952 | "--follow", 953 | "follow_flag", 954 | is_flag=True, 955 | default=False, 956 | help="Follow new log entries instead of seeing current log entries.", 957 | ) 958 | def rffmpeg_click_log(follow_flag): 959 | """ 960 | View the rffmpeg log file. 961 | """ 962 | if follow_flag: 963 | if not os.path.exists(config["logfile"]): 964 | click.echo("Failed to find log file; have you initialized rffmpeg?") 965 | exit(1) 966 | 967 | with open(config["logfile"]) as file_: 968 | # Go to the end of file 969 | file_.seek(0, 2) 970 | while True: 971 | curr_position = file_.tell() 972 | line = file_.readline() 973 | if not line: 974 | file_.seek(curr_position) 975 | sleep(0.1) 976 | else: 977 | click.echo(line, nl=False) 978 | else: 979 | with open(config["logfile"], "r") as logfh: 980 | click.echo_via_pager(logfh.readlines()) 981 | 982 | rffmpeg_click.add_command(rffmpeg_click_log) 983 | 984 | @click.command(name="clear", short_help="Clear processes and states.") 985 | @click.argument("host", required=False, default=None) 986 | def rffmpeg_click_log(host): 987 | """ 988 | Clear all active process and states from the database, optionally limited to a host with internal ID/IP/hostname/servername HOST. 989 | 990 | This command is designed to assist in rare error cases whereby stuck process states are present in the database, and should be used sparingly. This will not affect running processes negatively, though rffmpeg will no longer see them as active. It is recommended to run this command only when you are sure that no processes are actually running. 991 | """ 992 | with dbconn(config) as cur: 993 | if host is not None: 994 | try: 995 | host = int(host) 996 | field = "id" 997 | except ValueError: 998 | field = "servername" 999 | fieldAlt = "hostname" 1000 | 1001 | cur.execute(f"SELECT id FROM hosts WHERE {field} = {SQL_VAR_SIGN}", (host,)) 1002 | entry = cur.fetchall() 1003 | if len(entry) < 1: 1004 | cur.execute(f"SELECT id FROM hosts WHERE {fieldAlt} = {SQL_VAR_SIGN}", (host,)) 1005 | entry = cur.fetchall() 1006 | if len(entry) < 1: 1007 | fail("Host not found!") 1008 | if len(entry) > 1: 1009 | fail("Multiple hosts found, please be more specific!") 1010 | host_id = entry[0][0] 1011 | 1012 | click.echo(f"Clearing all active processes and states for host ID '{host_id}'") 1013 | cur.execute(f"SELECT id FROM processes WHERE host_id = {SQL_VAR_SIGN}", (host_id,)) 1014 | processes = cur.fetchall() 1015 | cur.execute(f"SELECT id FROM states WHERE host_id = {SQL_VAR_SIGN}", (host_id,)) 1016 | states = cur.fetchall() 1017 | 1018 | for process in processes: 1019 | cur.execute(f"DELETE FROM processes WHERE id = {SQL_VAR_SIGN}", process) 1020 | for state in states: 1021 | cur.execute(f"DELETE FROM states WHERE id = {SQL_VAR_SIGN}", state) 1022 | else: 1023 | click.echo("Clearing all active processes and states") 1024 | cur.execute("DELETE FROM processes") 1025 | cur.execute("DELETE FROM states") 1026 | 1027 | rffmpeg_click.add_command(rffmpeg_click_log) 1028 | 1029 | return rffmpeg_click(obj={}) 1030 | 1031 | 1032 | # Entrypoint 1033 | if __name__ == "__main__": 1034 | all_args = sys.argv 1035 | cmd_name = all_args[0] 1036 | 1037 | # Load the config 1038 | config = load_config() 1039 | 1040 | if "rffmpeg" in cmd_name: 1041 | run_control(config) 1042 | 1043 | else: 1044 | ffmpeg_args = all_args[1:] 1045 | run_ffmpeg(config, ffmpeg_args) 1046 | -------------------------------------------------------------------------------- /rffmpeg.yml.sample: -------------------------------------------------------------------------------- 1 | --- 2 | # Configuration file for rffmpeg 3 | # 4 | # Copy this sample to /etc/rffmpeg/rffmpeg.yml and replace the various attributes 5 | # with the values for your environment. For more details please see the README. 6 | # 7 | # Any commented value represents the default. Uncomment and alter as required. 8 | 9 | rffmpeg: 10 | # Logging configuration 11 | logging: 12 | # Enable or disable file logging. 13 | #log_to_file: true 14 | 15 | # Log messages to this file. 16 | # Ensure the user running rffmpeg can write to this directory. 17 | #logfile: "/var/log/jellyfin/rffmpeg.log" 18 | 19 | # Use a Jellyfin-logging compatible dated log format, e.g. "20221223_rffmpeg.log" 20 | # Supersedes the "logfile" directive above 21 | #datedlogfiles: false 22 | 23 | # Use this base directory for Jellyfin-logging compatible dated log files if you enable "datedlogfiles" 24 | # Set this to your Jellyfin logging directory if it differs from the default 25 | #datedlogdir: "/var/log/jellyfin/" 26 | 27 | # Show debugging messages 28 | #debug: false 29 | 30 | # Directory configuration 31 | directories: 32 | # Persistent directory to store state database. 33 | #state: "/var/lib/rffmpeg" 34 | 35 | # Temporary directory to store SSH persistence sockets. 36 | #persist: "/run/shm" 37 | 38 | # The user who should own the state directory and database. 39 | # This should normally be the user who normally runs rffmpeg commands (i.e. the media 40 | # server service user). 41 | #owner: jellyfin 42 | 43 | # The group who should own the state directory and database (an administrative group). 44 | # Use this group to control who is able to run "rffmpeg" management commands; users in 45 | # this group will have unlimited access to the tool to add/remove hosts, view status, etc. 46 | #group: sudo 47 | 48 | # Remote (SSH) configuration 49 | remote: 50 | # The remote SSH user to connect as. 51 | #user: jellyfin 52 | 53 | # How long to persist SSH sessions; 0 to disable SSH persistence. 54 | #persist: 300 55 | 56 | # A YAML list of additional SSH arguments (e.g. private keys). 57 | # One entry line per space-separated argument element. 58 | #args: 59 | # - "-i" 60 | # - "/var/lib/jellyfin/id_rsa" 61 | 62 | # Remote command configuration 63 | commands: 64 | # The path (either full or in $PATH) to the default SSH binary. 65 | #ssh: "/usr/bin/ssh" 66 | 67 | # A YAML list of prefixes to the ffmpeg command (e.g. sudo, nice, etc.). 68 | # One entry line per space-separated command element. 69 | #pre: 70 | # - "" 71 | 72 | # The (remote) ffmpeg and ffprobe command binary paths. 73 | #ffmpeg: "/usr/lib/jellyfin-ffmpeg/ffmpeg" 74 | #ffprobe: "/usr/lib/jellyfin-ffmpeg/ffprobe" 75 | 76 | # Optional local fallback ffmpeg and ffprobe binary paths, if different from the above. 77 | #fallback_ffmpeg: "/usr/lib/jellyfin-ffmpeg/ffmpeg" 78 | #fallback_ffprobe: "/usr/lib/jellyfin-ffmpeg/ffprobe" 79 | 80 | # Optional additions to special flags that output to stdout instead of stderr. This isn't an override. 81 | #special_flags: 82 | # - "-muxers" 83 | # - "-fp_format" 84 | --------------------------------------------------------------------------------