├── .gitignore ├── LICENSE.md ├── README.md ├── conti-demo.py ├── conti ├── __init__.py ├── common.py ├── encoder.py ├── filters.py ├── probe.py ├── source.py └── utils.py ├── pyproject.toml ├── settings-rtp.json └── settings-sdl.json /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | data/ 3 | vendor/ 4 | setting.json 5 | settings.json 6 | output/* 7 | dist -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 [Free Software Foundation, Inc.](http://fsf.org/) 5 | 6 | Everyone is permitted to copy and distribute verbatim copies of this license 7 | document, but changing it is not allowed. 8 | 9 | ## Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for software and 12 | other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed to take 15 | away your freedom to share and change the works. By contrast, the GNU General 16 | Public License is intended to guarantee your freedom to share and change all 17 | versions of a program--to make sure it remains free software for all its users. 18 | We, the Free Software Foundation, use the GNU General Public License for most 19 | of our software; it applies also to any other work released this way by its 20 | authors. You can apply it to your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not price. Our 23 | General Public Licenses are designed to make sure that you have the freedom to 24 | distribute copies of free software (and charge for them if you wish), that you 25 | receive source code or can get it if you want it, that you can change the 26 | software or use pieces of it in new free programs, and that you know you can do 27 | these things. 28 | 29 | To protect your rights, we need to prevent others from denying you these rights 30 | or asking you to surrender the rights. Therefore, you have certain 31 | responsibilities if you distribute copies of the software, or if you modify it: 32 | responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether gratis or for 35 | a fee, you must pass on to the recipients the same freedoms that you received. 36 | You must make sure that they, too, receive or can get the source code. And you 37 | must show them these terms so they know their rights. 38 | 39 | Developers that use the GNU GPL protect your rights with two steps: 40 | 41 | 1. assert copyright on the software, and 42 | 2. offer you this License giving you legal permission to copy, distribute 43 | and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains that 46 | there is no warranty for this free software. For both users' and authors' sake, 47 | the GPL requires that modified versions be marked as changed, so that their 48 | problems will not be attributed erroneously to authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run modified 51 | versions of the software inside them, although the manufacturer can do so. This 52 | is fundamentally incompatible with the aim of protecting users' freedom to 53 | change the software. The systematic pattern of such abuse occurs in the area of 54 | products for individuals to use, which is precisely where it is most 55 | unacceptable. Therefore, we have designed this version of the GPL to prohibit 56 | the practice for those products. If such problems arise substantially in other 57 | domains, we stand ready to extend this provision to those domains in future 58 | versions of the GPL, as needed to protect the freedom of users. 59 | 60 | Finally, every program is threatened constantly by software patents. States 61 | should not allow patents to restrict development and use of software on 62 | general-purpose computers, but in those that do, we wish to avoid the special 63 | danger that patents applied to a free program could make it effectively 64 | proprietary. To prevent this, the GPL assures that patents cannot be used to 65 | render the program non-free. 66 | 67 | The precise terms and conditions for copying, distribution and modification 68 | follow. 69 | 70 | ## TERMS AND CONDITIONS 71 | 72 | ### 0. Definitions. 73 | 74 | *This License* refers to version 3 of the GNU General Public License. 75 | 76 | *Copyright* also means copyright-like laws that apply to other kinds of works, 77 | such as semiconductor masks. 78 | 79 | *The Program* refers to any copyrightable work licensed under this License. 80 | Each licensee is addressed as *you*. *Licensees* and *recipients* may be 81 | individuals or organizations. 82 | 83 | To *modify* a work means to copy from or adapt all or part of the work in a 84 | fashion requiring copyright permission, other than the making of an exact copy. 85 | The resulting work is called a *modified version* of the earlier work or a work 86 | *based on* the earlier work. 87 | 88 | A *covered work* means either the unmodified Program or a work based on the 89 | Program. 90 | 91 | To *propagate* a work means to do anything with it that, without permission, 92 | would make you directly or secondarily liable for infringement under applicable 93 | copyright law, except executing it on a computer or modifying a private copy. 94 | Propagation includes copying, distribution (with or without modification), 95 | making available to the public, and in some countries other activities as well. 96 | 97 | To *convey* a work means any kind of propagation that enables other parties to 98 | make or receive copies. Mere interaction with a user through a computer 99 | network, with no transfer of a copy, is not conveying. 100 | 101 | An interactive user interface displays *Appropriate Legal Notices* to the 102 | extent that it includes a convenient and prominently visible feature that 103 | 104 | 1. displays an appropriate copyright notice, and 105 | 2. tells the user that there is no warranty for the work (except to the 106 | extent that warranties are provided), that licensees may convey the work 107 | under this License, and how to view a copy of this License. 108 | 109 | If the interface presents a list of user commands or options, such as a menu, a 110 | 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 for making 115 | modifications to it. *Object code* means any non-source form of a work. 116 | 117 | A *Standard Interface* means an interface that either is an official standard 118 | defined by a recognized standards body, or, in the case of interfaces specified 119 | for a particular programming language, one that is widely used among developers 120 | working in that language. 121 | 122 | The *System Libraries* of an executable work include anything, other than the 123 | work as a whole, that (a) is included in the normal form of packaging a Major 124 | Component, but which is not part of that Major Component, and (b) serves only 125 | to enable use of the work with that Major Component, or to implement a Standard 126 | Interface for which an implementation is available to the public in source code 127 | form. A *Major Component*, in this context, means a major essential component 128 | (kernel, window system, and so on) of the specific operating system (if any) on 129 | which the executable work runs, or a compiler used to produce the work, or an 130 | object code interpreter used to run it. 131 | 132 | The *Corresponding Source* for a work in object code form means all the source 133 | code needed to generate, install, and (for an executable work) run the object 134 | code and to modify the work, including scripts to control those activities. 135 | However, it does not include the work's System Libraries, or general-purpose 136 | tools or generally available free programs which are used unmodified in 137 | performing those activities but which are not part of the work. For example, 138 | Corresponding Source includes interface definition files associated with source 139 | files for the work, and the source code for shared libraries and dynamically 140 | linked subprograms that the work is specifically designed to require, such as 141 | by intimate data communication or control flow between those subprograms and 142 | other parts of the work. 143 | 144 | The Corresponding Source need not include anything that users can regenerate 145 | automatically from other parts of the Corresponding Source. 146 | 147 | The Corresponding Source for a work in source code form is that same work. 148 | 149 | ### 2. Basic Permissions. 150 | 151 | All rights granted under this License are granted for the term of copyright on 152 | the Program, and are irrevocable provided the stated conditions are met. This 153 | License explicitly affirms your unlimited permission to run the unmodified 154 | Program. The output from running a covered work is covered by this License only 155 | if the output, given its content, constitutes a covered work. This License 156 | acknowledges your rights of fair use or other equivalent, as provided by 157 | copyright law. 158 | 159 | You may make, run and propagate covered works that you do not convey, without 160 | conditions so long as your license otherwise remains in force. You may convey 161 | covered works to others for the sole purpose of having them make modifications 162 | exclusively for you, or provide you with facilities for running those works, 163 | provided that you comply with the terms of this License in conveying all 164 | material for which you do not control copyright. Those thus making or running 165 | the covered works for you must do so exclusively on your behalf, under your 166 | direction and control, on terms that prohibit them from making any copies of 167 | your copyrighted material outside their relationship with you. 168 | 169 | Conveying under any other circumstances is permitted solely under the 170 | conditions stated below. Sublicensing is not allowed; section 10 makes it 171 | unnecessary. 172 | 173 | ### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 174 | 175 | No covered work shall be deemed part of an effective technological measure 176 | under any applicable law fulfilling obligations under article 11 of the WIPO 177 | copyright treaty adopted on 20 December 1996, or similar laws prohibiting or 178 | restricting circumvention of such measures. 179 | 180 | When you convey a covered work, you waive any legal power to forbid 181 | circumvention of technological measures to the extent such circumvention is 182 | effected by exercising rights under this License with respect to the covered 183 | work, and you disclaim any intention to limit operation or modification of the 184 | work as a means of enforcing, against the work's users, your or third parties' 185 | legal rights to forbid circumvention of technological measures. 186 | 187 | ### 4. Conveying Verbatim Copies. 188 | 189 | You may convey verbatim copies of the Program's source code as you receive it, 190 | in any medium, provided that you conspicuously and appropriately publish on 191 | each copy an appropriate copyright notice; keep intact all notices stating that 192 | this License and any non-permissive terms added in accord with section 7 apply 193 | to the code; keep intact all notices of the absence of any warranty; and give 194 | all recipients a copy of this License along with the Program. 195 | 196 | You may charge any price or no price for each copy that you convey, and you may 197 | offer support or warranty protection for a fee. 198 | 199 | ### 5. Conveying Modified Source Versions. 200 | 201 | You may convey a work based on the Program, or the modifications to produce it 202 | from the Program, in the form of source code under the terms of section 4, 203 | provided that you also meet all of these conditions: 204 | 205 | - a) The work must carry prominent notices stating that you modified it, and 206 | giving a relevant date. 207 | - b) The work must carry prominent notices stating that it is released under 208 | this License and any conditions added under section 7. This requirement 209 | modifies the requirement in section 4 to *keep intact all notices*. 210 | - c) You must license the entire work, as a whole, under this License to 211 | anyone who comes into possession of a copy. This License will therefore 212 | apply, along with any applicable section 7 additional terms, to the whole 213 | of the work, and all its parts, regardless of how they are packaged. This 214 | License gives no permission to license the work in any other way, but it 215 | does not invalidate such permission if you have separately received it. 216 | - d) If the work has interactive user interfaces, each must display 217 | Appropriate Legal Notices; however, if the Program has interactive 218 | interfaces that do not display Appropriate Legal Notices, your work need 219 | not make them do so. 220 | 221 | A compilation of a covered work with other separate and independent works, 222 | which are not by their nature extensions of the covered work, and which are not 223 | combined with it such as to form a larger program, in or on a volume of a 224 | storage or distribution medium, is called an *aggregate* if the compilation and 225 | its resulting copyright are not used to limit the access or legal rights of the 226 | compilation's users beyond what the individual works permit. Inclusion of a 227 | covered work in an aggregate does not cause this License to apply to the other 228 | parts of the aggregate. 229 | 230 | ### 6. Conveying Non-Source Forms. 231 | 232 | You may convey a covered work in object code form under the terms of sections 4 233 | and 5, provided that you also convey the machine-readable Corresponding Source 234 | under the terms of this License, in one of these ways: 235 | 236 | - a) Convey the object code in, or embodied in, a physical product (including 237 | a physical distribution medium), accompanied by the Corresponding Source 238 | fixed on a durable physical medium customarily used for software 239 | interchange. 240 | - b) Convey the object code in, or embodied in, a physical product (including 241 | a physical distribution medium), accompanied by a written offer, valid for 242 | at least three years and valid for as long as you offer spare parts or 243 | customer support for that product model, to give anyone who possesses the 244 | object code either 245 | 1. a copy of the Corresponding Source for all the software in the product 246 | that is covered by this License, on a durable physical medium 247 | customarily used for software interchange, for a price no more than your 248 | reasonable cost of physically performing this conveying of source, or 249 | 2. access to copy the Corresponding Source from a network server at no 250 | charge. 251 | - c) Convey individual copies of the object code with a copy of the written 252 | offer to provide the Corresponding Source. This alternative is allowed only 253 | occasionally and noncommercially, and only if you received the object code 254 | with such an offer, in accord with subsection 6b. 255 | - d) Convey the object code by offering access from a designated place 256 | (gratis or for a charge), and offer equivalent access to the Corresponding 257 | Source in the same way through the same place at no further charge. You 258 | need not require recipients to copy the Corresponding Source along with the 259 | object code. If the place to copy the object code is a network server, the 260 | Corresponding Source may be on a different server operated by you or a 261 | third party) that supports equivalent copying facilities, provided you 262 | maintain clear directions next to the object code saying where to find the 263 | Corresponding Source. Regardless of what server hosts the Corresponding 264 | Source, you remain obligated to ensure that it is available for as long as 265 | needed to satisfy these requirements. 266 | - e) Convey the object code using peer-to-peer transmission, provided you 267 | inform other peers where the object code and Corresponding Source of the 268 | work are being offered to the general public at no charge under subsection 269 | 6d. 270 | 271 | A separable portion of the object code, whose source code is excluded from the 272 | Corresponding Source as a System Library, need not be included in conveying the 273 | object code work. 274 | 275 | A *User Product* is either 276 | 277 | 1. a *consumer product*, which means any tangible personal property which is 278 | normally used for personal, family, or household purposes, or 279 | 2. anything designed or sold for incorporation into a dwelling. 280 | 281 | In determining whether a product is a consumer product, doubtful cases shall be 282 | resolved in favor of coverage. For a particular product received by a 283 | particular user, *normally used* refers to a typical or common use of that 284 | class of product, regardless of the status of the particular user or of the way 285 | in which the particular user actually uses, or expects or is expected to use, 286 | the product. A product is a consumer product regardless of whether the product 287 | has substantial commercial, industrial or non-consumer uses, unless such uses 288 | represent the only significant mode of use of the product. 289 | 290 | *Installation Information* for a User Product means any methods, procedures, 291 | authorization keys, or other information required to install and execute 292 | modified versions of a covered work in that User Product from a modified 293 | version of its Corresponding Source. The information must suffice to ensure 294 | that the continued functioning of the modified object code is in no case 295 | prevented or interfered with solely because modification has been made. 296 | 297 | If you convey an object code work under this section in, or with, or 298 | specifically for use in, a User Product, and the conveying occurs as part of a 299 | transaction in which the right of possession and use of the User Product is 300 | transferred to the recipient in perpetuity or for a fixed term (regardless of 301 | how the transaction is characterized), the Corresponding Source conveyed under 302 | this section must be accompanied by the Installation Information. But this 303 | requirement does not apply if neither you nor any third party retains the 304 | ability to install modified object code on the User Product (for example, the 305 | work has been installed in ROM). 306 | 307 | The requirement to provide Installation Information does not include a 308 | requirement to continue to provide support service, warranty, or updates for a 309 | work that has been modified or installed by the recipient, or for the User 310 | Product in which it has been modified or installed. Access to a network may be 311 | denied when the modification itself materially and adversely affects the 312 | operation of the network or violates the rules and protocols for communication 313 | across the network. 314 | 315 | Corresponding Source conveyed, and Installation Information provided, in accord 316 | with this section must be in a format that is publicly documented (and with an 317 | implementation available to the public in source code form), and must require 318 | no special password or key for unpacking, reading or copying. 319 | 320 | ### 7. Additional Terms. 321 | 322 | *Additional permissions* are terms that supplement the terms of this License by 323 | making exceptions from one or more of its conditions. Additional permissions 324 | that are applicable to the entire Program shall be treated as though they were 325 | included in this License, to the extent that they are valid under applicable 326 | law. If additional permissions apply only to part of the Program, that part may 327 | be used separately under those permissions, but the entire Program remains 328 | governed by this License without regard to the additional permissions. 329 | 330 | When you convey a copy of a covered work, you may at your option remove any 331 | additional permissions from that copy, or from any part of it. (Additional 332 | permissions may be written to require their own removal in certain cases when 333 | you modify the work.) You may place additional permissions on material, added 334 | by you to a covered work, for which you have or can give appropriate copyright 335 | permission. 336 | 337 | Notwithstanding any other provision of this License, for material you add to a 338 | covered work, you may (if authorized by the copyright holders of that material) 339 | supplement the terms of this License with terms: 340 | 341 | - a) Disclaiming warranty or limiting liability differently from the terms of 342 | sections 15 and 16 of this License; or 343 | - b) Requiring preservation of specified reasonable legal notices or author 344 | attributions in that material or in the Appropriate Legal Notices displayed 345 | by works containing it; or 346 | - c) Prohibiting misrepresentation of the origin of that material, or 347 | requiring that modified versions of such material be marked in reasonable 348 | ways as different from the original version; or 349 | - d) Limiting the use for publicity purposes of names of licensors or authors 350 | of the material; or 351 | - e) Declining to grant rights under trademark law for use of some trade 352 | names, trademarks, or service marks; or 353 | - f) Requiring indemnification of licensors and authors of that material by 354 | anyone who conveys the material (or modified versions of it) with 355 | contractual assumptions of liability to the recipient, for any liability 356 | that these contractual assumptions directly impose on those licensors and 357 | authors. 358 | 359 | All other non-permissive additional terms are considered *further restrictions* 360 | within the meaning of section 10. If the Program as you received it, or any 361 | part of it, contains a notice stating that it is governed by this License along 362 | with a term that is a further restriction, you may remove that term. If a 363 | license document contains a further restriction but permits relicensing or 364 | conveying under this License, you may add to a covered work material governed 365 | by the terms of that license document, provided that the further restriction 366 | does not survive such relicensing or conveying. 367 | 368 | If you add terms to a covered work in accord with this section, you must place, 369 | in the relevant source files, a statement of the additional terms that apply to 370 | those files, or a notice indicating where to find the applicable terms. 371 | 372 | Additional terms, permissive or non-permissive, may be stated in the form of a 373 | separately written license, or stated as exceptions; the above requirements 374 | apply either way. 375 | 376 | ### 8. Termination. 377 | 378 | You may not propagate or modify a covered work except as expressly provided 379 | under this License. Any attempt otherwise to propagate or modify it is void, 380 | and will automatically terminate your rights under this License (including any 381 | patent licenses granted under the third paragraph of section 11). 382 | 383 | However, if you cease all violation of this License, then your license from a 384 | particular copyright holder is reinstated 385 | 386 | - a) provisionally, unless and until the copyright holder explicitly and 387 | finally terminates your license, and 388 | - b) permanently, if the copyright holder fails to notify you of the 389 | violation by some reasonable means prior to 60 days after the cessation. 390 | 391 | Moreover, your license from a particular copyright holder is reinstated 392 | permanently if the copyright holder notifies you of the violation by some 393 | reasonable means, this is the first time you have received notice of violation 394 | of this License (for any work) from that copyright holder, and you cure the 395 | violation prior to 30 days after your receipt of the notice. 396 | 397 | Termination of your rights under this section does not terminate the licenses 398 | of parties who have received copies or rights from you under this License. If 399 | your rights have been terminated and not permanently reinstated, you do not 400 | qualify to receive new licenses for the same material under section 10. 401 | 402 | ### 9. Acceptance Not Required for Having Copies. 403 | 404 | You are not required to accept this License in order to receive or run a copy 405 | of the Program. Ancillary propagation of a covered work occurring solely as a 406 | consequence of using peer-to-peer transmission to receive a copy likewise does 407 | not require acceptance. However, nothing other than this License grants you 408 | permission to propagate or modify any covered work. These actions infringe 409 | copyright if you do not accept this License. Therefore, by modifying or 410 | propagating a covered work, you indicate your acceptance of this License to do 411 | so. 412 | 413 | ### 10. Automatic Licensing of Downstream Recipients. 414 | 415 | Each time you convey a covered work, the recipient automatically receives a 416 | license from the original licensors, to run, modify and propagate that work, 417 | subject to this License. You are not responsible for enforcing compliance by 418 | third parties with this License. 419 | 420 | An *entity transaction* is a transaction transferring control of an 421 | organization, or substantially all assets of one, or subdividing an 422 | organization, or merging organizations. If propagation of a covered work 423 | results from an entity transaction, each party to that transaction who receives 424 | a copy of the work also receives whatever licenses to the work the party's 425 | predecessor in interest had or could give under the previous paragraph, plus a 426 | right to possession of the Corresponding Source of the work from the 427 | predecessor in interest, if the predecessor has it or can get it with 428 | reasonable efforts. 429 | 430 | You may not impose any further restrictions on the exercise of the rights 431 | granted or affirmed under this License. For example, you may not impose a 432 | license fee, royalty, or other charge for exercise of rights granted under this 433 | License, and you may not initiate litigation (including a cross-claim or 434 | counterclaim in a lawsuit) alleging that any patent claim is infringed by 435 | making, using, selling, offering for sale, or importing the Program or any 436 | portion of it. 437 | 438 | ### 11. Patents. 439 | 440 | A *contributor* is a copyright holder who authorizes use under this License of 441 | the Program or a work on which the Program is based. The work thus licensed is 442 | called the contributor's *contributor version*. 443 | 444 | A contributor's *essential patent claims* are all patent claims owned or 445 | controlled by the contributor, whether already acquired or hereafter acquired, 446 | that would be infringed by some manner, permitted by this License, of making, 447 | using, or selling its contributor version, but do not include claims that would 448 | be infringed only as a consequence of further modification of the contributor 449 | version. For purposes of this definition, *control* includes the right to grant 450 | patent sublicenses in a manner consistent with the requirements of this 451 | License. 452 | 453 | Each contributor grants you a non-exclusive, worldwide, royalty-free patent 454 | license under the contributor's essential patent claims, to make, use, sell, 455 | offer for sale, import and otherwise run, modify and propagate the contents of 456 | its contributor version. 457 | 458 | In the following three paragraphs, a *patent license* is any express agreement 459 | or commitment, however denominated, not to enforce a patent (such as an express 460 | permission to practice a patent or covenant not to sue for patent 461 | infringement). To *grant* such a patent license to a party means to make such 462 | an agreement or commitment not to enforce a patent against the party. 463 | 464 | If you convey a covered work, knowingly relying on a patent license, and the 465 | Corresponding Source of the work is not available for anyone to copy, free of 466 | charge and under the terms of this License, through a publicly available 467 | network server or other readily accessible means, then you must either 468 | 469 | 1. cause the Corresponding Source to be so available, or 470 | 2. arrange to deprive yourself of the benefit of the patent license for this 471 | particular work, or 472 | 3. arrange, in a manner consistent with the requirements of this License, to 473 | extend the patent license to downstream recipients. 474 | 475 | *Knowingly relying* means you have actual knowledge that, but for the patent 476 | license, your conveying the covered work in a country, or your recipient's use 477 | of the covered work in a country, would infringe one or more identifiable 478 | patents in that country that you have reason to believe are valid. 479 | 480 | If, pursuant to or in connection with a single transaction or arrangement, you 481 | convey, or propagate by procuring conveyance of, a covered work, and grant a 482 | patent license to some of the parties receiving the covered work authorizing 483 | them to use, propagate, modify or convey a specific copy of the covered work, 484 | then the patent license you grant is automatically extended to all recipients 485 | of the covered work and works based on it. 486 | 487 | A patent license is *discriminatory* if it does not include within the scope of 488 | its coverage, prohibits the exercise of, or is conditioned on the non-exercise 489 | of one or more of the rights that are specifically granted under this License. 490 | You may not convey a covered work if you are a party to an arrangement with a 491 | third party that is in the business of distributing software, under which you 492 | make payment to the third party based on the extent of your activity of 493 | conveying the work, and under which the third party grants, to any of the 494 | parties who would receive the covered work from you, a discriminatory patent 495 | license 496 | 497 | - a) in connection with copies of the covered work conveyed by you (or copies 498 | made from those copies), or 499 | - b) primarily for and in connection with specific products or compilations 500 | that contain the covered work, unless you entered into that arrangement, or 501 | that patent license was granted, prior to 28 March 2007. 502 | 503 | Nothing in this License shall be construed as excluding or limiting any implied 504 | license or other defenses to infringement that may otherwise be available to 505 | you under applicable patent law. 506 | 507 | ### 12. No Surrender of Others' Freedom. 508 | 509 | If conditions are imposed on you (whether by court order, agreement or 510 | otherwise) that contradict the conditions of this License, they do not excuse 511 | you from the conditions of this License. If you cannot convey a covered work so 512 | as to satisfy simultaneously your obligations under this License and any other 513 | pertinent obligations, then as a consequence you may not convey it at all. For 514 | example, if you agree to terms that obligate you to collect a royalty for 515 | further conveying from those to whom you convey the Program, the only way you 516 | could satisfy both those terms and this License would be to refrain entirely 517 | from conveying the Program. 518 | 519 | ### 13. Use with the GNU Affero General Public License. 520 | 521 | Notwithstanding any other provision of this License, you have permission to 522 | link or combine any covered work with a work licensed under version 3 of the 523 | GNU Affero General Public License into a single combined work, and to convey 524 | the resulting work. The terms of this License will continue to apply to the 525 | part which is the covered work, but the special requirements of the GNU Affero 526 | General Public License, section 13, concerning interaction through a network 527 | will apply to the combination as such. 528 | 529 | ### 14. Revised Versions of this License. 530 | 531 | The Free Software Foundation may publish revised and/or new versions of the GNU 532 | General Public License from time to time. Such new versions will be similar in 533 | spirit to the present version, but may differ in detail to address new problems 534 | or concerns. 535 | 536 | Each version is given a distinguishing version number. If the Program specifies 537 | that a certain numbered version of the GNU General Public License *or any later 538 | version* applies to it, you have the option of following the terms and 539 | conditions either of that numbered version or of any later version published by 540 | the Free Software Foundation. If the Program does not specify a version number 541 | of the GNU General Public License, you may choose any version ever published by 542 | the Free Software Foundation. 543 | 544 | If the Program specifies that a proxy can decide which future versions of the 545 | GNU General Public License can be used, that proxy's public statement of 546 | acceptance of a version permanently authorizes you to choose that version for 547 | the Program. 548 | 549 | Later license versions may give you additional or different permissions. 550 | However, no additional obligations are imposed on any author or copyright 551 | holder as a result of your choosing to follow a later version. 552 | 553 | ### 15. Disclaimer of Warranty. 554 | 555 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE 556 | LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER 557 | PARTIES PROVIDE THE PROGRAM *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER 558 | EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 559 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE 560 | QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 561 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 562 | CORRECTION. 563 | 564 | ### 16. Limitation of Liability. 565 | 566 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY 567 | COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS 568 | PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, 569 | INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE 570 | THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED 571 | INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE 572 | PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY 573 | HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 574 | 575 | ### 17. Interpretation of Sections 15 and 16. 576 | 577 | If the disclaimer of warranty and limitation of liability provided above cannot 578 | be given local legal effect according to their terms, reviewing courts shall 579 | apply local law that most closely approximates an absolute waiver of all civil 580 | liability in connection with the Program, unless a warranty or assumption of 581 | liability accompanies a copy of the Program in return for a fee. 582 | 583 | ## END OF TERMS AND CONDITIONS ### 584 | 585 | ### How to Apply These Terms to Your New Programs 586 | 587 | If you develop a new program, and you want it to be of the greatest possible 588 | use to the public, the best way to achieve this is to make it free software 589 | which everyone can redistribute and change under these terms. 590 | 591 | To do so, attach the following notices to the program. It is safest to attach 592 | them to the start of each source file to most effectively state the exclusion 593 | of warranty; and each file should have at least the *copyright* line and a 594 | pointer to where the full notice is found. 595 | 596 | 597 | Copyright (C) 598 | 599 | This program is free software: you can redistribute it and/or modify 600 | it under the terms of the GNU General Public License as published by 601 | the Free Software Foundation, either version 3 of the License, or 602 | (at your option) any later version. 603 | 604 | This program is distributed in the hope that it will be useful, 605 | but WITHOUT ANY WARRANTY; without even the implied warranty of 606 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 607 | GNU General Public License for more details. 608 | 609 | You should have received a copy of the GNU General Public License 610 | along with this program. If not, see . 611 | 612 | Also add information on how to contact you by electronic and paper mail. 613 | 614 | If the program does terminal interaction, make it output a short notice like 615 | this when it starts in an interactive mode: 616 | 617 | Copyright (C) 618 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 619 | This is free software, and you are welcome to redistribute it 620 | under certain conditions; type `show c' for details. 621 | 622 | The hypothetical commands `show w` and `show c` should show the appropriate 623 | parts of the General Public License. Of course, your program's commands might 624 | be different; for a GUI interface, you would use an *about box*. 625 | 626 | You should also get your employer (if you work as a programmer) or school, if 627 | any, to sign a *copyright disclaimer* for the program, if necessary. For more 628 | information on this, and how to apply and follow the GNU GPL, see 629 | [http://www.gnu.org/licenses/](http://www.gnu.org/licenses/). 630 | 631 | The GNU General Public License does not permit incorporating your program into 632 | proprietary programs. If your program is a subroutine library, you may consider 633 | it more useful to permit linking proprietary applications with the library. If 634 | this is what you want to do, use the GNU Lesser General Public License instead 635 | of this License. But first, please read 636 | [http://www.gnu.org/philosophy/why-not-lgpl.html](http://www.gnu.org/philosophy/why-not-lgpl.html). 637 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Conti 2 | ===== 3 | 4 | *FFMpeg based playout server* 5 | 6 | About the project 7 | ----------------- 8 | 9 | Conti is a simple linear video playout server. It enables you to broadcast 10 | your video files with minimal configuration and hardware requirements. 11 | 12 | Conti demo script can be modified to run simple stand-alone channels such as 13 | lobby TVs, info channels, community TV stations, and so on. 14 | 15 | For more complex projects, [Nebula](https://github.com/immstudios/nebula) 16 | broadcast automation system can be used for scheduling and playout control. 17 | 18 | ### Features 19 | 20 | Conti has a very simple architecture allowing extensive tweaking. Most of the features 21 | come from FFMpeg, notably: 22 | 23 | - Vast source format support 24 | - Multiple simultaneous outputs including RTP, RTMP, MPEG-TS, NDI and SDI 25 | - Video and audio filtering on a source, global, or output level. This includes 26 | on-the-fly loudness normalization, station logo burn-in, ARC and so on. 27 | - Up to 16 channel audio support with channels shuffling. 28 | - Hardware-accelerated encoding (nvenc) of selected formats (h.264, HEVC) 29 | 30 | ### Limitations 31 | 32 | - Most of the output formats does not support pausing. 33 | It is possible to pause Decklink or SDL outputs by calling `Conti.freeze(self)` method, 34 | but IP streams have to run all the time. 35 | - It is not possible to control displayed graphics overlays during playback. 36 | - There is probably no easy way to create a continuous text crawl. 37 | [Prove us wrong](https://github.com/immstudios/conti/issues/new). 38 | - Looping is not implemented yet (but is planned) 39 | - *source* and *output* filters usage differs slightly. We want to unify the behavior. 40 | 41 | Quick start 42 | ----------- 43 | 44 | Conti runs on Linux (no other OS has been tested) and requires Python3, FFMpeg and 45 | nxtools. 46 | 47 | ### FFMpeg 48 | 49 | For the most use-cases, FFMpeg build available in your favorite Linux distribution 50 | is sufficient. 51 | 52 | In case you need Blackmagic Decklink or NDI I/O, you may use our build script from 53 | [this repository](https://github.com/immstudios/installers). 54 | 55 | ### nxtools 56 | 57 | [nxtools](https://github.com/immstudios/nxtools) is a set of Python utilities 58 | we use for many tasks. Install it using `pip3 install nxtools` 59 | 60 | ### Running Conti 61 | 62 | Clone this repository and tweak conti.py script to point to your data location 63 | (directory with your video files) 64 | 65 | By default, Conti streams in RTP over multicast to `rtp://224.0.0.1:2000`, 66 | but you can change the destination as well as the encoding profile(s). 67 | 68 | Start `./conti.py` and tune your station: 69 | Start VLC on any machine in your network, hit ctrl+n and enter `rtp://@224.0.0.1:2000`. 70 | 71 | Architecture 72 | ------------ 73 | 74 | Conti uses several FFMpeg processes tied together using pipes to produce a gapless stream. 75 | Each **source** (`ContiSource` Python class) spawns an FFMpeg process with a filter-chain 76 | which handles format and tracks layout normalization and pipes its uncompressed output to 77 | the encoder process. Conti opens several source processes in advance, so right after one 78 | clip is finished, the next one can be started without delays. 79 | 80 | The encoder process applies *global output filter-chain* to the piped input (e.g. audio 81 | normalization), splits the output if there is more than one output specified, applies 82 | *per-output* filter-chains and transcode or output the result to the desired streams/devices. 83 | 84 | Examples 85 | -------- 86 | 87 | Feel free to tweak the sample script to meet your needs. 88 | You can modify the `get_next` method to play different media files in 89 | different parts of the day or to follow a playlist stored in a database. 90 | 91 | Following `settings.json` file instruct the `conti.py` demo script to playback media files from the 92 | chosen directory, the top-level `video_filters` parameter is applied to all outputs 93 | (in this case, black&white conversion). Two SDL outputs (desktop windows) are defined, but the audio 94 | output is not used. The second output has its feed horizontally flipped. 95 | 96 | ```json 97 | { 98 | "media_dir" : "/export/media.dir", 99 | "video_filters" : "hue=s=0", 100 | "outputs" : [ 101 | { 102 | "target" : "SDL Output 1", 103 | "audio" : false, 104 | "params" : { 105 | "c:v" : "rawvideo", 106 | "f" : "sdl", 107 | "pix_fmt" : "yuv420p" 108 | } 109 | }, 110 | { 111 | "target" : "SDL Output 2", 112 | "audio" : false, 113 | "video_filters": "hflip", 114 | "params" : { 115 | "c:v" : "rawvideo", 116 | "f" : "sdl", 117 | "pix_fmt" : "yuv420p" 118 | } 119 | } 120 | 121 | ] 122 | } 123 | ``` 124 | 125 | > Note: SDL is not available in the immstudios ffmpeg build (yet) 126 | 127 | ### Pipe format 128 | 129 | The example assumes 1080p25 is used as an "intermediate" format (the format which goes thru the pipe), 130 | but at the top level of the `settings.json` you may override the following default values. 131 | 132 | ```json 133 | { 134 | "width" : 1920, 135 | "height" : 1080, 136 | "frame_rate" : 25, 137 | "pixel_format" : "yuv422p", 138 | "audio_only" : false, 139 | "audio_codec" : "pcm_s16le", 140 | "audio_sample_rate" : 48000, 141 | } 142 | ``` 143 | 144 | ### Decklink 145 | 146 | Decklink cards are very picky regarding the used format, especially the interlaced flag. 147 | In order to output 1080i50, use the default values of the pipe format and use the following values 148 | for your output. 149 | 150 | ```json 151 | { 152 | "target" : "DeckLink SDI", 153 | "video_filters" : "setfields=tff", 154 | "params" : { 155 | "field_order" : "tt", 156 | "f" : "decklink", 157 | "pix_fmt" : "uyvy422" 158 | } 159 | } 160 | ``` 161 | 162 | ### Audio 163 | 164 | All sources are converted to 16channels audio, so in order to get a stereo output (for example for an IP stream), 165 | use `{"audio_filters" : "pan=stereo|c0=c0|c1=c1}` or similar to get the desired channel pair. 166 | 167 | 168 | 169 | 170 | -------------------------------------------------------------------------------- /conti-demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import os 4 | import sys 5 | import json 6 | import functools 7 | 8 | from nxtools import * 9 | 10 | from conti import * 11 | from conti.filters import * 12 | 13 | CONTI_DEBUG["decoder"] = False 14 | CONTI_DEBUG["encoder"] = True 15 | 16 | # 17 | # Default settings 18 | # 19 | 20 | settings = { 21 | "media_dir" : "data", 22 | "outputs" : [{ 23 | "target" : "rtp://224.0.0.1:2000", 24 | "audio_filters" : "pan=stereo|c0=c0|c1=c1, loudnorm=I=-23", 25 | "video_filters" : ["movie=/data/logo.png[logo]; " "scale=640x360"], 26 | "params" : { 27 | "c:v" : "libx264", 28 | "b:v" : "900k", 29 | "c:a" : "aac", 30 | "b:a" : "96k", 31 | "f" : "rtp_mpegts", 32 | "pix_fmt" : "yuv420p" 33 | } 34 | }] 35 | } 36 | 37 | 38 | 39 | # 40 | # Load custom settings from file 41 | # 42 | 43 | settings_file = "settings.json" 44 | if os.path.exists(settings_file) and not "--default" in sys.argv: 45 | try: 46 | custom_settings = json.load(open(settings_file)) 47 | except Exception: 48 | log_traceback() 49 | critical_error("Unable to parse 'settings.json' file") 50 | else: 51 | settings.update(custom_settings) 52 | 53 | 54 | # 55 | # Clips library and "playlist" engine 56 | # 57 | 58 | 59 | class Clips(object): 60 | """ 61 | This helper class collects clips from your data directory 62 | and provides get_next method. This method returns a ContiSource 63 | object for clip, which should be playing next :) 64 | 65 | In this example, it just iterates over the list of your media 66 | files in infinite loop. 67 | 68 | """ 69 | 70 | def __init__(self, data_dir): 71 | self.clips = [f.path for f in get_files(data_dir, exts=["mov", "mxf"])] 72 | if not self.clips: 73 | critical_error("There are no media files in '{}'".format(data_dir)) 74 | self.current_index = 0 75 | 76 | def get_next(self, conti): 77 | path = self.clips[self.current_index % len(self.clips)] 78 | self.current_index += 1 79 | source = ContiSource(conti, path) 80 | 81 | 82 | # Warning: Filters engine is subject of change 83 | source.filter_chain.add( 84 | FDrawText("video", "video", 85 | text=get_base_name(path), 86 | fontsize=48, 87 | fontcolor="white", 88 | x="(w/2) - (tw/2)", 89 | y="2*lh", 90 | box=1, 91 | boxborderw=8, 92 | boxcolor="black" 93 | ) 94 | ) 95 | 96 | 97 | return source 98 | 99 | if __name__ == "__main__": 100 | clips = Clips(settings["media_dir"]) 101 | conti = Conti(clips.get_next, **settings) 102 | 103 | # station logo burn-in 104 | logo_path = "data/logo.png" 105 | if os.path.exists(logo_path): 106 | conti.filter_chain.add( 107 | FSource(logo_path, "watermark"), 108 | FOverlay("video", "watermark", "video"), 109 | ) 110 | conti.start() 111 | -------------------------------------------------------------------------------- /conti/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ["Conti", "ContiSource", "CONTI_DEBUG"] 2 | 3 | import re 4 | import time 5 | import threading 6 | 7 | from nxtools import logging, log_traceback 8 | from .common import get_settings, CONTI_DEBUG 9 | from .encoder import ContiEncoder 10 | from .source import ContiSource 11 | 12 | 13 | class Conti(object): 14 | def __init__(self, get_next_item, **kwargs): 15 | self.get_next_item = get_next_item 16 | self.settings = get_settings(**kwargs) 17 | self.should_run = True 18 | self.started = False 19 | self.playlist = [] 20 | self.playlist_lenght = self.settings["playlist_length"] 21 | self.buff_size = 65536 # linux pipe buffer size 22 | self.paused = False 23 | self.encoder = ContiEncoder(self) 24 | 25 | @property 26 | def current(self): 27 | if not self.playlist: 28 | return False 29 | return self.playlist[0] 30 | 31 | @property 32 | def filter_chain(self): 33 | return self.encoder.filter_chain 34 | 35 | def append_next_item(self): 36 | next_item = self.get_next_item(self) 37 | if not next_item: 38 | time.sleep(.1) 39 | return 40 | next_item.open() 41 | if next_item: 42 | logging.debug("Appending {} to playlist".format(next_item)) 43 | self.playlist.append(next_item) 44 | return 45 | logging.error("Unable to get next item") 46 | 47 | def start(self): 48 | self.started = True 49 | self.encoder.start() 50 | 51 | monitor_thread = threading.Thread( 52 | target=self.monitor_thread, 53 | daemon=True 54 | ) 55 | source_progress_thread = threading.Thread( 56 | target=self.source_progress_thread, 57 | daemon=True 58 | ) 59 | encoder_progress_thread = threading.Thread( 60 | target=self.encoder_progress_thread, 61 | daemon=True 62 | ) 63 | 64 | monitor_thread.start() 65 | source_progress_thread.start() 66 | encoder_progress_thread.start() 67 | 68 | while not self.playlist: 69 | logging.debug("Playlist is not ready") 70 | time.sleep(.1) 71 | if self.settings.get("blocking", True): 72 | logging.debug("Starting main thread in blocking mode") 73 | self.main_thread() 74 | else: 75 | logging.debug("Starting main thread in non-blocking mode") 76 | main_thread = threading.Thread( 77 | target=self.main_thread, 78 | daemon=True 79 | ) 80 | main_thread.start() 81 | 82 | def main_thread(self): 83 | while self.should_run: 84 | if not self.playlist: 85 | time.sleep(.01) 86 | continue 87 | logging.info("Starting clip {}".format(self.playlist[0])) 88 | while self.should_run: 89 | if self.paused: 90 | time.sleep(.01) 91 | continue 92 | data = self.current.read(self.buff_size) 93 | if not data: 94 | self.current.proc.wait() 95 | if self.current.proc.poll() > 0: 96 | print() 97 | logging.error("Source error") 98 | print("\n".join(self.current.error_log)) 99 | print(str(self.current.proc.stderr.read())) 100 | print() 101 | break 102 | try: 103 | self.encoder.write(data) 104 | except BrokenPipeError: 105 | if self.should_run: 106 | self.encoder.proc.wait() 107 | print() 108 | logging.error("Encoder error") 109 | print("\n".join(self.encoder.error_log)) 110 | print(str(self.encoder.proc.stderr.read())) 111 | print() 112 | self.stop() 113 | # TODO: start encoder again, seek to 114 | # the same position and resume 115 | else: 116 | break 117 | self.playlist.pop(0) 118 | logging.debug("Conti main thread terminated") 119 | 120 | def monitor_thread(self): 121 | while self.should_run: 122 | while len(self.playlist) < self.playlist_lenght: 123 | self.append_next_item() 124 | time.sleep(.1) 125 | logging.debug("Conti monitor thread terminated") 126 | 127 | def source_progress_thread(self): 128 | sbuff = b"" 129 | while self.should_run: 130 | if not self.playlist: 131 | time.sleep(.01) 132 | continue 133 | 134 | source = self.current 135 | if source and source.proc.stderr: 136 | try: 137 | ch = source.proc.stderr.read(1) 138 | except Exception: 139 | log_traceback() 140 | else: 141 | if ch in ["\n", "\r", b"\n", b"\r"]: 142 | line = sbuff.decode("utf-8") 143 | if line.startswith("frame="): 144 | m = re.match(r".*frame=\s*(\d+)\s*fps.*", line) 145 | if m: 146 | current_frame = int(m.group(1)) 147 | source.position = \ 148 | current_frame / source.meta["video/fps_f"] 149 | self.progress_handler() 150 | elif CONTI_DEBUG["source"]: 151 | logging.debug("SOURCE:", line) 152 | else: 153 | source.error_log.append(line) 154 | sbuff = b"" 155 | else: 156 | sbuff += ch 157 | logging.debug("Conti source progress thread terminated") 158 | 159 | def encoder_progress_thread(self): 160 | ebuff = b"" 161 | while self.should_run: 162 | if not self.playlist: 163 | time.sleep(.01) 164 | continue 165 | 166 | if self.encoder and self.encoder.proc.stderr: 167 | try: 168 | ch = self.encoder.proc.stderr.read(1) 169 | except Exception: 170 | log_traceback() 171 | else: 172 | if ch in [b"\n", b"\r"]: 173 | line = ebuff.decode("utf-8") 174 | if line.startswith("frame="): 175 | pass 176 | # TODO: get fps/speed value to track performance 177 | 178 | else: 179 | if CONTI_DEBUG["encoder"]: 180 | logging.debug("ENCODER:", line) 181 | self.encoder.error_log.append(str(line)) 182 | if len(self.encoder.error_log) > 100: 183 | self.encoder.error_log = \ 184 | self.encoder.error_log[-100:] 185 | 186 | ebuff = b"" 187 | else: 188 | ebuff += ch 189 | logging.debug("Conti encoder progress thread terminated") 190 | 191 | def progress_handler(self): 192 | return 193 | 194 | def stop(self): 195 | logging.warning("Stopping playback") 196 | self.should_run = False 197 | self.encoder.stop() 198 | self.take() 199 | 200 | # 201 | # Playback interaction 202 | # 203 | 204 | def take(self): 205 | """Finish current item and skip to next one""" 206 | if not self.playlist: 207 | logging.error("Unable to take. Playlist is empty.") 208 | return False 209 | current = self.current 210 | if not current: 211 | logging.error("Unable to take. No clip is playing") 212 | return False 213 | current.stop() 214 | return True 215 | 216 | # WARNING: Freeze and abort should not be used if output is IP stream! 217 | # TODO: disallow this by checking output formats 218 | 219 | def freeze(self): 220 | self.paused = not self.paused 221 | 222 | def retake(self): 223 | logging.error("Retake is not implemented") 224 | return False 225 | 226 | def abort(self): 227 | logging.info("Aborting", self.current) 228 | self.current.stop() 229 | self.paused = True 230 | -------------------------------------------------------------------------------- /conti/common.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | DEVNULL = open(os.devnull, 'w') 5 | CONTI_DEBUG = { 6 | "source": False, 7 | "encoder": False 8 | } 9 | 10 | 11 | def get_settings(**kwargs): 12 | """Return a dict with the settings for the conti module.""" 13 | settings = { 14 | "gpu_id": None, 15 | "playlist_length": 2, 16 | 17 | # Processing format 18 | "width": 1920, 19 | "height": 1080, 20 | "frame_rate": 25, 21 | "pixel_format": "yuv422p", 22 | "audio_only": False, 23 | "audio_codec": "pcm_s16le", 24 | "audio_sample_rate": 48000, 25 | } 26 | 27 | settings.update(kwargs) 28 | return settings 29 | -------------------------------------------------------------------------------- /conti/encoder.py: -------------------------------------------------------------------------------- 1 | __all__ = ["ContiEncoder"] 2 | 3 | import os 4 | import signal 5 | import subprocess 6 | 7 | from nxtools import logging 8 | 9 | from .filters import ( 10 | FilterChain, 11 | FNull, 12 | FANull, 13 | RawFilter 14 | ) 15 | 16 | 17 | class ContiEncoder(object): 18 | """Conti encoder process.""" 19 | def __init__(self, parent): 20 | """ContiEncoder constructor.""" 21 | self.parent = parent 22 | self.pipe = None 23 | self.proc = None 24 | self.error_log = [] 25 | self.filter_chain = FilterChain() 26 | 27 | # TODO: Replace with rawfilter doing something 28 | # based on conti settings(interlacing and stuff) 29 | self.filter_chain.add(FNull("0:0", "video")) 30 | 31 | # TODO: Replace with rawfilter doing something 32 | # based on conti settings(loudness and stuff) 33 | self.filter_chain.add(FANull("0:1", "audio")) 34 | 35 | def __getitem__(self, key: str): 36 | """Return Conti settings value.""" 37 | return self.parent.settings[key] 38 | 39 | def get(self, key: str, default: str = None): 40 | """Return Conti settings value with default.""" 41 | return self.parent.settings.get(key, default) 42 | 43 | def __del__(self): 44 | """ContiEncoder destructor.""" 45 | self.stop() 46 | 47 | def stop(self): 48 | """Stop encoder process.""" 49 | if not self.proc: 50 | logging.warning("Unable to stop encoder. Not running.") 51 | return 52 | if self.proc.poll() is not None: 53 | logging.warning("Unable to stop encoder. Already stopped") 54 | return 55 | logging.warning("Terminating encoder process") 56 | os.kill(self.proc.pid, signal.SIGKILL) 57 | self.proc.wait() 58 | 59 | @property 60 | def pipe_path(self): 61 | """Return pipe path.""" 62 | return self.parent.settings["pipe_path"] 63 | 64 | @property 65 | def is_running(self): 66 | """Return True if encoder is running.""" 67 | if not self.proc: 68 | return False 69 | if self.proc.poll() is None: 70 | return True 71 | return False 72 | 73 | def write(self, data): 74 | """Write data to encoder process.""" 75 | if not self.is_running: 76 | return 77 | self.proc.stdin.write(data) 78 | 79 | def start(self): 80 | """Start encoder process.""" 81 | cmd = ["ffmpeg", "-hide_banner"] 82 | 83 | # Most of the output formats needs -re switch to keep 84 | # the encoding speed at real time. 85 | # With decklink, this is not needed nor desireable 86 | 87 | if "decklink" not in [ 88 | profile.get("params", {"f": None}) 89 | for profile in self["outputs"] 90 | ]: 91 | cmd.append("-re") 92 | 93 | # Custom output filterchain 94 | 95 | filters = self.get("audio_filters", []) 96 | if filters: 97 | if type(filters) == str: 98 | filters = [filters] 99 | self.filter_chain.add(RawFilter( 100 | "[audio]" + ",".join(filters) + "[audio]" 101 | )) 102 | 103 | pre_filters = self.get("pre_filters", []) 104 | if pre_filters: 105 | if type(pre_filters) == str: 106 | pre_filters = [pre_filters] 107 | for pf in pre_filters: 108 | self.filter_chain.add(RawFilter(pf)) 109 | 110 | filters = self.get("video_filters", []) 111 | if filters: 112 | if type(filters) == str: 113 | filters = [filters] 114 | self.filter_chain.add(RawFilter( 115 | "[video]" + ",".join(filters) + "[video]" 116 | )) 117 | 118 | # Split video and audio outputs to match needed count. 119 | # If there is no video or audio needed in the output profiles, 120 | # send output to nullsink or anullsink 121 | 122 | voutputs = [] 123 | aoutputs = [] 124 | for i, profile in enumerate(self["outputs"]): 125 | if profile.get("video", True): 126 | voutputs.append(i) 127 | if profile.get("audio", True): 128 | aoutputs.append(i) 129 | 130 | if voutputs: 131 | vsplit = "[video]split={}".format(len(voutputs)) 132 | for voutput in voutputs: 133 | vsplit += "[video{}]".format(voutput) 134 | self.filter_chain.add(RawFilter(vsplit)) 135 | else: 136 | self.filter_chain.add(RawFilter("[video]nullsink")) 137 | 138 | if aoutputs: 139 | asplit = "[audio]asplit={}".format(len(aoutputs)) 140 | for aoutput in aoutputs: 141 | asplit += "[audio{}]".format(aoutput) 142 | self.filter_chain.add(RawFilter(asplit)) 143 | else: 144 | self.filter_chain.add(RawFilter("[audio]anullsink")) 145 | 146 | # Per-output stream filterchain 147 | 148 | for i, profile in enumerate(self["outputs"]): 149 | vfilters = profile.get("video_filters", []) 150 | afilters = profile.get("audio_filters", []) 151 | if vfilters: 152 | if type(vfilters) == str: 153 | vfilters = [vfilters] 154 | self.filter_chain.add(RawFilter( 155 | "[video{}]".format(i) + 156 | ",".join(vfilters) + 157 | "[video{}]".format(i) 158 | )) 159 | if afilters: 160 | if type(afilters) == str: 161 | afilters = [afilters] 162 | self.filter_chain.add(RawFilter( 163 | "[audio{}]".format(i) + 164 | ",".join(afilters) + 165 | "[audio{}]".format(i) 166 | )) 167 | 168 | # Load AV stream from pipe and attach the finished filterchain 169 | 170 | cmd.extend([ 171 | "-i", "-", 172 | "-filter_complex", self.filter_chain.render(), 173 | ]) 174 | 175 | # Create output profiles 176 | 177 | for i, profile in enumerate(self["outputs"]): 178 | 179 | if self.parent.settings["audio_only"]: 180 | cmd.extend(["-map", "[audio]"]) 181 | else: 182 | if profile.get("video", True): 183 | cmd.extend(["-map", "[video{}]".format(i)]) 184 | if profile.get("audio", True): 185 | cmd.extend(["-map", "[audio{}]".format(i)]) 186 | 187 | params = profile.get("params", {}) 188 | for key in params: 189 | cmd.append("-{}".format(key)) 190 | value = params[key] 191 | if value is not None: 192 | cmd.append(str(value)) 193 | cmd.append(profile["target"]) 194 | 195 | # ... and start the encoder 196 | 197 | logging.debug( 198 | "Starting encoder with the following settings:\n", 199 | " ".join(cmd) 200 | ) 201 | self.proc = subprocess.Popen( 202 | cmd, 203 | stderr=subprocess.PIPE, 204 | stdin=subprocess.PIPE, 205 | stdout=None 206 | ) 207 | -------------------------------------------------------------------------------- /conti/filters.py: -------------------------------------------------------------------------------- 1 | class FBaseFilter(object): 2 | arg_names = [] 3 | 4 | def __init__(self, *args, **kwargs): 5 | assert len(args) == len(self.arg_names), \ 6 | f"Expected arguments: {', '.join(self.arg_names)}" 7 | self.args = {} 8 | for key, value in zip(self.arg_names, args): 9 | self.args[key] = value 10 | self.kwargs = kwargs 11 | 12 | def keys(self): 13 | return list(self.args.keys()) + ["kwargs"] 14 | 15 | def __getitem__(self, key): 16 | if key == "kwargs": 17 | if not self.kwargs: 18 | return "" 19 | return ":".join([ 20 | f"{key}={self.kwargs[key]}" 21 | for key in self.kwargs 22 | ]) 23 | return self.args[key] 24 | 25 | 26 | class FilterChain(object): 27 | def __init__(self, *args): 28 | self.filters = list(args) 29 | 30 | def __len__(self): 31 | return len(self.filters) 32 | 33 | def add(self, *args): 34 | for f in args: 35 | self.filters.append(f) 36 | 37 | def render(self): 38 | return ";".join([f.render() for f in self.filters]) 39 | 40 | 41 | # 42 | # Filters 43 | # 44 | 45 | 46 | class RawFilter(FBaseFilter): 47 | arg_names = ["string"] 48 | 49 | def render(self): 50 | return self["string"] 51 | 52 | 53 | class FNull(FBaseFilter): 54 | arg_names = ["input", "output"] 55 | 56 | def render(self): 57 | return "[{input}]null[{output}]".format(**self) 58 | 59 | 60 | class FANull(FBaseFilter): 61 | arg_names = ["input", "output"] 62 | 63 | def render(self): 64 | return "[{input}]anull[{output}]".format(**self) 65 | 66 | 67 | class FApad(FBaseFilter): 68 | arg_names = ["input", "output"] 69 | 70 | def render(self): 71 | if self.kwargs: 72 | return "[{input}]apad={kwargs}[{output}]".format(**self) 73 | return "[{input}]apad[{output}]".format(**self) 74 | 75 | 76 | class FAtrim(FBaseFilter): 77 | arg_names = ["input", "output"] 78 | 79 | def render(self): 80 | if self.kwargs: 81 | return "[{input}]atrim={kwargs}[{output}]".format(**self) 82 | return "[{input}]atrim[{output}]".format(**self) 83 | 84 | 85 | class FSource(FBaseFilter): 86 | arg_names = ["path", "output"] 87 | 88 | def render(self): 89 | result = "movie='{path}'".format(**self) 90 | if self.kwargs: 91 | result += ":{kwargs}".format(**self) 92 | result += "[{output}]".format(**self) 93 | return result 94 | 95 | 96 | class FOverlay(FBaseFilter): 97 | arg_names = ["background", "foreground", "output"] 98 | 99 | def render(self): 100 | result = "[{background}][{foreground}]overlay".format(**self) 101 | if self.kwargs: 102 | result += "={kwargs}".format(**self) 103 | result += "[{output}]".format(**self) 104 | return result 105 | 106 | 107 | class FDrawText(FBaseFilter): 108 | arg_names = ["input", "output"] 109 | 110 | def render(self): 111 | result = "[{input}]drawtext={kwargs}[{output}]".format(**self) 112 | return result 113 | 114 | 115 | class FSetField(FBaseFilter): 116 | arg_names = ["input", "output", "order"] 117 | 118 | def render(self): 119 | result = "[{input}]setfielded={order}[{output}]".format(**self) 120 | return result 121 | 122 | 123 | class FSplit(FBaseFilter): 124 | arg_names = ["input", "outputs"] 125 | 126 | def render(self): 127 | result = "[{}]".format(self["input"]) 128 | result += "split={}".format(len(self["outputs"])) 129 | result += "".join(["[{}]".format(o) for o in self["outputs"]]) 130 | return result 131 | -------------------------------------------------------------------------------- /conti/probe.py: -------------------------------------------------------------------------------- 1 | from nxtools import tc2s 2 | from nxtools.media import ffprobe 3 | 4 | __all__ = ["AudioTrack", "media_probe"] 5 | 6 | 7 | COMMON_ASPECT_RATIOS = [ 8 | (1, 1), 9 | (4, 3), 10 | (16, 9), 11 | (2.35, 1) 12 | ] 13 | 14 | 15 | class AudioTrack(dict): 16 | def __repr__(self): 17 | return "Audio track {index} ({channel_layout})".format(**self) 18 | 19 | @property 20 | def id(self): 21 | return self["index"] 22 | 23 | 24 | def guess_aspect(w: int, h: int): 25 | if 0 in [w, h]: 26 | return 0 27 | ratio = float(w) / float(h) 28 | return "{}/{}".format( 29 | *min( 30 | COMMON_ASPECT_RATIOS, 31 | key=lambda x: abs((float(x[0])/x[1])-ratio) 32 | ) 33 | ) 34 | 35 | 36 | def find_start_timecode(probe_result): 37 | tc_places = [ 38 | probe_result["format"].get("tags", {}).get("timecode", "00:00:00:00"), 39 | probe_result["format"].get("timecode", "00:00:00:00"), 40 | ] 41 | tc = "00:00:00:00" 42 | for i, tcp in enumerate(tc_places): 43 | if tcp != "00:00:00:00": 44 | tc = tcp 45 | break 46 | return tc 47 | 48 | 49 | def media_probe(source_path): 50 | probe_result = ffprobe(source_path) 51 | if not probe_result: 52 | return {} 53 | 54 | format_info = probe_result["format"] 55 | meta = {"audio_tracks": []} 56 | source_vdur = 0 57 | source_adur = 0 58 | 59 | for stream in probe_result["streams"]: 60 | if stream["codec_type"] == "video": 61 | # Frame rate detection 62 | fps_n, fps_d = [ 63 | float(e) for e in stream["r_frame_rate"].split("/") 64 | ] 65 | meta["video/fps_f"] = fps_n / fps_d 66 | meta["video/fps"] = "{}/{}".format(int(fps_n), int(fps_d)) 67 | 68 | # Aspect ratio detection 69 | try: 70 | dar_n, dar_d = [ 71 | float(e) for e in stream["display_aspect_ratio"].split(":") 72 | ] 73 | if not (dar_n and dar_d): 74 | raise Exception 75 | except Exception: 76 | dar_n, dar_d = float(stream["width"]), float(stream["height"]) 77 | 78 | meta["video/aspect_ratio_f"] = float(dar_n) / dar_d 79 | meta["video/aspect_ratio"] = guess_aspect(dar_n, dar_d) 80 | 81 | try: 82 | source_vdur = float(stream["duration"]) 83 | except Exception: 84 | source_vdur = 0 85 | 86 | meta["video/codec"] = stream["codec_name"] 87 | meta["video/pixel_format"] = stream["pix_fmt"] 88 | meta["video/width"] = int(stream["width"]) 89 | meta["video/height"] = int(stream["height"]) 90 | meta["video/index"] = int(stream["index"]) 91 | meta["video/color_range"] = stream.get("color_range", "") 92 | meta["video/color_space"] = stream.get("color_space", "") 93 | meta["video/nb_frames"] = int(stream.get("nb_frames", 0)) 94 | 95 | elif stream["codec_type"] == "audio": 96 | meta["audio_tracks"].append(AudioTrack(**stream)) 97 | try: 98 | source_adur = max(source_adur, float(stream["duration"])) 99 | except Exception: 100 | pass 101 | 102 | if meta.get("video/nb_frames", False): 103 | meta["duration"] = meta["video/nb_frames"] / meta["video/fps_f"] 104 | else: 105 | meta["duration"] = float(format_info["duration"]) \ 106 | or source_vdur or source_adur 107 | 108 | tc = find_start_timecode(probe_result) 109 | if tc != "00:00:00:00": 110 | meta["start_timecode"] = tc2s(tc) # TODO: fps 111 | return meta 112 | -------------------------------------------------------------------------------- /conti/source.py: -------------------------------------------------------------------------------- 1 | __all__ = ["ContiSource"] 2 | 3 | import os 4 | import signal 5 | import subprocess 6 | 7 | from nxtools import get_base_name, logging 8 | 9 | from .probe import media_probe 10 | from .filters import ( 11 | FilterChain, 12 | RawFilter, 13 | FNull, 14 | FApad, 15 | FAtrim 16 | ) 17 | 18 | 19 | class ContiSource(object): 20 | def __init__(self, parent, path, **kwargs): 21 | self.parent = parent 22 | self.path = path 23 | self.proc = None 24 | self.base_name = get_base_name(path) 25 | self.mark_in = kwargs.get("mark_in", 0) 26 | self.mark_out = kwargs.get("mark_out", 0) 27 | self.position = 0.0 28 | self.error_log = [] 29 | 30 | self.meta = {} 31 | self.probed = False 32 | if "meta" in kwargs: 33 | assert type(kwargs["meta"]) == dict 34 | self.meta.update(kwargs["meta"]) 35 | 36 | self.filter_chain = FilterChain() 37 | 38 | tracks = {k["index"]: k["channels"] for k in self.audio_tracks} 39 | 40 | if tracks: 41 | amerge = "" 42 | num_channels = 0 43 | for idx in tracks: 44 | amerge += "[0:{}]".format(idx) 45 | num_channels += tracks[idx] 46 | if len(tracks) == 1: 47 | amerge = "[0:{}]".format(idx) 48 | else: 49 | amerge += "amerge=inputs={},".format(len(tracks)) 50 | 51 | amerge += "pan=hexadecagonal|{}[audio]".format( 52 | "|".join([ 53 | "c{}=c{}".format(idx, idx) 54 | for idx in range(num_channels) 55 | ]) 56 | ) 57 | else: 58 | amerge = "anullsrc=channel_layout=hexadecagonal" 59 | amerge += ":sample_rate=48000[audio]" 60 | 61 | self.filter_chain.add(RawFilter(amerge)) 62 | 63 | if not self.parent.settings["audio_only"]: 64 | if self.video_index > -1: 65 | self.filter_chain.add( 66 | FNull("0:{}".format(self.video_index), "video") 67 | ) 68 | else: 69 | self.filter_chain.add(RawFilter("color=c=black:s={}x{}".format( 70 | self.parent.settings["width"], 71 | self.parent.settings["height"] 72 | ))) 73 | 74 | # 75 | # Class stuff 76 | # 77 | 78 | def __repr__(self): 79 | try: 80 | return "".format(self.base_name) 81 | except Exception: 82 | return super(ContiSource, self).__repr__() 83 | 84 | # 85 | # Metadata helpers 86 | # 87 | 88 | def load_meta(self): 89 | self.meta = media_probe(self.path) 90 | if not self.meta: 91 | raise IOError(f"Unable to open {self.path}") 92 | self.probed = True 93 | 94 | @property 95 | def original_duration(self): 96 | if "duration" not in self.meta: 97 | self.load_meta() 98 | return self.meta["duration"] 99 | 100 | @property 101 | def audio_tracks(self): 102 | if not ("audio_tracks" in self.meta and self.probed): 103 | self.load_meta() 104 | return self.meta.get("audio_tracks", []) 105 | 106 | @property 107 | def duration(self): 108 | return (self.mark_out or self.original_duration) - self.mark_in 109 | 110 | @property 111 | def video_codec(self): 112 | if not ("video/codec" in self.meta and self.probed): 113 | self.load_meta() 114 | return self.meta["video/codec"] 115 | 116 | @property 117 | def video_index(self): 118 | if not ("video/index" in self.meta and self.probed): 119 | self.load_meta() 120 | return self.meta.get("video/index", -1) 121 | 122 | # 123 | # Process control 124 | # 125 | 126 | @property 127 | def is_running(self): 128 | if not self.proc: 129 | return False 130 | if self.proc.poll() is None: 131 | return True 132 | return False 133 | 134 | def read(self, *args, **kwargs): 135 | if not self.proc: 136 | self.open() 137 | data = self.proc.stdout.read(*args, **kwargs) 138 | if not data: 139 | return None 140 | return data 141 | 142 | def open(self): 143 | conti_settings = self.parent.settings 144 | cmd = ["ffmpeg", "-hide_banner"] 145 | 146 | if self.mark_in: 147 | cmd.extend(["-ss", str(self.mark_in)]) 148 | cmd.extend(["-i", self.path]) 149 | 150 | self.filter_chain.add( 151 | FApad("audio", "audio", whole_dur=self.duration) 152 | ) 153 | self.filter_chain.add( 154 | FAtrim("audio", "audio", duration=self.duration) 155 | ) 156 | 157 | cmd.extend([ 158 | "-filter_complex", self.filter_chain.render(), 159 | "-t", str(self.duration) 160 | ]) 161 | 162 | if not conti_settings["audio_only"]: 163 | cmd.extend([ 164 | "-map", "[video]", 165 | "-c:v", "rawvideo", 166 | "-s", "{}x{}".format( 167 | conti_settings["width"], 168 | conti_settings["height"] 169 | ), 170 | "-pix_fmt", conti_settings["pixel_format"], 171 | "-r", str(conti_settings["frame_rate"]), 172 | ]) 173 | else: 174 | cmd.append("-vn") 175 | 176 | cmd.extend([ 177 | "-map", "[audio]", 178 | "-c:a", conti_settings["audio_codec"], 179 | "-ar", str(conti_settings["audio_sample_rate"]), 180 | "-max_interleave_delta", "400000", 181 | "-f", "avi", 182 | "-" 183 | ]) 184 | 185 | logging.debug("Executing", " ".join(cmd)) 186 | self.proc = subprocess.Popen( 187 | cmd, 188 | stdout=subprocess.PIPE, 189 | stderr=subprocess.PIPE, 190 | stdin=subprocess.PIPE 191 | ) 192 | 193 | def stop(self): 194 | if not self.proc: 195 | return 196 | logging.warning("Terminating source process") 197 | os.kill(self.proc.pid, signal.SIGKILL) 198 | self.proc.wait() 199 | 200 | def send_command(self, cmd): 201 | if not self.proc: 202 | return 203 | self.proc.stdin.write("C{}\n".format(cmd)) 204 | -------------------------------------------------------------------------------- /conti/utils.py: -------------------------------------------------------------------------------- 1 | from nxtools import logging 2 | from nxtools.media import ffprobe 3 | 4 | __all__ = ["check_track_durations"] 5 | 6 | 7 | def check_track_durations(source_path): 8 | data = ffprobe(source_path) 9 | durations = set() 10 | container_duration = data.get("duration", 0) 11 | for stream in data["streams"]: 12 | if not stream["codec_type"] in ["audio", "video"]: 13 | continue 14 | durations.add(stream.get("duration", container_duration)) 15 | 16 | res = len(durations) == 1 17 | if not res: 18 | logging.warning(f"{source_path} tracks duration mismatch: {durations}") 19 | return res 20 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "conti" 3 | version = "1.0" 4 | description = "Minimalistic FFMpeg based playout server" 5 | keywords = ["playout", "broadcast", "streaming", "ffmpeg", "television"] 6 | repository = "https://github.com/immstudios/conti" 7 | authors = ["Martin Wacker "] 8 | license = "MIT" 9 | readme = "README.md" 10 | classifiers=[ 11 | "Development Status :: 5 - Production/Stable", 12 | "Environment :: Console", 13 | "Intended Audience :: Developers", 14 | "License :: OSI Approved :: MIT License", 15 | "Natural Language :: English", 16 | "Operating System :: POSIX :: Linux", 17 | "Programming Language :: Python", 18 | "Topic :: Multimedia :: Video :: Conversion", 19 | ] 20 | 21 | [tool.poetry.dependencies] 22 | python = "^3.6" 23 | nxtools = "^1.6.0" 24 | 25 | [tool.poetry.dev-dependencies] 26 | 27 | [tool.poetry.scripts] 28 | test = 'scripts:test' 29 | docs = 'scripts:docs' 30 | 31 | [build-system] 32 | requires = ["poetry-core>=1.0.0"] 33 | build-backend = "poetry.core.masonry.api" 34 | -------------------------------------------------------------------------------- /settings-rtp.json: -------------------------------------------------------------------------------- 1 | { 2 | "media_dir" : "/home/martas/Desktop/testclips/", 3 | "video_filters" : "hue=s=0", 4 | "outputs" : [ 5 | { 6 | "target" : "rtp://224.0.0.1:2000", 7 | "audio_filters" : "pan=stereo|c0=c0|c1=c1", 8 | "video_filters" : "scale=640x360", 9 | "params" : { 10 | "c:v" : "libx264", 11 | "b:v" : "900k", 12 | "c:a" : "aac", 13 | "b:a" : "96k", 14 | "f" : "rtp_mpegts", 15 | "pix_fmt" : "yuv420p" 16 | } 17 | } 18 | 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /settings-sdl.json: -------------------------------------------------------------------------------- 1 | { 2 | "media_dir" : "/home/martas/Desktop/testclips/", 3 | "video_filters" : "hue=s=0", 4 | "outputs" : [ 5 | { 6 | "target" : "SDL Output", 7 | "audio" : false, 8 | "params" : { 9 | "c:v" : "rawvideo", 10 | "f" : "sdl", 11 | "pix_fmt" : "yuv420p" 12 | } 13 | }, 14 | { 15 | "target" : "SDL Output1", 16 | "audio" : false, 17 | "video_filters": "hflip", 18 | "params" : { 19 | "c:v" : "rawvideo", 20 | "f" : "sdl", 21 | "pix_fmt" : "yuv420p" 22 | } 23 | } 24 | 25 | ] 26 | } 27 | --------------------------------------------------------------------------------